From 9e54c8cf27b726929d040a971b31a8132bcfc927 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 20 Oct 2026 17:06:22 +0000 Subject: [PATCH 001/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.9=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index f5be5a9ab..413d11f82 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.9" +current_version = "0.41.0-beta.10" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index b339cf454..61aee21be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5698,7 +5698,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.9" +version = "0.41.0-beta.10" dependencies = [ "ahash", "anyhow", @@ -5796,7 +5796,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.9" +version = "0.41.0-beta.10" dependencies = [ "arrow-array", "arrow-buffer", @@ -5821,7 +5821,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.9" +version = "0.41.0-beta.10" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 7a9a89641..b6cbd8586 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.9 + 0.41.0-beta.10 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 83b27fefd..e64f65852 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.9 + 0.41.0-beta.10 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 4dd145b31..4e4a82b63 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.9 + 0.41.0-beta.10 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 3ef5438de..79a594f14 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.9" +version = "0.41.0-beta.10" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index da0158b7d..403b1d2c2 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 451766110..ef2d4ca40 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index d818cb60f..5b247be2c 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 4fe1c12cc..0c36b7213 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 7dc63ccaa..274877c83 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index dc97bbed8..67f0176f5 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 235bb0e55..5f3cf6032 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 22f51ce61..df083600a 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.9", + "version": "0.41.0-beta.10", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index ce4230f9d..615b7c5aa 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.9" +version = "0.41.0-beta.10" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 1daeef984..4649e560d 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.9" +version = "0.41.0-beta.10" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 951ae51ef603cba4af4582182ba9c54af9b68eab Mon Sep 17 00:00:00 2001 From: Dan Rammer Date: Tue, 20 Oct 2026 21:40:20 -0500 Subject: [PATCH 002/180] docs: add realtime engine (RTE) getting-started guide (#4548) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a user-facing realtime engine (RTE) page at `docs/web/tables/realtime-engine.mdx`, listed under **Management** after Branches. It is adapted from the internal WAL field guide (lancedb/sophon#6213), with the deployment and operations material left out. The page covers: - what RTE is and how it works (memtable → SSTables → compaction; reads merge the base table with the fresh tier) - getting started: `set_unenforced_primary_key`, indexes, `enable_rte` / `ALTER TABLE ... SET RTE`, `merge_insert` upserts and queries, partial updates, deletes, and `checkpoint_rte` / `disable_rte` - performance: write throughput and shard scaling, and read latency with and without RTE - a note on operations not yet supported (time travel, branching, `count_rows`, row IDs, `TABLESAMPLE`) Also aligns related docs with current RTE naming and behavior: - `sql/ddl/table.mdx`: `SET MEMWAL` / `UNSET MEMWAL` → `SET RTE` / `UNSET RTE` - `maintenance/background-jobs.mdx`: job names are `memwal_compaction` and `memwal_catchup_` - `feature-engineering/materialized-views.mdx`: MemWAL → realtime engine - Python `AsyncTable.enable_rte` / `RTEWriteSpec.with_maintained_indexes` docstrings: by default, indexes created after enabling RTE are maintained too The examples are written directly in the page rather than generated from `docs/web-tests`, because RTE needs an Enterprise server to run. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: XY Zhan --- docs/web/docs.json | 1 + .../materialized-views.mdx | 2 +- docs/web/maintenance/background-jobs.mdx | 6 +- docs/web/sql/ddl/table.mdx | 14 +- docs/web/tables/realtime-engine.mdx | 229 ++++++++++++++++++ python/python/lancedb/_lancedb.pyi | 6 +- python/python/lancedb/table.py | 12 +- 7 files changed, 251 insertions(+), 19 deletions(-) create mode 100644 docs/web/tables/realtime-engine.mdx diff --git a/docs/web/docs.json b/docs/web/docs.json index a8fb44007..9c9468a3b 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -327,6 +327,7 @@ "management/namespace", "management/table", "tables/branching", + "tables/realtime-engine", "management/materialized-view", "management/view" ] diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index ffe4fc959..1552c3638 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -52,7 +52,7 @@ In Python SDK 0.40.0, create the source with above does. Stable row IDs let the view track source rows across updates and compaction. Set this option when creating the table; it cannot be added later. -A source with a MemWAL write spec or retained, uncompacted write-ahead-log +A source with the [realtime engine](/tables/realtime-engine) enabled or retained, uncompacted write-ahead-log rows is not accepted by the local materialized-view implementation. ## Refresh behavior {#incremental} diff --git a/docs/web/maintenance/background-jobs.mdx b/docs/web/maintenance/background-jobs.mdx index dcfa31321..1a710fe79 100644 --- a/docs/web/maintenance/background-jobs.mdx +++ b/docs/web/maintenance/background-jobs.mdx @@ -27,13 +27,13 @@ also start cache-warming jobs through the admin API. ## Write-ahead log maintenance {#wal} -For a table with a [write-ahead log](/sql/ddl/table#properties) enabled, two jobs keep the +For a table with the [realtime engine](/tables/realtime-engine) enabled, two jobs keep the log from growing without bound: | Job type | What it does | | --- | --- | -| `sstable_compaction` | Folds a table shard's SSTables into the base table by primary key. Distinct from `compact`, which merges base-table fragments. The two are unrelated. | -| `wal_index_catchup` | Extends a base-table index over the rows `sstable_compaction` just folded in, and records how far the index has caught up. Nothing else advances that record. | +| `memwal_compaction` | Folds a table shard's SSTables into the base table by primary key. Distinct from `compact`, which merges base-table fragments. The two are unrelated. | +| `memwal_catchup_` | Extends a base-table index over the rows `memwal_compaction` just folded in, and records how far the index has caught up. Nothing else advances that record. The suffix names the index type, for example `memwal_catchup_btree`, `memwal_catchup_fts`, or `memwal_catchup_ivfpq`. | ## Index maintenance {#index} diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index ecb522fe6..792568220 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -102,18 +102,20 @@ duplicates impossible. It tells the planner what to assume. The column must be declared `NOT NULL`. ```sql -ALTER TABLE t SET MEMWAL -ALTER TABLE t SET MEMWAL WITH (sharding = 'bucket', column = 'id', buckets = 4) -ALTER TABLE t SET MEMWAL WITH (maintained_indexes = '') -ALTER TABLE t UNSET MEMWAL +ALTER TABLE t SET RTE +ALTER TABLE t SET RTE WITH (sharding = 'bucket', column = 'id', buckets = 4) +ALTER TABLE t SET RTE WITH (maintained_indexes = '') +ALTER TABLE t UNSET RTE ``` -A write-ahead log makes small frequent writes cheap by batching them out of the +The [realtime engine](/tables/realtime-engine) puts a write-ahead log in front +of the table, making small frequent writes cheap by batching them out of the commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be the table's unenforced primary key, and inserts into the table then need a scalar index on that key. `maintained_indexes` chooses which indexes are kept -current against WAL rows. A table with a computed column cannot take a +current against WAL rows; omitted, every supported index is kept current, +including ones created later. A table with a computed column cannot take a write-ahead log. See [Background jobs](/maintenance/background-jobs#wal) for how the log gets folded back into the table. diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx new file mode 100644 index 000000000..88738791c --- /dev/null +++ b/docs/web/tables/realtime-engine.mdx @@ -0,0 +1,229 @@ +--- +title: "Realtime engine (RTE)" +sidebarTitle: "Realtime Engine" +description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." +icon: "bolt" +keywords: ["rte", "realtime engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +--- + +Enterprise + +## What is the realtime engine? {#what-is-rte} + +Every write to a LanceDB table is normally a commit to the underlying Lance +dataset. That is ideal for bulk loads, but a stream of small upserts becomes a +stream of small commits, and each write is only visible once its commit lands. + +The realtime engine (RTE) puts an LSM-style write tier in front of the table. +It turns many small writes into a few large commits, and makes each write +**searchable within milliseconds** of being acknowledged. It is enabled per +table, and nothing about how you query that table changes. + +## How it works {#how-it-works} + +- **Writes.** A `merge_insert` or `delete` lands in an in-memory **memtable** + and is acknowledged once it is durable in the write-ahead log on object + storage. +- **Flush and compaction.** Memtables freeze into **SSTables**, which background + jobs compact into the base table, catching its indexes up as they go. See + [Background jobs](/maintenance/background-jobs#wal). +- **Reads.** Every query runs against the base table and the fresh tier + (memtables and SSTables) in parallel. Fresh rows supersede base rows with the + same primary key, and the two are merged into one result. +- **Indexes stay fresh.** Vector, full-text, BTree, bitmap, and most other + scalar indexes are maintained on the memtable, so new rows are searchable + through the index as soon as they are written. + +## Getting started {#getting-started} + +### 1. Create a table with a primary key {#primary-key} + +RTE deduplicates writes by primary key. Create the table with a non-nullable +key column, then declare it with `set_unenforced_primary_key`. The key is a +single `int32`, `int64`, string, or binary column, and cannot be changed once +set. + +```python +from datetime import timedelta + +import lancedb +import numpy as np +import pyarrow as pa +from lancedb import RTEWriteSpec +from lancedb.index import FTS, BTree, IvfPq + +db = lancedb.connect("db://my_db", api_key="...", host_override="https://...") + +n, dim = 1024, 128 +schema = pa.schema([ + pa.field("id", pa.int64(), nullable=False), + pa.field("vector", pa.list_(pa.float32(), dim)), + pa.field("text", pa.utf8()), +]) +initial_data = pa.table({ + "id": pa.array(range(n), pa.int64()), + "vector": pa.FixedSizeListArray.from_arrays( + pa.array(np.random.rand(n * dim).astype("float32")), dim), + "text": pa.array([f"doc {i} alpha bravo" for i in range(n)]), +}, schema=schema) +table = db.create_table("docs", initial_data, schema=schema) +table.set_unenforced_primary_key("id") +``` + +Or in SQL: + +```sql +ALTER TABLE docs SET UNENFORCED PRIMARY KEY (id) +``` + +### 2. Create indexes {#indexes} + +By default, RTE maintains every supported index on the table, including +indexes created after it is enabled. A scalar index on the primary key is +required for partial updates and deletes. + +```python +table.create_index("vector", config=IvfPq()) +table.create_index("text", config=FTS()) +table.create_index("id", config=BTree()) +table.wait_for_index(["vector_idx", "text_idx", "id_idx"], timeout=timedelta(minutes=5)) +``` + +### 3. Enable RTE {#enable} + +```python +table.enable_rte(RTEWriteSpec.unsharded()) +``` + +Or in SQL: + +```sql +ALTER TABLE docs SET RTE +``` + +### 4. Write and query {#write-and-query} + + +On an RTE table, an upsert through `merge_insert` is the only way to write +rows. Use the form below exactly: `when_matched_update_all()` with no filter, +plus `when_not_matched_insert_all()`. Other `merge_insert` forms, such as +conditional updates or deleting rows missing from the source, are rejected. + + +Writes go through `merge_insert` on the primary key, and are visible to queries +immediately: + +```python +new_rows = pa.table({ + "id": pa.array([2000, 2001], pa.int64()), + "vector": pa.FixedSizeListArray.from_arrays( + pa.array(np.random.rand(2 * dim).astype("float32")), dim), + "text": pa.array(["fresh charlie delta", "fresh echo foxtrot"]), +}, schema=schema) +query_vector = np.random.rand(dim).astype("float32") + +table.merge_insert("id") \ + .when_matched_update_all() \ + .when_not_matched_insert_all() \ + .execute(new_rows) + +table.search(query_vector).limit(10).to_list() +table.search("charlie").limit(10).to_list() +``` + +**Partial updates.** Send the primary key plus only the columns you want to +change; omitted columns keep their current values. This requires a scalar +index on the primary key. + +```python +patch = pa.table( + {"id": [0, 1], "text": ["doc 0 revised", "doc 1 revised"]}, + schema=pa.schema([schema.field("id"), schema.field("text")]), +) +table.merge_insert("id").when_matched_update_all().when_not_matched_insert_all().execute(patch) +``` + +**Deletes.** The predicate must bind the primary key to literal values. Ranges, +`OR`, and filters on other columns are rejected. Deletes require a scalar index +on the primary key. + +```python +table.delete("id IN (2000, 2001)") +``` + +### Disabling RTE {#disable} + +Stop writes and wait for in-flight writes to finish, then flush pending writes +into the base table and disable. `checkpoint_rte()` only drains writes that +existed when it started, so anything written during the checkpoint can be left +behind. `disable_rte()` is rejected while the write-ahead log still holds rows, +so run `checkpoint_rte()` first. + +```python +table.checkpoint_rte() +table.disable_rte() +``` + +## Performance {#performance} + +### Writes {#write-performance} + +RTE acknowledges a write as soon as it is durable in the write-ahead log, so +ingest is no longer limited by how fast the table can commit. + +**Compared with writing directly to the table.** On tables ranging from +hundreds of thousands to tens of millions of rows, RTE delivered 4–12× the +write throughput and 24–52× lower p99 write latency, depending on the mix of +inserts, updates, and deletes. + +**Scaling with shards.** An RTE table can be split into +[shards](/sql/ddl/table#properties) that write independently, and a single +table's ingest grows with its shard count. In our testing on AWS, with every +index on the table (vector, full-text, and BTree) kept current, a single table +reached these peak rates: + +| Shards | Peak ingest | +| --: | --: | +| 1 | 90 MB/s | +| 2 | 170 MB/s | +| 4 | 340 MB/s | +| 8 | 625 MB/s | +| 16 | 690 MB/s | +| 32 | 885 MB/s | + +Adding shards scales a table's ingest nearly linearly. + +### Reads {#read-performance} + +Reads on an RTE table stay close to those on a fully compacted table, even +with the fresh tier at its fullest before compaction. + +The table below compares a 5M-row table with a 128-dimension IVF-PQ index plus +BTree and FTS indexes, with and without RTE. The RTE table holds one +unflushed memtable and three SSTables, each from a 100k-row write wave, half of +which are updates to existing rows. Latencies are p50 in milliseconds. + +| Query | Without RTE | With RTE | +| --- | --: | --: | +| Primary-key lookup | 62 | 63 | +| Vector search | 68 | 71 | +| Vector search with prefilter | 90 | 91 | +| Full-text term | 63 | 64 | +| Full-text phrase | 68 | 82 | +| Hybrid search (RRF) | 68 | 83 | +| SQL point lookup | 189 | 187 | + +Most queries are within a few milliseconds of the base table. Hybrid and phrase +queries add roughly 15 ms to merge the two tiers. + + +Support for all table operations on RTE tables is coming soon. Time travel, +branching, `count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet +available. + + +## Next steps {#next-steps} + +- [Merge insert](/ingestion/merge-insert) +- [Background jobs](/maintenance/background-jobs#wal) +- [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 988482a97..5a613b210 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -850,9 +850,9 @@ class RTEWriteSpec: @staticmethod def unsharded() -> "RTEWriteSpec": ... def with_maintained_indexes(self, indexes: Optional[List[str]]) -> "RTEWriteSpec": - """Set which indexes the RTE keeps up to date. None resolves every - index on the table at install, failing if one cannot be maintained; - a list is verbatim, empty means none.""" + """Set which indexes the RTE keeps up to date. None is every index on + the table, now and later, skipping any it cannot maintain; a list is + verbatim, empty means none.""" ... def with_writer_config_defaults(self, defaults: Dict[str, str]) -> "RTEWriteSpec": """Return a copy of this spec recording the given default diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 48d5582d1..60404b73c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -5564,12 +5564,12 @@ class AsyncTable: via [`set_unenforced_primary_key`]; bucket sharding additionally requires it to be the single column being bucketed. - By default the RTE maintains every index on the table, resolved - here — a snapshot, so an index created afterwards needs the spec unset - and set again. This fails if one cannot be maintained; name the set - with ``with_maintained_indexes`` to install anyway. That pins an exact - set (a still-building index is rejected, not omitted); ``[]`` maintains - none. + By default the RTE maintains every index on the table, re-read as the + table changes, so an index created later is maintained too; one of a + kind the RTE cannot mirror is skipped. Name the set with + ``with_maintained_indexes`` to pin it instead: each name must already + exist and be maintainable (a still-building index is rejected, not + omitted); ``[]`` maintains none. Parameters ---------- From bedb6ab3b1d9f1feeafc380a3453ee9161f09e7d Mon Sep 17 00:00:00 2001 From: Lei Xu Date: Tue, 20 Oct 2026 21:47:11 -0700 Subject: [PATCH 003/180] docs(python): rework PyTorch page around StreamingDataset (#4606) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Rework `docs/web/training/torch.mdx` for people who already know the PyTorch `DataLoader`, built around `lancedb.streaming.StreamingDataset`. - The quickstart trains a state-to-action policy on the real `lance-format/lerobot-xvla-soft-fold` dataset loaded via `hf://`, using a zero-copy Arrow-to-tensor transform. - Add a short table mapping PyTorch idioms (`IterableDataset`, `DistributedSampler`, `collate_fn`, `random_split`, `StatefulDataLoader`) to their LanceDB equivalents. - Add an Optimizations section: Transform (including an `ExtractFrames` example using blob v2 and torchcodec), Distributed Training, and the existing Output Formats content moved underneath. ## Notes - The quickstart depends on #4602 (permutation building over tables with schema metadata), which is merged. - `ExtractFrames` takes a URI and opens the table lazily because a local `LanceTable` cannot yet be pickled into DataLoader workers. - The Permutation-based "Selecting columns" and "Using multiple DataLoader workers" sections further down are unchanged from main. ## Test plan - [x] Ran the quickstart, transform, `ExtractFrames` (main process and forkserver workers) and distributed snippets locally. - [x] Rendered the page with `mint dev` and checked for console errors. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 --- docs/web/training/torch.mdx | 163 +++++++++++++++++++++++++++++------- 1 file changed, 135 insertions(+), 28 deletions(-) diff --git a/docs/web/training/torch.mdx b/docs/web/training/torch.mdx index 53d33e39c..64bf9f5fc 100644 --- a/docs/web/training/torch.mdx +++ b/docs/web/training/torch.mdx @@ -1,7 +1,7 @@ --- title: "PyTorch Integration" sidebarTitle: "PyTorch" -description: Learn how to use LanceDB with PyTorch for training and inference. +description: Use a LanceDB table as a PyTorch IterableDataset, mapped onto the `torch.utils.data` concepts you already know. icon: fire availability: oss: available @@ -11,44 +11,151 @@ availability: tables in the Python SDK. --- -Use LanceDB tables as input to a PyTorch `DataLoader`. Select the columns you -need, choose a batch format, and read data in parallel for training or inference. +`StreamingDataset` is a LanceDB table exposed as a PyTorch +[`IterableDataset`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset), +so it drops into a stock [`DataLoader`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader). +It handles per-epoch shuffling, sharding across ranks and workers, prefetching, and exact resume, so you +don't write those yourself. The shuffle is fixed when the dataset is constructed, so each epoch needs a new +`StreamingDataset` built with that epoch's number. ## Quickstart {#quickstart} -The `Table` class in LanceDB implements a contract for a PyTorch -[Dataset](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.Dataset). - This means you can simply use a LanceDB table in a PyTorch dataloader directly. +```py Python icon=Python +import lancedb, pyarrow as pa, torch +from torch import nn +from lancedb.streaming import StreamingDataset -```py Python icon=Python -import lancedb -import torch -import pyarrow as pa -from lancedb.util import tbl_to_tensor +def to_samples(rb: pa.RecordBatch): + f = lambda c: torch.from_dlpack(rb[c].flatten()).view(len(rb), -1) + rows = zip(f("observation_state"), f("action")) + return [{"state": s, "action": a} for s, a in rows] -mem_db = lancedb.connect("memory://") -table = mem_db.create_table("test_table", pa.table({"a": range(1000)})) +uri = "hf://datasets/lance-format/lerobot-xvla-soft-fold/data" +db = lancedb.connect(uri, storage_options={"hf_enable_resolve_cache": "true"}) +table = db.open_table("frames") +train = StreamingDataset( + table, columns=["observation_state", "action"], + transform=to_samples) -# Any LanceDB table can be used as a PyTorch Dataset -dataloader = torch.utils.data.DataLoader( - table, batch_size=1024, shuffle=True, collate_fn=tbl_to_tensor -) - -for batch in dataloader: - print(batch) +model = nn.Sequential(nn.Linear(96, 256), nn.ReLU(), nn.Linear(256, 14)) +opt = torch.optim.AdamW(model.parameters(), lr=1e-3) +for batch in torch.utils.data.DataLoader(train, batch_size=256): + loss = nn.MSELoss()(model(batch["state"]), batch["action"]) + opt.zero_grad() + loss.backward() + opt.step() ``` -Although the `Table` class in LanceDB implements the `torch.utils.data.Dataset` interface, you may find that using -a table [Permutation](/training/data-loading) is more flexible. +`StreamingDataset` is a standard PyTorch `IterableDataset`, so it works with everything built for one: a stock +`DataLoader`, its default `collate_fn`, and worker processes. The transform returns plain tensors, so the +model, loss and optimizer are unmodified PyTorch. Here it streams the +[`lerobot-xvla-soft-fold`](https://huggingface.co/datasets/lance-format/lerobot-xvla-soft-fold) dataset +straight from the Hugging Face Hub to train a policy that predicts each `action` from the robot's +`observation_state`. -```py Python icon=Python -from lancedb.permutation import Permutation +## PyTorch concepts in LanceDB {#concept-map} -permutation = Permutation.identity(table) -dataloader = torch.utils.data.DataLoader(permutation) +| In PyTorch you would write | In LanceDB you use | +| --- | --- | +| An `IterableDataset` that reads files in `__iter__` | `StreamingDataset(table)` | +| `DistributedSampler`, or sharding by `get_worker_info()` in `__iter__` | `rank=` and `world_size=`. Each rank and each DataLoader worker reads its own disjoint splits | +| Decoding in `__getitem__` or `collate_fn` | `transform=`, which receives a whole Arrow `RecordBatch` and runs in a thread pool | +| `random_split`, `Subset`, or reading only the fields a model needs | `filter=""` and `columns=[...]`. Unselected columns are never read from storage | +| `StatefulDataLoader` | `state_dict()` and `load_state_dict()`, plus `StreamingDataLoader` for workers | + +The dataset does not copy your data. At construction it computes a shuffled assignment of row IDs to +`num_splits` fixed splits, then reads rows from the table as it iterates. It reads the table version +that exists at construction, so rows appended later do not appear mid-epoch. + +## Optimizations {#optimizations} + +The quickstart works as written. These sections cover what to tune as training scales up: the transform that +builds each sample, running across many GPUs, and the output format of a `Table` or `Permutation`. + +### Transform {#transform} + +A `transform` turns a batch of Arrow rows into the per-sample items your `DataLoader` collates. It receives a +whole `pyarrow.RecordBatch` (`read_batch_size` rows, 64 by default) rather than one sample at a time, so +vectorized code is cheap, and it must return exactly one item per row. The quickstart's transform is the +whole pattern: columns become tensors and each row becomes a dict, which the default `collate_fn` stacks into +a batch. Without a transform, rows arrive as plain Python dicts. + +Heavier per-sample work belongs in the same function, such as decoding video. Store each clip in a blob v2 +column (`lancedb.blob("video")`). A scan returns small descriptors instead of the video bytes, so reading +other columns never pulls video in. `fetch_blob_files` opens the clips for a batch of rows as file handles, +and torchcodec's `VideoDecoder` decodes just the frames you ask for. `ExtractFrames` samples 8 evenly spaced +frames from each clip: + +```py Python icon=Python +import functools +from torchcodec.decoders import VideoDecoder + +class ExtractFrames: + def __init__(self, uri: str, name: str, num_frames: int = 8) -> None: + self.uri, self.name, self.num_frames = uri, name, num_frames + + @functools.cached_property + def table(self) -> lancedb.table.Table: + return lancedb.connect(self.uri).open_table(self.name) + + def __call__(self, rb: pa.RecordBatch) -> list[dict[str, torch.Tensor]]: + samples = [] + for blob in self.table.fetch_blob_files("video", rb["_rowid"]): + decoder = VideoDecoder(blob) + idx = torch.linspace(0, len(decoder) - 1, self.num_frames).long() + samples.append({"frames": decoder.get_frames_at(idx.tolist()).data}) + return samples + +# `clips` is the table "clips" in the database at `uri`, with a blob v2 column "video" +train = StreamingDataset(clips, columns=["_rowid"], transform=ExtractFrames(uri, "clips")) ``` -## Output Formats {#output-formats} +Transforms run in a thread pool, one thread per CPU by default (`transform_parallelism`), overlapping with +storage reads and your training step. NumPy, PyArrow and PyTorch release the GIL, so vectorized +work runs in parallel. A pure-Python loop does not. If a profile shows the transform is the bottleneck, move +it into [DataLoader workers](#using-multiple-dataloader-workers). + +Real data has bad rows, such as a truncated frame. Raise inside the transform and set +`on_transform_error="skip"` (or `"warn"` to log each failure). LanceDB re-runs the failing batch one row at a +time, drops only the rows that raise, and counts them in `dataset.rows_skipped`. When the bad rows match a SQL +predicate, prefer `filter=`: it runs before the splits are built, so every split keeps the same length. + +### Distributed Training {#distributed-training} + +`StreamingDataset` takes the place of `DistributedSampler`. Pass the rank and world size, and each rank reads +its own disjoint part of the table, together covering it once per epoch: + +```py Python icon=Python +import torch.distributed as dist + +dist.init_process_group("nccl") +train = StreamingDataset( + table, columns=["observation_state", "action"], transform=to_samples, + num_splits=48, shuffle_seed=42, epoch=epoch, + rank=dist.get_rank(), world_size=dist.get_world_size()) +``` + +Everything after the dataset is standard distributed PyTorch. Wrap the model in `DistributedDataParallel` +and pass `batch_size` to the `DataLoader` per GPU, so the global batch is `batch_size * world_size`. Nothing +in the data path changes. + +Three arguments matter in distributed runs: + +- **`num_splits`** is how many fixed streams the table is divided into. It must be divisible by `world_size`, + and by `world_size * num_workers` when you use DataLoader workers. Choose a number with many divisors, such + as 48, and runs on 8, 4 or 2 GPUs see the same data at every step, provided the global batch size is a multiple of + `num_splits`. +- **`shuffle_seed` and `epoch`** must be identical on every rank. Pass a fixed `shuffle_seed` and increase + `epoch` each epoch. `shuffle_seed=None` draws a different random seed in each process, so ranks would read + overlapping rows and miss others. +- **`rank` and `world_size`** come from your launcher, for example `torchrun`. + +To resume after a failure, save `train.state_dict()` next to the model. It records progress per split, so the +resumed run continues from the same row even on a different number of GPUs. See +[Parallelism & Elasticity](/training/data-loading#parallelism-&-elasticity) and +[Checkpointing](/training/data-loading#checkpointing) for the batch-size rules and the multi-worker case. + +### Output Formats {#output-formats} By default, a `Table` data loader will emit Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to turn the fetched items into one batch. PyTorch's default collate function only knows how to combine tensors, NumPy @@ -68,7 +175,7 @@ the Arrow data in different ways. The `arrow` and `polars` formats will always `pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and `torch` formats will all require at least one full copy of the data and are the slowest options. -### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} +#### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting From b533fe431a26ee794c0cb229d729947c82cbc81e Mon Sep 17 00:00:00 2001 From: IOCRYPOSTO Date: Wed, 21 Oct 2026 11:49:28 +0530 Subject: [PATCH 004/180] docs: fix TypeScript file paths in AGENTS.md (#4612) Lines 105-106 of AGENTS.md tell agents to add TypeScript methods in `nodejs/src/table.ts` and `nodejs/src/native_table.ts`. Neither file exists; the abstract `Table` class and the concrete `LocalTable` class are both in `nodejs/lancedb/table.ts`. An agent following these steps searches for files that are not there. This updates both paths. Docs-only, no code change. Suggested by LanceDB support (Daisuke) after I reported it by email. --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f6d01db03..24465a28f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,8 +102,8 @@ TypeScript bindings changes: 1. Add napi-rs method binding on `Table` in `nodejs/src/table.rs`. 2. Run `pnpm build` to generate TypeScript definitions. -3. Add typescript method on abstract class `Table` in `nodejs/src/table.ts`. -4. Add concrete method on `LocalTable` class in `nodejs/src/native_table.ts`. +3. Add typescript method on abstract class `Table` in `nodejs/lancedb/table.ts`. +4. Add concrete method on `LocalTable` class in `nodejs/lancedb/table.ts`. * Note: despite the name, this class is also used for remote tables. 5. Add test in `nodejs/__test__/table.test.ts`. 6. Run `pnpm run docs` to generate TypeScript documentation. From b00061fb28fc09208fc9e8eed12391734de7554f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 21 Oct 2026 16:12:12 +0800 Subject: [PATCH 005/180] chore: update lance dependency to v14.0.0-beta.22 (#4614) Pin the Rust workspace and Java lance-core dependency to [Lance v14.0.0-beta.22](https://github.com/lance-format/lance/releases/tag/v14.0.0-beta.22), including managed data file parts and descriptor reuse from lance-format/lance#10176. This enables the next LanceDB preview release to provide the tagged dependency needed by lancedb/sophon#8898. No compatibility code changes are required. Update rustls-webpki to 0.103.16 and webpki-roots to 1.0.10 in the lockfile to resolve the two TLS advisories blocking dependency CI (RUSTSEC-2026-0382 and RUSTSEC-2026-0381), without adding advisory exceptions. The Java dependency availability blocker is resolved: both the beta.22 POM and JAR return HTTP 200 from maven.lance.org. On `ea043bf93`, the review reproducer (`cd java && ./mvnw -U -q test -pl lancedb-core -Dspotless.skip=true`) passes all 37 tests, and [Java CI attempt 2](https://github.com/lancedb/lancedb/actions/runs/39556336205/attempts/2) passes. --- Cargo.lock | 109 ++++++++++++++++++++++++++------------------------- Cargo.toml | 28 ++++++------- java/pom.xml | 2 +- 3 files changed, 70 insertions(+), 69 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 61aee21be..8722b0e49 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3584,8 +3584,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4441,7 +4441,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] @@ -5059,8 +5059,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arc-swap", "arrow", @@ -5110,6 +5110,7 @@ dependencies = [ "lance-tokenizer", "log", "moka", + "num-traits", "object_store 0.14.2", "permutation", "pin-project", @@ -5134,8 +5135,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5157,7 +5158,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5171,7 +5172,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-schema", @@ -5180,8 +5181,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrayref", "crunchy", @@ -5191,8 +5192,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5229,8 +5230,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow", "arrow-array", @@ -5261,8 +5262,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow", "arrow-array", @@ -5279,8 +5280,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "proc-macro2", "quote", @@ -5289,8 +5290,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-arith", "arrow-array", @@ -5323,8 +5324,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-arith", "arrow-array", @@ -5356,8 +5357,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "datafusion", "geo-traits", @@ -5371,8 +5372,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arc-swap", "arrow", @@ -5443,8 +5444,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-schema", @@ -5467,8 +5468,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow", "arrow-array", @@ -5511,8 +5512,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "byteorder", "ethnum", @@ -5529,8 +5530,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-schema", @@ -5544,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow", "async-trait", @@ -5559,8 +5560,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arc-swap", "arrow", @@ -5586,7 +5587,7 @@ dependencies = [ "object_store 0.14.2", "quick-xml 0.40.1", "rand 0.9.5", - "reqwest 0.12.28", + "reqwest 0.13.4", "roaring", "serde", "serde_json", @@ -5614,8 +5615,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5629,8 +5630,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow", "arrow-array", @@ -5670,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "arrow-array", "arrow-schema", @@ -5684,8 +5685,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "14.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.21#8c233c2e6aa6948524f352e5e4cd52bd1364f6ff" +version = "14.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" dependencies = [ "frostem", "icu_segmenter", @@ -8909,7 +8910,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] @@ -9239,9 +9240,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -11156,14 +11157,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.7" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] diff --git a/Cargo.toml b/Cargo.toml index e302d2891..1307de8f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.94.0" [workspace.dependencies] -lance = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=14.0.0-beta.21", default-features = false, "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=14.0.0-beta.21", "tag" = "v14.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=14.0.0-beta.22", default-features = false, "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=14.0.0-beta.22", default-features = false, "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=14.0.0-beta.22", default-features = false, "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 4e4a82b63..eb3208627 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 14.0.0-beta.21 + 14.0.0-beta.22 2.18.11 false 2.30.0 From 46ccbe4e2c375911b22a517e04dfb4785849d11d Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 21 Oct 2026 08:20:35 +0000 Subject: [PATCH 006/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.10=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.11?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 413d11f82..52cb1eb2f 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.10" +current_version = "0.41.0-beta.11" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 8722b0e49..cf0e79f3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5699,7 +5699,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.10" +version = "0.41.0-beta.11" dependencies = [ "ahash", "anyhow", @@ -5797,7 +5797,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.10" +version = "0.41.0-beta.11" dependencies = [ "arrow-array", "arrow-buffer", @@ -5822,7 +5822,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.10" +version = "0.41.0-beta.11" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index b6cbd8586..d6f3e7ef7 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.10 + 0.41.0-beta.11 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index e64f65852..6dd92bbac 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.10 + 0.41.0-beta.11 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index eb3208627..12a4272d4 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.10 + 0.41.0-beta.11 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 79a594f14..51dd5a4c2 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.10" +version = "0.41.0-beta.11" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 403b1d2c2..1b1794d77 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index ef2d4ca40..12e4eda00 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 5b247be2c..e19f0efce 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 0c36b7213..09c39080d 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 274877c83..bed7c26c7 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 67f0176f5..c5a64dcb3 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 5f3cf6032..4cdaaeffd 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index df083600a..1128a5299 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.10", + "version": "0.41.0-beta.11", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 615b7c5aa..4c221ef11 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.10" +version = "0.41.0-beta.11" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 4649e560d..4ec9a70b1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.10" +version = "0.41.0-beta.11" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 22b15d4df00e25bf1226e3bf3b82bf701ca29b2b Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 21 Oct 2026 18:45:57 +0800 Subject: [PATCH 007/180] chore: update lance dependency to v14.0.0-beta.23 (#4616) Update the Rust workspace and Java lance-core from beta.22 to [Lance v14.0.0-beta.23](https://github.com/lance-format/lance/releases/tag/v14.0.0-beta.23), including the supplied-sample IVF training API from lance-format/lance#10188. Non-Lance lockfile entries match current main; no compatibility code changes are required. Validation on `f591f5d5`: full-workspace Clippy (`--tests --all-features -- -D warnings`), Rust formatting, and Java checkstyle passed locally. The beta.23 [POM](https://maven.lance.org/org/lance/lance-core/14.0.0-beta.23/lance-core-14.0.0-beta.23.pom) and [JAR](https://maven.lance.org/org/lance/lance-core/14.0.0-beta.23/lance-core-14.0.0-beta.23.jar) are now published and both return HTTP 200. The review reproducer (`cd java && ./mvnw -U -q test -pl lancedb-core -Dspotless.skip=true`) passes all 37 tests with zero failures or skips; JUnit classpaths confirm beta.23 was loaded. [Java CI attempt 2](https://github.com/lancedb/lancedb/actions/runs/39568468567/attempts/2) also passes, resolving the Java dependency publication finding. --- Cargo.lock | 92 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 ++++++++-------- java/pom.xml | 2 +- 3 files changed, 61 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cf0e79f3b..9fbde0847 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3584,8 +3584,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5059,8 +5059,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arc-swap", "arrow", @@ -5135,8 +5135,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-buffer", @@ -5158,7 +5158,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-buffer", @@ -5172,7 +5172,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-schema", @@ -5181,8 +5181,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrayref", "crunchy", @@ -5192,8 +5192,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-buffer", @@ -5230,8 +5230,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow", "arrow-array", @@ -5262,8 +5262,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow", "arrow-array", @@ -5280,8 +5280,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "proc-macro2", "quote", @@ -5290,8 +5290,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-arith", "arrow-array", @@ -5324,8 +5324,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-arith", "arrow-array", @@ -5357,8 +5357,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "datafusion", "geo-traits", @@ -5372,8 +5372,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arc-swap", "arrow", @@ -5444,8 +5444,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-schema", @@ -5468,8 +5468,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow", "arrow-array", @@ -5512,8 +5512,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "byteorder", "ethnum", @@ -5530,8 +5530,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-schema", @@ -5545,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow", "async-trait", @@ -5560,8 +5560,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arc-swap", "arrow", @@ -5615,8 +5615,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-buffer", @@ -5630,8 +5630,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow", "arrow-array", @@ -5671,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "arrow-array", "arrow-schema", @@ -5685,8 +5685,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "14.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.22#72c5b645600bde5d2e0e0b629ed986e2018c62bf" +version = "14.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 1307de8f9..49f7ea6a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.94.0" [workspace.dependencies] -lance = { "version" = "=14.0.0-beta.22", default-features = false, "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=14.0.0-beta.22", default-features = false, "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=14.0.0-beta.22", default-features = false, "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=14.0.0-beta.22", "tag" = "v14.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=14.0.0-beta.23", default-features = false, "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=14.0.0-beta.23", default-features = false, "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=14.0.0-beta.23", default-features = false, "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 12a4272d4..c3e3dd771 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 14.0.0-beta.22 + 14.0.0-beta.23 2.18.11 false 2.30.0 From 1480a9ff5768b8c5016db6e1e4c44bb617c343f1 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 21 Oct 2026 10:48:07 +0000 Subject: [PATCH 008/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.11=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.12?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 52cb1eb2f..f2c9e44e1 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.11" +current_version = "0.41.0-beta.12" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 9fbde0847..1d5d05bdf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5699,7 +5699,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.11" +version = "0.41.0-beta.12" dependencies = [ "ahash", "anyhow", @@ -5797,7 +5797,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.11" +version = "0.41.0-beta.12" dependencies = [ "arrow-array", "arrow-buffer", @@ -5822,7 +5822,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.11" +version = "0.41.0-beta.12" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index d6f3e7ef7..5c1874e6f 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.11 + 0.41.0-beta.12 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 6dd92bbac..ad5adbc92 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.11 + 0.41.0-beta.12 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index c3e3dd771..db0ee33d7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.11 + 0.41.0-beta.12 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 51dd5a4c2..85ee5df04 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.11" +version = "0.41.0-beta.12" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 1b1794d77..080340224 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 12e4eda00..a2b5b8bf6 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index e19f0efce..96bda03c7 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 09c39080d..edd596044 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index bed7c26c7..953c46250 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index c5a64dcb3..236d356be 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 4cdaaeffd..205f0ee11 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 1128a5299..023c4e400 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.11", + "version": "0.41.0-beta.12", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 4c221ef11..e6a0e457a 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.11" +version = "0.41.0-beta.12" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 4ec9a70b1..5e6dd315f 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.11" +version = "0.41.0-beta.12" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 0fbc0981ddd7577d3bc24dc6e0d31ddfe24b3455 Mon Sep 17 00:00:00 2001 From: Colin Patrick McCabe Date: Wed, 21 Oct 2026 14:26:47 -0700 Subject: [PATCH 009/180] feat: document all OAuthFlowType entries in authentication.mdx (#4565) Previously, authentication.mdx only documented a subset of the existing OAuthFlowType entries. We should document all of them. --- docs/web/enterprise/authentication.mdx | 312 ++++++++++++++++++++++--- 1 file changed, 282 insertions(+), 30 deletions(-) diff --git a/docs/web/enterprise/authentication.mdx b/docs/web/enterprise/authentication.mdx index 3a570d1d9..9074c641c 100644 --- a/docs/web/enterprise/authentication.mdx +++ b/docs/web/enterprise/authentication.mdx @@ -3,7 +3,7 @@ title: "Authentication" sidebarTitle: "Authentication" description: "Authentication modes for LanceDB Enterprise: API keys and OAuth credentials." icon: key -keywords: ["authentication", "oauth", "api key", "azure managed identity", "client credentials"] +keywords: ["authentication", "oauth", "api key", "authorization code", "device code", "azure managed identity", "client credentials"] availability: oss: unavailable enterprise: available @@ -13,9 +13,9 @@ availability: [Architecture](/architecture). --- -A deployment authenticates every request before -[authorization](/governance/authorization) decides what it may do, against a -`db://` remote table, in one of two ways: +A deployment authenticates each request over a `db://` connection before +[authorization](/governance/authorization) decides what it may do. +Choose one of these methods: - **API keys**: a long-lived shared secret passed as `api_key` on connect. Works in every SDK. - **OAuth 2.0**: short-lived bearer tokens obtained from your identity provider, refreshed automatically by the client. @@ -28,55 +28,91 @@ identities so no secret material lives on the client. Pass the API key from your Enterprise tenant on `connect`. This works with both the synchronous and asynchronous Python clients, as well as TypeScript -and Rust. +and Rust. Load the key from an environment variable or secret manager. -```python + +```python Python icon="python" +import os import lancedb db = lancedb.connect( uri="db://your-database-uri", - api_key="your-api-key", + api_key=os.environ["LANCEDB_API_KEY"], region="us-east-1", host_override="https://your-enterprise-endpoint.com", ) ``` -An API key belongs in the environment rather than in source. See -[Database](/management/database#deployment) for the connection options. +```typescript TypeScript icon="square-js" +import * as lancedb from "@lancedb/lancedb"; + +const apiKey = process.env.LANCEDB_API_KEY; +if (!apiKey) throw new Error("LANCEDB_API_KEY is required"); + +const db = await lancedb.connect("db://your-database-uri", { + apiKey, + region: "us-east-1", + hostOverride: "https://your-enterprise-endpoint.com", +}); +``` + +```rust Rust icon="rust" +let api_key = std::env::var("LANCEDB_API_KEY")?; + +let db = lancedb::connect("db://your-database-uri") + .api_key(&api_key) + .region("us-east-1") + .host_override("https://your-enterprise-endpoint.com") + .execute() + .await?; +``` + + +For Rust, enable the `remote` feature on the `lancedb` dependency to use +API key or OAuth authentication. + +See [Database](/management/database#deployment) for the connection options. ## OAuth {#oauth} -The async Python client and the TypeScript client can obtain bearer tokens +The async Python, TypeScript, and Rust clients can obtain bearer tokens from an OIDC issuer and attach them to every request. Token acquisition, caching, and refresh are handled inside the client. Your application code only provides the configuration. A deployment accepts these tokens only when its administrator has configured -it with your identity provider. Ask them for the issuer URL, client ID and -scopes to use. +it with your identity provider. Ask them for the issuer URL, client ID, scopes, +and any resource or audience required by the provider. For Authorization Code, +register the loopback redirect URI with the provider. For Device Code, enable +the provider's device authorization grant for your application. In Python, OAuth is supported through `lancedb.connect_async`. The synchronous `connect` entry point continues to use API key authentication for `db://` URIs. In TypeScript, `lancedb.connect` accepts `oauthConfig` directly. +In Rust, use `.oauth_config(config)` on the connection builder. ### Supported flows {#supported-flows} -`OAuthFlowType` selects how the client acquires tokens: +`OAuthFlowType` (Python and TypeScript) or `OAuthFlow` (Rust) selects how the +client acquires tokens: -| Flow | Python value | TypeScript value | When to use | -| --- | --- | --- | --- | -| Client Credentials | `OAuthFlowType.CLIENT_CREDENTIALS` | `OAuthFlowType.ClientCredentials` | Service-to-service / machine-to-machine. Requires a client ID and client secret registered with your identity provider. | -| Azure Managed Identity | `OAuthFlowType.AZURE_MANAGED_IDENTITY` | `OAuthFlowType.AzureManagedIdentity` | Workloads running on Azure compute (VMs, AKS, App Service, Container Apps). Tokens are fetched from the Azure IMDS endpoint, so no client secret is stored on the client. | +| Flow | Python value | TypeScript value | Rust value | When to use | +| --- | --- | --- | --- | --- | +| Client Credentials | `OAuthFlowType.CLIENT_CREDENTIALS` | `OAuthFlowType.ClientCredentials` | `OAuthFlow::ClientCredentials` | Service-to-service / machine-to-machine. Requires a client ID and client secret registered with your identity provider. | +| Authorization Code | `OAuthFlowType.AUTHORIZATION_CODE` | `OAuthFlowType.AuthorizationCode` | `OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new())` | Interactive user sign-in through a browser and local callback server. Uses S256 PKCE by default. | +| Device Code | `OAuthFlowType.DEVICE_CODE` | `OAuthFlowType.DeviceCode` | `OAuthFlow::DeviceCode` | CLI or headless sign-in. The client displays a verification URL and user code for the user to enter on another device. | +| Azure Managed Identity | `OAuthFlowType.AZURE_MANAGED_IDENTITY` | `OAuthFlowType.AzureManagedIdentity` | `OAuthFlow::AzureManagedIdentity { client_id: None }` | Azure workloads with access to the IMDS endpoint. Tokens are fetched from IMDS, so no client secret is stored on the client. | ### Configure OAuth {#configure-oauth} Build an OAuth config and pass it on connect. Use `oauth_config` in Python and -`oauthConfig` in TypeScript. +Rust, and `oauthConfig` in TypeScript. ```python Python icon="python" +import os import lancedb from lancedb.remote import OAuthConfig, OAuthFlowType @@ -84,7 +120,7 @@ from lancedb.remote import OAuthConfig, OAuthFlowType oauth_config = OAuthConfig( issuer_url="https://login.microsoftonline.com/{tenant}/v2.0", client_id="your-application-client-id", - client_secret="your-application-client-secret", + client_secret=os.environ["LANCEDB_OAUTH_CLIENT_SECRET"], scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.CLIENT_CREDENTIALS, ) @@ -101,11 +137,14 @@ db = await lancedb.connect_async( import * as lancedb from "@lancedb/lancedb"; import { OAuthConfig, OAuthFlowType } from "@lancedb/lancedb"; +const clientSecret = process.env.LANCEDB_OAUTH_CLIENT_SECRET; +if (!clientSecret) throw new Error("LANCEDB_OAUTH_CLIENT_SECRET is required"); + // Client Credentials (service-to-service) const oauthConfig: OAuthConfig = { issuerUrl: "https://login.microsoftonline.com/{tenant}/v2.0", clientId: "your-application-client-id", - clientSecret: "your-application-client-secret", + clientSecret, scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.ClientCredentials, }; @@ -116,9 +155,34 @@ const db = await lancedb.connect("db://your-database-uri", { oauthConfig, }); ``` + +```rust Rust icon="rust" +use lancedb::remote::{OAuthConfig, OAuthFlow}; + +// Client Credentials (service-to-service) +let oauth_config = OAuthConfig { + issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), + client_id: "your-application-client-id".into(), + client_secret: Some(std::env::var("LANCEDB_OAUTH_CLIENT_SECRET")?), + scopes: vec!["api://lancedb-api/.default".into()], + flow: OAuthFlow::ClientCredentials, + client_auth_method: None, + resource: None, + audience: None, + refresh_buffer_secs: None, + token_cache: None, +}; + +let db = lancedb::connect("db://your-database-uri") + .region("us-east-1") + .host_override("https://your-enterprise-endpoint.com") + .oauth_config(oauth_config) + .execute() + .await?; +``` -For workloads running on Azure compute, use a managed identity instead of a +For Azure workloads with access to IMDS, use a managed identity instead of a client secret: @@ -130,8 +194,8 @@ oauth_config = OAuthConfig( client_id="your-application-client-id", scopes=["api://lancedb-api/.default"], flow=OAuthFlowType.AZURE_MANAGED_IDENTITY, - # Optional: required only for user-assigned managed identities. - managed_identity_client_id="your-user-assigned-identity-client-id", + # Set only for a user-assigned managed identity: + # managed_identity_client_id="your-user-assigned-identity-client-id", ) ``` @@ -143,31 +207,219 @@ const oauthConfig: OAuthConfig = { clientId: "your-application-client-id", scopes: ["api://lancedb-api/.default"], flow: OAuthFlowType.AzureManagedIdentity, - // Optional: required only for user-assigned managed identities. - managedIdentityClientId: "your-user-assigned-identity-client-id", + // Set only for a user-assigned managed identity: + // managedIdentityClientId: "your-user-assigned-identity-client-id", +}; +``` + +```rust Rust icon="rust" +use lancedb::remote::{OAuthConfig, OAuthFlow}; + +let oauth_config = OAuthConfig { + issuer_url: "https://login.microsoftonline.com/{tenant}/v2.0".into(), + client_id: "your-application-client-id".into(), + client_secret: None, + scopes: vec!["api://lancedb-api/.default".into()], + flow: OAuthFlow::AzureManagedIdentity { + // Set to Some("your-user-assigned-identity-client-id".into()) + // only for a user-assigned managed identity. + client_id: None, + }, + client_auth_method: None, + resource: None, + audience: None, + refresh_buffer_secs: None, + token_cache: None, }; ``` +`managed_identity_client_id` / `managedIdentityClientId` selects a user-assigned +identity. Omit it for a system-assigned identity. The required `client_id` / +`clientId` field does not select the Azure managed identity. +In Rust, set the `client_id` inside `OAuthFlow::AzureManagedIdentity` to +`Some(...)` for a user-assigned identity, or `None` for a system-assigned +identity. The top-level `OAuthConfig::client_id` is the application client ID. + +For interactive sign-in, configure Authorization Code or Device Code. The +authorization URL or device verification instructions are written to standard +error. Authorization Code also tries to open a browser and listens for the +callback at `http://127.0.0.1:8400/callback` by default. Register that redirect +URI with your identity provider. Public clients can omit `client_secret`; +request a refresh token from your provider (often by including +`offline_access`) if you want to reuse the session. + + +```python Python icon="python" +import lancedb +from lancedb.remote import OAuthConfig, OAuthFlowType, TokenCacheOptions + +# Use DEVICE_CODE for a CLI without a local browser or callback server. +oauth_config = OAuthConfig( + issuer_url="https://your-issuer.example.com", + client_id="your-public-client-id", + scopes=["openid", "offline_access", "lancedb.read"], + flow=OAuthFlowType.AUTHORIZATION_CODE, + token_cache=TokenCacheOptions(), +) + +db = await lancedb.connect_async( + uri="db://your-database-uri", + region="us-east-1", + host_override="https://your-enterprise-endpoint.com", + oauth_config=oauth_config, +) +``` + +```typescript TypeScript icon="square-js" +import * as lancedb from "@lancedb/lancedb"; +import { OAuthFlowType, type OAuthConfig } from "@lancedb/lancedb"; + +// Use OAuthFlowType.DeviceCode for a CLI without a local browser or callback server. +const oauthConfig: OAuthConfig = { + issuerUrl: "https://your-issuer.example.com", + clientId: "your-public-client-id", + scopes: ["openid", "offline_access", "lancedb.read"], + flow: OAuthFlowType.AuthorizationCode, + tokenCache: {}, +}; + +const db = await lancedb.connect("db://your-database-uri", { + region: "us-east-1", + hostOverride: "https://your-enterprise-endpoint.com", + oauthConfig, +}); +``` + +```rust Rust icon="rust" +use lancedb::remote::{AuthorizationCodeOptions, OAuthConfig, OAuthFlow, TokenCacheOptions}; + +// Use OAuthFlow::DeviceCode for a CLI without a local browser or callback server. +let oauth_config = OAuthConfig { + issuer_url: "https://your-issuer.example.com".into(), + client_id: "your-public-client-id".into(), + client_secret: None, + scopes: vec![ + "openid".into(), + "offline_access".into(), + "lancedb.read".into(), + ], + flow: OAuthFlow::AuthorizationCode(AuthorizationCodeOptions::new()), + client_auth_method: None, + resource: None, + audience: None, + refresh_buffer_secs: None, + token_cache: Some(TokenCacheOptions::new()), +}; + +let db = lancedb::connect("db://your-database-uri") + .region("us-east-1") + .host_override("https://your-enterprise-endpoint.com") + .oauth_config(oauth_config.clone()) + .execute() + .await?; +``` + + +With `DEVICE_CODE` / `DeviceCode` / `OAuthFlow::DeviceCode`, the same +configuration and connection calls apply; only the `flow` value changes. + +### Reuse an interactive session {#reuse-an-interactive-session} + +By default, tokens stay in process memory. Set `token_cache` / `tokenCache` +for Authorization Code or Device Code to keep refresh tokens across process +restarts. Only refresh tokens are persisted; access tokens and client secrets +are not written to the cache. Set `cache_dir` / `cacheDir` to choose the +directory, or leave it unset to use the platform cache directory. Your +identity provider must issue a refresh token for a later process to sign in +without prompting again. + +Use `OAuthSession` with the same config to log in before connecting, inspect +whether a refresh token is cached, or remove the local cached credential: + + +```python Python icon="python" +from lancedb.remote import OAuthSession + +session = OAuthSession(oauth_config) +status = await session.login() +print(status.refreshable) +status = await session.status() # Does not contact the provider. +print(status.refreshable) +logout = await session.logout() +print(logout.removed) +``` + +```typescript TypeScript icon="square-js" +import { OAuthSession } from "@lancedb/lancedb"; + +const session = new OAuthSession(oauthConfig); +const status = await session.login(); +console.log(status.refreshable); +const current = await session.status(); // Does not contact the provider. +console.log(current.refreshable); +const logout = await session.logout(); +console.log(logout.removed); +``` + +```rust Rust icon="rust" +use lancedb::remote::OAuthSession; + +let session = OAuthSession::new(oauth_config)?; +let status = session.login().await?; +println!("{}", status.refreshable); +let status = session.status().await?; // Does not contact the provider. +println!("{}", status.refreshable); +let logout = session.logout().await?; +println!("{}", logout.removed); +``` + + +`login()` runs the interactive flow even when a session is cached. `logout()` +removes the local cache entry; it does not revoke the provider's token or end +a browser sign-in. `OAuthSession` requires a persistent cache and supports +only Authorization Code and Device Code. A cache is unused for Client +Credentials and rejected for Azure Managed Identity. + ### Configuration reference {#configuration-reference} -The same configuration is available in both SDKs. Python uses `snake_case` -field names; TypeScript uses `camelCase`. +The same configuration is available in all three SDKs. Python and Rust use +`snake_case` field names; TypeScript uses `camelCase`. In Rust, set optional +`OAuthConfig` fields to `Some(value)` or `None`. Configure `redirect_uri`, +`callback_port`, and `use_pkce` through the builder methods on +`AuthorizationCodeOptions`, and select a managed identity through +`OAuthFlow::AzureManagedIdentity { client_id: ... }`. | Python field / TypeScript field | Required | Description | | --- | --- | --- | | `issuer_url` / `issuerUrl` | Yes | OIDC issuer URL or OAuth authority URL. For Azure, use `https://login.microsoftonline.com/{tenant_id}/v2.0`. | | `client_id` / `clientId` | Yes | Application / client ID registered with your identity provider. | | `scopes` | Yes | List of OAuth scopes to request. For Azure managed identity, provide exactly one scope or resource, for example `["api://your-app-id/.default"]`. | -| `flow` | No | Selects the OAuth flow. Defaults to Client Credentials. | -| `client_secret` / `clientSecret` | Conditional | Required for Client Credentials. Redacted from the config's `repr` (Python) and `Debug` output (TypeScript native binding) so it does not leak into logs. | +| `flow` | Yes in Rust; otherwise no | Selects the OAuth flow. Defaults to Client Credentials in Python and TypeScript; Rust requires an explicit `OAuthFlow`. | +| `client_secret` / `clientSecret` | Conditional | Required for Client Credentials; only required for Authorization Code and Device Code when the provider registers a confidential client. Redacted from the config's `repr` (Python) and `Debug` output (Rust and TypeScript native binding). | +| `client_auth_method` / `clientAuthMethod` | No | Token endpoint authentication: `ClientAuthMethod.NONE` / `ClientAuthMethod.None` for a public client, `ClientAuthMethod.CLIENT_SECRET_BASIC` / `ClientAuthMethod.ClientSecretBasic`, or `ClientAuthMethod.CLIENT_SECRET_POST` / `ClientAuthMethod.ClientSecretPost`. Defaults to Basic when a client secret is set and no client authentication otherwise. The secret methods require `client_secret` / `clientSecret`. Omit for Azure Managed Identity. | +| `redirect_uri` / `redirectUri` | No | Authorization Code loopback callback URI. Defaults to `http://127.0.0.1:{callback_port}/callback`; register it with the provider. | +| `callback_port` / `callbackPort` | No | Authorization Code callback server port (default 8400). If `redirect_uri` / `redirectUri` has an explicit port, the two ports must match. | +| `use_pkce` / `usePkce` | No | Enable S256 PKCE for Authorization Code (default `true`). | | `managed_identity_client_id` / `managedIdentityClientId` | No | Client ID of a user-assigned managed identity. Only used with Azure Managed Identity; omit for system-assigned identities. | +| `resource` | No | RFC 8707 resource indicator, an absolute URI without a fragment. Sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | +| `audience` | No | Provider-specific audience sent to authorization and token endpoints, including refresh requests. Not supported for Azure Managed Identity. | | `refresh_buffer_secs` / `refreshBufferSecs` | No | How many seconds before token expiry to proactively refresh. Defaults to 300. Keep this well below the token TTL: setting it greater than or equal to the TTL forces a refresh on every request. | +| `token_cache` / `tokenCache` | No | Opt in to a persistent refresh-token cache for Authorization Code or Device Code. Use `TokenCacheOptions()` in Python, `{}` in TypeScript, or `Some(TokenCacheOptions::new())` in Rust. Defaults to an in-memory session. | + +`TokenCacheOptions` also accepts `cache_dir` / `cacheDir` to select a cache +directory and `lock_timeout_secs` / `lockTimeoutSecs` to set the wait for a +cross-process refresh lock (default 30 seconds). +In Rust, use the `TokenCacheOptions::cache_dir(...)` and +`TokenCacheOptions::lock_timeout_secs(...)` builder methods. Token endpoint +authentication uses `Some(ClientAuthMethod::None)`, +`Some(ClientAuthMethod::ClientSecretBasic)`, or +`Some(ClientAuthMethod::ClientSecretPost)`; `None` selects the default. Treat the client secret like any other production credential. Load it from a secret manager or environment variable rather than committing it to source -control. Both SDKs deliberately omit the secret from their debug/repr output +control. All three SDKs deliberately omit the secret from their debug/repr output so accidental log lines do not expose the value. From d97df0c82b3f7b6525bb7b108ddc154f7f16a2ca Mon Sep 17 00:00:00 2001 From: Esteban Gutierrez Date: Wed, 21 Oct 2026 17:11:36 -0500 Subject: [PATCH 010/180] fix: update trust-store pins for the eMudhra CA compromise (#4624) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cargo.lock: webpki-root-certs 1.0.10; webpki-roots 1.0.10 and rustls-webpki 0.103.16 are already current. docs/web-tests/rs/Cargo.lock: rustls-webpki 0.103.16. python/uv.lock: certifi 2026.10.19, the only entry that changes. The root crate drops the root CA whose intermediates were compromised (Mozilla bug 2083449), and rustls-webpki 0.103.16 rejects chains that carry the compromised eMudhra intermediate keys. certifi 2026.10.19 is the release the certifi advisory names as fixed: it drops the same root and keeps the issuer's other roots, so HTTPS connections that chain to them keep working. Relative to the previous 2026.6.17 pin it also adds Telia EC and RSA TLS Root CA v3 and SECOM TLS ECC and RSA Root CA 2024 and drops Atos TrustedRoot 2011. The webpki-root-certs entry is written by hand with the crates.io checksum. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Esteban Gutierrez Co-authored-by: Claude Opus 5.1 --- Cargo.lock | 4 ++-- docs/web-tests/rs/Cargo.lock | 4 ++-- python/uv.lock | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1d5d05bdf..3b4086203 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11144,9 +11144,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.7" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31141ce3fc3e300ae89b78c0dd67f9708061d1d2eda54b8209346fd6be9a92c" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock index 447bae7f6..6e288950e 100644 --- a/docs/web-tests/rs/Cargo.lock +++ b/docs/web-tests/rs/Cargo.lock @@ -5561,9 +5561,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", diff --git a/python/uv.lock b/python/uv.lock index ace8b98b9..e808f5f9e 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -443,11 +443,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.6.17" +version = "2026.10.19" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c9/c7/424b75da314c1045981bd9777432fad05a9e0c69daa4ed7e308bbaffe405/certifi-2026.6.17.tar.gz", hash = "sha256:024c88eeec92ca068db80f02b8b07c9cef7b9fe261d1d535abfd5abd6f6af432", size = 134594, upload-time = "2026-06-17T10:31:07.894Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ef/2f/c5464532e965badff2f4c4c1a3a83f5697f0d7c407ed0cda44aaa99bb451/certifi-2026.6.17-py3-none-any.whl", hash = "sha256:2227dcbaafe0d2f59279d1762ddddc37783ed4354594f194ffc31d20f41fc3db", size = 133289, upload-time = "2026-06-17T10:31:06.348Z" }, + { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, ] [[package]] From a4544c54722c4b29c88f0190bf58f1ddd7d50a66 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 21 Oct 2026 20:27:11 -0700 Subject: [PATCH 011/180] feat: configure automatic refresh when declaring computed columns (#4607) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `auto_refresh_enabled` and `auto_refresh_interval_seconds` to the Rust builder and Python sync/async add-column APIs for computed columns and registered Function outputs. Python users can configure refresh when declaring a column: ```python table.add_columns( computed={"total": "price * quantity"}, auto_refresh_enabled=True, auto_refresh_interval_seconds=300, ) ``` Omit the interval to let the server determine when to refresh: ```python table.add_columns(computed={"discounted_total": "total * 0.9"}) ``` The async API accepts the same options: ```python await async_table.add_columns( computed={"total": "price * quantity"}, auto_refresh_enabled=True, auto_refresh_interval_seconds=300, ) ``` For an existing registered `FunctionApplication`, the options also apply to Function columns. Disabling automatic refresh still permits explicit refresh: ```python table.add_columns( {"features": function_application}, auto_refresh_enabled=False, auto_refresh_interval_seconds=300, ) table.refresh_column("features") ``` Options apply to every output declared by a call. Automatic refresh is enabled by default; when the interval is omitted, the server determines when to refresh. An explicit interval sets a minimum delay after a successful refresh. The interval does not force recomputation of unchanged inputs. Invalid intervals and options on one-time transforms are rejected before declaration. Native declarations persist `computed_column.auto_refresh_enabled` and an explicitly supplied `computed_column.auto_refresh_interval_seconds` in each output field’s metadata in the same commit as the declaration. An omitted interval is neither stored nor sent in remote requests. Remote declarations forward the settings to Cloud/Enterprise servers. Local tables store these settings; automatic execution requires a supporting server with scheduling enabled. --- .../feature-engineering/refresh-column.mdx | 48 +++++++ docs/web/sql/ddl/table.mdx | 45 +++++- python/python/lancedb/_lancedb.pyi | 11 +- python/python/lancedb/remote/table.py | 11 +- python/python/lancedb/table.py | 73 +++++++++- .../tests/test_first_class_function_slice1.py | 23 +++- python/python/tests/test_table.py | 50 +++++++ python/src/table.rs | 29 +++- rust/lancedb/src/remote/table.rs | 86 ++++++++---- rust/lancedb/src/table.rs | 10 +- rust/lancedb/src/table/add_columns.rs | 128 +++++++++++++++++- rust/lancedb/src/table/computed_columns.rs | 100 ++++++++++++++ rust/lancedb/src/table/schema_evolution.rs | 6 + 13 files changed, 573 insertions(+), 47 deletions(-) diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index f4550ed24..ce36daa32 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -57,6 +57,54 @@ That is what makes the call idempotent and safe to retry. However, unlike a spreadsheet formula, nothing is recomputed until you refresh, so a derived column is stale between an update and the next refresh. +{/* +Draft for automatic computed-column refresh. Keep the released manual-refresh +instructions above until the server feature is available. + +## Automatic refresh {#automatic} + +Set scheduling options when declaring a computed column: + +```python +table.add_columns( + computed={"doubled": "x * 2"}, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=300, +) +``` + +Both options apply to every computed output declared in that call, including +registered Function outputs. Automatic refresh is enabled by default. When +the interval is omitted, the server determines when to refresh. Local tables +persist only an explicitly configured interval; automatic execution requires a +Cloud or Enterprise server with its separate `column_refresh.enabled` switch +turned on. That server switch is disabled in the base configuration. + +The interval is a positive minimum delay after the last successful refresh +of that output. A first refresh is immediately eligible. The scheduler still +checks input freshness and waits for computed ancestors to settle; the timer +does not make unchanged inputs require recomputation. Each Function output's +interval is independent, so refreshing a sibling does not postpone it. + +Pacing uses retained live Job Registry history. If completed jobs are archived +before a configured interval expires, the scheduler can lose the last-success +timestamp and refresh earlier. Leave archival disabled, or retain live history +for at least the longest configured column interval. Archival is disabled in +the base configuration; its default retention threshold is seven days. + +Change a stored setting through SQL: + +```sql +ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_enabled = false; +ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_interval_seconds = 600; +ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_enabled = true; +``` + +Disabling automatic refresh prevents new automatic jobs. Inflight jobs may +finish, and manual refresh remains available. Re-enabling wakes maintenance +to consider accumulated changes under the interval and dependency rules. +*/} + ## Refreshing part of a table {#partial} Enterprise In SQL a refresh can be scoped to a diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 792568220..11e7a3900 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -51,6 +51,43 @@ The column is committed empty and the expression is stored, not evaluated: declaring one on a billion-row table costs what declaring one on an empty table costs. [`REFRESH COLUMN`](/sql/dml/refresh) fills it. +{/* +Draft for automatic computed-column refresh. Enable this section when the +server feature is released. + +### Automatic refresh options {#automatic-refresh-options} + +```sql +ALTER TABLE t ADD COLUMN doubled AS value * 2 +WITH (auto_refresh_enabled = true, auto_refresh_interval_seconds = 300); + +ALTER TABLE t ALTER COLUMN doubled SET auto_refresh_enabled = false; +ALTER TABLE t ALTER COLUMN doubled SET auto_refresh_interval_seconds = 600; +ALTER TABLE t ALTER COLUMN doubled SET auto_refresh_enabled = true; +``` + +Automatic refresh is enabled by default. An explicitly configured interval is +stored in each computed output's field metadata; when omitted, the server +determines when to refresh. The interval must be a positive integer +and is minimum pacing after a successful refresh of that output; unchanged +inputs do not force work. A new column is immediately eligible for its first +refresh. The server's separate automatic-refresh switch must also be enabled. + +These options also work beside a Function binding's `version` and `branch`: + +```sql +ALTER TABLE t ADD COLUMN (label, score) AS classify(text) +WITH (version = 'fv_1', auto_refresh_enabled = true, + auto_refresh_interval_seconds = 300); +ALTER TABLE t ALTER COLUMN score SET auto_refresh_enabled = false; +``` + +Declaration settings initialize every output in the group; later SET commands +change one output. Disabling automatic refresh prevents new submissions while +allowing inflight jobs to finish and explicit REFRESH COLUMN to run. Column +SUSPEND/RESUME syntax is not supported. +*/} + {/* Draft for the Functions release. @@ -81,12 +118,14 @@ ALTER TABLE t ADD COLUMN (label, score) AS classify(text) WITH (version = 'fv_1' ```sql ALTER TABLE t ADD COLUMN c AS f(x) FILTER (WHERE keep) WITH (version = 'fv_1') -ALTER TABLE t ADD COLUMN c AS f(x) WITH (num_workers = '2') +REFRESH COLUMN c ON t WITH (num_workers = 2) ``` -`WITH` on a plain computed column accepts only `version`. Resource options such -as `num_workers` apply to function columns, where there are workers to size. +Declaration `WITH` accepts `auto_refresh_enabled` and +`auto_refresh_interval_seconds`. Function bindings also accept `version` and +`branch`. Worker resource options such as `num_workers` belong on +`REFRESH COLUMN ... WITH (...)`. */} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5a613b210..89c69e721 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -501,10 +501,17 @@ class Table: async def delete(self, filter: Union[str, PyExpr]) -> DeleteResult: ... async def add_columns(self, columns: list[tuple[str, str]]) -> AddColumnsResult: ... async def add_computed_columns( - self, columns: list[tuple[str, str]] + self, + columns: list[tuple[str, str]], + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[int] = None, ) -> AddColumnsResult: ... async def add_function_columns( - self, application_json: str, output_name: Optional[str] + self, + application_json: str, + output_name: Optional[str], + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[int] = None, ) -> AddColumnsResult: ... async def refresh_column(self, column: str) -> RefreshColumnResult: ... async def refresh_column_async(self, column: str) -> Job: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index eec958799..96b988911 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1001,8 +1001,17 @@ class RemoteTable(Table): | None = None, *, computed: Dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ) -> AddColumnsResult: - return LOOP.run(self._table.add_columns(transforms, computed=computed)) + return LOOP.run( + self._table.add_columns( + transforms, + computed=computed, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, + ) + ) def refresh_column(self, column: str): return LOOP.run(self._table.refresh_column(column)) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 60404b73c..d5872e6f0 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2561,6 +2561,8 @@ class Table(ABC): | None = None, *, computed: Dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ): """ Add new columns with defined values. @@ -2605,6 +2607,15 @@ class Table(ABC): [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Cannot be combined with ``transforms``. + auto_refresh_enabled: bool, optional + Enable automatic refresh for each declared computed output. Defaults + to True. Local tables store this option; scheduling requires a server. + auto_refresh_interval_seconds: int, optional + Positive minimum interval after a successful refresh, in seconds. + When omitted, the server determines when to refresh. Applies to every + computed output in this call. + Scheduling options require computed or Function columns. + Returns ------- AddColumnsResult @@ -4803,8 +4814,17 @@ class LanceTable(Table): | None = None, *, computed: Dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ) -> AddColumnsResult: - return LOOP.run(self._table.add_columns(transforms, computed=computed)) + return LOOP.run( + self._table.add_columns( + transforms, + computed=computed, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, + ) + ) def refresh_column(self, column: str) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose @@ -6852,6 +6872,8 @@ class AsyncTable: | None = None, *, computed: dict[str, str] | None = None, + auto_refresh_enabled: bool | None = None, + auto_refresh_interval_seconds: int | None = None, ) -> AddColumnsResult: """ Add new columns with defined values. @@ -6891,12 +6913,46 @@ class AsyncTable: On LanceDB Cloud and Enterprise the expression is planned by the server. Cannot be combined with ``transforms``. + auto_refresh_enabled: bool, optional + Enable automatic refresh for each computed output declared by this + call. Defaults to True. Local tables store the setting; automatic + scheduling requires Cloud or Enterprise. + auto_refresh_interval_seconds: int, optional + Positive minimum seconds after a successful refresh before another + automatic refresh is eligible. When omitted, the server determines when + to refresh. Unchanged inputs do + not force recomputation. Applies to every declared computed output. + These options cannot be used with one-time transforms or ordinary + all-null columns. + + Examples + -------- + >>> await table.add_columns( # doctest: +SKIP + ... computed={"total": "price * quantity"}, + ... auto_refresh_enabled=True, + ... auto_refresh_interval_seconds=300, + ... ) + Returns ------- AddColumnsResult version: the new version number of the table after adding columns. """ + if auto_refresh_enabled is not None and type(auto_refresh_enabled) is not bool: + raise ValueError("auto_refresh_enabled must be a boolean") + if auto_refresh_interval_seconds is not None and ( + type(auto_refresh_interval_seconds) is not int + or not 0 < auto_refresh_interval_seconds <= (2**64 - 1) // 1000 + ): + raise ValueError( + "auto_refresh_interval_seconds must be a positive integer " + "no greater than u64::MAX / 1000" + ) + options_supplied = ( + auto_refresh_enabled is not None + or auto_refresh_interval_seconds is not None + ) function_application = None function_output_name = None if isinstance(transforms, FunctionApplication): @@ -6920,7 +6976,10 @@ class AsyncTable: ) function_application._ensure_declarable() return await self._inner.add_function_columns( - function_application.to_canonical_json(), function_output_name + function_application.to_canonical_json(), + function_output_name, + auto_refresh_enabled, + auto_refresh_interval_seconds, ) if isinstance(transforms, pa.Field): @@ -6934,7 +6993,15 @@ class AsyncTable: raise ValueError( "add_columns cannot take both transforms and computed columns" ) - return await self._inner.add_computed_columns(list(computed.items())) + return await self._inner.add_computed_columns( + list(computed.items()), + auto_refresh_enabled, + auto_refresh_interval_seconds, + ) + if options_supplied: + raise ValueError( + "automatic refresh options require computed or Function columns" + ) if transforms is None: raise ValueError("add_columns requires transforms or computed columns") if isinstance(transforms, pa.Schema): diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index b08dadf36..06730a5f1 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -398,8 +398,21 @@ class _FunctionDeclarationInner: def __init__(self): self.calls = [] - async def add_function_columns(self, application_json, output_name): - self.calls.append((json.loads(application_json), output_name)) + async def add_function_columns( + self, + application_json, + output_name, + auto_refresh_enabled, + auto_refresh_interval_seconds, + ): + self.calls.append( + ( + json.loads(application_json), + output_name, + auto_refresh_enabled, + auto_refresh_interval_seconds, + ) + ) return "declared" @@ -420,14 +433,18 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica ) assert result == "declared" assert inner.calls[-1][1] == "features" + assert inner.calls[-1][2:] == (None, None) bare = application._copy(update={"columns": {}}).rename( columns={"normalized_text": "search_text"} ) - result = await table.add_columns(bare) + result = await table.add_columns( + bare, auto_refresh_enabled=False, auto_refresh_interval_seconds=300 + ) assert result == "declared" assert inner.calls[-1][1] is None assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"} + assert inner.calls[-1][2:] == (False, 300) @pytest.mark.asyncio diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 7ec2003b7..755e94d7f 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4869,3 +4869,53 @@ async def test_refresh_column_async_job_async_table(tmp_path): assert result.published_version == 4 assert await job.status() == "finished" assert (await table.to_arrow())["tripled"].to_pylist() == [9] + + +@pytest.mark.parametrize("interval", [None, 300]) +def test_computed_auto_refresh_options(tmp_path, interval): + db = lancedb.connect(tmp_path) + table = db.create_table("refresh_options", [{"x": 1}]) + before = table.version + table.add_columns( + computed={"doubled": "x * 2", "tripled": "x * 3"}, + auto_refresh_enabled=False, + auto_refresh_interval_seconds=interval, + ) + assert table.version == before + 1 + for column in ("doubled", "tripled"): + metadata = table.schema.field(column).metadata + assert metadata[b"computed_column.auto_refresh_enabled"] == b"false" + if interval is None: + assert b"computed_column.auto_refresh_interval_seconds" not in metadata + else: + assert metadata[b"computed_column.auto_refresh_interval_seconds"] == b"300" + table.refresh_column("doubled") + assert table.to_arrow()["doubled"].to_pylist() == [2] + + +@pytest.mark.parametrize("value", [0, -1, True, 1.5, "300", 2**64]) +def test_computed_auto_refresh_rejects_invalid_interval(tmp_path, value): + table = lancedb.connect(tmp_path).create_table("invalid_options", [{"x": 1}]) + with pytest.raises(ValueError, match="auto_refresh_interval_seconds"): + table.add_columns( + computed={"doubled": "x * 2"}, auto_refresh_interval_seconds=value + ) + assert table.schema.names == ["x"] + + +def test_auto_refresh_options_require_computed_columns(tmp_path): + table = lancedb.connect(tmp_path).create_table("invalid_kind", [{"x": 1}]) + with pytest.raises(ValueError, match="require computed"): + table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True) + + +@pytest.mark.asyncio +async def test_async_computed_auto_refresh_uses_server_interval(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("server_interval", [{"x": 1}]) + before = await table.version() + await table.add_columns(computed={"doubled": "x * 2"}) + assert await table.version() == before + 1 + metadata = (await table.schema()).field("doubled").metadata + assert metadata[b"computed_column.auto_refresh_enabled"] == b"true" + assert b"computed_column.auto_refresh_interval_seconds" not in metadata diff --git a/python/src/table.rs b/python/src/table.rs index 6cea168ec..c1d23d151 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use lancedb::table::computed_columns::ComputedColumnOptions; use std::{ collections::HashMap, sync::{ @@ -1803,35 +1804,59 @@ impl Table { }) } + #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn add_computed_columns( self_: PyRef<'_, Self>, columns: Vec<(String, String)>, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); + let options = ComputedColumnOptions { + auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), + auto_refresh_interval_seconds, + }; + options.validate().infer_error()?; future_into_py(self_.py(), async move { let mut builder = inner.add_columns(); for (name, expression) in columns { builder = builder.computed(name, expression); } - let result = builder.execute().await.infer_error()?; + let result = builder + .computed_options(options) + .execute() + .await + .infer_error()?; Ok(AddColumnsResult::from(result)) }) } + #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn add_function_columns( self_: PyRef<'_, Self>, application_json: String, output_name: Option, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let application = lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?; let inner = self_.inner_ref()?.clone(); + let options = ComputedColumnOptions { + auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), + auto_refresh_interval_seconds, + }; + options.validate().infer_error()?; future_into_py(self_.py(), async move { let builder = match output_name { Some(name) => inner.add_columns().function_as(name, application), None => inner.add_columns().function(application), }; - let result = builder.execute().await.infer_error()?; + let result = builder + .computed_options(options) + .execute() + .await + .infer_error()?; Ok(AddColumnsResult::from(result)) }) } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3325f6943..1c569f6e5 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3497,7 +3497,11 @@ impl BaseTable for RemoteTable { Ok(result) } - async fn add_computed_columns(&self, columns: &[(String, String)]) -> Result { + async fn add_computed_columns( + &self, + columns: &[(String, String)], + options: crate::table::computed_columns::ComputedColumnOptions, + ) -> Result { self.check_mutable().await?; crate::table::computed_columns::ensure_not_function_bound( self.schema().await?.as_ref(), @@ -3516,7 +3520,10 @@ impl BaseTable for RemoteTable { }, ) .collect::>(); - let mut body = serde_json::json!({ "new_columns": entries }); + let mut body = serde_json::json!({ "new_columns": entries, "auto_refresh_enabled": options.auto_refresh_enabled }); + if let Some(interval) = options.auto_refresh_interval_seconds { + body["auto_refresh_interval_seconds"] = serde_json::json!(interval); + } self.apply_branch_body(&mut body); let request = self .client @@ -3550,6 +3557,7 @@ impl BaseTable for RemoteTable { &self, application: &crate::function::FunctionApplication, output_name: Option<&str>, + options: crate::table::computed_columns::ComputedColumnOptions, ) -> Result { self.check_mutable().await?; let schema = self.schema().await?; @@ -3570,6 +3578,7 @@ impl BaseTable for RemoteTable { .collect::>(); let mut body = serde_json::json!({ "new_columns": new_columns, + "auto_refresh_enabled": options.auto_refresh_enabled, "function": { "application": plan.application, "binding_metadata_version": plan.binding_metadata_version, @@ -3579,6 +3588,9 @@ impl BaseTable for RemoteTable { "outputs": plan.outputs, }, }); + if let Some(interval) = options.auto_refresh_interval_seconds { + body["auto_refresh_interval_seconds"] = serde_json::json!(interval); + } self.apply_branch_body(&mut body); let request = self .client @@ -9263,31 +9275,44 @@ mod tests { /// client never types the expression itself. #[tokio::test] async fn test_add_computed_columns_sends_the_expression() { - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => simple_describe_response(), - "/v1/table/my_table/add_columns/" => { - assert_eq!(request.method(), "POST"); - let body = request.body().unwrap().as_bytes().unwrap(); - let value: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!( - value["new_columns"], - serde_json::json!([{"name": "doubled", "computed": "x * 2"}]) - ); - http::Response::builder() - .status(200) - .body(r#"{"version": 7}"#.to_string()) - .unwrap() - } - path => panic!("Unexpected path: {path}"), - }); + for interval in [None, Some(300)] { + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/add_columns/" => { + assert_eq!(request.method(), "POST"); + let body = request.body().unwrap().as_bytes().unwrap(); + let value: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!( + value["new_columns"], + serde_json::json!([{"name": "doubled", "computed": "x * 2"}]) + ); + assert_eq!(value["auto_refresh_enabled"], false); + if let Some(interval) = interval { + assert_eq!(value["auto_refresh_interval_seconds"], interval); + } else { + assert!(value.get("auto_refresh_interval_seconds").is_none()); + } + http::Response::builder() + .status(200) + .body(r#"{"version": 7}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + }); - let result = table - .add_columns() - .computed("doubled", "x * 2") - .execute() - .await - .unwrap(); - assert_eq!(result.version, 7); + let result = table + .add_columns() + .computed("doubled", "x * 2") + .computed_options(crate::table::computed_columns::ComputedColumnOptions { + auto_refresh_enabled: false, + auto_refresh_interval_seconds: interval, + }) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 7); + } } #[tokio::test] @@ -9305,10 +9330,11 @@ mod tests { request.body().unwrap().as_bytes().unwrap(), ) .unwrap(); - let expected: serde_json::Value = serde_json::from_str(include_str!( + let mut expected: serde_json::Value = serde_json::from_str(include_str!( "../../tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json" )) .unwrap(); + expected["auto_refresh_enabled"] = serde_json::json!(true); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -9504,10 +9530,11 @@ mod tests { request.body().unwrap().as_bytes().unwrap(), ) .unwrap(); - let expected: serde_json::Value = serde_json::from_str(include_str!( + let mut expected: serde_json::Value = serde_json::from_str(include_str!( "../../tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json" )) .unwrap(); + expected["auto_refresh_enabled"] = serde_json::json!(true); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -9550,10 +9577,11 @@ mod tests { "/v1/table/my_table/add_columns/" => { let actual: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - let expected: serde_json::Value = serde_json::from_str(include_str!( + let mut expected: serde_json::Value = serde_json::from_str(include_str!( "../../tests/fixtures/first_class_functions/v1/remote_multi_output_declaration_request.json" )) .unwrap(); + expected["auto_refresh_enabled"] = serde_json::json!(true); assert_eq!(actual, expected); http::Response::builder() .status(200) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index d99926ae1..61a710dcd 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -814,6 +814,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn add_computed_columns( &self, _columns: &[(String, String)], + _options: computed_columns::ComputedColumnOptions, ) -> Result { Err(Error::NotSupported { message: "computed columns are not supported on this table type".into(), @@ -824,6 +825,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { &self, _application: &crate::function::FunctionApplication, _output_name: Option<&str>, + _options: computed_columns::ComputedColumnOptions, ) -> Result { Err(Error::NotSupported { message: "Function columns are supported only on LanceDB Cloud and Enterprise".into(), @@ -3768,8 +3770,12 @@ impl BaseTable for NativeTable { Ok(result) } - async fn add_computed_columns(&self, columns: &[(String, String)]) -> Result { - let result = schema_evolution::execute_declare(self, columns).await?; + async fn add_computed_columns( + &self, + columns: &[(String, String)], + options: computed_columns::ComputedColumnOptions, + ) -> Result { + let result = schema_evolution::execute_declare(self, columns, options).await?; self.bump_freshness(); Ok(result) } diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 635a99bea..4f9cbb772 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use lance::dataset::NewColumnTransform; use super::BaseTable; +use super::computed_columns::ComputedColumnOptions; use super::schema_evolution::AddColumnsResult; use crate::function::FunctionApplication; use crate::{Error, Result}; @@ -19,6 +20,7 @@ pub struct AddColumnsBuilder { computed: Vec<(String, String)>, function: Option<(FunctionApplication, Option)>, read_columns: Option>, + options: Option, } impl std::fmt::Debug for AddColumnsBuilder { @@ -41,6 +43,7 @@ impl AddColumnsBuilder { computed: Vec::new(), function: None, read_columns: None, + options: None, } } @@ -139,6 +142,26 @@ impl AddColumnsBuilder { self } + /// Configure automatic refresh for every output declared in this call. + /// Settings are stored with the declaration. They require computed or + /// Function columns; local tables persist them without starting a scheduler. + /// + /// ``` + /// # use lancedb::{Table, table::computed_columns::ComputedColumnOptions}; + /// # async fn declare(table: &Table) -> lancedb::Result<()> { + /// table.add_columns().computed("doubled", "x * 2") + /// .computed_options(ComputedColumnOptions { + /// auto_refresh_enabled: true, + /// auto_refresh_interval_seconds: Some(300), + /// }).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn computed_options(mut self, options: ComputedColumnOptions) -> Self { + self.options = Some(options); + self + } + /// Add the columns. pub async fn execute(self) -> Result { let Self { @@ -147,7 +170,18 @@ impl AddColumnsBuilder { computed, function, read_columns, + options, } = self; + if let Some(options) = options { + options.validate()?; + if computed.is_empty() && function.is_none() { + return Err(Error::InvalidInput { + message: "automatic refresh options require computed or Function columns" + .into(), + }); + } + } + let options = options.unwrap_or_default(); let declaration_count = usize::from(!computed.is_empty()) + usize::from(function.is_some()); if transform.is_some() && declaration_count != 0 || declaration_count > 1 { @@ -179,7 +213,7 @@ impl AddColumnsBuilder { .into(), }); } - parent.add_computed_columns(&computed).await + parent.add_computed_columns(&computed, options).await } (None, true, Some((application, output_name))) => { if read_columns.is_some() { @@ -189,7 +223,7 @@ impl AddColumnsBuilder { }); } parent - .add_function_columns(&application, output_name.as_deref()) + .add_function_columns(&application, output_name.as_deref(), options) .await } _ => unreachable!("mixed add_columns modes were rejected above"), @@ -201,6 +235,9 @@ impl AddColumnsBuilder { mod tests { use std::sync::Arc; + use super::ComputedColumnOptions; + use crate::table::computed_columns::AUTO_REFRESH_INTERVAL_META_KEY; + use arrow_array::{Int32Array, RecordBatch, record_batch}; use arrow_schema::{DataType, Field, Schema}; use lance::dataset::{BatchUDF, NewColumnTransform}; @@ -214,6 +251,93 @@ mod tests { conn.create_table(name, batch).execute().await.unwrap() } + #[tokio::test] + async fn computed_options_commit_with_declaration() { + let table = table_with_two_columns("options").await; + let version = table.version().await.unwrap(); + let options = ComputedColumnOptions { + auto_refresh_enabled: false, + auto_refresh_interval_seconds: Some(300), + }; + let result = table + .add_columns() + .computed("doubled", "x * 2") + .computed_options(options) + .execute() + .await + .unwrap(); + assert_eq!(result.version, version + 1); + let schema = table.schema().await.unwrap(); + assert_eq!( + ComputedColumnOptions::from_metadata( + schema.field_with_name("doubled").unwrap().metadata() + ) + .unwrap(), + options + ); + for interval in [0, u64::MAX] { + let invalid = ComputedColumnOptions { + auto_refresh_interval_seconds: Some(interval), + ..options + }; + assert!( + table + .add_columns() + .computed("bad", "x") + .computed_options(invalid) + .execute() + .await + .is_err() + ); + } + assert!( + table + .add_columns() + .transform(NewColumnTransform::SqlExpressions(vec![( + "once".into(), + "x".into() + )])) + .computed_options(options) + .execute() + .await + .is_err() + ); + assert!( + table + .schema() + .await + .unwrap() + .field_with_name("bad") + .is_err() + ); + } + + #[tokio::test] + async fn omitted_refresh_interval_stays_unset() { + let table = table_with_two_columns("server_interval").await; + let version = table.version().await.unwrap(); + let result = table + .add_columns() + .computed("doubled", "x * 2") + .execute() + .await + .unwrap(); + assert_eq!(result.version, version + 1); + let schema = table.schema().await.unwrap(); + let metadata = schema.field_with_name("doubled").unwrap().metadata(); + assert!(!metadata.contains_key(AUTO_REFRESH_INTERVAL_META_KEY)); + assert_eq!( + ComputedColumnOptions::from_metadata(metadata).unwrap(), + ComputedColumnOptions::default() + ); + assert!( + serde_json::to_value(ComputedColumnOptions::default()) + .unwrap() + .get("auto_refresh_interval_seconds") + .is_none() + ); + } + #[tokio::test] async fn test_requires_a_transform() { let table = table_with_two_columns("no_transform").await; diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 9a3922b2b..e86b350ee 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -55,6 +55,106 @@ pub const EXPRESSION_META_KEY: &str = "computed_column.expression"; /// Field metadata key holding the column's inputs, as a JSON array of names. pub const INPUTS_META_KEY: &str = "computed_column.inputs"; +/// Whether the server may automatically refresh this output. +pub const AUTO_REFRESH_ENABLED_META_KEY: &str = "computed_column.auto_refresh_enabled"; +/// Minimum interval between successful automatic refreshes, in seconds. +pub const AUTO_REFRESH_INTERVAL_META_KEY: &str = "computed_column.auto_refresh_interval_seconds"; + +/// Scheduling settings persisted on each computed output. Local tables store +/// these settings; automatic scheduling requires a Cloud or Enterprise server. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ComputedColumnOptions { + /// Permit automatic refresh. Manual refresh is always available. + pub auto_refresh_enabled: bool, + /// Minimum seconds after a successful refresh before another is eligible. + /// When omitted, the server determines when to refresh. + #[serde(skip_serializing_if = "Option::is_none")] + pub auto_refresh_interval_seconds: Option, +} + +impl Default for ComputedColumnOptions { + fn default() -> Self { + Self { + auto_refresh_enabled: true, + auto_refresh_interval_seconds: None, + } + } +} + +impl ComputedColumnOptions { + /// Reject intervals that cannot be represented by the server scheduler. + pub fn validate(&self) -> Result<()> { + if self + .auto_refresh_interval_seconds + .is_some_and(|interval| interval == 0 || interval.checked_mul(1000).is_none()) + { + return Err(Error::InvalidInput { + message: "auto_refresh_interval_seconds must be a positive integer no greater than u64::MAX / 1000".into(), + }); + } + Ok(()) + } + + /// Read scheduling settings, using defaults for omitted properties. + pub fn from_metadata(metadata: &HashMap) -> Result { + let mut options = Self::default(); + if let Some(value) = metadata.get(AUTO_REFRESH_ENABLED_META_KEY) { + options.auto_refresh_enabled = value.parse().map_err(|_| Error::InvalidInput { + message: "auto_refresh_enabled must be true or false".into(), + })?; + } + if let Some(value) = metadata.get(AUTO_REFRESH_INTERVAL_META_KEY) { + options.auto_refresh_interval_seconds = + Some(value.parse().map_err(|_| Error::InvalidInput { + message: "auto_refresh_interval_seconds must be a positive integer".into(), + })?); + } + options.validate()?; + Ok(options) + } + + /// Attach validated settings to newly declared computed output fields. + pub fn apply_to_schema(&self, schema: &ArrowSchema) -> Result { + self.validate()?; + let fields = schema + .fields() + .iter() + .map(|field| { + if computed_column_from_field(field).is_none() + || field + .metadata() + .get(FUNCTION_OUTPUT_ORDINAL_META_KEY) + .is_some_and(|ordinal| { + ordinal == &FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL.to_string() + }) + { + return field.clone(); + } + let mut metadata = field.metadata().clone(); + metadata.extend(self.metadata()); + Arc::new(field.as_ref().clone().with_metadata(metadata)) + }) + .collect::>(); + Ok(ArrowSchema::new_with_metadata( + fields, + schema.metadata().clone(), + )) + } + + /// Field metadata values shared by native and server declaration paths. + pub fn metadata(&self) -> HashMap { + let mut metadata = HashMap::from([( + AUTO_REFRESH_ENABLED_META_KEY.into(), + self.auto_refresh_enabled.to_string(), + )]); + if let Some(interval) = self.auto_refresh_interval_seconds { + metadata.insert(AUTO_REFRESH_INTERVAL_META_KEY.into(), interval.to_string()); + } + metadata + } +} + /// Field metadata key holding the Function binding identity. pub const FUNCTION_BINDING_ID_META_KEY: &str = "computed_column.function.binding_id"; diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index c541a9a43..1ad532d0a 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -13,6 +13,7 @@ use lance::dataset::transaction::{Operation, Transaction, UpdateMap, UpdateMapEn use lance::dataset::{ColumnAlteration, CommitBuilder, Dataset, NewColumnTransform}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::sync::Arc; use super::computed_columns; use super::{BaseTable, NativeTable}; @@ -128,6 +129,7 @@ pub(crate) async fn execute_add_columns( pub(crate) async fn execute_declare( table: &NativeTable, columns: &[(String, String)], + options: computed_columns::ComputedColumnOptions, ) -> Result { use lance::dataset::mem_wal::DatasetMemWalExt; @@ -157,6 +159,10 @@ pub(crate) async fn execute_declare( }); } let transform = computed_columns::declare(table.schema().await?, columns)?; + let NewColumnTransform::AllNulls(schema) = transform else { + unreachable!("declarations are all-null") + }; + let transform = NewColumnTransform::AllNulls(Arc::new(options.apply_to_schema(&schema)?)); commit_add_columns(table, transform, None).await } From 1564ec10c8534a828aa38b2fb05c36b464844945 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 21 Oct 2026 23:18:30 -0700 Subject: [PATCH 012/180] feat: add Bootstrap split strategy for sampling with replacement (#4597) ## Context `StreamingDataset`'s shipped split strategies (`split_random`, `split_sequential`, `split_hash`, `split_calculated`) all share one trait: every row in the base table is assigned to exactly one split, exactly once. They only differ in *how* that one-to-one assignment is chosen -- none of them can express "give me a resampled stream of N rows, allowing repeats." That's a distinct, common need in ML training: **the bootstrap** -- the statistical technique (Efron, 1979) of estimating a dataset's properties by resampling it *with replacement*. It's the same sense scikit-learn's bagging classifiers mean by `bootstrap=True`. `SplitStrategy::Bootstrap` adds exactly this to the data loader: sample rows uniformly with replacement from the (optionally filtered) base table, independently per split. ## Main use cases - **Bagging / ensemble training** (e.g. random forests): each split trains on an independent bootstrap resample of the training set. - **Oversampling a rare class**: filter to the minority class, then sample it up to whatever count balances it against the majority, instead of exhausting its small set once per epoch. - **Fixed-size training steps independent of dataset size**: want exactly N batches per epoch regardless of whether the table has 50 rows or 50 million? Set `num_samples` directly instead of it being implicitly `len(dataset)`. - **Weighted sampling without a weight column**: filter to "eligible" rows (e.g. a windowed-sampling workload filtering to valid window-start positions), then bootstrap the filtered set -- an item with more eligible rows is naturally drawn proportionally more often, with no explicit per-row weight needed. ## Example (an actual run, not a hypothetical one) A 5-row base table (`row_id` 0..4), sampled via `Bootstrap { num_samples: 8, sizes: Fixed(2), seed: Some(42) }`: ``` row_id split_id 0 0 2 0 4 0 4 0 <- row 4 repeated within split 0 4 1 <- row 4 also drawn in split 1 (independent draw) 4 1 1 1 2 1 ``` 8 output rows from a 5-row table -- not 5. Row 4 drawn 4 times total, row 3 never drawn. That's with-replacement sampling actually behaving like with-replacement sampling, not an even round-robin dressed up with a new name. ## What changed Adds `SplitStrategy::Bootstrap` (uniform sampling with replacement, optionally filtered, independently seeded per split -- a given split's content doesn't depend on how many other splits there are, the same elastic-determinism property documented for the loader's other strategies). No new `PermutationBuilder` Rust method was needed: `with_split_strategy` already accepts any `SplitStrategy` value generically. Python binding: `PermutationBuilder.bootstrap_sample(num_samples, *, ratios=None, counts=None, fixed=None, seed=None, split_names=None)`, mirroring `split_random`'s existing shape. Also adds a generic `split_strategy` parameter to `StreamingDataset`'s constructor (a callable taking/returning a `PermutationBuilder`), since it previously could only reach `split_random`/`split_sequential` even though `split_hash`/`split_calculated` already shipped. This unblocks `Bootstrap` and any future strategy without further constructor changes. --- python/python/lancedb/_lancedb.pyi | 9 + python/python/lancedb/permutation.py | 44 +++ python/python/lancedb/streaming.py | 150 ++++++- .../python/tests/test_elastic_dataloader.py | 227 +++++++++++ python/python/tests/test_permutation.py | 70 ++++ python/src/permutation.rs | 44 +++ .../src/dataloader/permutation/builder.rs | 6 +- .../src/dataloader/permutation/split.rs | 365 +++++++++++++++++- 8 files changed, 909 insertions(+), 6 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 89c69e721..96bc7752b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -947,6 +947,15 @@ class AsyncPermutationBuilder: counts: Optional[List[int]] = None, fixed: Optional[int] = None, ) -> "AsyncPermutationBuilder": ... + def bootstrap_sample( + self, + num_samples: int, + *, + ratios: Optional[List[float]] = None, + counts: Optional[List[int]] = None, + fixed: Optional[int] = None, + seed: Optional[int] = None, + ) -> "AsyncPermutationBuilder": ... def split_calculated(self, calculation: str) -> "AsyncPermutationBuilder": ... def shuffle( self, seed: Optional[int], clump_size: Optional[int] diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 103ec0aa4..355ebf798 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -169,6 +169,50 @@ class PermutationBuilder: ) return self + def bootstrap_sample( + self, + num_samples: int, + *, + ratios: Optional[list[float]] = None, + counts: Optional[list[int]] = None, + fixed: Optional[int] = None, + seed: Optional[int] = None, + split_names: Optional[list[str]] = None, + ) -> "PermutationBuilder": + """ + Sample rows uniformly **with replacement**, independently per split. + + Unlike the other split strategies, the number of output rows is + ``num_samples``, not the number of (optionally filtered) input rows: the + same row can appear zero, one, or many times, and ``num_samples`` may be + larger or smaller than the input row count. Useful for bootstrap + resampling, oversampling rare classes, or any training workload that + wants a fixed-size stream of random draws rather than a single + deterministic pass over every row. Combine with :meth:`filter` to + restrict the eligible population. + + One of ratios, counts, or fixed must be provided, with the same meaning + as in :meth:`split_random`, except they divide ``num_samples`` across + splits rather than the input row count: if fixed is 4, each split gets + ``num_samples // 4`` samples. + + Each split draws its own sample using a seed derived independently from + ``(seed, split_index)``, so a split's content does not change if the samples are + later redistributed across a different number of splits. + + The optional split_names can be provided to name the splits. If not provided, + the splits can only be referenced by their index. + """ + self._async.bootstrap_sample( + num_samples, + ratios=ratios, + counts=counts, + fixed=fixed, + seed=seed, + split_names=split_names, + ) + return self + def split_calculated( self, calculation: str, split_names: Optional[list[str]] = None ) -> "PermutationBuilder": diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 91ca6ce28..4a4ffd1f5 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -19,6 +19,7 @@ above. """ import ctypes +import hashlib import heapq import logging import os @@ -39,6 +40,7 @@ from torch.utils.data import DataLoader, IterableDataset, get_worker_info from .permutation import ( Permutation, + PermutationBuilder, Transforms, permutation_builder, _drop_base_version, @@ -244,6 +246,20 @@ class StreamingDataset(IterableDataset): default) rows are shuffled using ``shuffle_seed`` and ``epoch``. When ``False`` rows are divided into splits sequentially in storage order, which can be useful for deterministic debugging or evaluation. + Ignored when ``split_strategy`` is provided. + split_strategy: + Escape hatch for any ``PermutationBuilder`` split strategy this class + doesn't otherwise expose a dedicated parameter for -- ``split_hash``, + ``split_calculated``, ``bootstrap_sample`` (uniform sampling with + replacement), or any strategy added later. A callable that receives a + fresh ``PermutationBuilder`` for ``table`` and returns a configured one; + it is called and ``.execute()``'d directly, taking over permutation + construction entirely. When provided, ``shuffle``, ``shuffle_seed``, + ``epoch``, and ``shuffle_clump_size`` are ignored -- the callable is + solely responsible for how rows are split and ordered. For example, + ``split_strategy=lambda b: b.bootstrap_sample(10_000, fixed=num_splits, + seed=42)`` draws 10,000 samples with replacement, divided evenly across + ``num_splits`` splits. shuffle_seed: Base seed for the random permutation. Combined with ``epoch`` so each epoch produces a different ordering. Pass ``None`` to generate @@ -393,6 +409,9 @@ class StreamingDataset(IterableDataset): *, num_splits: Optional[int] = None, shuffle: bool = True, + split_strategy: Optional[ + Callable[[PermutationBuilder], PermutationBuilder] + ] = None, shuffle_seed: Optional[int] = 0, epoch: int = 0, rank: int = 0, @@ -583,13 +602,70 @@ class StreamingDataset(IterableDataset): builder = permutation_builder(table) if filter is not None: builder = builder.filter(filter) - if shuffle: + if split_strategy is not None: + # Escape hatch: lets any PermutationBuilder split strategy drive this + # dataset (split_hash, split_calculated, bootstrap_sample, or any future + # strategy) without StreamingDataset needing a bespoke parameter for each + # one. shuffle/shuffle_seed/epoch/shuffle_clump_size are ignored in this + # path -- the caller's split_strategy is solely responsible for ordering. + self._perm_table = split_strategy(builder).execute() + # _rank_splits below assumes split ids are exactly 0..num_splits-1 with no + # gaps (every other path guarantees this by always building with + # fixed=num_splits) -- a split_strategy callable has no such guarantee, and + # a mismatch would otherwise silently drop rows (ids >= num_splits) or leave + # some ranks reading an empty split (missing ids < num_splits). + split_value_counts = ( + self._perm_table.to_arrow().column("split_id").value_counts() + ) + counts_by_split = dict( + zip( + split_value_counts.field("values").to_pylist(), + split_value_counts.field("counts").to_pylist(), + ) + ) + expected_splits = set(range(num_splits)) + if set(counts_by_split) != expected_splits: + raise ValueError( + f"split_strategy produced split ids {sorted(counts_by_split)}, " + f"but num_splits={num_splits} requires exactly " + f"{{0, ..., {num_splits - 1}}}. Pass num_splits matching the " + "strategy's own split count (e.g. `fixed=num_splits` on " + "bootstrap_sample/split_random/etc.)." + ) + # The round-robin iteration below (and in _iter_owned) assumes every + # split has the same row count -- it stops as soon as any one owned + # split is exhausted (see its own comment: "all splits exhaust + # simultaneously"). Every other path guarantees this by always building + # with fixed=num_splits; a split_strategy using ratios/counts/split_hash + # weights has no such guarantee, and unequal sizes would otherwise + # silently drop rows from the larger splits -- or, with world_size > 1 + # where each rank owns different splits, end ranks after different row + # counts and desync or hang a distributed run's end-of-epoch collectives. + if len(set(counts_by_split.values())) > 1: + raise ValueError( + f"split_strategy produced unequal split sizes " + f"{counts_by_split} (split id -> row count). Every split must " + "have the same row count. Use `fixed=num_splits` rather than " + "`ratios`/`counts`/weighted `split_hash`, which can produce " + "unequal sizes, or split unevenly-sized groups into separate " + "StreamingDatasets instead." + ) + elif shuffle: perm_seed = shuffle_seed + epoch * _EPOCH_PRIME self._perm_table = builder.split_random( fixed=num_splits, seed=perm_seed, clump_size=shuffle_clump_size ).execute() else: self._perm_table = builder.split_sequential(fixed=num_splits).execute() + # Only the split_strategy path needs a permutation fingerprint in the + # checkpoint (see `_checkpoint_snapshot`): split_random/split_sequential are + # already fully pinned by shuffle_seed/num_splits, and a fingerprint over raw + # row ids would spuriously reject an otherwise-valid resume after those row + # ids get renumbered by compaction (row ids are not stable by default). + self._uses_split_strategy = split_strategy is not None + # Lazily computed and cached by `_perm_fingerprint` -- `_perm_table` never + # changes after construction, so this is correct to compute once. + self._perm_fingerprint_cache: Optional[str] = None if self._blocks_per_epoch == "auto": self._blocks_per_epoch = self._estimate_blocks_per_epoch() @@ -1406,11 +1482,51 @@ class StreamingDataset(IterableDataset): ) return state + @property + def _perm_fingerprint(self) -> str: + """Cheap identity check for the built permutation, computed once and cached + (``_perm_table`` never changes after construction). + + Only meaningful -- and only recorded in a checkpoint -- for the + ``split_strategy`` path (see ``_checkpoint_snapshot``): ``num_splits``/ + ``shuffle_seed`` alone cannot detect a `load_state_dict` resuming saved + per-split progress against a *different* permutation than the one that + produced it, since a ``split_strategy`` callable ignores ``shuffle_seed`` + entirely -- e.g. a ``bootstrap_sample`` with no seed (or any changed + callable) can rebuild a completely different permutation on the next run + while ``shuffle_seed`` keeps its same default value and the existing check + passes anyway. ``split_random``/``split_sequential`` are already fully + pinned by ``shuffle_seed``/``num_splits`` and must *not* additionally be + fingerprinted: this hashes physical row ids, which are not stable across + compaction by default, so checking it on those paths would reject an + otherwise-valid resume after the table gets compacted between save and + load even though the seeded permutation itself is unchanged. + """ + if self._perm_fingerprint_cache is None: + arrow_tbl = self._perm_table.to_arrow() + hasher = hashlib.sha256() + hasher.update(str(arrow_tbl.num_rows).encode()) + for name in ("row_id", "split_id"): + column = arrow_tbl.column(name).combine_chunks() + hasher.update(column.to_numpy(zero_copy_only=False).tobytes()) + self._perm_fingerprint_cache = hasher.hexdigest() + return self._perm_fingerprint_cache + def _checkpoint_snapshot(self) -> dict: + # Only recorded for split_strategy: split_random/split_sequential are + # already fully pinned by shuffle_seed/num_splits below, and row ids are not + # stable across compaction by default, so fingerprinting them unconditionally + # would reject an otherwise-valid resume after the table got compacted. + perm_fingerprint = ( + {"perm_fingerprint": self._perm_fingerprint} + if (self._uses_split_strategy) + else {} + ) if self._pack_sequences is not None: return { "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, + **perm_fingerprint, "epoch": self._epoch, "pack_sequences": self._pack_sequences, "eos_id": self._eos_id, @@ -1431,6 +1547,7 @@ class StreamingDataset(IterableDataset): return { "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, + **perm_fingerprint, "epoch": self._epoch, "samples_consumed_per_split": samples, "positions_consumed_per_split": positions, @@ -1560,8 +1677,16 @@ class StreamingDataset(IterableDataset): Raises ``ValueError`` if ``num_splits`` or ``shuffle_seed`` differ from the checkpoint, since a different split structure or shuffle order - makes mid-epoch resumption meaningless. Packed checkpoints - pin ``pack_sequences``, ``eos_id``, ``pad_id``, + makes mid-epoch resumption meaningless. Also raises if the checkpoint + was built with ``split_strategy`` and records a permutation fingerprint + that does not match the current dataset's permutation -- this catches a + changed or non-deterministically-reseeded ``split_strategy`` that + ``num_splits``/``shuffle_seed`` alone cannot detect, since ``shuffle_seed`` + is unused on that path. Checkpoints from ``split_random``/ + ``split_sequential`` never carry this fingerprint (row ids are not stable + across compaction, so it would reject an otherwise-valid resume), and + continue to rely on ``shuffle_seed``/``num_splits`` alone as before. + Packed checkpoints pin ``pack_sequences``, ``eos_id``, ``pad_id``, ``blocks_per_epoch``, and ``epoch``. """ if state["num_splits"] != self._num_splits: @@ -1574,6 +1699,19 @@ class StreamingDataset(IterableDataset): f"shuffle_seed mismatch: checkpoint has {state['shuffle_seed']}, " f"current dataset has {self._shuffle_seed}" ) + checkpoint_fingerprint = state.get("perm_fingerprint") + if ( + checkpoint_fingerprint is not None + and checkpoint_fingerprint != self._perm_fingerprint + ): + raise ValueError( + "permutation mismatch: this checkpoint was saved against a " + "different permutation (e.g. a split_strategy that resamples " + "differently between runs, such as bootstrap_sample with no " + "seed, or a changed callable) than the current dataset built. " + "Resuming would apply saved per-split positions to the wrong " + "rows." + ) self._consumer_checkpoint_requires_uniform = False if "pack_buffers" in state or self._pack_sequences is not None: @@ -1675,6 +1813,10 @@ class StreamingDataset(IterableDataset): first = states[0] packed = "pack_buffers" in first config_keys = ["shuffle_seed", "num_splits", "epoch"] + if "perm_fingerprint" in first: + # Absent only in checkpoints saved before this key existed; skip rather + # than KeyError so old checkpoints keep merging. + config_keys.append("perm_fingerprint") if packed: config_keys.extend( ["pack_sequences", "eos_id", "pad_id", "blocks_per_epoch"] @@ -1684,6 +1826,8 @@ class StreamingDataset(IterableDataset): if ("pack_buffers" in state) != packed: raise ValueError("cannot merge packed and unpacked state dicts") for key in config_keys: + if key not in state: + continue if state[key] != first[key]: raise ValueError( f"{key} mismatch across state dicts: " diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 9d18752f1..5eb3f095c 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -3297,3 +3297,230 @@ def test_streaming_dataset_over_remote_table(): assert len(server.scans) == 1, "the permutation is built with one row-id scan" assert server.takes, "rows must be fetched with row-id takes" assert_server_safe_row_id_requests(server) + + +# --------------------------------------------------------------------------- +# split_strategy escape hatch +# --------------------------------------------------------------------------- + + +def test_split_strategy_bootstrap_sample(lance_table): + """split_strategy lets StreamingDataset use bootstrap_sample directly, producing + more rows than the base table has (sampling with replacement).""" + num_samples = 4 * NUM_ROWS + ds = StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + num_samples, fixed=NUM_SPLITS, seed=SHUFFLE_SEED + ), + num_splits=NUM_SPLITS, + ) + ids = [row["id"] for row in ds] + + assert len(ids) == num_samples + # 4x oversampling a small table must produce at least one repeat. + assert len(set(ids)) < len(ids) + assert set(ids).issubset(set(range(NUM_ROWS))) + + +def test_split_strategy_matches_direct_permutation_builder_use(lance_table): + """StreamingDataset(split_strategy=...), read single-process (no DataLoader + workers, so this one process owns every split and round-robins across all of + them), must yield exactly what calling the same strategy directly on a + PermutationBuilder would read, interleaved one row per split per cycle. + + Reads each split via __getitems__ (explicit indices), not plain iteration: + Permutation's sequential __iter__ returns empty for a permutation with repeated + row_ids (confirmed directly -- len() is correct, __getitems__ returns the right + rows, but `for row in perm` yields nothing). That's a pre-existing limitation of + Permutation's iterator, unrelated to Bootstrap sampling's correctness: it doesn't + affect StreamingDataset or this benchmark, since both only ever read via + explicit-index batched fetches (take_offsets/__getitems__), never the plain + iterator -- flagged separately, not fixed here (out of scope for this change). + """ + from lancedb.permutation import Permutation, permutation_builder + + def strategy(builder): + return builder.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=1) + + direct_perm_tbl = strategy(permutation_builder(lance_table)).execute() + expected_by_split = [] + for split in range(NUM_SPLITS): + perm = Permutation.from_tables(lance_table, direct_perm_tbl, split=split) + rows = perm.__getitems__(list(range(len(perm)))) + expected_by_split.append([row["id"] for row in rows]) + samples_per_split = len(expected_by_split[0]) + expected = [ + expected_by_split[split][cycle] + for cycle in range(samples_per_split) + for split in range(NUM_SPLITS) + ] + + ds = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS) + actual = [row["id"] for row in ds] + assert actual == expected + + +def test_split_strategy_is_reproducible_across_instances(lance_table): + def strategy(builder): + return builder.bootstrap_sample(3 * NUM_ROWS, fixed=NUM_SPLITS, seed=99) + + ds1 = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS) + ds2 = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS) + + assert [row["id"] for row in ds1] == [row["id"] for row in ds2] + + +def test_split_strategy_num_splits_mismatch_raises(lance_table): + """StreamingDataset(split_strategy=...) must reject a strategy whose split + count doesn't match num_splits. `_rank_splits` assumes split ids are exactly + 0..num_splits-1 with no gaps; a mismatch would otherwise silently drop rows + (split ids >= num_splits) or leave some ranks reading an empty split (missing + ids < num_splits).""" + with pytest.raises(ValueError, match="num_splits"): + StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + 2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED + ), + num_splits=NUM_SPLITS + 1, # the strategy above always builds NUM_SPLITS + ) + + +def test_split_strategy_unequal_split_sizes_raises(lance_table): + """StreamingDataset(split_strategy=...) must reject a strategy whose splits + all exist (ids 0..num_splits-1) but aren't the same size. The round-robin + iteration (see _iter_owned) assumes every owned split has the same row count + and stops as soon as any one is exhausted -- `ratios`/`counts` (unlike + `fixed`) can produce unequal split sizes, which would otherwise silently + drop rows from the larger splits.""" + with pytest.raises(ValueError, match="unequal split sizes"): + StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + 100, ratios=[0.7, 0.3], seed=SHUFFLE_SEED + ), + num_splits=2, + ) + + +def test_split_strategy_permutation_mismatch_on_resume_raises(lance_table): + """load_state_dict must reject resuming against a different permutation than + the one that produced the checkpoint. num_splits/shuffle_seed alone can't catch + this for split_strategy, since that path ignores shuffle_seed entirely: a + bootstrap_sample reseeded differently resamples completely differently while + shuffle_seed keeps whatever value the caller passed either way, so the + pre-existing checks would pass despite the mismatch.""" + + def strategy(seed): + return lambda b: b.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=seed) + + ds1 = StreamingDataset( + lance_table, + split_strategy=strategy(1), + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + ) + it = iter(ds1) + for _ in range(NUM_SPLITS): # one full cycle: every split advances uniformly + next(it) + checkpoint = ds1.state_dict() + + ds2 = StreamingDataset( + lance_table, + split_strategy=strategy(2), # different seed -> a different permutation + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, # unchanged -- irrelevant on this path + ) + with pytest.raises(ValueError, match="permutation mismatch"): + ds2.load_state_dict(checkpoint) + + +def test_split_strategy_resume_with_matching_permutation_succeeds(lance_table): + """The common case: resuming against the same split_strategy (same seed) must + work exactly like the non-split_strategy checkpoint/resume path, continuing + from exactly the same position with no gaps or repeats.""" + + def strategy(b): + return b.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=7) + + ds1 = StreamingDataset( + lance_table, + split_strategy=strategy, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + ) + it = iter(ds1) + for _ in range(NUM_SPLITS): + next(it) + checkpoint = ds1.state_dict() + remaining_original = [row["id"] for row in it] + + ds2 = StreamingDataset( + lance_table, + split_strategy=strategy, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + ) + ds2.load_state_dict(checkpoint) # must not raise + remaining_resumed = [row["id"] for row in ds2] + + assert remaining_original == remaining_resumed + + +def test_default_checkpoint_omits_perm_fingerprint(lance_table): + """split_random/split_sequential checkpoints must not carry a + perm_fingerprint -- see test_default_checkpoint_resumes_after_compaction for + why checking one on this path would be wrong, not just unnecessary.""" + ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED) + assert "perm_fingerprint" not in ds.state_dict() + + +def test_split_strategy_checkpoint_includes_perm_fingerprint(lance_table): + ds = StreamingDataset( + lance_table, + split_strategy=lambda b: b.bootstrap_sample( + 2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED + ), + num_splits=NUM_SPLITS, + ) + assert "perm_fingerprint" in ds.state_dict() + + +def test_default_checkpoint_resumes_after_compaction(lance_table): + """split_random/split_sequential checkpoints must resume normally even after + the table is compacted between save and load. Lance row ids are not stable + across compaction by default (confirmed empirically: a 2-fragment table's + row ids differ before and after `optimize()`), so fingerprinting raw row ids + on this path -- instead of relying on shuffle_seed/num_splits alone, as it + does -- would reject this resume even though the seeded permutation itself + is unchanged.""" + lance_table.add(pa.table({"id": [NUM_ROWS]})) # a second fragment to compact + + ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED) + it = iter(ds) + for _ in range(NUM_SPLITS): + next(it) + checkpoint = ds.state_dict() + assert "perm_fingerprint" not in checkpoint + + before_compaction = set( + lance_table.to_lance() + .to_table(columns=[], with_row_id=True)["_rowid"] + .to_pylist() + ) + lance_table.optimize() + after_compaction = set( + lance_table.to_lance() + .to_table(columns=[], with_row_id=True)["_rowid"] + .to_pylist() + ) + assert before_compaction != after_compaction, ( + "test setup didn't actually renumber row ids -- fix the fixture, not " + "the assertion below" + ) + + ds_resumed = StreamingDataset( + lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED + ) + ds_resumed.load_state_dict(checkpoint) # must not raise diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 5e8bb1d76..ed1894340 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -161,6 +161,76 @@ def test_split_random_with_seed(mem_db): assert data1["split_id"] == data2["split_id"] +def test_bootstrap_sample_fixed(mem_db): + """Output row count is num_samples, not the input row count, and splits divide + it evenly.""" + tbl = mem_db.create_table("test_table", pa.table({"x": range(20)})) + permutation_tbl = ( + permutation_builder(tbl).bootstrap_sample(1000, fixed=4, seed=42).execute() + ) + + assert permutation_tbl.count_rows() == 1000 + + data = permutation_tbl.search(None).to_arrow().to_pydict() + split_ids = data["split_id"] + assert set(split_ids) == {0, 1, 2, 3} + for split_id in range(4): + assert split_ids.count(split_id) == 250 + + # Every sampled row_id must still be one of the 20 real rows. + assert set(data["row_id"]).issubset(set(range(20))) + + +def test_bootstrap_sample_draws_with_replacement(mem_db): + """Sampling more rows than exist must produce repeats.""" + tbl = mem_db.create_table("test_table", pa.table({"x": range(5)})) + permutation_tbl = ( + permutation_builder(tbl).bootstrap_sample(500, fixed=1, seed=1).execute() + ) + + data = permutation_tbl.search(None).to_arrow().to_pydict() + assert len(data["row_id"]) == 500 + # Only 5 distinct rows exist, so with 500 draws every one of them must repeat. + for row_id in range(5): + assert data["row_id"].count(row_id) > 1 + + +def test_bootstrap_sample_with_seed_is_reproducible(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"x": range(50)})) + + perm1 = permutation_builder(tbl).bootstrap_sample(200, fixed=2, seed=42).execute() + perm2 = permutation_builder(tbl).bootstrap_sample(200, fixed=2, seed=42).execute() + + data1 = perm1.search(None).to_arrow().to_pydict() + data2 = perm2.search(None).to_arrow().to_pydict() + assert data1["row_id"] == data2["row_id"] + assert data1["split_id"] == data2["split_id"] + + +def test_bootstrap_sample_respects_filter(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"x": range(20)})) + permutation_tbl = ( + permutation_builder(tbl) + .filter("x >= 15") + .bootstrap_sample(100, fixed=1, seed=7) + .execute() + ) + + data = permutation_tbl.search(None).to_arrow().to_pydict() + assert len(data["row_id"]) == 100 + assert set(data["row_id"]).issubset(set(range(15, 20))) + + +def test_bootstrap_sample_requires_exactly_one_size_arg(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"x": range(10)})) + with pytest.raises(ValueError): + permutation_builder(tbl).bootstrap_sample(10).execute() + with pytest.raises(ValueError): + permutation_builder(tbl).bootstrap_sample( + 10, ratios=[0.5, 0.5], fixed=2 + ).execute() + + def test_split_hash(mem_db): """Test hash-based splitting.""" tbl = mem_db.create_table( diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 24ca2b5a3..4e07d439e 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -178,6 +178,50 @@ impl PyAsyncPermutationBuilder { }) } + #[pyo3(signature = (num_samples, *, ratios=None, counts=None, fixed=None, seed=None, split_names=None))] + pub fn bootstrap_sample( + slf: PyRefMut<'_, Self>, + num_samples: u64, + ratios: Option>, + counts: Option>, + fixed: Option, + seed: Option, + split_names: Option>, + ) -> PyResult { + // Check that exactly one split type is provided + let split_args_count = [ratios.is_some(), counts.is_some(), fixed.is_some()] + .iter() + .filter(|&&x| x) + .count(); + + if split_args_count != 1 { + return Err(pyo3::exceptions::PyValueError::new_err( + "Exactly one of 'ratios', 'counts', or 'fixed' must be provided", + )); + } + + let sizes = if let Some(ratios) = ratios { + SplitSizes::Percentages(ratios) + } else if let Some(counts) = counts { + SplitSizes::Counts(counts) + } else if let Some(fixed) = fixed { + SplitSizes::Fixed(fixed) + } else { + unreachable!("One of the split arguments must be provided"); + }; + + slf.modify(|builder| { + builder.with_split_strategy( + SplitStrategy::Bootstrap { + num_samples, + sizes, + seed, + }, + split_names, + ) + }) + } + pub fn split_calculated( slf: PyRefMut<'_, Self>, calculation: String, diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 32e7063a3..15f8c3cd3 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -316,6 +316,10 @@ impl PermutationBuilder { } else { self.sort_by_column(rows, ROW_ID).await? }; + // Bootstrap's output row count (num_samples) differs from its input row count + // (num_rows); every other strategy's output matches its input. The shuffler + // must be told the former, not assume it always equals the latter. + let output_rows = splitter.output_row_count(num_rows); let split_data = splitter.apply(rows, num_rows).await?; // Shuffle data if requested @@ -328,7 +332,7 @@ impl PermutationBuilder { temp_dir: self.config.temp_dir.clone(), max_rows_per_file: 10 * 1024 * 1024, }); - shuffler.shuffle(split_data, num_rows).await? + shuffler.shuffle(split_data, output_rows).await? } }; diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index cfa8e5235..b4e5deac1 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -11,6 +11,7 @@ use arrow_schema::{DataType, Field, Schema}; use datafusion_common::hash_utils::{RandomState, create_hashes}; use futures::{StreamExt, TryStreamExt}; use lance_arrow::SchemaExt; +use rand::Rng; use lance_core::ROW_ID; @@ -19,7 +20,7 @@ use crate::{ arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}, dataloader::{ permutation::shuffle::{Shuffler, ShufflerConfig}, - permutation::util::TemporaryDirectory, + permutation::util::{TemporaryDirectory, non_crypto_rng}, }, query::{Query, QueryBase, Select}, }; @@ -76,6 +77,59 @@ pub enum SplitStrategy { /// /// If this strategy is used then the counts/percentages in the SplitSizes are ignored. Calculated { calculation: String }, + /// Rows are sampled uniformly **with replacement** from the base table (combine with + /// [`PermutationBuilder::with_filter`] to restrict the eligible population), independently + /// per split. Named after "the bootstrap" -- the statistical technique of estimating a + /// dataset's properties by resampling it with replacement -- the same sense `bootstrap=True` + /// has in scikit-learn's bagging classifiers. + /// + /// Every other strategy partitions the table: each row goes to exactly one split, exactly + /// once. `Bootstrap` does not partition -- it resamples. The number of output rows is + /// `num_samples`, not the number of input rows: the same row can appear zero, one, or many + /// times, and `num_samples` may be larger or smaller than the (filtered) input row count. + /// Typical uses: + /// + /// - **Bagging / ensemble training** (e.g. random forests): each split is an independent + /// bootstrap resample of the training set. + /// - **Oversampling a rare class**: filter to the minority class, then sample it up to + /// whatever count balances it against the majority, instead of exhausting its small set + /// once per epoch. + /// - **Fixed-size training steps independent of dataset size**: `num_samples` is set + /// directly rather than being implicitly `len(dataset)`. + /// - **Weighted sampling without a weight column**: filter to "eligible" rows (e.g. a + /// windowed-sampling workload filtering to valid window-start positions), then bootstrap + /// the filtered set -- an item with more eligible rows is naturally drawn proportionally + /// more often, with no explicit per-row weight needed. + /// + /// `sizes` divides `num_samples` across splits (reusing [`SplitSizes`], so `Fixed(n)` means + /// "n splits, each getting `num_samples / n` samples", the same convention `Random` and + /// `Sequential` use). Each split draws its own sample using a seed derived independently + /// from `(seed, split_index)`, so a given split's content does not change if `num_samples` + /// is redistributed across a different number of splits -- the same elastic-determinism + /// property documented for the data loader's other strategies. + /// + /// Example: a 5-row base table (`row_id` 0..4), `Bootstrap { num_samples: 8, sizes: + /// Fixed(2), seed: Some(42) }` produced (an actual run, not a hypothetical one): + /// + /// ```text + /// row_id split_id + /// 0 0 + /// 2 0 + /// 4 0 + /// 4 0 <- row 4 repeated within split 0 + /// 4 1 <- row 4 also drawn in split 1 (independent draw) + /// 4 1 + /// 1 1 + /// 2 1 + /// ``` + /// + /// 8 output rows from a 5-row table, row 4 drawn 4 times total, row 3 never drawn -- + /// exactly the with-replacement behavior the name promises, not an even round-robin. + Bootstrap { + num_samples: u64, + sizes: SplitSizes, + seed: Option, + }, } impl SplitStrategy { @@ -107,6 +161,25 @@ impl SplitStrategy { } Self::Sequential { sizes } => sizes.validate(num_rows), Self::Calculated { .. } => Ok(()), + Self::Bootstrap { + num_samples, sizes, .. + } => { + if num_rows == 0 { + return Err(Error::InvalidInput { + message: "Bootstrap strategy requires at least one eligible row to \ + sample from (check the filter, if one is set)" + .to_string(), + }); + } + if *num_samples == 0 { + return Err(Error::InvalidInput { + message: "Bootstrap strategy requires num_samples > 0".to_string(), + }); + } + // Validated against num_samples, not num_rows: sampling is with replacement, + // so num_samples may exceed the number of eligible rows. + sizes.validate(*num_samples) + } } } } @@ -314,6 +387,95 @@ impl Splitter { ))) } + /// Materializes the full (filtered) row id stream -- random access is required since + /// with-replacement sampling can draw any position, including ones already drawn -- then + /// independently samples each split's share with its own derived RNG seed. + async fn apply_bootstrap( + &self, + source: SendableRecordBatchStream, + num_samples: u64, + sizes: &SplitSizes, + seed: Option, + ) -> Result { + let schema = source.schema(); + let row_id_field = schema.field(0).clone(); + let batches: Vec = source.try_collect().await?; + let row_id_arrays = batches + .iter() + .map(|b| b.column(0).as_ref()) + .collect::>(); + let row_ids = arrow::compute::concat(&row_id_arrays)?; + // Sample against however many rows this scan actually returned, not the + // separately computed `num_rows` count checked by `validate` -- that count and + // this scan are two different queries, not pinned to one snapshot, so a + // concurrent append or delete between them could otherwise push + // `random_range` out of `row_ids`'s real bounds. + let num_eligible_rows = row_ids.len() as u64; + if num_eligible_rows == 0 { + return Err(Error::InvalidInput { + message: "Bootstrap strategy found no eligible rows to sample from in \ + this scan (the table or its filter may have changed since \ + validation)" + .to_string(), + }); + } + + let split_sample_counts = sizes.to_counts(num_samples); + + // `try_reserve_exact` (fallible) rather than `with_capacity` (infallible -- + // aborts the whole process via `handle_alloc_error` on failure, which no + // caller can catch) so an unreasonably large `num_samples` becomes a normal, + // catchable error instead of a crash. This bounds the failure mode, not peak + // memory itself: the output is still one fully materialized RecordBatch, not + // streamed in chunks. + let too_large = || Error::InvalidInput { + message: format!( + "Bootstrap strategy's num_samples ({num_samples}) is too large to \ + allocate in memory" + ), + }; + let mut position_indices = Vec::::new(); + position_indices + .try_reserve_exact(num_samples as usize) + .map_err(|_| too_large())?; + let mut split_ids = Vec::::new(); + split_ids + .try_reserve_exact(num_samples as usize) + .map_err(|_| too_large())?; + for (split_idx, &count) in split_sample_counts.iter().enumerate() { + // Derive an independent seed per split (rather than one RNG shared across all + // splits) so a split's sample doesn't depend on how many other splits there are. + let split_seed = seed.map(|s| { + s.wrapping_add( + (split_idx as u64) + .wrapping_mul(0x9E37_79B9_7F4A_7C15) + .wrapping_add(1), + ) + }); + let mut rng = non_crypto_rng(&split_seed); + for _ in 0..count { + position_indices.push(rng.random_range(0..num_eligible_rows)); + split_ids.push(split_idx as u64); + } + } + + let indices = UInt64Array::from(position_indices); + let sampled_row_ids = arrow::compute::take(row_ids.as_ref(), &indices, None)?; + let split_id_array: Arc = Arc::new(UInt64Array::from(split_ids)); + + let new_schema = Arc::new(Schema::new(vec![ + row_id_field, + Field::new(SPLIT_ID_COLUMN, DataType::UInt64, false), + ])); + let result_batch = + RecordBatch::try_new(new_schema.clone(), vec![sampled_row_ids, split_id_array])?; + + Ok(Box::pin(SimpleRecordBatchStream::new( + futures::stream::once(std::future::ready(Ok(result_batch))), + new_schema, + ))) + } + pub async fn apply( &self, source: SendableRecordBatchStream, @@ -357,6 +519,14 @@ impl Splitter { self.apply_hash(source, split_weights, *discard_weight) .await } + SplitStrategy::Bootstrap { + num_samples, + sizes, + seed, + } => { + self.apply_bootstrap(source, *num_samples, sizes, *seed) + .await + } } } @@ -377,7 +547,13 @@ impl Splitter { pub fn orders_by_split_id(&self) -> bool { match &self.strategy { - SplitStrategy::Hash { .. } | SplitStrategy::Calculated { .. } => true, + // Bootstrap emits samples grouped split-by-split already (see apply_bootstrap), + // rather than relying on the shared pipeline's sort-by-split-id step: within-split + // draw order is meaningful to callers (e.g. a warmup/measured split within one + // split's stream), and sort stability for ties isn't documented behavior to lean on. + SplitStrategy::Hash { .. } + | SplitStrategy::Calculated { .. } + | SplitStrategy::Bootstrap { .. } => true, SplitStrategy::NoSplit | SplitStrategy::Sequential { .. } // It may be strange but for random we shuffle and then assign splits so the result is @@ -385,6 +561,26 @@ impl Splitter { | SplitStrategy::Random { .. } => false, } } + + /// The row count `apply` produces from `num_rows` input rows. Equal to `num_rows` + /// for every strategy except `Bootstrap`, whose output size is `num_samples` + /// regardless of how many (filtered) input rows it draws from. Callers that need + /// to validate or pre-size `apply`'s output (e.g. the shuffler) must use this + /// instead of assuming the input and output row counts match. + /// + /// For `Bootstrap`, this is `sizes.to_counts(num_samples)`'s sum, not + /// `num_samples` itself: `to_counts` can emit less than its input (e.g. + /// `Fixed(n)` when `n` does not divide `num_samples` evenly, or explicit + /// `counts`/`ratios` that do not use every sample) and `apply_bootstrap` only + /// ever emits exactly what `to_counts` returns. + pub fn output_row_count(&self, num_rows: u64) -> u64 { + match &self.strategy { + SplitStrategy::Bootstrap { + num_samples, sizes, .. + } => sizes.to_counts(*num_samples).iter().sum(), + _ => num_rows, + } + } } /// Split configuration - either percentages or absolute counts @@ -807,4 +1003,169 @@ mod tests { assert_eq!(num_in_split_0, 12); // 24% assert_eq!(num_in_split_1, 30); // 60% } + + #[tokio::test] + async fn test_bootstrap_split_schema_and_counts() { + let splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 1000, + sizes: SplitSizes::Fixed(4), + seed: Some(42), + }, + ); + + let split_batches = splitter + .apply(test_data(), 50) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let schema = split_batches[0].schema(); + let split_batch = concat_batches(&schema, &split_batches).unwrap(); + + // Schema stays exactly [row_id, split_id], same as every other strategy. + let field_names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect(); + assert_eq!(field_names, vec!["id", SPLIT_ID_COLUMN]); + + // Output row count is num_samples, not num_rows (50) -- sampling is with replacement. + assert_eq!(split_batch.num_rows(), 1000); + + let split_ids = split_batch.column(1).as_primitive::().values(); + for split_id in [0u64, 1, 2, 3] { + assert_eq!(split_ids.iter().filter(|v| **v == split_id).count(), 250); + } + + // With 1000 draws from only 50 distinct rows, some row id must repeat. + let row_ids = split_batch.column(0).as_primitive::().values(); + let mut seen = std::collections::HashSet::new(); + assert!(!row_ids.iter().all(|v| seen.insert(*v))); + } + + #[tokio::test] + async fn test_bootstrap_split_seed_is_reproducible() { + let make_splitter = || { + Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 200, + sizes: SplitSizes::Fixed(2), + seed: Some(7), + }, + ) + }; + + let first = make_splitter() + .apply(test_data(), 50) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let second = make_splitter() + .apply(test_data(), 50) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + let schema = first[0].schema(); + let first = concat_batches(&schema, &first).unwrap(); + let second = concat_batches(&schema, &second).unwrap(); + assert_eq!(first.column(0), second.column(0)); + assert_eq!(first.column(1), second.column(1)); + } + + #[tokio::test] + async fn test_bootstrap_split_respects_filter() { + // Bootstrap is driven through a filter the same way every other strategy is -- the + // base table rows reaching Splitter::apply are already filtered by the time they get + // here, so this exercises the same num_rows=0 guard a fully-filtered-out population + // would hit. + let splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Fixed(1), + seed: Some(1), + }, + ); + let Err(err) = splitter.apply(test_data(), 0).await else { + panic!("expected Bootstrap over zero eligible rows to fail"); + }; + assert!(err.to_string().contains("at least one eligible row")); + } + + fn empty_data() -> SendableRecordBatchStream { + lance_datagen::gen_batch() + .with_seed(Seed::from(42)) + .col(ID_COLUMN, lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(0), BatchCount::from(1)) + } + + #[test] + fn test_output_row_count() { + // Bootstrap's output row count is independent of the input size -- every + // other strategy's output matches its input. The shuffler relies on this + // (see builder.rs) instead of assuming input and output row counts match. + let bootstrap = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 1000, + sizes: SplitSizes::Fixed(4), + seed: Some(42), + }, + ); + assert_eq!(bootstrap.output_row_count(50), 1000); + + // Not num_samples itself: `Fixed(3)` doesn't divide 1000 evenly, so + // `to_counts` emits 333 * 3 = 999, one short of num_samples -- + // `apply_bootstrap` only ever emits exactly what `to_counts` returns. + let bootstrap_uneven = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 1000, + sizes: SplitSizes::Fixed(3), + seed: Some(42), + }, + ); + assert_eq!(bootstrap_uneven.output_row_count(50), 999); + + let sequential = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Sequential { + sizes: SplitSizes::Fixed(2), + }, + ); + assert_eq!(sequential.output_row_count(50), 50); + } + + #[tokio::test] + async fn test_bootstrap_rejects_empty_scan_cleanly() { + // The eligibility count `validate` checks and this scan are two separate + // queries against the table, not pinned to one snapshot -- a concurrent + // delete could shrink the real scan to zero rows after `validate` already + // passed on a nonzero count. Calling `apply_bootstrap` directly (bypassing + // `apply`'s `validate`) reproduces exactly that: a scan that returns zero + // rows regardless of what count was validated upstream. It must return a + // clean `Err`, not panic on an out-of-range `take` or an empty-range + // `random_range`. + let splitter = Splitter::new( + TemporaryDirectory::None, + SplitStrategy::Bootstrap { + num_samples: 10, + sizes: SplitSizes::Fixed(1), + seed: Some(1), + }, + ); + let Err(err) = splitter + .apply_bootstrap(empty_data(), 10, &SplitSizes::Fixed(1), Some(1)) + .await + else { + panic!("expected Bootstrap over an empty scan to fail cleanly, not panic"); + }; + assert!(err.to_string().contains("no eligible rows")); + } } From f9680806c982d30a85fd70c0542a8dc2b20ee5d9 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 21 Oct 2026 23:47:09 -0700 Subject: [PATCH 013/180] feat(python): expose materialized view auto-refresh creation options (#4621) Expose optional `auto_refresh_enabled` and `auto_refresh_interval_seconds` when creating materialized views from Python and Rust. Omitted intervals remain unset: the server determines when to refresh. ```python view = db.create_materialized_view( "recent_orders", "orders", auto_refresh_enabled=True, auto_refresh_interval_seconds=300, ) ``` ## Architecture and workflow - Python synchronous, asynchronous, job-returning and namespace wrappers forward both optional values through PyO3 to the Rust creation builder. Both default to `None`; no client interval is selected. - Remote creation calls `POST /v1/materialized_view/{id}/create` with the defining query and only the supplied refresh properties. A `202 Accepted` response must contain a job ID. Existing job tracking waits for the server's ordinary SQL CREATE job before synchronous creation opens the view. - The server validates and authorizes the CREATE, then uses the existing SQL worker to populate the view and persist its refresh settings. The Lance agent subsequently uses those settings to submit REFRESH SQL jobs. - Explicit positive finite fractional seconds are preserved. An interval alone does not enable refresh. Embedded connections retain manual refresh, accept explicit disabled state, and reject requests for automatic scheduling rather than ignore them. Includes API documentation and coverage for omission, false, fractional/invalid intervals, namespace forwarding, server job IDs and invalid acceptance responses. Requires the server REST-create endpoint to be deployed before SDK release. Existing remote `with_no_data=True` remains unsupported. --- docs/src/python/python.md | 16 ++ python/python/lancedb/_lancedb.pyi | 4 + python/python/lancedb/db.py | 27 ++++ python/python/lancedb/namespace.py | 16 ++ python/python/lancedb/remote/db.py | 8 + .../python/tests/test_materialized_views.py | 105 ++++++++++++- python/src/connection.rs | 22 ++- rust/lancedb/src/materialized_view.rs | 44 +++++- rust/lancedb/src/remote/db.rs | 140 ++++++++++++++---- 9 files changed, 349 insertions(+), 33 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index c8a82851f..f4c697497 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -377,6 +377,22 @@ listing a storage directory. ## Materialized Views (Synchronous) +On Cloud and Enterprise, creation accepts `auto_refresh_enabled` and +`auto_refresh_interval_seconds`: + +```python +view = db.create_materialized_view( + "recent_orders", + "orders", + auto_refresh_enabled=True, + auto_refresh_interval_seconds=300, +) +``` + +Omit `auto_refresh_interval_seconds` to let the server determine when to refresh. +These options also apply to asynchronous creation and creation jobs. Embedded +connections support manual refresh and reject automatic scheduling requests. + ::: lancedb.materialized_view.MaterializedView ::: lancedb.materialized_view.MaterializedViewDefinition diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 96bc7752b..96eef064c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -270,6 +270,8 @@ class Connection(object): filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Table: ... async def create_materialized_view_async( self, @@ -279,6 +281,8 @@ class Connection(object): filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 47d24b762..5def89b01 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -607,6 +607,8 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. @@ -631,6 +633,13 @@ class DBConnection(EnforceOverrides): Cap the view at this many rows, in materialization order. with_no_data: bool, default False Skip the initial refresh and leave the backing table empty. + auto_refresh_enabled: bool, optional + Enable or disable automatic refresh on Cloud and Enterprise. + When omitted, the server determines whether automatic refresh is enabled. + Embedded databases do not support automatic refresh. + auto_refresh_interval_seconds: float, optional + Positive, finite refresh interval in seconds on Cloud and Enterprise. + When omitted, the server determines when to refresh. Returns ------- @@ -649,6 +658,8 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: """Submit materialized-view creation and return its job. @@ -1706,6 +1717,8 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. See @@ -1734,6 +1747,8 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return MaterializedView(self.open_table(name)) @@ -1748,6 +1763,8 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: job = LOOP.run( self._conn.create_materialized_view_async( @@ -1757,6 +1774,8 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return Job(job) @@ -2767,6 +2786,8 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. See @@ -2782,6 +2803,8 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, ) return AsyncMaterializedView(AsyncTable(inner)) @@ -2795,6 +2818,8 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. @@ -2810,6 +2835,8 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, ) return AsyncJob(inner) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 26c62925f..f8675ebb5 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -665,6 +665,8 @@ class LanceNamespaceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. See @@ -680,6 +682,8 @@ class LanceNamespaceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ).name ) @@ -695,6 +699,8 @@ class LanceNamespaceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: job = LOOP.run( self._inner.create_materialized_view_async( @@ -704,6 +710,8 @@ class LanceNamespaceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return Job(job) @@ -1288,6 +1296,8 @@ class AsyncLanceNamespaceDBConnection: where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" view = await self._inner.create_materialized_view( @@ -1297,6 +1307,8 @@ class AsyncLanceNamespaceDBConnection: where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. @@ -1311,6 +1323,8 @@ class AsyncLanceNamespaceDBConnection: where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job.""" return await self._inner.create_materialized_view_async( @@ -1320,6 +1334,8 @@ class AsyncLanceNamespaceDBConnection: where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ac6b8b99d..89c7f8a78 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -723,6 +723,8 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: from .table import RemoteTable @@ -734,6 +736,8 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return MaterializedView( @@ -755,6 +759,8 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + auto_refresh_enabled: Optional[bool] = None, + auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: job = LOOP.run( self._conn.create_materialized_view_async( @@ -764,6 +770,8 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + auto_refresh_enabled=auto_refresh_enabled, + auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) ) return Job(job) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index bd1b2a0bb..46972a15c 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -129,8 +129,21 @@ def test_sync_remote_create_uses_public_async_connection(): where=None, limit=None, with_no_data=False, + auto_refresh_enabled=None, + auto_refresh_interval_seconds=None, ): - calls.append((name, source, select, where, limit, with_no_data)) + calls.append( + ( + name, + source, + select, + where, + limit, + with_no_data, + auto_refresh_enabled, + auto_refresh_interval_seconds, + ) + ) return StubAsyncMaterializedView() async def drop_materialized_view(self, name, *, namespace_path=None): @@ -148,9 +161,11 @@ def test_sync_remote_create_uses_public_async_connection(): where="age >= 18", limit=10, with_no_data=True, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=0.5, ) assert view.name == "adults" - assert calls == [("adults", "people", ["name"], "age >= 18", 10, True)] + assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)] db.drop_materialized_view("adults", namespace_path=["analytics"]) assert calls[-1] == ("drop", "adults", ["analytics"]) @@ -550,3 +565,89 @@ def test_local_materialized_view_listing_pages_and_resume(tmp_path): assert sorted([first, *resumed]) == ["a_view", "z_view"] assert resumed.page_token() is None assert list(resumed) == [] + + +@pytest.mark.parametrize( + "options", + [ + {}, + {"auto_refresh_enabled": True}, + {"auto_refresh_enabled": False, "auto_refresh_interval_seconds": 0.5}, + ], +) +def test_remote_create_forwards_refresh_options_without_interval_default(options): + with mock_remote_materialized_view_create() as (host, requests): + db = lancedb.connect("db://dev", api_key="fake", host_override=host) + job = db.create_materialized_view_async("adults", "people", **options) + assert job.id == "mv-create-123" + assert requests == [ + ( + "/v1/materialized_view/adults/create", + { + "query": 'SELECT * FROM "people"', + **options, + }, + ) + ] + + +@pytest.mark.asyncio +async def test_async_remote_create_keeps_interval_unspecified(): + with mock_remote_materialized_view_create() as (host, requests): + db = await lancedb.connect_async("db://dev", api_key="fake", host_override=host) + job = await db.create_materialized_view_async( + "adults", + "people", + auto_refresh_enabled=True, + ) + assert job.id == "mv-create-123" + assert requests[0][1] == { + "query": 'SELECT * FROM "people"', + "auto_refresh_enabled": True, + } + + +@pytest.mark.parametrize( + "options", + [ + {"auto_refresh_enabled": True}, + {"auto_refresh_interval_seconds": 300}, + ], +) +def test_embedded_create_refuses_automatic_refresh_before_creating_view( + tmp_path, options +): + db = make_db(tmp_path) + with pytest.raises(NotImplementedError, match="Cloud or Enterprise"): + db.create_materialized_view("adults", "people", **options) + assert "adults" not in db.table_names() + + +@pytest.mark.parametrize("seconds", [0, -1, float("nan"), float("inf")]) +def test_remote_create_rejects_invalid_interval_without_request(seconds): + with mock_remote_materialized_view_create() as (host, requests): + db = lancedb.connect("db://dev", api_key="fake", host_override=host) + with pytest.raises(ValueError, match="positive, finite"): + db.create_materialized_view_async( + "adults", "people", auto_refresh_interval_seconds=seconds + ) + assert requests == [] + + +def test_namespace_forwards_automatic_refresh_request(tmp_path): + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + with pytest.raises(NotImplementedError, match="Cloud or Enterprise"): + db.create_materialized_view("mv", "source", auto_refresh_enabled=True) + + +@pytest.mark.asyncio +async def test_async_namespace_forwards_automatic_refresh_request(tmp_path): + db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) + with pytest.raises(NotImplementedError, match="Cloud or Enterprise"): + await db.create_materialized_view("mv", "source", auto_refresh_enabled=True) + + +def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path): + db = make_db(tmp_path) + view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False) + assert view.table.count_rows() == 3 diff --git a/python/src/connection.rs b/python/src/connection.rs index 9ac081b9d..7e20f5f99 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -412,7 +412,8 @@ impl Connection { }) } - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -421,10 +422,18 @@ impl Connection { filter: Option, limit: Option, with_no_data: bool, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let mut builder = inner.create_materialized_view(name, source); + if let Some(enabled) = auto_refresh_enabled { + builder = builder.auto_refresh_enabled(enabled); + } + if let Some(seconds) = auto_refresh_interval_seconds { + builder = builder.auto_refresh_interval_seconds(seconds); + } if let Some(projections) = projections { builder = builder.select(projections); } @@ -440,7 +449,8 @@ impl Connection { }) } - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, @@ -449,10 +459,18 @@ impl Connection { filter: Option, limit: Option, with_no_data: bool, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let mut builder = inner.create_materialized_view(name, source); + if let Some(enabled) = auto_refresh_enabled { + builder = builder.auto_refresh_enabled(enabled); + } + if let Some(seconds) = auto_refresh_interval_seconds { + builder = builder.auto_refresh_interval_seconds(seconds); + } if let Some(projections) = projections { builder = builder.select(projections); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 95e3baac7..ecdd1783b 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -280,7 +280,7 @@ pub struct MaterializedViewInfo { /// The backend-independent request used to create a remote materialized view. #[doc(hidden)] -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] pub struct CreateMaterializedViewRequest { /// Name of the new view. pub name: String, @@ -290,6 +290,10 @@ pub struct CreateMaterializedViewRequest { pub query: String, /// Whether to skip the initial population job. pub with_no_data: bool, + /// Whether the server should refresh the view automatically. + pub auto_refresh_enabled: Option, + /// Refresh interval in seconds. When absent, the server determines when to refresh. + pub auto_refresh_interval_seconds: Option, } /// Prefix of the internal columns holding source columns a computed column @@ -1570,6 +1574,8 @@ pub struct CreateMaterializedViewBuilder { filter: Option, limit: Option, with_no_data: bool, + auto_refresh_enabled: Option, + auto_refresh_interval_seconds: Option, } fn source_sql_identifier( @@ -1603,6 +1609,8 @@ impl CreateMaterializedViewBuilder { filter: None, limit: None, with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, } } @@ -1651,6 +1659,32 @@ impl CreateMaterializedViewBuilder { self } + /// Enable or disable automatic refresh on Cloud and Enterprise. + /// When omitted, the server determines whether automatic refresh is enabled. + /// Embedded databases do not support automatic refresh. + pub fn auto_refresh_enabled(mut self, enabled: bool) -> Self { + self.auto_refresh_enabled = Some(enabled); + self + } + + /// Set a positive, finite refresh interval in seconds on Cloud and Enterprise. + /// When omitted, the server determines when to refresh. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// db.create_materialized_view("recent_orders", "orders") + /// .auto_refresh_enabled(true) + /// .auto_refresh_interval_seconds(300.0) + /// .execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn auto_refresh_interval_seconds(mut self, seconds: f64) -> Self { + self.auto_refresh_interval_seconds = Some(seconds); + self + } + fn query(&self) -> Result { fn quote(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) @@ -1693,6 +1727,8 @@ impl CreateMaterializedViewBuilder { namespace_path: self.namespace.clone(), query: self.query()?, with_no_data: self.with_no_data, + auto_refresh_enabled: self.auto_refresh_enabled, + auto_refresh_interval_seconds: self.auto_refresh_interval_seconds, }) .await; } @@ -1719,6 +1755,12 @@ impl CreateMaterializedViewBuilder { } async fn execute_native(self) -> Result { + if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { + return Err(Error::NotSupported { + message: "automatic materialized-view refresh requires Cloud or Enterprise" + .to_string(), + }); + } let source = self .connection .open_table(&self.source) diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a0f4aa953..4a8cbf32e 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -51,10 +51,6 @@ use super::table::RemoteTable; use super::util::parse_server_version; use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; -fn quote_sql_identifier(identifier: &str) -> String { - format!("\"{}\"", identifier.replace('"', "\"\"")) -} - // Request structure for the remote clone table API #[derive(serde::Serialize)] struct RemoteCloneTableRequest { @@ -67,6 +63,15 @@ struct RemoteCloneTableRequest { is_shallow: Option, } +#[derive(serde::Serialize)] +struct RemoteCreateMaterializedViewRequest { + query: String, + #[serde(skip_serializing_if = "Option::is_none")] + auto_refresh_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + auto_refresh_interval_seconds: Option, +} + // the versions of the server that we support // for any new feature that we need to change the SDK behavior, we should bump the server version, // and add a feature flag as method of `ServerVersion` here. @@ -877,16 +882,43 @@ impl Database for RemoteDatabase { .to_string(), }); } - let client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { - message: "SQL is unavailable for this remote database client".to_string(), + if let Some(seconds) = request.auto_refresh_interval_seconds + && (!seconds.is_finite() || seconds <= 0.0) + { + return Err(Error::InvalidInput { + message: "auto_refresh_interval_seconds must be positive, finite seconds".into(), + }); + } + let identifier = build_table_identifier(&request.name, &request.namespace_path)?; + let body = RemoteCreateMaterializedViewRequest { + query: request.query, + auto_refresh_enabled: request.auto_refresh_enabled, + auto_refresh_interval_seconds: request.auto_refresh_interval_seconds, + }; + let request = self + .client + .post(&format!("/v1/materialized_view/{identifier}/create")) + .json(&body); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let status = response.status(); + let body = response.text().await.err_to_http(request_id.clone())?; + if status != StatusCode::ACCEPTED { + return Err(Error::Http { + source: "materialized-view creation must return 202 Accepted".into(), + request_id, + status_code: Some(status), + }); + } + let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { + source: "materialized-view create response did not contain a valid job_id".into(), + request_id, + status_code: Some(status), })?; - let namespace = request.namespace_path; - let statement = format!( - "CREATE MATERIALIZED VIEW {} AS {}", - quote_sql_identifier(&request.name), - request.query - ); - Ok(client.submit_as_job(statement, namespace, || async { Ok(()) })) + Ok(Job::new(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) } async fn drop_materialized_view_async( @@ -1964,21 +1996,73 @@ mod tests { } #[tokio::test] - async fn test_create_materialized_view_requires_sql_client() { - let db = super::RemoteDatabase::new_mock(|request| -> http::Response { - panic!("unexpected REST request: {}", request.url().path()) - }); - let error = db - .create_materialized_view_async(CreateMaterializedViewRequest { - name: "adults".into(), - namespace_path: vec!["analytics".into()], - query: "SELECT age AS \"age\" FROM \"raw\".\"people\" WHERE age >= 18 LIMIT 10" - .into(), - with_no_data: false, - }) - .await - .unwrap_err(); - assert!(error.to_string().contains("SQL is unavailable")); + async fn test_create_materialized_view_uses_rest_and_preserves_optional_settings() { + for (enabled, interval) in [(None, None), (Some(true), None), (Some(false), Some(0.5))] { + let db = super::RemoteDatabase::new_mock(move |request| { + assert_eq!(request.method(), "POST"); + assert_eq!( + request.url().path(), + "/v1/materialized_view/analytics$adults/create" + ); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["query"], "SELECT * FROM people"); + assert_eq!( + body.get("auto_refresh_enabled"), + enabled.map(serde_json::Value::from).as_ref() + ); + assert_eq!( + body.get("auto_refresh_interval_seconds"), + interval.map(serde_json::Value::from).as_ref() + ); + http::Response::builder() + .status(202) + .body(serde_json::json!({"job_id": "j1-mv-create"}).to_string()) + .unwrap() + }); + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "adults".into(), + namespace_path: vec!["analytics".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: enabled, + auto_refresh_interval_seconds: interval, + }) + .await + .unwrap(); + assert_eq!(job.id(), Some("j1-mv-create")); + } + } + + #[tokio::test] + async fn test_create_materialized_view_rejects_invalid_acceptance() { + for (status, body) in [ + (200, r#"{"job_id":"j1"}"#), + (202, "{}"), + (202, r#"{"job_id":""}"#), + ] { + let db = super::RemoteDatabase::new_mock(move |_| { + http::Response::builder().status(status).body(body).unwrap() + }); + let error = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "adults".into(), + namespace_path: vec![], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .err() + .unwrap(); + assert!(error.to_string().contains(if status == 200 { + "202 Accepted" + } else { + "job_id" + })); + } } #[tokio::test] From dd4a527727e3409b2a329225d802be45ca48ee86 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 22 Oct 2026 16:13:27 +0800 Subject: [PATCH 014/180] fix(index): preserve registered scalar plugin type names (#4627) Native `list_indices()` drops registered scalar plugin types absent from LanceDB's fixed enum, and `index_stats()` reports them as `Unknown`. Preserve their registered display names through `IndexType::Custom(String)`. Resolve these names through Lance's shared `IndexDetails` registry entry point. Registered types such as MinHashLSH become visible; system and unregistered types remain excluded. Existing builtin aliases retain their canonical names. Rust consumers with exhaustive `IndexType` matches need to handle the added variant. Manual validation with [Lance #10224](https://github.com/lance-format/lance/pull/10224) at `fcc070f88a`: a downstream statistics-only plugin appears as `Custom("Sketch")` in native listing and statistics. Its `load_index` deliberately returns an error, and repeated calls do not construct additional plugin instances, verifying metadata-only lookup through the shared registry. --- rust/lancedb/src/index.rs | 30 +++++++++ rust/lancedb/src/table.rs | 10 +-- .../lancedb/tests/registered_scalar_plugin.rs | 66 +++++++++++++++++++ 3 files changed, 98 insertions(+), 8 deletions(-) create mode 100644 rust/lancedb/tests/registered_scalar_plugin.rs diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 82f8ad845..712a15fa0 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use chrono::{DateTime, Utc}; +use lance::index::scalar::IndexDetails; use scalar::FtsIndexBuilder; use serde::Deserialize; use serde_with::skip_serializing_none; @@ -382,10 +383,38 @@ pub enum IndexType { // FTS #[serde(alias = "INVERTED", alias = "Inverted")] FTS, + /// A registered scalar index plugin's display name, preserved verbatim. + /// + /// For example, `Custom("Sketch".into()).to_string()` returns `"Sketch"`. + Custom(String), /// Catch-all for index types not recognized by this version of LanceDB. Unknown, } +impl IndexType { + pub(crate) fn from_description( + description: &dyn lance_index::traits::IndexDescription, + ) -> Self { + let index_type = description.index_type().parse().unwrap_or(Self::Unknown); + if index_type != Self::Unknown { + return index_type; + } + let Some(metadata) = description.segments().first() else { + return Self::Unknown; + }; + if lance_index::is_system_index(metadata) { + return Self::Unknown; + } + let Some(details) = metadata.index_details.as_ref() else { + return Self::Unknown; + }; + IndexDetails(details.clone()) + .get_plugin() + .map(|plugin| Self::Custom(plugin.name().to_string())) + .unwrap_or(Self::Unknown) + } +} + impl std::fmt::Display for IndexType { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { @@ -405,6 +434,7 @@ impl std::fmt::Display for IndexType { Self::BloomFilter => write!(f, "BLOOM_FILTER"), Self::RTree => write!(f, "RTREE"), Self::FTS => write!(f, "FTS"), + Self::Custom(name) => f.write_str(name), Self::Unknown => write!(f, "UNKNOWN"), } } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 61a710dcd..39e6f1911 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -3821,10 +3821,7 @@ impl BaseTable for NativeTable { let mut indices: Vec = descriptions .iter() .filter_map(|idx_desc| { - let index_type: crate::index::IndexType = idx_desc - .index_type() - .parse() - .unwrap_or(crate::index::IndexType::Unknown); + let index_type = crate::index::IndexType::from_description(idx_desc.as_ref()); if index_type == crate::index::IndexType::Unknown { // Internal or future index types that this version doesn't recognize // (e.g. Lance's internal FragReuseIndex) are silently excluded from @@ -3960,10 +3957,7 @@ impl BaseTable for NativeTable { return Ok(None); }; - let index_type: crate::index::IndexType = description - .index_type() - .parse() - .unwrap_or(crate::index::IndexType::Unknown); + let index_type = crate::index::IndexType::from_description(description.as_ref()); let is_vector = matches!( index_type, diff --git a/rust/lancedb/tests/registered_scalar_plugin.rs b/rust/lancedb/tests/registered_scalar_plugin.rs new file mode 100644 index 000000000..2f5620cc8 --- /dev/null +++ b/rust/lancedb/tests/registered_scalar_plugin.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{RecordBatchIterator, record_batch}; +use lance::{Dataset, index::DatasetIndexExt}; +use lance_index::scalar::ScalarIndexParams; +use lancedb::index::IndexType; + +// MinHashLSH is a registered scalar plugin without a LanceDB IndexType variant. +// It exercises the same metadata-only fallback as a downstream plugin. +#[tokio::test] +async fn list_registered_scalar_plugin_with_its_type_name() { + let directory = tempfile::tempdir().unwrap(); + let batch = record_batch!(( + "value", + Utf8, + ["alpha beta", "beta gamma", "gamma delta", "delta alpha"] + )) + .unwrap(); + let mut dataset = Dataset::write( + RecordBatchIterator::new([Ok(batch.clone())], batch.schema()), + directory.path().join("test.lance").to_str().unwrap(), + None, + ) + .await + .unwrap(); + dataset + .create_index_builder( + &["value"], + lance_index::IndexType::Scalar, + &ScalarIndexParams::new("minhashlsh".into()), + ) + .name("profile".into()) + .train(false) + .await + .unwrap(); + + let connection = lancedb::connect(directory.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = connection.open_table("test").execute().await.unwrap(); + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!(indices[0].name, "profile"); + assert_eq!( + indices[0].index_type, + IndexType::Custom("MinHashLsh".into()) + ); + assert_eq!(indices[0].index_type.to_string(), "MinHashLsh"); + assert_eq!(indices[0].columns, ["value"]); + assert!( + indices[0] + .type_url + .as_deref() + .unwrap() + .ends_with("MinHashLshIndexDetails") + ); + let statistics = table.index_stats("profile").await.unwrap().unwrap(); + assert_eq!( + statistics.index_type, + IndexType::Custom("MinHashLsh".into()) + ); + assert_eq!(statistics.num_indexed_rows, 0); + assert_eq!(statistics.num_unindexed_rows, 4); +} From a5079b0fc6c47100f8f5030b8dd99e40c9d576de Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 22 Oct 2026 19:41:40 +0800 Subject: [PATCH 015/180] chore: update lance dependency to v15.0.0-beta.1 (#4628) --- .github/workflows/npm-publish.yml | 32 +++---- Cargo.lock | 152 +++++++++++++++++++++--------- Cargo.toml | 28 +++--- docs/web/indexing/fts-index.mdx | 8 +- java/pom.xml | 2 +- rust/lancedb/src/index/scalar.rs | 11 +++ 6 files changed, 154 insertions(+), 79 deletions(-) diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index c3724de8d..a8dd3993e 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -71,9 +71,9 @@ jobs: # https://github.com/napi-rs/napi-rs/blob/main/debian.Dockerfile docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian pre_build: |- - set -e && - apt-get update && - apt-get install -y protobuf-compiler pkg-config && + set -e + apt-get update + apt-get install -y protobuf-compiler pkg-config # The base image (manylinux2014-cross) sets TARGET_CC to the old # GCC 4.8 cross-compiler. aws-lc-sys checks TARGET_CC before CC, # so it picks up GCC even though the napi-rs image sets CC=clang. @@ -84,10 +84,10 @@ jobs: host: ubuntu-2404-8x-x64 features: fp16kernels pre_build: |- - set -e && - sudo apt-get update && - sudo apt-get install -y protobuf-compiler pkg-config && - rustup target add x86_64-unknown-linux-musl && + set -e + sudo apt-get update + sudo apt-get install -y protobuf-compiler pkg-config + rustup target add x86_64-unknown-linux-musl export EXTRA_ARGS="-x" - target: aarch64-unknown-linux-gnu host: ubuntu-2404-8x-x64 @@ -103,13 +103,13 @@ jobs: # linker process 7.0 -> 4.0 GiB (lancedb/sophon#7313). linker: /tmp/aarch64-lld-clang pre_build: |- - set -e && - apt-get update && - apt-get install -y protobuf-compiler pkg-config && - export TARGET_CC=clang TARGET_CXX=clang++ && + set -e + apt-get update + apt-get install -y protobuf-compiler pkg-config + export TARGET_CC=clang TARGET_CXX=clang++ # The manylinux2014 sysroot has glibc 2.17 headers which lack # AT_HWCAP2 (added in Linux 3.17). Define it for aws-lc-sys. - export CFLAGS="$CFLAGS -DAT_HWCAP2=26" && + export CFLAGS="$CFLAGS -DAT_HWCAP2=26" rustup target add aarch64-unknown-linux-gnu # Not `&&`-chained: in dash, errexit does not fire for a # non-final command in an `&&` list, so failures were ignored. @@ -136,10 +136,10 @@ jobs: lto: thin codegen_units: 16 pre_build: |- - set -e && - sudo apt-get update && - sudo apt-get install -y protobuf-compiler && - rustup target add aarch64-unknown-linux-musl && + set -e + sudo apt-get update + sudo apt-get install -y protobuf-compiler + rustup target add aarch64-unknown-linux-musl export EXTRA_ARGS="-x" name: build - ${{ matrix.settings.target }} runs-on: ${{ matrix.settings.host }} diff --git a/Cargo.lock b/Cargo.lock index 3b4086203..c72df37e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3584,8 +3584,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5059,8 +5059,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arc-swap", "arrow", @@ -5135,8 +5135,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-buffer", @@ -5158,7 +5158,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-buffer", @@ -5172,7 +5172,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-schema", @@ -5181,8 +5181,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrayref", "crunchy", @@ -5192,8 +5192,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-buffer", @@ -5230,8 +5230,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow", "arrow-array", @@ -5262,8 +5262,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow", "arrow-array", @@ -5280,8 +5280,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "proc-macro2", "quote", @@ -5290,8 +5290,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-arith", "arrow-array", @@ -5324,8 +5324,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-arith", "arrow-array", @@ -5357,8 +5357,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "datafusion", "geo-traits", @@ -5372,8 +5372,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arc-swap", "arrow", @@ -5387,6 +5387,7 @@ dependencies = [ "async-recursion", "async-trait", "bitvec", + "blake3", "bytes", "crossbeam-queue", "datafusion", @@ -5421,6 +5422,7 @@ dependencies = [ "lance-tokenizer", "libsais-rs", "log", + "nalgebra", "ndarray", "num-traits", "object_store 0.14.2", @@ -5444,8 +5446,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-schema", @@ -5468,8 +5470,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow", "arrow-array", @@ -5512,8 +5514,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "byteorder", "ethnum", @@ -5530,8 +5532,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-schema", @@ -5545,8 +5547,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow", "async-trait", @@ -5560,8 +5562,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arc-swap", "arrow", @@ -5615,8 +5617,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-buffer", @@ -5630,8 +5632,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow", "arrow-array", @@ -5671,8 +5673,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-schema", @@ -5685,8 +5687,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "14.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v14.0.0-beta.23#ea81833500fe251568854dfd889524bc4ebcbaea" +version = "15.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "frostem", "icu_segmenter", @@ -6411,6 +6413,21 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "nalgebra" +version = "0.33.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d43ddcacf343185dfd6de2ee786d9e8b1c2301622afab66b6c73baf9882abfd" +dependencies = [ + "approx", + "matrixmultiply", + "num-complex", + "num-rational", + "num-traits", + "simba", + "typenum", +] + [[package]] name = "napi" version = "3.12.5" @@ -6650,6 +6667,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -9268,6 +9296,15 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3944826ff8fa8093089aba3acb4ef44b9446a99a16f3bf4e74af3f77d340ab7d" +[[package]] +name = "safe_arch" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" +dependencies = [ + "bytemuck", +] + [[package]] name = "safetensors" version = "0.7.0" @@ -9676,6 +9713,19 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simba" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c99284beb21666094ba2b75bbceda012e610f5479dfcc2d6e2426f53197ffd95" +dependencies = [ + "approx", + "num-complex", + "num-traits", + "paste", + "wide", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -11182,6 +11232,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wide" +version = "0.7.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" +dependencies = [ + "bytemuck", + "safe_arch", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/Cargo.toml b/Cargo.toml index 49f7ea6a6..3ac246149 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.94.0" [workspace.dependencies] -lance = { "version" = "=14.0.0-beta.23", default-features = false, "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=14.0.0-beta.23", default-features = false, "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=14.0.0-beta.23", default-features = false, "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=14.0.0-beta.23", "tag" = "v14.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/docs/web/indexing/fts-index.mdx b/docs/web/indexing/fts-index.mdx index 832b67315..4660e8b01 100644 --- a/docs/web/indexing/fts-index.mdx +++ b/docs/web/indexing/fts-index.mdx @@ -99,7 +99,7 @@ await async_table.create_index("payload.text", config=FTS(with_position=True)) | `stem` | bool | `True` | Apply stemming (`running` → `run`) | | `remove_stop_words` | bool | `True` | Drop common stop words | | `ascii_folding` | bool | `True` | Normalize accented characters | -| `custom_stop_words` | list[str] | `None` | Extra stop words to drop in addition to the language defaults. Requires `remove_stop_words=True`. | +| `custom_stop_words` | list[str] | `None` | Explicit stop-word list that replaces the built-in list. Requires `remove_stop_words=True`. | | `ngram_min_length` | int | `3` | Minimum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `ngram_max_length` | int | `3` | Maximum n-gram length. Applies only when `base_tokenizer="ngram"`. | | `prefix_only` | bool | `False` | Index only prefix n-grams rather than all substrings. Applies only when `base_tokenizer="ngram"`. | @@ -123,7 +123,11 @@ await async_table.create_index("payload.text", config=FTS(with_position=True)) Model-backed tokenizers such as `jieba/default`, `lindera/ipadic`, and `lindera/ko-dic` require tokenizer model files in Lance's language model home. Lance looks under the default platform data directory for `lance/language_models`, or you can set `LANCE_LANGUAGE_MODEL_HOME` to point to another model root. For example, `jieba/default` is resolved under `/jieba/default/...`. For a table in LanceDB Enterprise, the files must be present where the deployment builds and queries the index, so ask its administrator whether they are installed. -`language` is used by token filters, not by the base tokenizer. Stemming supports Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. Built-in stop-word removal supports Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Portuguese, Russian, Spanish, and Swedish. For other stemming languages, set `remove_stop_words=False` or pass `custom_stop_words`. +`language` is used by token filters, not by the base tokenizer. Stemming and language-specific stop-word removal support Arabic, Danish, Dutch, English, Finnish, French, German, Greek, Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish, Swedish, Tamil, and Turkish. The ICU tokenizer uses a combined multilingual stop-word list. An explicit `custom_stop_words` list replaces the built-in list for either tokenizer. + + +Lance `15.0.0-beta.1` revises the built-in stop-word lists, including the multilingual list used by ICU. Existing index metadata records tokenizer settings, but does not freeze these built-in lists. Rebuild affected FTS indexes with the same configuration before serving queries with the updated SDK, so stored terms and query tokens use the same lists. Indexes with stop-word removal disabled or an explicit `custom_stop_words` list are unaffected by this change. + ### Posting block size {#posting-block-size} diff --git a/java/pom.xml b/java/pom.xml index db0ee33d7..5cc7e365e 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 14.0.0-beta.23 + 15.0.0-beta.1 2.18.11 false 2.30.0 diff --git a/rust/lancedb/src/index/scalar.rs b/rust/lancedb/src/index/scalar.rs index 5bfc2b4e6..5d2256381 100644 --- a/rust/lancedb/src/index/scalar.rs +++ b/rust/lancedb/src/index/scalar.rs @@ -65,6 +65,17 @@ pub struct FmIndexBuilder {} /// A ZoneMap index stores min/max summaries for ranges of rows and can /// accelerate range predicates by pruning zones that cannot match. /// +/// ZoneMap indexes use per-fragment write seeds by default for strings, binary +/// data, and supported types wider than eight bytes. Creating a seed-enabled +/// index activates a table capability immediately, before any version 1 seed +/// is written. A mutation retaining a legacy seed-enabled index also activates +/// it. Older clients cannot read or write the resulting snapshots, so upgrade +/// all readers and writers before creating such an index or mutating a table +/// that already has one. The capability +/// remains set in subsequent snapshots, including after dropping the index or +/// restoring an older version; dropping the index does not restore access for +/// older clients. Opening a table alone does not activate the capability. +/// /// ``` /// use lancedb::{ /// index::{scalar::ZoneMapIndexBuilder, Index}, From 9f0f6400bc3490962542fff9e3f0ce26da1182a1 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Thu, 22 Oct 2026 11:53:10 +0000 Subject: [PATCH 016/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.12=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index f2c9e44e1..0909579cb 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.12" +current_version = "0.41.0-beta.13" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index c72df37e3..7f36dc088 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5701,7 +5701,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.12" +version = "0.41.0-beta.13" dependencies = [ "ahash", "anyhow", @@ -5799,7 +5799,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.12" +version = "0.41.0-beta.13" dependencies = [ "arrow-array", "arrow-buffer", @@ -5824,7 +5824,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.12" +version = "0.41.0-beta.13" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 5c1874e6f..0c887f66f 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.12 + 0.41.0-beta.13 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index ad5adbc92..87c5d4cb8 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.12 + 0.41.0-beta.13 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 5cc7e365e..1f3e0efb0 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.12 + 0.41.0-beta.13 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 85ee5df04..1b9d47e46 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.12" +version = "0.41.0-beta.13" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 080340224..bd4b95463 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index a2b5b8bf6..6e4e57684 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 96bda03c7..f77c50ee2 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index edd596044..b671b7ebf 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 953c46250..b75738ff1 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 236d356be..7158748f9 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 205f0ee11..83d0fb6f2 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 023c4e400..9bade7200 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.12", + "version": "0.41.0-beta.13", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index e6a0e457a..ad1790a99 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.12" +version = "0.41.0-beta.13" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 5e6dd315f..486eb1e8e 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.12" +version = "0.41.0-beta.13" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From ba7b7f15c2a576062a480e6863abfa092b6e0e58 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:07:18 +0800 Subject: [PATCH 017/180] fix(node): reject musl binaries with unresolved AVX-512 symbol (#3791) ## Summary - inspect the assembled x64 musl addon for the unresolved AVX-512 distance-table symbol before npm publication - fail the publish lifecycle with an actionable error if the broken symbol is present - add regression coverage using the dynamic-symbol output from the affected 0.27.x artifact ## Root cause LanceDB 0.27.x could enable the Rust AVX-512 distance-table callsite when the separate C kernel build did not emit its object, leaving `sum_4bit_dist_table_32bytes_batch_avx512` undefined in the musl addon. The current Lance dependency includes the upstream split-kernel cfg fix, and the published 0.33.0 musl artifact no longer has the undefined symbol, but the LanceDB publish path did not verify that property before releasing an addon. This adds a release guard around the corrected implementation so the same invalid binary cannot be published again. ## Validation - `pnpm lint` - `pnpm run build` - `pnpm test --runInBand` (680 passed, 5 skipped) - `pnpm run docs` - checked published artifacts: 0.27.1 is rejected for the unresolved symbol; 0.33.0 is accepted Fixes #3200 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- nodejs/.npmignore | 1 + nodejs/__test__/native_symbols.test.ts | 47 ++++++++++++++++ nodejs/package.json | 3 +- nodejs/scripts/check-native-symbols.js | 77 ++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 1 deletion(-) create mode 100644 nodejs/__test__/native_symbols.test.ts create mode 100644 nodejs/scripts/check-native-symbols.js diff --git a/nodejs/.npmignore b/nodejs/.npmignore index 41f6643a6..128c0d36d 100644 --- a/nodejs/.npmignore +++ b/nodejs/.npmignore @@ -15,6 +15,7 @@ renovate.json src lancedb examples +scripts nodejs-artifacts Cargo.toml biome.json diff --git a/nodejs/__test__/native_symbols.test.ts b/nodejs/__test__/native_symbols.test.ts new file mode 100644 index 000000000..5445867f6 --- /dev/null +++ b/nodejs/__test__/native_symbols.test.ts @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const { + checkNativeBinary, + findForbiddenUndefinedSymbols, +} = require("../scripts/check-native-symbols.js"); + +test("detects the unresolved AVX-512 symbol from broken musl binaries", () => { + const output = [ + " U napi_create_function", + " U sum_4bit_dist_table_32bytes_batch_avx512", + " U strlen", + ].join("\n"); + + expect(findForbiddenUndefinedSymbols(output)).toEqual([ + "sum_4bit_dist_table_32bytes_batch_avx512", + ]); +}); + +test("accepts native binaries without unresolved internal Lance symbols", () => { + const runNm = jest.fn(() => ({ + status: 0, + stdout: + " U napi_create_function\n U strlen\n", + stderr: "", + })); + + expect(() => checkNativeBinary("lancedb.node", runNm)).not.toThrow(); + expect(runNm).toHaveBeenCalledWith( + "nm", + ["-D", "--undefined-only", "lancedb.node"], + { encoding: "utf8" }, + ); +}); + +test("rejects native binaries with the unresolved AVX-512 symbol", () => { + const runNm = jest.fn(() => ({ + status: 0, + stdout: " U sum_4bit_dist_table_32bytes_batch_avx512\n", + stderr: "", + })); + + expect(() => checkNativeBinary("lancedb.node", runNm)).toThrow( + "lancedb.node contains unresolved internal Lance symbols: sum_4bit_dist_table_32bytes_batch_avx512", + ); +}); diff --git a/nodejs/package.json b/nodejs/package.json index 9bade7200..21f903235 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -90,7 +90,8 @@ "postdocs": "node typedoc_post_process.js", "lint": "biome check . && biome format .", "lint-fix": "biome check --write . && biome format --write .", - "prepublishOnly": "napi prepublish -t npm", + "check:native-symbols": "node scripts/check-native-symbols.js", + "prepublishOnly": "pnpm check:native-symbols && napi prepublish -t npm", "test": "jest --verbose", "integration": "S3_TEST=1 pnpm test", "universal": "napi universalize", diff --git a/nodejs/scripts/check-native-symbols.js b/nodejs/scripts/check-native-symbols.js new file mode 100644 index 000000000..2f6dbf9b8 --- /dev/null +++ b/nodejs/scripts/check-native-symbols.js @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const { spawnSync } = require("node:child_process"); +const { existsSync } = require("node:fs"); +const path = require("node:path"); + +const FORBIDDEN_UNDEFINED_SYMBOLS = new Set([ + "sum_4bit_dist_table_32bytes_batch_avx512", +]); + +function findForbiddenUndefinedSymbols(output) { + const found = new Set(); + + for (const line of output.split(/\r?\n/)) { + const columns = line.trim().split(/\s+/); + const symbol = columns.at(-1)?.split("@")[0]; + if (symbol && FORBIDDEN_UNDEFINED_SYMBOLS.has(symbol)) { + found.add(symbol); + } + } + + return [...found].sort(); +} + +function checkNativeBinary(binaryPath, runNm = spawnSync) { + const result = runNm("nm", ["-D", "--undefined-only", binaryPath], { + encoding: "utf8", + }); + + if (result.error) { + throw new Error(`Unable to inspect ${binaryPath}: ${result.error.message}`); + } + if (result.status !== 0) { + throw new Error( + `Unable to inspect ${binaryPath}: nm exited with status ${result.status}\n${result.stderr}`, + ); + } + + const forbidden = findForbiddenUndefinedSymbols(result.stdout); + if (forbidden.length > 0) { + throw new Error( + `${binaryPath} contains unresolved internal Lance symbols: ${forbidden.join( + ", ", + )}`, + ); + } +} + +function main() { + const binaryPath = path.resolve( + __dirname, + "..", + "npm", + "linux-x64-musl", + "lancedb.linux-x64-musl.node", + ); + + if (!existsSync(binaryPath)) { + throw new Error( + `Missing ${binaryPath}; assemble the native artifacts before publishing`, + ); + } + + checkNativeBinary(binaryPath); +} + +if (require.main === module) { + try { + main(); + } catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + } +} + +module.exports = { checkNativeBinary, findForbiddenUndefinedSymbols }; From a98667749d923512c1f26b65167da5aea0c6669c Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:09:01 +0800 Subject: [PATCH 018/180] fix(python): verify Lance-created IVF_RQ compatibility (#3793) ## Summary - add regression coverage for an IVF_RQ index created through the Lance Python API and consumed through LanceDB - verify a fresh LanceDB handle can list and query the externally-created index ## Root cause Lance 4.0.0-beta.5 could serialize `rotate_mat_position` as null, while the Lance 2.0.0 reader used by LanceDB 0.29.2 required a `u32`. Upstream Lance fixed the incompatible IVF_RQ metadata handling and index versioning, and the current LanceDB dependency includes that repair. LanceDB was missing coverage for the reported mixed-API workflow, allowing the compatibility regression to go undetected. ## Validation - `cd python && uv run --extra tests pytest python/tests/test_index.py -q` (24 passed) - `uv run --project python --extra dev ruff format .` - `uv run --project python --extra dev ruff check .` - `uv run --project python --extra dev ruff format --check python/python/tests/test_index.py` - `uv run --project python --extra dev ruff check python/python/tests/test_index.py` Fixes #3092 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/tests/test_index.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index fe6ebe87a..0252a09ad 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -430,6 +430,28 @@ async def test_create_ivfrq_index(some_table: AsyncTable): assert indices[0].name == "vector_idx" +@pytest.mark.asyncio +async def test_read_ivfrq_index_created_with_lance(db_async, some_table: AsyncTable): + pytest.importorskip("lance") + dataset = await some_table.to_lance() + dataset.create_index( + "vector", + index_type="IVF_RQ", + metric="cosine", + num_partitions=1, + ) + + # Open a fresh LanceDB handle so the index is discovered from disk. + table = await db_async.open_table("some_table") + indices = await table.list_indices() + assert len(indices) == 1 + assert indices[0].index_type == "IvfRq" + assert indices[0].columns == ["vector"] + + results = await table.query().nearest_to(list(range(DIM))).limit(8).to_arrow() + assert len(results) == 8 + + @pytest.mark.asyncio async def test_create_hnswpq_index(some_table: AsyncTable): await some_table.create_index("vector", config=HnswPq(num_partitions=10)) From 102518ebda39513aa0bf337be96706df5ad558a0 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:09:16 +0800 Subject: [PATCH 019/180] fix(python): preserve nested fields in filtered scans (#3816) ## Summary - add a Python regression for filtered scans over deeply nested list/struct values - verify the public query path returns every nested sibling field without an Arrow schema mismatch ## Root cause Older Lance scanner code split filter projections into partial nested arrays and did not recursively merge List children, so a sibling field could be omitted from the returned array while remaining in the declared schema. That merge was fixed upstream in lance-format/lance#4838, and the Lance revision currently pinned by LanceDB contains that fix. This test makes the repair durable at the LanceDB Python API boundary. ## Validation - cd python && uv run --extra tests pytest python/tests/test_query.py::test_filter_preserves_deeply_nested_struct_fields -q - cd python && uv run --extra tests pytest python/tests/test_query.py -q - uv run --project python --extra tests --extra dev ruff check . - uv run --project python --extra tests --extra dev ruff format --check python/python/tests/test_query.py Fixes #2217 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/tests/test_query.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index c8d0ad159..58ea7deb5 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -833,6 +833,28 @@ def test_with_row_id(table: lancedb.table.Table): assert rs["_rowid"].to_pylist() == [0, 1] +def test_filter_preserves_deeply_nested_struct_fields(tmp_db): + # Regression test for https://github.com/lancedb/lancedb/issues/2217. + data = [ + { + "item": "test", + "sub_obj": { + "second_sub_obj": [ + { + "third_sub_obj": {"int_val": 1}, + "str_val": "test", + } + ] + }, + } + ] + table = tmp_db.create_table("deeply_nested_struct", data=data) + + result = table.search().where("item = 'test'").limit(1).to_arrow() + + assert result.to_pylist() == data + + def test_blob_v2_query_omits_auto_row_id(tmp_db): table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_omits_auto_rowid") From 40af9f350e785d762cc887e029718fc9904bbe0b Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:09:32 +0800 Subject: [PATCH 020/180] fix(python): avoid deadlock for query-backed iterators (#3820) ## Summary - move synchronous iterator preparation off LanceDB's singleton background event loop - keep the loop available when an input iterator executes a synchronous table query - cover query-backed iterators for both `Table.add` and `create_table` ## Root cause The async implementations prepared input data on the singleton background loop and peeked at the first item of iterators there. If that iterator called a synchronous LanceDB query, `LOOP.run()` scheduled the query on the same loop and blocked waiting for it, so neither operation could progress. ## Validation - `ruff format` on the changed Python files - `ruff check .` - `cd python && uv run --frozen --extra tests pytest python/tests/test_table.py -q` (138 passed) - the broader non-slow suite was attempted but hit a native segmentation fault in the external DataFusion `register_table_provider` path; an isolated control using the pre-change inline preparation behavior reproduced the same unrelated crash Fixes #2107 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/db.py | 13 +++++++++++-- python/python/lancedb/table.py | 16 ++++++++++++---- python/python/tests/test_table.py | 24 ++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 5def89b01..e1e5d270a 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -5,6 +5,7 @@ from __future__ import annotations from abc import abstractmethod +import asyncio from datetime import timedelta from pathlib import Path import sys @@ -2652,8 +2653,16 @@ class AsyncConnection(object): if fill_value is None: fill_value = 0.0 - data, schema = sanitize_create_table( - data, schema, metadata, on_bad_vectors, fill_value + # Input preparation may advance a user-provided iterator. Keep that work + # off the background event loop so an iterator can use the synchronous + # LanceDB API without blocking the loop that API needs to make progress. + data, schema = await asyncio.to_thread( + sanitize_create_table, + data, + schema, + metadata, + on_bad_vectors, + fill_value, ) validate_schema(schema) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index d5872e6f0..006ef8cb9 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -6213,8 +6213,12 @@ class AsyncTable: if mode == "overwrite": # For overwrite, apply the same preprocessing as create_table # so vector columns are inferred as FixedSizeList. - data, _ = sanitize_create_table( - data, None, on_bad_vectors=on_bad_vectors, fill_value=fill_value + data, _ = await asyncio.to_thread( + sanitize_create_table, + data, + None, + on_bad_vectors=on_bad_vectors, + fill_value=fill_value, ) if blob_v2_column_paths(schema): # Plain bytes cannot be inferred as blob v2. Keep matching blob @@ -6224,7 +6228,8 @@ class AsyncTable: elif on_bad_vectors != "error" or ( schema.metadata is not None and b"embedding_functions" in schema.metadata ): - data = _sanitize_data( + data = await asyncio.to_thread( + _sanitize_data, data, schema, metadata=schema.metadata, @@ -6233,7 +6238,10 @@ class AsyncTable: allow_subschema=True, ) _register_optional_converters() - data = to_scannable(data) + # Converting an iterator peeks at its first item. A synchronous query in + # that iterator schedules work on LOOP, so peeking on LOOP's own thread + # would deadlock waiting for itself. + data = await asyncio.to_thread(to_scannable, data) progress, owns = _normalize_progress(progress) try: return await self._inner.add( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 755e94d7f..095f0b911 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -518,6 +518,30 @@ def test_add(mem_db: DBConnection): _add(table, schema) +def test_add_from_iterator_that_queries_table(mem_db: DBConnection): + source = mem_db.create_table("source", data=pa.table({"id": range(16)})) + target = mem_db.create_table("target", schema=source.schema) + + def batches(): + for _ in range(5): + yield source.search().limit(10).to_arrow() + + target.add(batches()) + + assert target.count_rows() == 50 + + +def test_create_table_from_iterator_that_queries_table(mem_db: DBConnection): + source = mem_db.create_table("source", data=pa.table({"id": range(16)})) + + def batches(): + yield source.search().limit(10).to_arrow() + + target = mem_db.create_table("target", data=batches()) + + assert target.count_rows() == 10 + + def test_add_releases_arrow_buffers_without_gc(mem_db: DBConnection): """Regression test for https://github.com/lancedb/lancedb/issues/2512.""" schema = pa.schema([pa.field("x", pa.int64())]) From a1230cf9a490c1768cbec2709edf772543d27331 Mon Sep 17 00:00:00 2001 From: Li Zinuo Date: Fri, 23 Oct 2026 01:09:46 +0800 Subject: [PATCH 021/180] fix: preserve unbounded plain queries in namespace pushdown (#3927) ## What Preserve unbounded plain-query semantics in the Rust Namespace `QueryTable` adapter. Plain queries without an explicit limit are now encoded with `i32::MAX`. Explicit limits remain unchanged, while vector and FTS queries continue to use the default top-k of 10. ## Root cause The Rust Namespace adapter converted a missing limit using: ```rust q.limit.unwrap_or(10) ``` This turned an unbounded plain query into an explicit `k=10`, silently truncating the results returned by Namespace pushdown. ## Tests Added regression coverage for unbounded and explicitly limited plain queries, while verifying that vector and FTS queries retain their default limit. ```shell cargo fmt --all -- --check cargo test --quiet --features remote -p lancedb \ test_convert_to_namespace_query --lib ``` close #3926. --- rust/lancedb/src/table/query.rs | 56 ++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index cf70c6626..f625a4aff 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -671,6 +671,12 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { }); } + let k = match q.limit { + Some(limit) => limit as i32, + None if q.full_text_search.is_some() => DEFAULT_TOP_K as i32, + None => i32::MAX, + }; + let filter = q.filter.as_ref().map(filter_to_sql).transpose()?; let columns = match &q.select { @@ -723,7 +729,7 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { Ok(NsQueryTableRequest { id: None, // Will be set by caller vector, - k: q.limit.unwrap_or(10) as i32, + k, filter, columns, prefilter: Some(q.prefilter), @@ -1073,6 +1079,54 @@ mod tests { assert!(ns_request.vector.single_vector.as_ref().unwrap().is_empty()); } + #[test] + fn test_convert_to_namespace_query_plain_query_without_limit() { + let any_query = AnyQuery::Query(QueryRequest::default()); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, i32::MAX); + } + + #[test] + fn test_convert_to_namespace_query_plain_query_with_explicit_limit() { + let any_query = AnyQuery::Query(QueryRequest { + limit: Some(10), + ..Default::default() + }); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, 10); + } + + #[test] + fn test_convert_to_namespace_query_vector_without_limit() { + let query_vector = Arc::new(Float32Array::from(vec![1.0, 2.0, 3.0, 4.0])); + let any_query = AnyQuery::VectorQuery(VectorQueryRequest { + query_vector: vec![query_vector as ArrayRef], + ..Default::default() + }); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, 10); + } + + #[test] + fn test_convert_to_namespace_query_fts_without_limit() { + let any_query = AnyQuery::Query(QueryRequest { + full_text_search: Some(lance_index::scalar::FullTextSearchQuery::new( + "hello world".to_string(), + )), + ..Default::default() + }); + + let ns_request = convert_to_namespace_query(&any_query).unwrap(); + + assert_eq!(ns_request.k, 10); + } + #[tokio::test] async fn test_execute_query_local_routing() { use crate::connect; From 548a1903216075756ae7e6e6eecb671a78f38dd8 Mon Sep 17 00:00:00 2001 From: primorLee Date: Fri, 23 Oct 2026 01:10:00 +0800 Subject: [PATCH 022/180] fix(python): refresh zero-lifetime OAuth tokens (#3971) ## Summary - treat an OAuth `expires_in` value of zero as an explicit immediate expiration - refresh zero-lifetime tokens instead of caching them indefinitely - add a regression test covering two consecutive header requests ## Tests - `pytest python/tests/test_header_provider.py -q` (16 passed) - `ruff format --check python/lancedb/remote/header.py python/tests/test_header_provider.py` - `ruff check python/lancedb/remote/header.py python/tests/test_header_provider.py` --- python/python/lancedb/remote/header.py | 2 +- python/python/tests/test_header_provider.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/remote/header.py b/python/python/lancedb/remote/header.py index 206b7a7cb..5f5bd12d8 100644 --- a/python/python/lancedb/remote/header.py +++ b/python/python/lancedb/remote/header.py @@ -141,7 +141,7 @@ class OAuthProvider(HeaderProvider): # Set expiration if provided expires_in = token_data.get("expires_in") - if expires_in: + if expires_in is not None: self._token_expires_at = time.time() + expires_in else: # Token doesn't expire or expiration unknown diff --git a/python/python/tests/test_header_provider.py b/python/python/tests/test_header_provider.py index 187b0a50a..e50ff3270 100644 --- a/python/python/tests/test_header_provider.py +++ b/python/python/tests/test_header_provider.py @@ -114,6 +114,24 @@ class TestOAuthProvider: "x-lancedb-credential-type": "oidc", } + def test_zero_lifetime_token_is_refreshed(self): + """A token that expires immediately must not be cached indefinitely.""" + call_count = 0 + + def fetcher(): + nonlocal call_count + call_count += 1 + return { + "access_token": f"token{call_count}", + "expires_in": 0, + } + + provider = OAuthProvider(fetcher, refresh_buffer_seconds=0) + + assert provider.get_headers() == {"Authorization": "Bearer token1"} + assert provider.get_headers() == {"Authorization": "Bearer token2"} + assert call_count == 2 + def test_missing_access_token(self): """Test error handling when access_token is missing.""" From 6d92307fc34b81adc0c040da367c6f9b64f0aeba Mon Sep 17 00:00:00 2001 From: Zhewen Tan <1090179959@qq.com> Date: Fri, 23 Oct 2026 01:10:15 +0800 Subject: [PATCH 023/180] fix(python): accept tuple and Arrow vector queries (#3972) ## Summary Sync `Table.search()` declares tuple, `pyarrow.Array`, and `pyarrow.ChunkedArray` query vectors as supported, and the async query path already accepts them. The sync query builder only classified lists and NumPy arrays as vectors, however, so these inputs were routed through embedding/FTS resolution and then rejected. Arrow and tuple inputs also did not contribute a query dimension when selecting among multiple vector columns. This change: - recognizes the supported tuple and Arrow containers as sync vector queries for both `auto` and explicit `vector` query types; - converts them to the existing internal `float32` NumPy representation at the sync builder boundary; - infers dimensions from tuple, primitive Arrow, and list-valued Arrow queries so schemas with differently sized vector columns select the matching column. The regression test uses two vector columns with dimensions 2 and 3. It verifies tuple, Arrow array, and chunked Arrow queries through both sync query modes and confirms the dimension-2 column is selected. ## Test plan - `pytest python/tests/test_table.py::test_sync_search_accepts_supported_vector_containers -q` (6 passed) - `pytest python/tests/test_util.py python/tests/test_query.py python/tests/test_table.py -q -m "not slow and not s3_test"` (308 passed, 1 skipped, 1 deselected) - `pytest python/tests -q -m "not slow and not s3_test" --ignore=python/tests/docs` (981 passed, 25 skipped, 65 deselected) - `ruff format --check python` - `ruff check python` - `cargo fmt --all --check` Co-authored-by: Xuanwo --- python/python/lancedb/query.py | 9 +++++--- python/python/lancedb/util.py | 11 +++++++++- python/python/tests/test_table.py | 36 +++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index c427820e8..53f56a2c0 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -82,6 +82,7 @@ if TYPE_CHECKING: T = TypeVar("T", bound="LanceModel") AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"] +_SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray) # Number of rows a hybrid query returns when no limit was set on it. This # mirrors the default the Rust query builder applies to its sub-queries. @@ -1024,10 +1025,12 @@ class LanceQueryBuilder(ABC): fast_search=fast_search, ) - if isinstance(query, list): + if isinstance(query, (list, tuple)): query = np.array(query, dtype=np.float32) elif isinstance(query, np.ndarray): query = query.astype(np.float32) + elif isinstance(query, (pa.Array, pa.ChunkedArray)): + query = np.array(query.to_pylist(), dtype=np.float32) else: raise TypeError(f"Unsupported query type: {type(query)}") @@ -1049,7 +1052,7 @@ class LanceQueryBuilder(ABC): query = cls._query_to_vector(table, query, vector_column_name) return query, query_type elif query_type == "auto": - if isinstance(query, (list, np.ndarray)): + if isinstance(query, _SYNC_VECTOR_QUERY_TYPES): return query, "vector" else: conf = table.embedding_functions.get(vector_column_name) @@ -1065,7 +1068,7 @@ class LanceQueryBuilder(ABC): @classmethod def _query_to_vector(cls, table, query, vector_column_name): - if isinstance(query, (list, np.ndarray)): + if isinstance(query, _SYNC_VECTOR_QUERY_TYPES): return query conf = table.embedding_functions.get(vector_column_name) if conf is not None: diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index d4533887b..3babc3872 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -309,7 +309,16 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]: if query.ndim == 0: return None return query.shape[-1] - if isinstance(query, list) and query: + if isinstance(query, (pa.Array, pa.ChunkedArray)): + if len(query) == 0: + return None + if pa.types.is_fixed_size_list(query.type): + return query.type.list_size + if pa.types.is_list(query.type) or pa.types.is_large_list(query.type): + first = query[0].as_py() + return len(first) if first is not None else None + return len(query) + if isinstance(query, (list, tuple)) and query: first = query[0] if isinstance(first, (list, tuple, np.ndarray)): return len(first) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 095f0b911..7a4f5981c 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3697,6 +3697,42 @@ def test_multiple_vector_columns(mem_db: DBConnection): assert result1["text"][0] != result2["text"][0] +@pytest.mark.parametrize( + "query", + [ + (0.0, 0.0), + pa.array([0.0, 0.0]), + pa.chunked_array([[0.0], [0.0]]), + ], +) +@pytest.mark.parametrize("query_type", ["auto", "vector"]) +def test_sync_search_accepts_supported_vector_containers( + mem_db: DBConnection, query, query_type +): + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("small", pa.list_(pa.float32(), 2)), + pa.field("large", pa.list_(pa.float32(), 3)), + ] + ) + table = mem_db.create_table( + "supported_vector_containers", + data=pa.table( + { + "id": [1, 2], + "small": [[0.0, 0.0], [1.0, 1.0]], + "large": [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0]], + }, + schema=schema, + ), + ) + + result = table.search(query, query_type=query_type).limit(1).to_arrow() + + assert result["id"].to_pylist() == [1] + + def test_create_scalar_index(mem_db: DBConnection): vec_array = pa.array( [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]], pa.list_(pa.float32(), 2) From ae97d43f4bc3c1c01950c3a0d8369f21ceba014d Mon Sep 17 00:00:00 2001 From: Vinayak Vathare <137673662+VathareVinayak@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:40:30 +0530 Subject: [PATCH 024/180] fix(python): preserve valid embeddings when an OpenAI batch is rejected (#4005) Retries individual inputs one at a time when the OpenAI API rejects a batch with BadRequestError, instead of discarding the whole batch. Valid inputs now still get embeddings; only the actually-bad input resolves to None, and the log names the exact failing input. Fixes #1677 --- python/python/lancedb/embeddings/openai.py | 25 ++++++++---- python/python/tests/test_embeddings.py | 45 ++++++++++++++++++++++ 2 files changed, 63 insertions(+), 7 deletions(-) diff --git a/python/python/lancedb/embeddings/openai.py b/python/python/lancedb/embeddings/openai.py index 1edfaa2ca..d4ecbdf3f 100644 --- a/python/python/lancedb/embeddings/openai.py +++ b/python/python/lancedb/embeddings/openai.py @@ -101,24 +101,35 @@ class OpenAIEmbeddings(TextEmbeddingFunction): valid_indices.append(idx) # TODO retry, rate limit, token limit - try: + def embed_batch(texts_batch, indices_batch): kwargs = { - "input": valid_texts, + "input": texts_batch, "model": self.name, } if self.name != "text-embedding-ada-002": kwargs["dimensions"] = self.dim rs = self._openai_client.embeddings.create(**kwargs) - valid_embeddings = { - idx: v.embedding for v, idx in zip(rs.data, valid_indices) - } + return {idx: v.embedding for v, idx in zip(rs.data, indices_batch)} + + def embed_one_or_log(idx, text): + # Retry a single rejected input + try: + return embed_batch([text], [idx]) + except openai.BadRequestError: + logging.exception("Bad request for input at index %d: %r", idx, text) + return {} + + try: + valid_embeddings = embed_batch(valid_texts, valid_indices) except openai.AuthenticationError: logging.error("Authentication failed: Invalid API key provided") raise except openai.BadRequestError: - logging.exception("Bad request: %s", texts) - return [None] * len(texts) + # Retry each input individually + valid_embeddings = {} + for idx, text in zip(valid_indices, valid_texts): + valid_embeddings.update(embed_one_or_log(idx, text)) except Exception: logging.exception("OpenAI embeddings error") raise diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 9434033e1..c42172f77 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -596,6 +596,51 @@ def test_openai_no_retry_on_401(mock_sleep): assert mock_sleep.call_count == 0 +def test_openai_bad_request_partial_batch_recovery(): + # Regression test for issue #1677 + + # Fake exception types, avoids requiring the optional openai/httpx deps + class FakeBadRequestError(Exception): + pass + + class FakeAuthenticationError(Exception): + pass + + fake_openai_module = MagicMock() + fake_openai_module.BadRequestError = FakeBadRequestError + fake_openai_module.AuthenticationError = FakeAuthenticationError + + registry = get_registry() + model = registry.get("openai").create(name="text-embedding-ada-002") + + def fake_create(input, model=None, **kwargs): + # Full batch always rejected + if len(input) > 1: + raise FakeBadRequestError("bad request") + if input[0] == "bad text": + raise FakeBadRequestError("bad request") + embedding = MagicMock() + embedding.embedding = [0.1, 0.2, 0.3] + result = MagicMock() + result.data = [embedding] + return result + + mock_client = MagicMock() + mock_client.embeddings.create.side_effect = fake_create + + with ( + patch( + "lancedb.embeddings.openai.attempt_import_or_raise", + return_value=fake_openai_module, + ), + patch.object(type(model), "_openai_client", new_callable=lambda: mock_client), + ): + embeddings = model.generate_embeddings(["good text", "bad text"]) + + assert embeddings[0] == [0.1, 0.2, 0.3] + assert embeddings[1] is None + + def test_ollama_embeddings_pickle(): """OllamaEmbeddings must pickle even after the cached client is created.""" registry = get_registry() From 0c3a1c92c862d1f4d251d55eacafabe225277722 Mon Sep 17 00:00:00 2001 From: Madan Kumar Date: Thu, 22 Oct 2026 22:40:45 +0530 Subject: [PATCH 025/180] fix(python): don't crash inferring schema for an all-null vector column (#4034) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #4033 `create_table(data=...)` without an explicit schema raised `IndexError: index out of bounds` when a `vector`/`embedding`-named list column was all-null. `_modal_list_size` infers the dimension with `pc.mode(pc.list_value_length(arr))[0]`, and pyarrow's `mode` skips nulls, so an all-null column produces a zero-length result and the `[0]` subscript blows up. The sibling `_infer_vector_dim` already guards the identical `pc.mode(...)` with a `len == 0` check and returns `None`; `_modal_list_size` just didn't. This makes `_modal_list_size` return `Optional[int]` and return `None` when every value is null, and the call site then leaves the column as a variable-length list instead of inventing a fixed size — the dimension is genuinely unknowable when there are no non-null rows. Added a regression test that creates a table from an all-null `list` vector column and asserts it succeeds, the column stays a `list`, and the rows are queryable. It fails on `main` with the `IndexError` and passes with this change. --- python/python/lancedb/table.py | 17 ++++++++++++++--- python/python/tests/test_table.py | 24 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 006ef8cb9..ff866d4db 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -5335,6 +5335,12 @@ def _infer_target_schema( # Use the most common length of the list as the dimensions dim = _modal_list_size(peeked.column(i)) + if dim is None: + # Every list entry is null (e.g. embeddings not computed yet), + # so the dimension is unknowable. Leave the column as a + # variable-length list instead of guessing a fixed size. + continue + # Determine target type based on value type if pa.types.is_floating(field.type.value_type): target_type = pa.list_(pa.float32(), dim) @@ -5374,9 +5380,14 @@ def _infer_target_schema( return schema, reader -def _modal_list_size(arr: Union[pa.ListArray, pa.ChunkedArray]) -> int: - # Use the most common length of the list as the dimensions - return pc.mode(pc.list_value_length(arr))[0].as_py()["mode"] +def _modal_list_size(arr: Union[pa.ListArray, pa.ChunkedArray]) -> Optional[int]: + # Use the most common length of the list as the dimensions. pyarrow's + # `mode` skips nulls, so an all-null column yields an empty result; return + # None in that case so the caller can keep a variable-length list. + modes = pc.mode(pc.list_value_length(arr)) + if len(modes) == 0: + return None + return modes[0].as_py()["mode"] def _infer_vector_dim(arr: Union[pa.Array, pa.ChunkedArray]) -> Optional[int]: diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 7a4f5981c..827f2ef58 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -280,6 +280,30 @@ def test_create_table_infers_large_int_vectors(mem_db: DBConnection): assert vector_column.to_pylist() == [[0.0, 300.0]] +def test_create_table_all_null_vector_column(mem_db: DBConnection): + # A vector column can legitimately arrive with every value null, e.g. when + # the embeddings have not been computed yet. The dimension is unknowable in + # that case, so schema inference must not crash and should leave the column + # as a variable-length list rather than a fixed-size one. + data = pa.table( + { + "id": pa.array([1, 2]), + "vector": pa.array([None, None], type=pa.list_(pa.float32())), + } + ) + + table = mem_db.create_table("all_null_vector", data=data) + + vector_field = table.schema.field("vector") + assert pa.types.is_list(vector_field.type) + assert vector_field.type.value_type == pa.float32() + + result = table.to_arrow() + assert result.num_rows == 2 + assert result.column("vector").to_pylist() == [None, None] + assert table.count_rows() == 2 + + @pytest.mark.asyncio async def test_create_table_async_infers_large_int_vectors( mem_db_async: AsyncConnection, From 79e256959fa44f6f335e4b0e6409a6c21b6dcde3 Mon Sep 17 00:00:00 2001 From: Mohd Quamar Tyagi <104281681+Tyagiquamar@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:54:57 +0530 Subject: [PATCH 026/180] fix(python): accept pathlib.Path in get_uri_scheme and get_uri_location (#4132) This PR converts the uri parameter to string before calling urlparse in get_uri_scheme and get_uri_location, allowing pathlib.Path objects to be passed seamlessly without raising a TypeError. --------- Co-authored-by: Xuanwo --- python/python/lancedb/util.py | 15 ++++++++------- python/python/tests/test_util.py | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index 3babc3872..f1a652924 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -34,20 +34,20 @@ def safe_import_adlfs(): adlfs = safe_import_adlfs() -def get_uri_scheme(uri: str) -> str: +def get_uri_scheme(uri: Union[str, pathlib.Path]) -> str: """ Get the scheme of a URI. If the URI does not have a scheme, assume it is a file URI. Parameters ---------- - uri : str + uri : str or pathlib.Path The URI to parse. Returns ------- str: The scheme of the URI. """ - parsed = urlparse(uri) + parsed = urlparse(str(uri)) scheme = parsed.scheme if not scheme: scheme = "file" @@ -61,25 +61,26 @@ def get_uri_scheme(uri: str) -> str: return scheme -def get_uri_location(uri: str) -> str: +def get_uri_location(uri: Union[str, pathlib.Path]) -> str: """ Get the location of a URI. If the parameter is not a url, assumes it is just a path Parameters ---------- - uri : str + uri : str or pathlib.Path The URI to parse. Returns ------- str: Location part of the URL, without scheme """ - parsed = urlparse(uri) + uri_str = str(uri) + parsed = urlparse(uri_str) if len(parsed.scheme) == 1: # Windows drive names are parsed as the scheme # e.g. "c:\path" -> ParseResult(scheme="c", netloc="", path="/path", ...) # So we add special handling here for schemes that are a single character - return uri + return uri_str if not parsed.netloc: return parsed.path diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index 741214794..4671109b8 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -30,6 +30,7 @@ import pytest import lancedb from lancedb.util import ( flatten_columns, + get_uri_location, get_uri_scheme, inf_vector_column_query, join_uri, @@ -86,6 +87,22 @@ def test_normalize_uri(): assert parsed_scheme == expected_scheme +def test_get_uri_scheme_and_location_pathlib(): + # Test pathlib.Path instances + abs_path = pathlib.Path("/tmp/data") + rel_path = pathlib.Path("relative/data") + + assert get_uri_scheme(abs_path) == "file" + assert get_uri_scheme(rel_path) == "file" + + assert get_uri_location(abs_path) == str(abs_path) + assert get_uri_location(rel_path) == str(rel_path) + + # String URIs still behave identically + assert get_uri_scheme("s3://bucket/data") == "s3" + assert get_uri_location("s3://bucket/data") == "bucket/data" + + def test_join_uri_remote(): schemes = ["s3", "az", "gs"] for scheme in schemes: From d4b2290babbc8ab83a4287551b0145fd7ed05f44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=BF=97=E8=B0=A6?= <89645338+simpleqt@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:25:13 +0800 Subject: [PATCH 027/180] fix(python): correct the voyageai reranker env var docstring (#4201) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `VoyageAIReranker`'s `api_key` docstring said it falls back to `OPENAI_API_KEY`, but the class actually reads `VOYAGE_API_KEY` (and raises a "VOYAGE_API_KEY not set" error without it) — the docstring was copy-pasted from the OpenAI reranker. Docstring-only fix. --- python/python/lancedb/rerankers/voyageai.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python/lancedb/rerankers/voyageai.py b/python/python/lancedb/rerankers/voyageai.py index 0f41ba927..d3dbd59ac 100644 --- a/python/python/lancedb/rerankers/voyageai.py +++ b/python/python/lancedb/rerankers/voyageai.py @@ -32,7 +32,7 @@ class VoyageAIReranker(Reranker): return_score : str, default "relevance" options are "relevance" or "all". Only "relevance" is supported for now. api_key : str, default None - The API key to use. If None, will use the OPENAI_API_KEY environment variable. + The API key to use. If None, will use the VOYAGE_API_KEY environment variable. truncation : Optional[bool], default None """ From 9a590913767d31a0ba5ff524c7884052cec2451f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=BF=97=E8=B0=A6?= <89645338+simpleqt@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:25:29 +0800 Subject: [PATCH 028/180] fix(python): add missing space in the hybrid search error message (#4202) `LanceHybridQueryBuilder._validate_query`'s ValueError concatenated two adjacent string literals without a separator, rendering "...explicitly for hybrid search.**But** not both.". Added the trailing space. String-only change. --- python/python/lancedb/query.py | 2 +- python/python/tests/test_hybrid_query.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 53f56a2c0..fe8c33861 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2441,7 +2441,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): if query is not None and (vector is not None or text is not None): raise ValueError( "You can either provide a string query in search() method " - "or set `vector()` and `text()` explicitly for hybrid search." + "or set `vector()` and `text()` explicitly for hybrid search. " "But not both." ) diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 8d670a136..19050093c 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -536,3 +536,15 @@ def test_normalize_scores(): assert pc.equal(result, expected), ( f"Expected {expected} but got {result} for invert={invert}" ) + + +def test_hybrid_query_rejects_query_with_vector(sync_table: Table): + # Pins the full message: the space between "hybrid search." and "But" is + # load-bearing (see the _validate_query literal concatenation). + with pytest.raises(ValueError) as excinfo: + sync_table.search("dog", query_type="hybrid").vector([0.5, -0.5]).to_arrow() + assert str(excinfo.value) == ( + "You can either provide a string query in search() method " + "or set `vector()` and `text()` explicitly for hybrid search. " + "But not both." + ) From 82bfe7d38e38285424e843f2491b9680c59c30d2 Mon Sep 17 00:00:00 2001 From: Joaquin Hui Gomez <132194176+joaquinhuigomez@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:25:43 +0100 Subject: [PATCH 029/180] fix: table_names should not list loose .lance files as tables (#4203) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `table_names()` enumerates with `read_dir`, which returns files as well as directories, filtered only on the `.lance` extension — so a loose `foo.lance` *file* at the database prefix is reported as a table. `list_tables()` already applies the correct rule ("Only child directories can be tables"), and `test_listing_ignores_non_table_children` documents it, so the two listing APIs currently disagree. The practical damage is in `drop_all_tables()`, which is built on `table_names`: with a loose `.lance` file present it deletes some real tables, fails on the file with `os error 20 (NotADirectory)`, and then fails the same way on every retry — the database can never be emptied through the API, and the partial drop is not recoverable. `table_names` now lists via `list_with_delimiter` and filters `common_prefixes` through the same `table_name` helper `list_tables` uses; the sort/`start_after`/`limit` handling is unchanged. `drop_tables` additionally attempts every name before returning, still reporting the first error unchanged (kept rather than an aggregate error so the mapped exception types in the bindings stay exactly as they are). Extended the non-table-children test to cover `table_names`, plus tests for the drop behavior — all three fail without the fix. Full `cargo test -p lancedb --lib --features remote` 1320 passed on the repo-pinned 1.97 toolchain; clippy/fmt clean. --- rust/lancedb/src/database/listing.rs | 120 +++++++++++++++++++++------ 1 file changed, 94 insertions(+), 26 deletions(-) diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 71e9f0ef1..700c855dd 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -750,26 +750,39 @@ impl ListingDatabase { uri.push_str(&format!("?{}", query_string)); } let commit_handler = commit_handler_from_url(&uri, &Some(object_store_params)).await?; + // One name that cannot be dropped must not strand the names after it: a caller + // dropping every table would otherwise be left with a partly dropped database that + // the same call cannot finish. Every name is attempted and the first failure is + // still what the call reports, so a caller matching on the error sees what it saw + // before. + let mut first_error = None; for name in names { let dir_name = format!("{}.{}", name, LANCE_EXTENSION); let full_path = self.base_path.clone().join(dir_name.clone()); - commit_handler.delete(&full_path).await?; + let dropped: Result<()> = async { + commit_handler.delete(&full_path).await?; - self.object_store - .remove_dir_all(full_path.clone()) - .await - .map_err(|err| match err { - // this error is not lance::Error::DatasetNotFound, as the method - // `remove_dir_all` may be used to remove something not be a dataset - lance::Error::NotFound { .. } => Error::TableNotFound { - name: name.clone(), - source: Box::new(err), - }, - _ => Error::from(err), - })?; + self.object_store + .remove_dir_all(full_path.clone()) + .await + .map_err(|err| match err { + // this error is not lance::Error::DatasetNotFound, as the method + // `remove_dir_all` may be used to remove something not be a dataset + lance::Error::NotFound { .. } => Error::TableNotFound { + name: name.clone(), + source: Box::new(err), + }, + _ => Error::from(err), + }) + } + .await; + + if let Err(err) = dropped { + first_error.get_or_insert(err); + } } - Ok(()) + first_error.map_or(Ok(()), Err) } /// Inherit storage options from the connection into the target map @@ -930,20 +943,18 @@ impl Database for ListingDatabase { if !request.namespace_path.is_empty() { return self.namespace_database().table_names(request).await; } - let mut f = self + // Only child directories can be tables, the same rule `list_tables` lists by: a + // loose object named like a table is not one, and a name handed back for it is a + // name the caller can neither open nor drop. + let dir_suffix = format!(".{LANCE_EXTENSION}"); + let listing = self .object_store - .read_dir(self.base_path.clone()) - .await? + .list_with_delimiter(Some(&self.base_path)) + .await?; + let mut f = listing + .common_prefixes .iter() - .map(Path::new) - .filter(|path| { - let is_lance = path - .extension() - .and_then(|e| e.to_str()) - .map(|e| e == LANCE_EXTENSION); - is_lance.unwrap_or(false) - }) - .filter_map(|p| p.file_stem().and_then(|s| s.to_str().map(String::from))) + .filter_map(|location| table_name(location, &dir_suffix)) .collect::>(); f.sort(); if let Some(start_after) = request.start_after { @@ -1697,6 +1708,63 @@ mod tests { .unwrap(); assert_eq!(page.tables, vec!["real"]); + + // The deprecated name listing answers the same question and so follows the same + // rule: a name it hands back has to be one a caller can open and drop. + #[allow(deprecated)] + let names = db.table_names(TableNamesRequest::default()).await.unwrap(); + assert_eq!(names, vec!["real"]); + } + + /// Dropping the database drops its tables and leaves everything else alone. A loose + /// `*.lance` object under the database prefix is not a table, so it is neither dropped + /// nor allowed to strand the tables that are. + #[tokio::test] + async fn test_drop_all_tables_leaves_loose_lance_files() { + let (tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b"]).await; + // Sorts between the two tables, so a drop that stops at the first failure would + // leave `b` behind. + let loose = tempdir.path().join("aaa-loose.lance"); + std::fs::write(&loose, b"not a table").unwrap(); + + db.drop_all_tables(&[]).await.unwrap(); + + #[allow(deprecated)] + let names = db.table_names(TableNamesRequest::default()).await.unwrap(); + assert!(names.is_empty(), "a table survived the drop: {names:?}"); + assert!(!tempdir.path().join("a.lance").exists()); + assert!(!tempdir.path().join("b.lance").exists()); + assert!( + loose.exists(), + "a loose object was dropped as if it were a table" + ); + } + + /// A name that cannot be dropped does not strand the names after it: every name is + /// attempted, and the failure is still what the call reports. + #[tokio::test] + async fn test_drop_tables_attempts_every_name() { + let (tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b"]).await; + + let result = db + .drop_tables(vec![ + "a".to_string(), + "missing".to_string(), + "b".to_string(), + ]) + .await; + + assert!( + matches!(result, Err(Error::TableNotFound { .. })), + "dropping a table that is not there did not report it: {result:?}" + ); + assert!(!tempdir.path().join("a.lance").exists()); + assert!( + !tempdir.path().join("b.lance").exists(), + "the table after the failing name was left behind" + ); } #[tokio::test] From d37a6b76a465a1fc62372ffe51d4cf4bb5233633 Mon Sep 17 00:00:00 2001 From: SIDDARTHA REDDY <75976672+SIDDARTHAREDDY8@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:25:58 -0400 Subject: [PATCH 030/180] fix: gate remote job error construction behind the remote feature (#4233) ## Summary Fixes #4142: `lancedb` failed to compile without the `remote` feature. `TerminalResult::decode` in `rust/lancedb/src/job.rs` constructed the `Error::Http` variant unconditionally, but that variant is declared behind `#[cfg(feature = "remote")]` in `rust/lancedb/src/error.rs`. Since the crate's default feature set is empty, a plain `lancedb = "0.38"` dependency failed with: ``` error[E0599]: no variant named `Http` found for enum `error::Error` --> rust/lancedb/src/job.rs:102:40 ``` The module itself is not remote-only (it carries local job support), so instead of gating `pub mod job`, both `Error::Http` constructions now go through a small `remote_job_error` helper that resolves to `Error::Http` with the `remote` feature and falls back to `Error::Runtime` without it. A `request_id` is only ever `Some` for remote jobs, so the fallback is unreachable in practice without the feature. ## Testing - Reproduced the reported failure on current `main`: `cargo check -p lancedb --no-default-features` failed with the exact E0599 errors from the issue before the change, and passes after it. - `cargo check -p lancedb --features remote` passes with no errors and no new warnings. - Added two regression tests in `rust/lancedb/src/job.rs` (`decode_missing_result_uses_feature_appropriate_error`, `decode_unparsable_result_uses_feature_appropriate_error`) asserting the error variant matches the feature configuration. The test code compiles under the fixed configuration (`cargo check --tests` passes), and the branching logic was executed standalone against both feature cfgs (3/3 green with and without `remote`). The full `cargo test` binary link could not complete on the small build VM available here (the linker stalled), so CI coverage of the new tests is appreciated. - `cargo fmt --all -- --check` is clean. ## Disclosure AI assistance was used while preparing this change (code search, editing, and verification commands were agent-driven); the diagnosis, fix design, and all test results above were verified by actually running the builds. --- rust/lancedb/src/job.rs | 80 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 71 insertions(+), 9 deletions(-) diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 711a73033..6865e59ee 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -101,21 +101,19 @@ impl TerminalResult { fn decode(self) -> Result { let value = self.value.ok_or_else(|| match &self.request_id { - Some(request_id) => Error::Http { - source: "successful typed job response did not contain a result".into(), - request_id: request_id.clone(), - status_code: None, - }, + Some(request_id) => remote_job_error( + request_id.clone(), + "successful typed job response did not contain a result".to_string(), + ), None => Error::Runtime { message: "successful typed job did not contain a result".to_string(), }, })?; serde_json::from_value(value).map_err(|error| match self.request_id { - Some(request_id) => Error::Http { - source: format!("failed to parse typed job result: {error}").into(), + Some(request_id) => remote_job_error( request_id, - status_code: None, - }, + format!("failed to parse typed job result: {error}"), + ), None => Error::Runtime { message: format!("failed to parse typed job result: {error}"), }, @@ -123,6 +121,28 @@ impl TerminalResult { } } +/// Build the error for a failed remote typed-job result. +/// +/// The `Error::Http` variant is gated behind the `remote` feature, so without +/// it we fall back to `Error::Runtime`. A `request_id` is only ever `Some` +/// for remote jobs, making the fallback unreachable in practice without the +/// feature. +#[cfg(feature = "remote")] +fn remote_job_error(request_id: String, source: String) -> Error { + Error::Http { + source: source.into(), + request_id, + status_code: None, + } +} + +#[cfg(not(feature = "remote"))] +fn remote_job_error(request_id: String, source: String) -> Error { + Error::Runtime { + message: format!("{source} (request_id={request_id})"), + } +} + type ResultDecoder = Arc Result + Send + Sync>; enum JobInner { @@ -634,4 +654,46 @@ mod tests { assert!(matches!(job.wait().await, Err(Error::JobCancelled { .. }))); assert_eq!(job.status().await.unwrap(), "cancelled"); } + + #[test] + fn decode_missing_result_uses_feature_appropriate_error() { + // A `request_id` is only `Some` for remote jobs. The error for a + // missing result must use `Error::Http` with the `remote` feature and + // fall back to `Error::Runtime` without it (where `Error::Http` + // does not exist). See https://github.com/lancedb/lancedb/issues/4142. + let result = TerminalResult { + value: None, + request_id: Some("req-1".to_string()), + }; + let err = result.decode::().unwrap_err(); + #[cfg(feature = "remote")] + assert!( + matches!(err, Error::Http { .. }), + "expected Error::Http, got {err:?}" + ); + #[cfg(not(feature = "remote"))] + assert!( + matches!(err, Error::Runtime { .. }), + "expected Error::Runtime, got {err:?}" + ); + } + + #[test] + fn decode_unparsable_result_uses_feature_appropriate_error() { + let result = TerminalResult { + value: Some(Value::String("not a u64".to_string())), + request_id: Some("req-1".to_string()), + }; + let err = result.decode::().unwrap_err(); + #[cfg(feature = "remote")] + assert!( + matches!(err, Error::Http { .. }), + "expected Error::Http, got {err:?}" + ); + #[cfg(not(feature = "remote"))] + assert!( + matches!(err, Error::Runtime { .. }), + "expected Error::Runtime, got {err:?}" + ); + } } From 66b5b5bbdcb816b547927fb082f3f96925951e5e Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:26:13 +0800 Subject: [PATCH 031/180] fix(python): clarify unavailable CUDA index acceleration (#4249) ## Summary - preflight CUDA availability and initialization before accelerated index training - direct unavailable or misconfigured CUDA environments to the explicit CPU path - cover both legacy and unified Python index APIs ## Root cause LanceDB delegated accelerator requests directly to PyLance. When PyTorch lacked CUDA support or CUDA initialization failed, users received a low-level assertion or runtime error with no indication that omitting `accelerator` or setting `accelerator=None` creates the index on CPU. The repair validates CUDA before training and preserves explicit accelerator semantics without silently changing the requested backend. ## Scope This PR addresses only the separately reproduced CUDA availability and initialization error. It does not close #1766; the reported query failure after successful CUDA index creation remains open pending reproducible evidence. ## Validation - `uv run --extra tests pytest python/tests/test_table.py -k create_index -q` (10 passed) - `ruff format .` - `ruff check .` - CPU-only integration check confirms the actionable fallback message Related to #1766 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/table.py | 35 +++++++++++++++++++++-- python/python/tests/test_table.py | 47 ++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ff866d4db..35ec7a466 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -119,6 +119,33 @@ def _should_push_down_query_table( return namespace_client is not None and "QueryTable" in pushdown_operations +_CUDA_UNAVAILABLE_MESSAGE = ( + "CUDA acceleration is unavailable in this Python environment. Install a " + "CUDA-enabled PyTorch build and verify that the CUDA device is accessible, or " + "omit `accelerator` (or set `accelerator=None`) to create the index on CPU." +) + + +def _validate_index_accelerator(accelerator: Any) -> None: + if not isinstance(accelerator, str) or accelerator.split(":", 1)[0] != "cuda": + return + + try: + import torch + + cuda_available = torch.cuda.is_available() + except (ImportError, RuntimeError, AssertionError) as err: + raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err + + if not cuda_available: + raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) + + try: + torch.cuda.init() + except (RuntimeError, AssertionError) as err: + raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err + + def _polars_predicate_pushdown_barrier(frame: Any) -> Any: """Return a Polars frame unchanged while blocking predicate pushdown.""" return frame @@ -3600,7 +3627,9 @@ class LanceTable(Table): # Handle accelerator through pylance if accelerator is not None: - self.to_lance().create_index( + dataset = self.to_lance() + _validate_index_accelerator(accelerator) + dataset.create_index( column=column, index_type=index_type, metric=metric, @@ -3625,6 +3654,8 @@ class LanceTable(Table): acc = getattr(config, "accelerator", None) if acc is not None: # Dispatch to pylance for GPU acceleration + dataset = self.to_lance() + _validate_index_accelerator(acc) index_type_map = { "IvfFlat": "IVF_FLAT", "IvfSq": "IVF_SQ", @@ -3636,7 +3667,7 @@ class LanceTable(Table): cfg_type = type(config).__name__ lance_index_type = index_type_map.get(cfg_type, "IVF_PQ") - self.to_lance().create_index( + dataset.create_index( column=column, index_type=lance_index_type, metric=getattr(config, "distance_type", "l2"), diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 827f2ef58..b241adb0a 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -15,7 +15,7 @@ from datetime import date, datetime, timedelta from decimal import Decimal, localcontext from time import sleep from typing import List -from unittest.mock import patch +from unittest.mock import MagicMock, patch import lancedb from lancedb import table as table_module @@ -1773,6 +1773,51 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): ) +@pytest.mark.parametrize("api", ["legacy", "unified"]) +@pytest.mark.parametrize("cuda_failure", ["unavailable", "init_error"]) +def test_create_index_cuda_failure_suggests_cpu( + api, cuda_failure, mem_db: DBConnection +): + table = mem_db.create_table( + f"test_cuda_unavailable_{api}", + data=[{"vector": [3.1, 4.1]}, {"vector": [5.9, 26.5]}], + ) + torch = MagicMock() + torch.cuda.is_available.return_value = cuda_failure == "init_error" + if cuda_failure == "init_error": + torch.cuda.init.side_effect = RuntimeError("CUDA driver initialization failed") + + with ( + patch.dict(sys.modules, {"torch": torch}), + patch.object(table, "to_lance") as to_lance, + ): + if api == "legacy": + with ( + pytest.warns(DeprecationWarning, match="create_index"), + pytest.raises(RuntimeError, match="accelerator=None.*CPU"), + ): + table.create_index( + metric="dot", + num_partitions=1, + num_sub_vectors=1, + vector_column_name="vector", + accelerator="cuda", + ) + else: + with pytest.raises(RuntimeError, match="accelerator=None.*CPU"): + table.create_index( + "vector", + config=IvfPq( + distance_type="dot", + num_partitions=1, + num_sub_vectors=1, + accelerator="cuda", + ), + ) + + to_lance.return_value.create_index.assert_not_called() + + @patch("lancedb.table.AsyncTable.create_index") def test_create_index_name_and_train_parameters( mock_create_index, mem_db: DBConnection From 624defd109c161505e84b26e66f43a35b71ac16c Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:26:28 +0800 Subject: [PATCH 032/180] fix: preserve sliced child validity during struct merge (#4261) ## Root cause The pinned Lance Arrow crate rebuilt a sliced struct child with its original Arrow offset but supplied a validity bitmap containing only the visible rows. Arrow requires the bitmap to cover the offset as well, so filtered vector searches involving nullable nested fields could panic with `null_bit_buffer size too small`. ## Fix - Carry an offset-aligned validity bitmap when propagating parent nulls to a sliced child. - Vendor the pinned `lance-arrow` crate until a Lance release includes the fix; include it in Maturin source distributions. - Add unit regressions for sliced children and parent bitmaps, plus a record-batch merge regression. ## Validation - The issue's 8,600-row Python reproducer completes its filtered flat dot search and returns 8,448 rows without a panic. - The targeted Rust merge regression and two focused Python query tests pass. - Rust formatting, Ruff formatting and lint, the vendored crate tests, and the workspace Cargo checks passed. The Maturin source archive includes the patched crate. Fixes #4260 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- Cargo.lock | 2 +- Cargo.toml | 7 +- python/Cargo.toml | 2 + python/vendor/lance-arrow/Cargo.toml | 33 + python/vendor/lance-arrow/README.lancedb.md | 7 + python/vendor/lance-arrow/README.md | 6 + python/vendor/lance-arrow/src/bfloat16.rs | 406 +++ python/vendor/lance-arrow/src/deepcopy.rs | 356 +++ python/vendor/lance-arrow/src/floats.rs | 292 ++ python/vendor/lance-arrow/src/ipc.rs | 621 ++++ python/vendor/lance-arrow/src/json.rs | 1538 +++++++++ python/vendor/lance-arrow/src/lib.rs | 3102 +++++++++++++++++++ python/vendor/lance-arrow/src/list.rs | 177 ++ python/vendor/lance-arrow/src/memory.rs | 92 + python/vendor/lance-arrow/src/scalar.rs | 302 ++ python/vendor/lance-arrow/src/schema.rs | 208 ++ python/vendor/lance-arrow/src/stream.rs | 554 ++++ python/vendor/lance-arrow/src/struct.rs | 227 ++ rust/lancedb/tests/nullable_struct_merge.rs | 64 + 19 files changed, 7994 insertions(+), 2 deletions(-) create mode 100644 python/vendor/lance-arrow/Cargo.toml create mode 100644 python/vendor/lance-arrow/README.lancedb.md create mode 100644 python/vendor/lance-arrow/README.md create mode 100644 python/vendor/lance-arrow/src/bfloat16.rs create mode 100644 python/vendor/lance-arrow/src/deepcopy.rs create mode 100644 python/vendor/lance-arrow/src/floats.rs create mode 100644 python/vendor/lance-arrow/src/ipc.rs create mode 100644 python/vendor/lance-arrow/src/json.rs create mode 100644 python/vendor/lance-arrow/src/lib.rs create mode 100644 python/vendor/lance-arrow/src/list.rs create mode 100644 python/vendor/lance-arrow/src/memory.rs create mode 100644 python/vendor/lance-arrow/src/scalar.rs create mode 100644 python/vendor/lance-arrow/src/schema.rs create mode 100644 python/vendor/lance-arrow/src/stream.rs create mode 100644 python/vendor/lance-arrow/src/struct.rs create mode 100644 rust/lancedb/tests/nullable_struct_merge.rs diff --git a/Cargo.lock b/Cargo.lock index 7f36dc088..34ee05cb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5136,7 +5136,6 @@ dependencies = [ [[package]] name = "lance-arrow" version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" dependencies = [ "arrow-array", "arrow-buffer", @@ -5834,6 +5833,7 @@ dependencies = [ "datafusion-common", "env_logger", "futures", + "lance-arrow", "lance-core", "lance-io", "lance-namespace", diff --git a/Cargo.toml b/Cargo.toml index 3ac246149..870ef5d07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ lance-datagen = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" lance-file = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lance-io = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lance-index = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { version = "=15.0.0-beta.1", tag = "v15.0.0-beta.1", git = "https://github.com/lance-format/lance.git" } lance-linalg = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lance-namespace = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lance-namespace-impls = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } @@ -26,7 +27,7 @@ lance-table = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = lance-testing = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lance-datafusion = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lance-encoding = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { version = "=15.0.0-beta.1", path = "python/vendor/lance-arrow" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow @@ -79,6 +80,10 @@ tonic = { version = "0.14", features = ["tls-native-roots", "tls-aws-lc"] } uuid = { version = "1.7.0", features = ["v4", "v7"] } chrono = { version = "0.4", default-features = false, features = ["clock"] } +[patch."https://github.com/lance-format/lance.git"] +# Carry the offset-safe validity fix until it is available in a Lance release. +lance-arrow = { path = "python/vendor/lance-arrow" } + [patch.crates-io] # Lance v14.0.0-beta.18 requires multipart write modes from this upstream revision. object_store = { git = "https://github.com/apache/arrow-rs-object-store.git", rev = "c10758c207c0103355f940f0c736fb8ecb157b04" } diff --git a/python/Cargo.toml b/python/Cargo.toml index ad1790a99..076299a7d 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -22,6 +22,8 @@ bytes.workspace = true lancedb.workspace = true datafusion-common.workspace = true lance-core.workspace = true +# The workspace path dependency includes the patched crate in Maturin sources. +lance-arrow.workspace = true lance-namespace.workspace = true lance-namespace-impls.workspace = true lance-io.workspace = true diff --git a/python/vendor/lance-arrow/Cargo.toml b/python/vendor/lance-arrow/Cargo.toml new file mode 100644 index 000000000..9cb156f2e --- /dev/null +++ b/python/vendor/lance-arrow/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "lance-arrow" +version = "15.0.0-beta.1" +edition = "2024" +authors = ["Lance Devs "] +license = "Apache-2.0" +repository = "https://github.com/lance-format/lance" +readme = "README.md" +description = "Arrow Extension for Lance" +keywords = ["data-format", "data-science", "machine-learning", "apache-arrow", "data-analytics"] +categories = ["database-implementations"] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +arrow-array.workspace = true +arrow-buffer.workspace = true +arrow-data.workspace = true +arrow-ipc = { workspace = true, features = ["zstd"] } +arrow-ord.workspace = true +arrow-schema.workspace = true +arrow-select.workspace = true +bytemuck = { version = "1", default-features = false, features = ["extern_crate_alloc"] } +bytes.workspace = true +futures.workspace = true +half = { workspace = true, features = ["std", "bytemuck"] } +lance-jsonb.workspace = true +num-traits.workspace = true +rand = { workspace = true, features = ["small_rng"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { version = "0.2", features = ["js"] } diff --git a/python/vendor/lance-arrow/README.lancedb.md b/python/vendor/lance-arrow/README.lancedb.md new file mode 100644 index 000000000..5ed714e08 --- /dev/null +++ b/python/vendor/lance-arrow/README.lancedb.md @@ -0,0 +1,7 @@ +This directory contains `rust/lance-arrow` from Lance tag `v15.0.0-beta.1` +(commit `46a7cfe1fba5efa1f90deea4c7b14d414b991409`), licensed under Apache-2.0. + +LanceDB carries a local fix in `src/lib.rs` for sliced child validity bitmaps +until a Lance release includes the fix. The patch is selected in the root +`Cargo.toml`; the rest of Lance stays on the pinned release. An explicit unsafe +block in `src/bfloat16.rs` lets this copy pass LanceDB's Rust 2024 warning gate. diff --git a/python/vendor/lance-arrow/README.md b/python/vendor/lance-arrow/README.md new file mode 100644 index 000000000..e0f129a3a --- /dev/null +++ b/python/vendor/lance-arrow/README.md @@ -0,0 +1,6 @@ +# lance-arrow + +`lance-arrow` is an internal sub-crate, containing [Apache-Arrow](https://github.com/apache/arrow-rs) +extensions used by [Lance](https://github.com/lance-format/lance). + +**Important Note**: This crate is **not intended for external usage**. diff --git a/python/vendor/lance-arrow/src/bfloat16.rs b/python/vendor/lance-arrow/src/bfloat16.rs new file mode 100644 index 000000000..1a60e5ece --- /dev/null +++ b/python/vendor/lance-arrow/src/bfloat16.rs @@ -0,0 +1,406 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! bfloat16 support for Apache Arrow. + +use std::fmt::Formatter; +use std::slice; + +use arrow_array::{Array, FixedSizeBinaryArray, builder::BooleanBufferBuilder}; +use arrow_buffer::{Buffer, MutableBuffer}; +use arrow_data::ArrayData; +use arrow_schema::{ArrowError, DataType, Field as ArrowField}; +use half::bf16; + +use crate::{ARROW_EXT_NAME_KEY, FloatArray}; + +/// The name of the bfloat16 extension in Arrow metadata +pub const BFLOAT16_EXT_NAME: &str = "lance.bfloat16"; + +/// Check whether the given field is a bfloat16 field +/// +/// A field is a bfloat16 field if it has a data type of `FixedSizeBinary(2)` and the metadata +/// contains the bfloat16 extension name. +pub fn is_bfloat16_field(field: &ArrowField) -> bool { + field.data_type() == &DataType::FixedSizeBinary(2) + && field + .metadata() + .get(ARROW_EXT_NAME_KEY) + .map(|name| name == BFLOAT16_EXT_NAME) + .unwrap_or_default() +} + +/// The bfloat16 data type +/// +/// This implements the [`ArrowFloatType`](crate::floats::ArrowFloatType) trait for bfloat16 values. +#[derive(Debug)] +pub struct BFloat16Type {} + +/// An array of bfloat16 values +/// +/// Note that bfloat16 is not the same thing as fp16 which is supported natively by arrow-rs. +#[derive(Clone)] +pub struct BFloat16Array { + inner: FixedSizeBinaryArray, +} + +impl std::fmt::Debug for BFloat16Array { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "BFloat16Array\n[\n")?; + from_arrow::print_long_array(&self.inner, f, |array, i, f| { + if array.is_null(i) { + write!(f, "null") + } else { + let binary_values = array.value(i); + let value = + bf16::from_bits(u16::from_le_bytes([binary_values[0], binary_values[1]])); + write!(f, "{:?}", value) + } + })?; + write!(f, "]") + } +} + +impl BFloat16Array { + pub fn from_iter_values(iter: impl IntoIterator) -> Self { + let values: Vec = iter.into_iter().collect(); + values.into() + } + + pub fn len(&self) -> usize { + self.inner.len() + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + pub fn is_null(&self, i: usize) -> bool { + self.inner.is_null(i) + } + + pub fn null_count(&self) -> usize { + self.inner.null_count() + } + + pub fn iter(&self) -> BFloat16Iter<'_> { + BFloat16Iter { + array: self, + index: 0, + } + } + + pub fn value(&self, i: usize) -> bf16 { + assert!( + i < self.len(), + "Trying to access an element at index {} from a BFloat16Array of length {}", + i, + self.len() + ); + // Safety: + // `i < self.len() + unsafe { self.value_unchecked(i) } + } + + /// # Safety + /// Caller must ensure that `i < self.len()` + pub unsafe fn value_unchecked(&self, i: usize) -> bf16 { + // SAFETY: the caller guarantees that `i` is within this array's bounds. + let binary_value = unsafe { self.inner.value_unchecked(i) }; + bf16::from_bits(u16::from_le_bytes([binary_value[0], binary_value[1]])) + } + + pub fn into_inner(self) -> FixedSizeBinaryArray { + self.inner + } +} + +impl FromIterator> for BFloat16Array { + fn from_iter>>(iter: I) -> Self { + let mut buffer = MutableBuffer::new(10); + // No null buffer builder :( + let mut nulls = BooleanBufferBuilder::new(10); + let mut len = 0; + + for maybe_value in iter { + if let Some(value) = maybe_value { + let bytes = value.to_le_bytes(); + buffer.extend(bytes); + } else { + buffer.extend([0u8, 0u8]); + } + nulls.append(maybe_value.is_some()); + len += 1; + } + + let null_buffer = nulls.finish(); + let num_valid = null_buffer.count_set_bits(); + let null_buffer = if num_valid == len { + None + } else { + Some(null_buffer.into_inner()) + }; + + let array_data = ArrayData::builder(DataType::FixedSizeBinary(2)) + .len(len) + .add_buffer(buffer.into()) + .null_bit_buffer(null_buffer); + // SAFETY: the value buffer contains exactly `2 * len` bytes (two bytes + // pushed per iteration of the loop above, including the zero-fill for + // null slots), which matches the `FixedSizeBinary(2)` storage layout. + // The null bit buffer, when present, has `len` bits appended above, so + // its length covers the array's logical range. + let array_data = unsafe { array_data.build_unchecked() }; + Self { + inner: FixedSizeBinaryArray::from(array_data), + } + } +} + +impl FromIterator for BFloat16Array { + fn from_iter>(iter: I) -> Self { + Self::from_iter_values(iter) + } +} + +impl From> for BFloat16Array { + fn from(data: Vec) -> Self { + let len = data.len(); + // Zero-copy: `bf16` is `#[repr(transparent)]` over `u16` and derives + // `bytemuck::Pod`, so `cast_vec` reinterprets the allocation in place — + // no per-element copy or heap alloc. The crate-root `compile_error!` + // pins `target_endian = "little"`, so the resulting bytes match the + // `FixedSizeBinary(2)` on-disk order Lance writes elsewhere. + let raw: Vec = bytemuck::cast_vec(data); + let array_data = ArrayData::builder(DataType::FixedSizeBinary(2)) + .len(len) + .add_buffer(Buffer::from_vec(raw)); + // SAFETY: the value buffer contains exactly `2 * len` bytes — one + // `u16` per element after the layout-compatible cast — matching the + // `FixedSizeBinary(2)` storage layout. No null buffer is attached, so + // every element is logically valid. + let array_data = unsafe { array_data.build_unchecked() }; + Self { + inner: FixedSizeBinaryArray::from(array_data), + } + } +} + +impl TryFrom for BFloat16Array { + type Error = ArrowError; + + fn try_from(value: FixedSizeBinaryArray) -> Result { + if value.value_length() == 2 { + Ok(Self { inner: value }) + } else { + Err(ArrowError::InvalidArgumentError( + "FixedSizeBinaryArray must have a value length of 2".to_string(), + )) + } + } +} + +impl PartialEq for BFloat16Array { + fn eq(&self, other: &Self) -> bool { + self.inner.eq(&other.inner) + } +} + +pub struct BFloat16Iter<'a> { + array: &'a BFloat16Array, + index: usize, +} + +impl<'a> Iterator for BFloat16Iter<'a> { + type Item = Option; + + fn next(&mut self) -> Option { + if self.index >= self.array.len() { + return None; + } + let i = self.index; + self.index += 1; + if self.array.is_null(i) { + Some(None) + } else { + Some(Some(self.array.value(i))) + } + } +} + +/// Methods that are lifted from arrow-rs temporarily until they are made public. +mod from_arrow { + use arrow_array::Array; + + /// Helper function for printing potentially long arrays. + pub(super) fn print_long_array( + array: &A, + f: &mut std::fmt::Formatter, + print_item: F, + ) -> std::fmt::Result + where + A: Array, + F: Fn(&A, usize, &mut std::fmt::Formatter) -> std::fmt::Result, + { + let head = std::cmp::min(10, array.len()); + + for i in 0..head { + if array.is_null(i) { + writeln!(f, " null,")?; + } else { + write!(f, " ")?; + print_item(array, i, f)?; + writeln!(f, ",")?; + } + } + if array.len() > 10 { + if array.len() > 20 { + writeln!(f, " ...{} elements...,", array.len() - 20)?; + } + + let tail = std::cmp::max(head, array.len() - 10); + + for i in tail..array.len() { + if array.is_null(i) { + writeln!(f, " null,")?; + } else { + write!(f, " ")?; + print_item(array, i, f)?; + writeln!(f, ",")?; + } + } + } + Ok(()) + } +} + +impl FloatArray for FixedSizeBinaryArray { + type FloatType = BFloat16Type; + + /// Returns the underlying `bf16` values as a borrowed slice. + /// + /// # Preconditions + /// + /// - `value_length()` must be 2 (the `FixedSizeBinary(2)` storage shape + /// used by [`BFloat16Array`]). Asserted at entry. + /// - The value buffer must be at least 2-byte aligned. Lance's in-tree + /// constructors always satisfy this: value buffers are built either via + /// `MutableBuffer` (aligned to arrow-buffer's `ALIGNMENT` constant, ≥32 + /// bytes) or via `Buffer::from_vec::` (aligned to `align_of::()` + /// == 2); both meet `bf16`'s 2-byte requirement. Externally-built + /// `FixedSizeBinaryArray`s arriving via FFI, IPC, or + /// `Buffer::from_custom_allocation` are not required by arrow-rs to be + /// aligned beyond a single byte; passing one to this method violates the + /// precondition. A `debug_assert` below catches such inputs in debug and + /// test builds. + /// + /// # Endianness + /// + /// `lance-arrow` is gated on `target_endian = "little"` at the crate root, + /// so this method always returns values in the same byte order Lance writes + /// (see [`BFloat16Array::value`] and the [`FromIterator`] impls). + fn as_slice(&self) -> &[bf16] { + assert_eq!( + self.value_length(), + 2, + "BFloat16 arrays must use FixedSizeBinary(2) storage" + ); + debug_assert_eq!( + (self.value_data().as_ptr() as usize) % std::mem::align_of::(), + 0, + "BFloat16 value buffer must be at least 2-byte aligned" + ); + // SAFETY: + // - The assert above pins `value_size == 2`, so `value_data().len() / 2` + // equals the array's logical element count. + // `FixedSizeBinaryArray::From` constructs its value buffer + // as `buffers[0].slice_with_length(offset * 2, len * 2)` (arrow-array + // `fixed_size_binary_array.rs`), so `value_data()` already returns + // the offset-adjusted slice. Do not replace `value_data()` with an + // accessor that returns the un-sliced backing buffer. + // - `bf16` is `#[repr(transparent)]` over `u16` (size 2, alignment 2); + // every `u16` bit pattern is a valid `bf16`, so any byte content + // yields a defined value — never UB. + // - Alignment is the caller's responsibility per the precondition + // documented above. The `debug_assert_eq!` immediately preceding this + // block catches violations in debug and test builds only — release + // builds rely on callers honoring the precondition. arrow-rs + // declares `FixedSizeBinary(n)`'s + // `BufferSpec::FixedWidth { alignment: align_of::() == 1 }` + // (arrow-data `data.rs`), so arrow-rs alone does not guarantee + // 2-byte alignment. Lance's in-tree construction paths build value + // buffers via `MutableBuffer` (arrow-buffer `ALIGNMENT` constant, + // ≥32 bytes) or `Buffer::from_vec::` (2-byte aligned), both of + // which satisfy `bf16`'s 2-byte requirement. + // - The returned slice borrows from `self`; the underlying ref-counted, + // immutable Arrow buffer cannot be mutated or freed for the slice's + // lifetime. + unsafe { + slice::from_raw_parts( + self.value_data().as_ptr() as *const bf16, + self.value_data().len() / 2, + ) + } + } + + fn from_values(values: Vec) -> Self { + BFloat16Array::from(values).into_inner() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_basics() { + let values: Vec = vec![1.0, 2.0, 3.0]; + let values: Vec = values.iter().map(|v| bf16::from_f32(*v)).collect(); + + let array = BFloat16Array::from_iter_values(values.clone()); + let array2 = BFloat16Array::from(values.clone()); + assert_eq!(array, array2); + assert_eq!(array.len(), 3); + + // Pin the raw little-endian bytes emitted by `From>` (rewritten to + // reinterpret the Vec via `bytemuck::cast_vec`), so a layout/byte-order + // regression is caught directly rather than only through Debug formatting. + // bf16 is the high 16 bits of the f32: 1.0->0x3F80, 2.0->0x4000, 3.0->0x4040. + let inner = array2.clone().into_inner(); + let raw_bytes: Vec = (0..inner.len()) + .flat_map(|i| inner.value(i).to_vec()) + .collect(); + assert_eq!(raw_bytes, vec![0x80, 0x3F, 0x00, 0x40, 0x40, 0x40]); + + let expected_fmt = "BFloat16Array\n[\n 1.0,\n 2.0,\n 3.0,\n]"; + assert_eq!(expected_fmt, format!("{:?}", array)); + + for (expected, value) in values.iter().zip(array.iter()) { + assert_eq!(Some(*expected), value); + } + + for (expected, value) in values.as_slice().iter().zip(array2.iter()) { + assert_eq!(Some(*expected), value); + } + + let arrow_array = array.into_inner(); + assert_eq!(arrow_array.as_slice(), values.as_slice()); + } + + #[test] + fn test_nulls() { + let values: Vec> = + vec![Some(bf16::from_f32(1.0)), None, Some(bf16::from_f32(3.0))]; + let array = BFloat16Array::from_iter(values.clone()); + assert_eq!(array.len(), 3); + assert_eq!(array.null_count(), 1); + + let expected_fmt = "BFloat16Array\n[\n 1.0,\n null,\n 3.0,\n]"; + assert_eq!(expected_fmt, format!("{:?}", array)); + + for (expected, value) in values.iter().zip(array.iter()) { + assert_eq!(*expected, value); + } + } +} diff --git a/python/vendor/lance-arrow/src/deepcopy.rs b/python/vendor/lance-arrow/src/deepcopy.rs new file mode 100644 index 000000000..5df4339b5 --- /dev/null +++ b/python/vendor/lance-arrow/src/deepcopy.rs @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::sync::Arc; + +use arrow_array::{Array, RecordBatch, make_array}; +use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer}; +use arrow_data::{ArrayData, ArrayDataBuilder, transform::MutableArrayData}; +use arrow_schema::DataType; + +pub fn deep_copy_buffer(buffer: &Buffer) -> Buffer { + Buffer::from(buffer.as_slice()) +} + +pub fn deep_copy_nulls(nulls: Option<&NullBuffer>) -> Option { + let nulls = nulls?; + let bit_buffer = deep_copy_buffer(nulls.inner().inner()); + // SAFETY: `null_count` is taken from the source `NullBuffer`, which already + // upheld `NullBuffer::new_unchecked`'s invariant — the unset-bit count over + // the logical bit slice `[bit_offset, bit_offset + bit_len)`. `NullBuffer::slice` + // adjusts only `BooleanBuffer::bit_offset` / `bit_len` and never byte-advances + // the inner `Buffer`, so `deep_copy_buffer` (which copies the source `Buffer`'s + // `as_slice()` view from byte 0) reproduces the exact bit pattern at the same + // bit offsets; the unset-bit count is therefore preserved. `BooleanBuffer::new` + // panics (does not UB) if `bit_offset + bit_len > 8 * buffer.len()`, and the + // copy has the same length, so that check still passes. + Some(unsafe { + NullBuffer::new_unchecked( + BooleanBuffer::new(bit_buffer, nulls.offset(), nulls.len()), + nulls.null_count(), + ) + }) +} + +pub fn deep_copy_array_data(data: &ArrayData) -> ArrayData { + let data_type = data.data_type().clone(); + let len = data.len(); + let nulls = deep_copy_nulls(data.nulls()); + let offset = data.offset(); + let buffers = data + .buffers() + .iter() + .map(deep_copy_buffer) + .collect::>(); + let child_data = data + .child_data() + .iter() + .map(deep_copy_array_data) + .collect::>(); + // SAFETY: `build_unchecked` inherits `ArrayData::new_unchecked`'s contract — + // `(data_type, len, offset, nulls, buffers, child_data)` must form a valid + // Arrow array. This call reproduces `data` structurally: `data_type`, `len`, + // and `offset` are forwarded unchanged; each buffer is replaced by a byte- + // identical copy of its offset-applied `as_slice()` view (the output buffer + // is `MutableBuffer`-allocated, at least as aligned as the source); `nulls` + // is deep-copied with the same bit offset/length and unset-bit count (see + // `deep_copy_nulls`); `child_data` is recursively cloned with the same + // guarantee. Every value-level invariant the source upheld — UTF-8 validity, + // monotonic offsets, in-bounds dictionary indices, run-end monotonicity, + // struct child-length matching — therefore transfers to the copy. If the + // source `ArrayData` was itself constructed via `new_unchecked` with an + // invalid payload, this function faithfully reproduces that invalidity. + unsafe { + ArrayDataBuilder::new(data_type) + .len(len) + .nulls(nulls) + .offset(offset) + .buffers(buffers) + .child_data(child_data) + .build_unchecked() + } +} + +pub fn deep_copy_array(array: &dyn Array) -> Arc { + let data = array.to_data(); + let data = deep_copy_array_data(&data); + make_array(data) +} + +pub fn deep_copy_batch(batch: &RecordBatch) -> crate::Result { + let arrays = batch + .columns() + .iter() + .map(|array| deep_copy_array(array)) + .collect::>(); + RecordBatch::try_new(batch.schema(), arrays) +} + +/// Deep copy array data, extracting only the sliced portion using MutableArrayData +/// This is the most efficient and correct way to copy just the sliced data +pub fn deep_copy_array_data_sliced(data: &ArrayData) -> ArrayData { + // Use MutableArrayData to efficiently copy just the slice + let mut mutable = MutableArrayData::new(vec![data], false, data.len()); + + // Which index this takes depends on the layout, because arrow's extenders + // disagree about who applies `ArrayData::offset()`. The bit-packed one adds + // it to the raw values buffer itself, so an offset-applied index there + // reads from twice the offset and runs off the end of the buffer. Every + // other layout either reads through an already-offset-applied view or + // forwards the index to children carrying their own offsets, and takes the + // absolute index it has always been given. + let start = match data.data_type() { + DataType::Boolean => 0, + _ => data.offset(), + }; + mutable.extend(0, start, start + data.len()); + + // Freeze into immutable ArrayData + mutable.freeze() +} + +/// Deep copy an array, extracting only the sliced portion using MutableArrayData +pub fn deep_copy_array_sliced(array: &dyn Array) -> Arc { + let data = array.to_data(); + let data = deep_copy_array_data_sliced(&data); + make_array(data) +} + +/// Deep copy a RecordBatch, extracting only the sliced portion using MutableArrayData +pub fn deep_copy_batch_sliced(batch: &RecordBatch) -> crate::Result { + let arrays = batch + .columns() + .iter() + .map(|array| deep_copy_array_sliced(array)) + .collect::>(); + RecordBatch::try_new(batch.schema(), arrays) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{Array, BooleanArray, Int32Array, RecordBatch, StringArray}; + use arrow_data::ArrayDataBuilder; + use arrow_schema::{DataType, Field, Schema}; + + #[test] + fn raw_sliced_fixed_size_list_data_keeps_its_child_offset() { + // `ArrayData::slice` records the offset on the parent and leaves the + // child whole -- a shape `FixedSizeListArray::slice` never produces, + // but a legal one this public helper can be handed directly. Arrow's + // extender forwards `start * size` to that unsliced child and adds + // nothing, so the index it gets has to be the absolute one; this is + // here to stop the boolean fix from being generalised over it. + let child = Int32Array::from(vec![10, 11, 20, 21]).to_data(); + let field = Arc::new(Field::new_list_field(DataType::Int32, false)); + let data = ArrayDataBuilder::new(DataType::FixedSizeList(field, 2)) + .len(2) + .add_child_data(child) + .build() + .unwrap(); + let sliced = data.slice(1, 1); + + let copied = super::deep_copy_array_data_sliced(&sliced); + let copied_child = Int32Array::from(copied.child_data()[0].clone()); + assert_eq!(copied_child.values().as_ref(), &[20, 21]); + } + + #[test] + fn raw_sliced_struct_of_fixed_size_list_reaches_the_right_values() { + // Slicing raw struct data pushes the window into the struct's children, + // and a fixed-size-list child takes it as its own parent offset with + // its values left whole. Two levels of offset, and the absolute index + // has to remain right through both of them. + let values = Int32Array::from(vec![10, 11, 20, 21, 30, 31]).to_data(); + let item = Arc::new(Field::new_list_field(DataType::Int32, false)); + let list = ArrayDataBuilder::new(DataType::FixedSizeList(item, 2)) + .len(3) + .add_child_data(values) + .build() + .unwrap(); + let field = Arc::new(Field::new("l", list.data_type().clone(), false)); + let data = ArrayDataBuilder::new(DataType::Struct(vec![field].into())) + .len(3) + .add_child_data(list) + .build() + .unwrap(); + let sliced = data.slice(2, 1); + + let copied = super::deep_copy_array_data_sliced(&sliced); + let copied_values = Int32Array::from(copied.child_data()[0].child_data()[0].clone()); + assert_eq!(copied_values.values().as_ref(), &[30, 31]); + } + + #[test] + fn raw_parent_offset_struct_keeps_the_selected_child_row() { + // A struct whose children are whole and whose window is the parent + // offset: arrow's struct extender forwards the index to those children + // untouched, so it has to be the absolute one. + let field = Arc::new(Field::new("a", DataType::Int32, false)); + let data = ArrayDataBuilder::new(DataType::Struct(vec![field].into())) + .len(1) + .offset(1) + .add_child_data(Int32Array::from(vec![10, 20]).to_data()) + .build() + .unwrap(); + + let copied = super::deep_copy_array_data_sliced(&data); + let copied_child = Int32Array::from(copied.child_data()[0].clone()); + assert_eq!(copied_child.values().as_ref(), &[20]); + } + + #[test] + fn sliced_boolean_deep_copy_reads_from_the_slice() { + // A boolean slice keeps its `ArrayData::offset()` -- the buffer cannot + // advance by a fraction of a byte -- so a copy that adds the offset on + // top of what `MutableArrayData` already applies reads past the end of + // the values buffer and panics. + let array = BooleanArray::from(vec![true, false, true, false, true, false, true, false]); + for (offset, len) in [(0usize, 8usize), (1, 7), (3, 5), (7, 1)] { + let sliced = array.slice(offset, len); + let copied = super::deep_copy_array_sliced(&sliced); + let copied = copied.as_any().downcast_ref::().unwrap(); + let expected: Vec = (0..len).map(|i| sliced.value(i)).collect(); + let actual: Vec = (0..len).map(|i| copied.value(i)).collect(); + assert_eq!(actual, expected, "offset={offset} len={len}"); + } + } + + #[test] + fn sliced_boolean_deep_copy_keeps_its_nulls() { + let array = BooleanArray::from(vec![ + Some(true), + None, + Some(false), + Some(true), + None, + Some(false), + ]); + let sliced = array.slice(1, 4); + let copied = super::deep_copy_array_sliced(&sliced); + let copied = copied.as_any().downcast_ref::().unwrap(); + let expected: Vec> = (0..sliced.len()) + .map(|i| (!sliced.is_null(i)).then(|| sliced.value(i))) + .collect(); + let actual: Vec> = (0..copied.len()) + .map(|i| (!copied.is_null(i)).then(|| copied.value(i))) + .collect(); + assert_eq!(actual, expected); + } + + #[test] + fn test_deep_copy_sliced_array_with_nulls() { + let array = Arc::new(Int32Array::from(vec![ + Some(1), + None, + Some(3), + None, + Some(5), + ])); + let sliced_array = array.slice(1, 3); + let copied_array = super::deep_copy_array(&sliced_array); + assert_eq!(sliced_array.len(), copied_array.len()); + assert_eq!(sliced_array.nulls(), copied_array.nulls()); + } + + #[test] + fn test_deep_copy_array_data_sliced() { + let array = Int32Array::from((0..1000).collect::>()); + let sliced = array.slice(100, 10); + + let sliced_data = sliced.to_data(); + let copied_data = super::deep_copy_array_data_sliced(&sliced_data); + + assert_eq!(copied_data.len(), 10); + assert_eq!(copied_data.offset(), 0); + + // Verify data correctness + let copied_array = Int32Array::from(copied_data); + for i in 0..10 { + assert_eq!(copied_array.value(i), 100 + i as i32); + } + } + + #[test] + fn test_deep_copy_array_sliced() { + let array = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])); + let sliced = array.slice(1, 3); + + let copied = super::deep_copy_array_sliced(&sliced); + + assert_eq!(copied.len(), 3); + let copied_int = copied.as_any().downcast_ref::().unwrap(); + assert_eq!(copied_int.value(0), 2); + assert_eq!(copied_int.value(1), 3); + assert_eq!(copied_int.value(2), 4); + } + + #[test] + fn test_deep_copy_batch_sliced() { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", DataType::Utf8, false), + ])); + + let id_array = Arc::new(Int32Array::from((0..100).collect::>())); + let name_array = Arc::new(StringArray::from( + (0..100) + .map(|i| format!("name_{}", i)) + .collect::>(), + )); + + let batch = RecordBatch::try_new( + schema, + vec![id_array as Arc, name_array as Arc], + ) + .unwrap(); + + let sliced = batch.slice(10, 5); + let copied = super::deep_copy_batch_sliced(&sliced).unwrap(); + + assert_eq!(copied.num_rows(), 5); + assert_eq!(copied.num_columns(), 2); + + // Verify data correctness + let id_col = copied + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let name_col = copied + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + + for i in 0..5 { + assert_eq!(id_col.value(i), 10 + i as i32); + assert_eq!(name_col.value(i), format!("name_{}", 10 + i)); + } + } + + #[test] + fn test_deep_copy_array_sliced_with_nulls() { + let array = Arc::new(Int32Array::from(vec![ + Some(1), + None, + Some(3), + None, + Some(5), + ])); + let sliced = array.slice(1, 3); // [None, Some(3), None] + + let copied = super::deep_copy_array_sliced(&sliced); + + assert_eq!(copied.len(), 3); + assert_eq!(copied.null_count(), 2); // Two nulls in the slice + + let copied_int = copied.as_any().downcast_ref::().unwrap(); + assert!(!copied_int.is_valid(0)); // None + assert!(copied_int.is_valid(1)); // Some(3) + assert!(!copied_int.is_valid(2)); // None + assert_eq!(copied_int.value(1), 3); + } +} diff --git a/python/vendor/lance-arrow/src/floats.rs b/python/vendor/lance-arrow/src/floats.rs new file mode 100644 index 000000000..0024fbb02 --- /dev/null +++ b/python/vendor/lance-arrow/src/floats.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Floats Array + +use std::fmt::{Debug, Display}; +use std::iter::Sum; +use std::sync::Arc; +use std::{ + fmt::Formatter, + ops::{AddAssign, DivAssign}, +}; + +use arrow_array::{ + Array, FixedSizeBinaryArray, Float16Array, Float32Array, Float64Array, + types::{Float16Type, Float32Type, Float64Type}, +}; +use arrow_schema::{DataType, Field}; +use half::{bf16, f16}; +use num_traits::{AsPrimitive, Bounded, Float, FromPrimitive}; + +use super::bfloat16::{BFloat16Array, BFloat16Type}; +use crate::Result; +use crate::bfloat16::is_bfloat16_field; + +/// Float data type. +/// +/// This helps differentiate between the different float types, +/// because bf16 is not officially supported [DataType] in arrow-rs. +#[derive(Debug)] +pub enum FloatType { + BFloat16, + Float16, + Float32, + Float64, +} + +impl std::fmt::Display for FloatType { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + Self::BFloat16 => write!(f, "bfloat16"), + Self::Float16 => write!(f, "float16"), + Self::Float32 => write!(f, "float32"), + Self::Float64 => write!(f, "float64"), + } + } +} + +/// Try to convert a [DataType] to a [FloatType]. To support bfloat16, always +/// prefer using the `TryFrom<&Field>` implementation. +impl TryFrom<&DataType> for FloatType { + type Error = crate::ArrowError; + + fn try_from(value: &DataType) -> Result { + match *value { + DataType::Float16 => Ok(Self::Float16), + DataType::Float32 => Ok(Self::Float32), + DataType::Float64 => Ok(Self::Float64), + _ => Err(crate::ArrowError::InvalidArgumentError(format!( + "{:?} is not a floating type", + value + ))), + } + } +} + +impl TryFrom<&Field> for FloatType { + type Error = crate::ArrowError; + + fn try_from(field: &Field) -> Result { + match field.data_type() { + DataType::FixedSizeBinary(2) if is_bfloat16_field(field) => Ok(Self::BFloat16), + _ => Self::try_from(field.data_type()), + } + } +} + +/// Trait for float types used in Lance indexes +/// +/// This mimics the utilities provided by [`arrow_array::ArrowPrimitiveType`] +/// but applies to all float types (including bfloat16) +pub trait ArrowFloatType: Debug { + type Native: FromPrimitive + + FloatToArrayType + + AsPrimitive + + Debug + + Display; + + const FLOAT_TYPE: FloatType; + const MIN: Self::Native; + const MAX: Self::Native; + + /// Arrow Float Array Type. + type ArrayType: FloatArray; + + /// Returns empty array of this type. + fn empty_array() -> Self::ArrayType { + >::from_values(Vec::new()) + } +} + +/// Trait to be implemented by native types that have a corresponding [`ArrowFloatType`] +/// implementation. +/// +/// This helps define what operations are supported by native floats and also helps convert +/// from a native type back to the corresponding Arrow float type. +pub trait FloatToArrayType: + Float + + Bounded + + Sum + + AddAssign + + AsPrimitive + + AsPrimitive + + DivAssign + + Send + + Sync + + Copy +{ + /// The corresponding [`ArrowFloatType`] implementation for this native type + type ArrowType: ArrowFloatType; +} + +impl FloatToArrayType for bf16 { + type ArrowType = BFloat16Type; +} + +impl FloatToArrayType for f16 { + type ArrowType = Float16Type; +} + +impl FloatToArrayType for f32 { + type ArrowType = Float32Type; +} + +impl FloatToArrayType for f64 { + type ArrowType = Float64Type; +} + +impl ArrowFloatType for BFloat16Type { + type Native = bf16; + + const FLOAT_TYPE: FloatType = FloatType::BFloat16; + const MIN: Self::Native = bf16::MIN; + const MAX: Self::Native = bf16::MAX; + + type ArrayType = FixedSizeBinaryArray; +} + +impl ArrowFloatType for Float16Type { + type Native = f16; + + const FLOAT_TYPE: FloatType = FloatType::Float16; + const MIN: Self::Native = f16::MIN; + const MAX: Self::Native = f16::MAX; + + type ArrayType = Float16Array; +} + +impl ArrowFloatType for Float32Type { + type Native = f32; + + const FLOAT_TYPE: FloatType = FloatType::Float32; + const MIN: Self::Native = f32::MIN; + const MAX: Self::Native = f32::MAX; + + type ArrayType = Float32Array; +} + +impl ArrowFloatType for Float64Type { + type Native = f64; + + const FLOAT_TYPE: FloatType = FloatType::Float64; + const MIN: Self::Native = f64::MIN; + const MAX: Self::Native = f64::MAX; + + type ArrayType = Float64Array; +} + +/// [FloatArray] is a trait that is implemented by all float type arrays +/// +/// This is similar to [`arrow_array::PrimitiveArray`] but applies to all float types (including bfloat16) +/// and is implemented as a trait and not a struct +pub trait FloatArray: Array + Clone + 'static { + type FloatType: ArrowFloatType; + + /// Returns a reference to the underlying data as a slice. + /// + /// # Panics + /// + /// Implementations may panic if the array's storage shape does not match + /// the expected element layout. In particular, the `bf16` impl panics if + /// `value_length() != 2` (the `FixedSizeBinary(2)` shape required by + /// `BFloat16Array`). + /// + /// # Preconditions + /// + /// Implementations may impose additional invariants on the underlying + /// buffer. The `bf16` impl requires the value buffer to be at least + /// 2-byte aligned — satisfied automatically by every in-tree Lance + /// constructor, but external callers passing externally-built arrays + /// (FFI, IPC, `Buffer::from_custom_allocation`) must ensure alignment. + /// See the impl's docstring for details. + fn as_slice(&self) -> &[T::Native]; + + /// Construct an array from a vector of values. + fn from_values(values: Vec) -> Self; + + /// Construct an array from an iterator of values. + fn from_iter_values(values: impl IntoIterator) -> Self + where + Self: Sized, + { + Self::from_values(values.into_iter().collect()) + } +} + +impl FloatArray for Float16Array { + type FloatType = Float16Type; + + fn as_slice(&self) -> &[::Native] { + self.values() + } + + fn from_values(values: Vec<::Native>) -> Self { + Self::from(values) + } +} + +impl FloatArray for Float32Array { + type FloatType = Float32Type; + + fn as_slice(&self) -> &[::Native] { + self.values() + } + + fn from_values(values: Vec<::Native>) -> Self { + Self::from(values) + } +} + +impl FloatArray for Float64Array { + type FloatType = Float64Type; + + fn as_slice(&self) -> &[::Native] { + self.values() + } + + fn from_values(values: Vec<::Native>) -> Self { + Self::from(values) + } +} + +/// Convert a float32 array to another float array +/// +/// This is used during queries as query vectors are always provided as float32 arrays +/// and need to be converted to the appropriate float type for the index. +pub fn coerce_float_vector(input: &Float32Array, float_type: FloatType) -> Result> { + match float_type { + FloatType::BFloat16 => Ok(Arc::new( + BFloat16Array::from_iter_values(input.values().iter().map(|v| bf16::from_f32(*v))) + .into_inner(), + )), + FloatType::Float16 => Ok(Arc::new(Float16Array::from_iter_values( + input.values().iter().map(|v| f16::from_f32(*v)), + ))), + FloatType::Float32 => Ok(Arc::new(input.clone())), + FloatType::Float64 => Ok(Arc::new(Float64Array::from_iter_values( + input.values().iter().map(|v| *v as f64), + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_coerce_float_vector_bfloat16() { + let input = Float32Array::from(vec![1.0f32, 2.0, 3.0]); + let array = coerce_float_vector(&input, FloatType::BFloat16).unwrap(); + + assert_eq!(array.data_type(), &DataType::FixedSizeBinary(2)); + + let fixed = array + .as_any() + .downcast_ref::() + .unwrap(); + let expected: Vec = input.values().iter().map(|v| bf16::from_f32(*v)).collect(); + assert_eq!(fixed.as_slice(), expected.as_slice()); + } +} diff --git a/python/vendor/lance-arrow/src/ipc.rs b/python/vendor/lance-arrow/src/ipc.rs new file mode 100644 index 000000000..099c362b4 --- /dev/null +++ b/python/vendor/lance-arrow/src/ipc.rs @@ -0,0 +1,621 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Zero-copy Arrow IPC stream read/write utilities. +//! +//! Provides helpers for serializing and deserializing [`RecordBatch`]es as +//! self-delimiting Arrow IPC streams using synchronous [`Read`]/[`Write`] I/O. +//! +//! These are designed for embedding IPC streams inside larger binary formats +//! (e.g. a cache entry that contains multiple IPC sections). Each stream is +//! self-delimiting (schema + batches + EOS marker) and can be read back +//! independently. +//! +//! # Zero-copy reads +//! +//! [`read_ipc_stream`] and [`read_ipc_stream_single`] take `&Bytes` and use +//! [`Bytes::slice`] to produce each message buffer. Because `Bytes::slice` +//! increments a reference count rather than copying, the resulting +//! [`Buffer`]s — and the array data decoded from them by [`FileDecoder`] — +//! are all backed by the same allocation as the input. + +use std::io::{Read, Write}; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_buffer::Buffer; +use arrow_ipc::convert::fb_to_schema; +use arrow_ipc::reader::FileDecoder; +use arrow_ipc::root_as_message; +use arrow_ipc::writer::StreamWriter; +use arrow_schema::ArrowError; +use bytes::Bytes; + +// --------------------------------------------------------------------------- +// Length-prefixed byte utilities +// --------------------------------------------------------------------------- + +/// Write `data` prefixed by its length as a little-endian `u64`. +/// +/// Paired with [`read_len_prefixed_bytes`]. +pub fn write_len_prefixed_bytes(writer: &mut dyn Write, data: &[u8]) -> Result<(), ArrowError> { + writer + .write_all(&(data.len() as u64).to_le_bytes()) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + writer + .write_all(data) + .map_err(|e| ArrowError::IoError(e.to_string(), e)) +} + +/// Read a byte slice written by [`write_len_prefixed_bytes`]. +/// +/// Reads an 8-byte little-endian length then exactly that many bytes. +pub fn read_len_prefixed_bytes(reader: &mut dyn Read) -> Result, ArrowError> { + let mut len_buf = [0u8; 8]; + reader + .read_exact(&mut len_buf) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + let len = u64::from_le_bytes(len_buf) as usize; + let mut buf = vec![0u8; len]; + reader + .read_exact(&mut buf) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + Ok(buf) +} + +// --------------------------------------------------------------------------- +// IPC stream utilities +// --------------------------------------------------------------------------- + +// 4-byte continuation marker used by modern Arrow IPC streams. +const IPC_CONTINUATION: [u8; 4] = [0xff; 4]; + +/// Write `batch` as a single-batch Arrow IPC stream to `writer`. +pub fn write_ipc_stream(batch: &RecordBatch, writer: &mut dyn Write) -> Result<(), ArrowError> { + let mut sw = StreamWriter::try_new(&mut *writer, batch.schema_ref())?; + sw.write(batch)?; + sw.finish() +} + +/// Write all batches from `iter` as a single Arrow IPC stream to `writer`. +/// +/// `iter` must yield at least one batch; the schema is inferred from the first +/// batch. Returns `ArrowError::InvalidArgumentError` if the iterator is empty. +/// If you need to write an empty stream (schema only, no rows), construct a +/// `StreamWriter` directly. +pub fn write_ipc_stream_batches(iter: I, writer: &mut dyn Write) -> Result<(), ArrowError> +where + I: IntoIterator, +{ + let mut iter = iter.into_iter(); + let first = iter + .next() + .ok_or_else(|| ArrowError::InvalidArgumentError("no batches to serialize".into()))?; + let mut sw = StreamWriter::try_new(&mut *writer, first.schema_ref())?; + sw.write(&first)?; + for batch in iter { + sw.write(&batch)?; + } + sw.finish() +} + +/// Read one complete Arrow IPC stream message from `data` as a zero-copy [`Buffer`]. +/// +/// Parses the first message starting at byte 0 of `data`. Returns `None` on +/// EOS (size field == 0) or empty input. The returned [`Buffer`] is backed by +/// `data`'s allocation — no bytes are copied. +/// +/// The caller should advance its position by `buf.len()` after each call. +fn read_one_ipc_message(data: &Bytes) -> Result, ArrowError> { + let bytes = data.as_ref(); + + if bytes.is_empty() { + return Ok(None); + } + if bytes.len() < 4 { + return Err(ArrowError::IoError( + "IPC: truncated header".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated IPC header"), + )); + } + + let has_continuation = bytes[..4] == IPC_CONTINUATION; + let (size_bytes, prefix_len): ([u8; 4], usize) = if has_continuation { + if bytes.len() < 8 { + return Err(ArrowError::IoError( + "IPC: truncated header after continuation".into(), + std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "truncated after continuation", + ), + )); + } + (bytes[4..8].try_into().unwrap(), 8) + } else { + (bytes[..4].try_into().unwrap(), 4) + }; + + let meta_size = u32::from_le_bytes(size_bytes) as usize; + if meta_size == 0 { + return Ok(None); // EOS + } + + let meta_end = prefix_len + meta_size; + if bytes.len() < meta_end { + return Err(ArrowError::IoError( + "IPC: truncated metadata".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated IPC metadata"), + )); + } + + let msg = root_as_message(&bytes[prefix_len..meta_end]) + .map_err(|e| ArrowError::ParseError(format!("IPC message parse error: {e}")))?; + let body_len = msg.bodyLength() as usize; + + let total = meta_end + body_len; + if bytes.len() < total { + return Err(ArrowError::IoError( + "IPC: truncated body".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated IPC body"), + )); + } + + // Zero-copy: Bytes::slice shares the backing allocation; Buffer::from + // wraps it without copying. + Ok(Some(Buffer::from(data.slice(0..total)))) +} + +/// Read a length-prefixed byte slice at `offset` in `data`, advancing `offset`. +/// +/// Reads an 8-byte little-endian length, then slices exactly that many bytes +/// from `data`. The returned [`Bytes`] is zero-copy (shares `data`'s allocation). +pub fn read_len_prefixed_bytes_at(data: &Bytes, offset: &mut usize) -> Result { + let bytes = data.as_ref(); + let len_end = offset + .checked_add(8) + .filter(|&e| e <= bytes.len()) + .ok_or_else(|| { + ArrowError::IoError( + "length-prefixed bytes: truncated length field".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated length"), + ) + })?; + let len = u64::from_le_bytes(bytes[*offset..len_end].try_into().unwrap()) as usize; + *offset = len_end; + let data_end = offset + .checked_add(len) + .filter(|&e| e <= bytes.len()) + .ok_or_else(|| { + ArrowError::IoError( + "length-prefixed bytes: truncated data".into(), + std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated data"), + ) + })?; + let result = data.slice(*offset..data_end); + *offset = data_end; + Ok(result) +} + +/// Read all [`RecordBatch`]es from one Arrow IPC stream starting at `offset`, +/// advancing `offset` past the stream (including the EOS marker). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation. +pub fn read_ipc_stream_at( + data: &Bytes, + offset: &mut usize, +) -> Result, ArrowError> { + let batches = read_ipc_stream(&data.slice(*offset..))?; + + // Recompute how many bytes were consumed by re-parsing message sizes. + // We can't get this from read_ipc_stream directly, so we re-walk the + // message headers (metadata only, no body re-read) to sum up lengths. + let slice = &data.as_ref()[*offset..]; + let mut consumed = 0usize; + loop { + let rem = &slice[consumed..]; + if rem.is_empty() { + break; + } + let has_cont = rem.len() >= 4 && rem[..4] == IPC_CONTINUATION; + let (size_bytes, prefix_len): ([u8; 4], usize) = if has_cont { + if rem.len() < 8 { + break; + } + (rem[4..8].try_into().unwrap(), 8) + } else { + if rem.len() < 4 { + break; + } + (rem[..4].try_into().unwrap(), 4) + }; + let meta_size = u32::from_le_bytes(size_bytes) as usize; + if meta_size == 0 { + // EOS — consume it and stop. + consumed += prefix_len; + break; + } + let meta_end = prefix_len + meta_size; + if rem.len() < meta_end { + break; + } + let msg = root_as_message(&rem[prefix_len..meta_end]) + .map_err(|e| ArrowError::ParseError(format!("IPC message parse error: {e}")))?; + let body_len = msg.bodyLength() as usize; + consumed += meta_end + body_len; + } + *offset += consumed; + + Ok(batches) +} + +/// Read exactly one [`RecordBatch`] from one Arrow IPC stream starting at `offset`, +/// advancing `offset` past the stream (including the EOS marker). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation. +pub fn read_ipc_stream_single_at( + data: &Bytes, + offset: &mut usize, +) -> Result { + let mut batches = read_ipc_stream_at(data, offset)?; + match batches.len() { + 1 => Ok(batches.remove(0)), + n => Err(ArrowError::ParseError(format!( + "expected exactly 1 IPC record batch, got {n}" + ))), + } +} + +/// Extract the prefix length and metadata size from a raw IPC message buffer. +/// +/// Modern IPC streams have an 8-byte prefix `[continuation: 4][size: 4]`. +/// Legacy streams have a 4-byte prefix `[size: 4]`. Returns `(prefix_len, meta_size)`. +fn parse_ipc_message_prefix(buf: &Buffer) -> Result<(usize, usize), ArrowError> { + let has_continuation = buf.len() >= 4 && buf[..4] == IPC_CONTINUATION; + if has_continuation { + if buf.len() < 8 { + return Err(ArrowError::ParseError( + "IPC message buffer too short".into(), + )); + } + let meta_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()) as usize; + Ok((8, meta_size)) + } else { + if buf.len() < 4 { + return Err(ArrowError::ParseError( + "IPC message buffer too short".into(), + )); + } + let meta_size = u32::from_le_bytes(buf[..4].try_into().unwrap()) as usize; + Ok((4, meta_size)) + } +} + +/// Read all [`RecordBatch`]es from one Arrow IPC stream. +/// +/// Zero-copy: each batch's array data buffers are borrowed from the input +/// message buffer(s) and not copied during decoding. +/// +/// Uses [`FileDecoder`] directly (rather than `StreamDecoder`) to avoid a +/// known edge case where `StreamDecoder` does not produce a batch for messages +/// with a zero-length body when the message exactly fills the decode buffer. +pub fn read_ipc_stream(data: &Bytes) -> Result, ArrowError> { + let mut offset = 0usize; + + let schema_buf = read_one_ipc_message(&data.slice(offset..))?.ok_or_else(|| { + ArrowError::ParseError("IPC stream: expected schema message, got EOS".into()) + })?; + offset += schema_buf.len(); + + let (prefix_len, meta_size) = parse_ipc_message_prefix(&schema_buf)?; + let schema_msg = root_as_message(&schema_buf[prefix_len..prefix_len + meta_size]) + .map_err(|e| ArrowError::ParseError(format!("IPC schema parse error: {e}")))?; + let schema = Arc::new(fb_to_schema(schema_msg.header_as_schema().ok_or_else( + || ArrowError::ParseError("IPC stream: first message is not a schema".into()), + )?)); + let mut decoder = FileDecoder::new(schema, schema_msg.version()); + + let mut batches = Vec::new(); + + loop { + let Some(buf) = read_one_ipc_message(&data.slice(offset..))? else { + break; + }; + offset += buf.len(); + + let (prefix_len, meta_size) = parse_ipc_message_prefix(&buf)?; + let msg = root_as_message(&buf[prefix_len..prefix_len + meta_size]) + .map_err(|e| ArrowError::ParseError(format!("IPC message parse error: {e}")))?; + let body_len = msg.bodyLength() as usize; + + // Block offset = 0 since the buffer starts at the message boundary. + // metaDataLength = prefix_len + meta_size (prefix + flatbuf + padding). + let block = arrow_ipc::Block::new(0, (prefix_len + meta_size) as i32, body_len as i64); + + match msg.header_type() { + arrow_ipc::MessageHeader::RecordBatch => { + if let Some(batch) = decoder.read_record_batch(&block, &buf)? { + batches.push(batch); + } + } + arrow_ipc::MessageHeader::DictionaryBatch => { + decoder.read_dictionary(&block, &buf)?; + } + _ => break, + } + } + + Ok(batches) +} + +/// Read exactly one [`RecordBatch`] from one Arrow IPC stream. +pub fn read_ipc_stream_single(data: &Bytes) -> Result { + let mut batches = read_ipc_stream(data)?; + match batches.len() { + 1 => Ok(batches.remove(0)), + n => Err(ArrowError::ParseError(format!( + "expected exactly 1 IPC record batch, got {n}" + ))), + } +} + +// --------------------------------------------------------------------------- +// Aligned IPC sections +// --------------------------------------------------------------------------- + +/// Byte alignment that each IPC section's stream start is padded to. +/// +/// When several IPC streams are concatenated into one larger blob (e.g. a +/// cache entry), a section that starts at an arbitrary offset would leave its +/// array data misaligned. [`FileDecoder`] with `require_alignment = false` +/// then silently copies each buffer into a freshly aligned allocation on +/// every read, defeating zero-copy. Padding each section start to a 64-byte +/// boundary keeps the decoded buffers borrowed directly from the input. +pub const IPC_SECTION_ALIGNMENT: usize = 64; + +/// Number of zero-padding bytes needed to advance `pos` to the next +/// [`IPC_SECTION_ALIGNMENT`] boundary. +fn section_padding(pos: usize) -> usize { + (IPC_SECTION_ALIGNMENT - (pos % IPC_SECTION_ALIGNMENT)) % IPC_SECTION_ALIGNMENT +} + +/// A [`Write`] adapter that counts the bytes written through it. +struct CountingWriter<'a> { + inner: &'a mut dyn Write, + count: usize, +} + +impl Write for CountingWriter<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let n = self.inner.write(buf)?; + self.count += n; + Ok(n) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + +/// Write zero padding so the next byte lands on an [`IPC_SECTION_ALIGNMENT`] +/// boundary, advancing `pos` past it. +fn write_section_padding(writer: &mut dyn Write, pos: &mut usize) -> Result<(), ArrowError> { + let pad = section_padding(*pos); + if pad > 0 { + const ZEROS: [u8; IPC_SECTION_ALIGNMENT] = [0u8; IPC_SECTION_ALIGNMENT]; + writer + .write_all(&ZEROS[..pad]) + .map_err(|e| ArrowError::IoError(e.to_string(), e))?; + *pos += pad; + } + Ok(()) +} + +/// Write `batch` as a 64-byte-aligned single-batch Arrow IPC section. +/// +/// `pos` is the absolute byte offset of `writer` within the enclosing blob. +/// Zero padding is written first so the IPC stream begins on an +/// [`IPC_SECTION_ALIGNMENT`] boundary, then the stream itself. `pos` is +/// advanced past both the padding and the stream so the caller can write +/// further aligned sections. +/// +/// Paired with [`read_ipc_section_at`]. For the decoded buffers to be borrowed +/// zero-copy, the blob must ultimately be read back from a buffer whose base +/// address is at least 64-byte aligned. +pub fn write_ipc_section( + writer: &mut dyn Write, + pos: &mut usize, + batch: &RecordBatch, +) -> Result<(), ArrowError> { + write_section_padding(writer, pos)?; + + let mut counting = CountingWriter { + inner: writer, + count: 0, + }; + write_ipc_stream(batch, &mut counting)?; + *pos += counting.count; + Ok(()) +} + +/// Read a single [`RecordBatch`] from an aligned IPC section at `offset`. +/// +/// Skips the alignment padding written by [`write_ipc_section`], then reads +/// the stream, advancing `offset` past the section (padding + stream + EOS). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation when `data`'s base +/// address is at least 64-byte aligned (see [`write_ipc_section`]). +pub fn read_ipc_section_at(data: &Bytes, offset: &mut usize) -> Result { + *offset += section_padding(*offset); + read_ipc_stream_single_at(data, offset) +} + +/// Write `batches` as a single 64-byte-aligned multi-batch Arrow IPC section. +/// +/// Like [`write_ipc_section`] but emits every batch from `iter` into one IPC +/// stream (schema + N batches + EOS). `iter` must yield at least one batch. +/// Paired with [`read_ipc_section_batches_at`]. +pub fn write_ipc_section_batches( + writer: &mut dyn Write, + pos: &mut usize, + iter: I, +) -> Result<(), ArrowError> +where + I: IntoIterator, +{ + write_section_padding(writer, pos)?; + + let mut counting = CountingWriter { + inner: writer, + count: 0, + }; + write_ipc_stream_batches(iter, &mut counting)?; + *pos += counting.count; + Ok(()) +} + +/// Read all [`RecordBatch`]es from an aligned multi-batch IPC section at +/// `offset`, advancing `offset` past the section (padding + stream + EOS). +/// +/// Zero-copy: array buffers borrow from `data`'s allocation when `data`'s base +/// address is at least 64-byte aligned (see [`write_ipc_section_batches`]). +pub fn read_ipc_section_batches_at( + data: &Bytes, + offset: &mut usize, +) -> Result, ArrowError> { + *offset += section_padding(*offset); + read_ipc_stream_at(data, offset) +} + +#[cfg(test)] +mod tests { + use arrow_array::{ArrayRef, record_batch}; + + use super::*; + + #[test] + fn test_ipc_roundtrip() { + let batch1 = record_batch!( + ("int", Int32, [1, 2, 3]), + ("str", Utf8, ["foo", "bar", "baz"]) + ) + .unwrap(); + let batch2 = record_batch!(("int", Int32, [4, 5]), ("str", Utf8, ["qux", "quux"])).unwrap(); + let batches = vec![batch1.clone(), batch2.clone()]; + + let mut buf = Vec::new(); + write_ipc_stream_batches(batches, &mut buf).unwrap(); + + let data = Bytes::from(buf); + + let batches = read_ipc_stream(&data).unwrap(); + assert_eq!(batches.len(), 2); + assert_eq!(batches[0], batch1); + assert_eq!(batches[1], batch2); + + let data_base = data.as_ptr() as usize; + let data_end = data_base + data.len(); + let assert_col_zero_copy = |array: &ArrayRef| { + for buffer in array.to_data().buffers() { + let ptr = buffer.as_ptr() as usize; + assert!( + ptr >= data_base && ptr < data_end, + "buffer at {ptr:#x} is not backed by the input Bytes allocation \ + [{data_base:#x}..{data_end:#x})" + ); + } + }; + + for batch in &batches { + assert_eq!(batch.schema(), batch1.schema()); + assert_col_zero_copy(batch.column(0)); + assert_col_zero_copy(batch.column(1)); + } + } + + /// Allocate a [`Bytes`] whose base address is 64-byte aligned, modelling a + /// backend that reads cache entries into an aligned buffer. A plain + /// `Bytes::from(vec)` only guarantees the allocator's alignment for `u8`. + fn aligned_bytes(payload: &[u8]) -> Bytes { + let mut v = vec![0u8; payload.len() + IPC_SECTION_ALIGNMENT]; + let pad = section_padding(v.as_ptr() as usize); + v[pad..pad + payload.len()].copy_from_slice(payload); + Bytes::from(v).slice(pad..pad + payload.len()) + } + + #[test] + fn test_aligned_ipc_sections_are_zero_copy() { + // A LargeBinary column exercises the i64-offset buffer whose 8-byte + // alignment requirement triggers a realigning memcpy when misaligned. + let blocks = arrow_array::LargeBinaryArray::from_vec(vec![&b"hello"[..], b"world"]); + let section_a = RecordBatch::try_from_iter([("a", Arc::new(blocks) as ArrayRef)]).unwrap(); + let section_b = record_batch!(("b", Int64, [10i64, 20, 30, 40, 50])).unwrap(); + + let mut buf = Vec::new(); + // Arbitrary, deliberately non-64-aligned preamble so the first section + // must be padded rather than landing at offset 0 by luck. + buf.extend_from_slice(&[0xABu8; 7]); + let mut pos = buf.len(); + // The first section's stream begins after padding the 7-byte preamble + // up to the next 64-byte boundary. + assert_eq!(7 + section_padding(7), IPC_SECTION_ALIGNMENT); + write_ipc_section(&mut buf, &mut pos, §ion_a).unwrap(); + write_ipc_section(&mut buf, &mut pos, §ion_b).unwrap(); + + let data = aligned_bytes(&buf); + assert_eq!( + section_padding(data.as_ptr() as usize), + 0, + "base not aligned" + ); + + let mut offset = 7; + let read_a = read_ipc_section_at(&data, &mut offset).unwrap(); + let read_b = read_ipc_section_at(&data, &mut offset).unwrap(); + assert_eq!(read_a, section_a); + assert_eq!(read_b, section_b); + + let data_base = data.as_ptr() as usize; + let data_end = data_base + data.len(); + for batch in [&read_a, &read_b] { + for buffer in batch.column(0).to_data().buffers() { + let ptr = buffer.as_ptr() as usize; + assert!( + ptr >= data_base && ptr < data_end, + "section buffer at {ptr:#x} was realigned out of the input \ + [{data_base:#x}..{data_end:#x}) — misaligned section", + ); + } + } + } + + #[test] + fn test_aligned_multi_batch_section_roundtrip_zero_copy() { + // A multi-batch section (e.g. IVF SQ storage chunks) must round-trip + // every batch and decode the first batch's buffers zero-copy. + let b1 = record_batch!(("v", Int64, [1i64, 2, 3])).unwrap(); + let b2 = record_batch!(("v", Int64, [4i64, 5])).unwrap(); + let b3 = record_batch!(("v", Int64, [6i64])).unwrap(); + + let mut buf = vec![0xCDu8; 5]; + let mut pos = buf.len(); + write_ipc_section_batches(&mut buf, &mut pos, [b1.clone(), b2.clone(), b3.clone()]) + .unwrap(); + + let data = aligned_bytes(&buf); + let mut offset = 5; + let read = read_ipc_section_batches_at(&data, &mut offset).unwrap(); + assert_eq!(read, vec![b1, b2, b3]); + assert_eq!(offset, buf.len(), "offset should land at section end"); + + let data_base = data.as_ptr() as usize; + let data_end = data_base + data.len(); + for buffer in read[0].column(0).to_data().buffers() { + let ptr = buffer.as_ptr() as usize; + assert!( + ptr >= data_base && ptr < data_end, + "first batch buffer at {ptr:#x} was realigned out of the input", + ); + } + } +} diff --git a/python/vendor/lance-arrow/src/json.rs b/python/vendor/lance-arrow/src/json.rs new file mode 100644 index 000000000..df908c4cb --- /dev/null +++ b/python/vendor/lance-arrow/src/json.rs @@ -0,0 +1,1538 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! JSON support for Apache Arrow. + +use std::convert::TryFrom; +use std::sync::Arc; + +use arrow_array::builder::{GenericStringBuilder, LargeBinaryBuilder}; +use arrow_array::cast::AsArray; +use arrow_array::{ + Array, ArrayRef, FixedSizeListArray, GenericStringArray, LargeBinaryArray, LargeListArray, + LargeStringArray, ListArray, MapArray, OffsetSizeTrait, RecordBatch, StringArray, StructArray, +}; +use arrow_schema::{ArrowError, DataType, Field as ArrowField, Fields, Schema}; +use lance_jsonb::OwnedJsonb; +use lance_jsonb::jsonpath::{JsonPath, Selector}; + +use crate::ARROW_EXT_NAME_KEY; + +/// Arrow extension type name for JSON data (Lance internal) +pub const JSON_EXT_NAME: &str = "lance.json"; + +/// Arrow extension type name for JSON data (Arrow official) +pub const ARROW_JSON_EXT_NAME: &str = "arrow.json"; + +/// Check if a field is a JSON extension field (Lance internal JSONB storage) +pub fn is_json_field(field: &ArrowField) -> bool { + field.data_type() == &DataType::LargeBinary + && field + .metadata() + .get(ARROW_EXT_NAME_KEY) + .map(|name| name == JSON_EXT_NAME) + .unwrap_or_default() +} + +/// Check if a field is an Arrow JSON extension field (PyArrow pa.json() type) +pub fn is_arrow_json_field(field: &ArrowField) -> bool { + // Arrow JSON extension type uses Utf8 or LargeUtf8 as storage type + (field.data_type() == &DataType::Utf8 || field.data_type() == &DataType::LargeUtf8) + && field + .metadata() + .get(ARROW_EXT_NAME_KEY) + .map(|name| name == ARROW_JSON_EXT_NAME) + .unwrap_or_default() +} + +/// Check if a field or any of its descendants is a JSON field +pub fn has_json_fields(field: &ArrowField) -> bool { + if is_json_field(field) { + return true; + } + + match field.data_type() { + DataType::Struct(fields) => fields.iter().any(|f| has_json_fields(f)), + DataType::List(f) | DataType::LargeList(f) | DataType::FixedSizeList(f, _) => { + has_json_fields(f) + } + DataType::Map(f, _) => has_json_fields(f), + _ => false, + } +} + +/// Check if a field or any of its descendants is an Arrow JSON field +pub fn has_arrow_json_fields(field: &ArrowField) -> bool { + if is_arrow_json_field(field) { + return true; + } + + match field.data_type() { + DataType::Struct(fields) => fields.iter().any(|f| has_arrow_json_fields(f)), + DataType::List(f) | DataType::LargeList(f) | DataType::FixedSizeList(f, _) => { + has_arrow_json_fields(f) + } + DataType::Map(f, _) => has_arrow_json_fields(f), + _ => false, + } +} + +/// The Arrow representation holding a JSON field's values. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JsonEncoding { + /// JSONB bytes: [`JSON_EXT_NAME`] over `LargeBinary`. Lance stores JSON + /// this way. + Jsonb, + /// JSON text: [`ARROW_JSON_EXT_NAME`] over `Utf8` or `LargeUtf8`. Callers + /// write JSON this way, and reads return it this way by default. + Text, +} + +impl JsonEncoding { + /// The encoding of `field`'s values, or `None` when `field` does not hold + /// JSON. + pub fn of_field(field: &ArrowField) -> Option { + if is_json_field(field) { + Some(Self::Jsonb) + } else if is_arrow_json_field(field) { + Some(Self::Text) + } else { + None + } + } +} + +/// The values of a JSON column, readable as JSONB or as text whichever +/// encoding they arrived in. +/// +/// Code that computes on JSON, such as tokenizers and indices, reads values +/// through this type, so its behavior does not depend on whether they come +/// from storage or from a caller. +#[derive(Debug, Clone, Copy)] +pub struct JsonValues<'a> { + encoding: JsonEncoding, + array: &'a ArrayRef, +} + +impl<'a> JsonValues<'a> { + /// Read `array` as the values of `field`, or `None` when `field` does not + /// hold JSON. + pub fn try_new(field: &ArrowField, array: &'a ArrayRef) -> Option { + JsonEncoding::of_field(field).map(|encoding| Self { encoding, array }) + } + + pub fn encoding(&self) -> JsonEncoding { + self.encoding + } + + /// The values as JSONB. Text values are parsed, so invalid JSON fails. + pub fn to_jsonb(&self) -> Result { + match self.encoding { + JsonEncoding::Jsonb => Ok(self.array.as_binary::().clone()), + JsonEncoding::Text => Ok(JsonArray::try_from(self.array.clone())?.into_inner()), + } + } + + /// The values as JSON text: the input array when it already holds text, + /// otherwise `LargeUtf8` decoded from JSONB. + pub fn to_text(&self) -> ArrayRef { + match self.encoding { + JsonEncoding::Jsonb => Arc::new(decode_jsonb_array::(self.array.as_binary())), + JsonEncoding::Text => self.array.clone(), + } + } +} + +/// Create a JSON field with the appropriate extension metadata +pub fn json_field(name: &str, nullable: bool) -> ArrowField { + let mut field = ArrowField::new(name, DataType::LargeBinary, nullable); + let mut metadata = std::collections::HashMap::new(); + metadata.insert(ARROW_EXT_NAME_KEY.to_string(), JSON_EXT_NAME.to_string()); + field.set_metadata(metadata); + field +} + +/// A specialized array for JSON data stored as JSONB binary format +#[derive(Debug, Clone)] +pub struct JsonArray { + inner: LargeBinaryArray, +} + +impl JsonArray { + /// Create a new JsonArray from an iterator of JSON strings + pub fn try_from_iter(iter: I) -> Result + where + I: IntoIterator>, + S: AsRef, + { + let mut builder = LargeBinaryBuilder::new(); + + for json_str in iter { + match json_str { + Some(s) => { + let encoded = encode_json(s.as_ref()).map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to encode JSON: {}", e)) + })?; + builder.append_value(&encoded); + } + None => builder.append_null(), + } + } + + Ok(Self { + inner: builder.finish(), + }) + } + + /// Get the underlying LargeBinaryArray + pub fn into_inner(self) -> LargeBinaryArray { + self.inner + } + + /// Get a reference to the underlying LargeBinaryArray + pub fn inner(&self) -> &LargeBinaryArray { + &self.inner + } + + /// Get the value at index i as decoded JSON string + pub fn value(&self, i: usize) -> Result { + if self.inner.is_null(i) { + return Err(ArrowError::InvalidArgumentError( + "Value is null".to_string(), + )); + } + + let jsonb_bytes = self.inner.value(i); + Ok(decode_json(jsonb_bytes)) + } + + /// Get the value at index i as raw JSONB bytes + pub fn value_bytes(&self, i: usize) -> &[u8] { + self.inner.value(i) + } + + /// Get JSONPath value from the JSON at index i + pub fn json_path(&self, i: usize, path: &str) -> Result, ArrowError> { + if self.inner.is_null(i) { + return Ok(None); + } + + let path = parse_json_path(path)?; + Ok(select_json_path(self.inner.value(i), &path)?.map(|value| value.to_string())) + } + + /// Convert to Arrow string array (JSON as UTF-8) + pub fn to_arrow_json(&self) -> ArrayRef { + Arc::new(decode_jsonb_array::(&self.inner)) + } + + pub fn len(&self) -> usize { + self.inner.len() + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + pub fn is_null(&self, i: usize) -> bool { + self.inner.is_null(i) + } +} + +// TryFrom implementations for string arrays +impl TryFrom for JsonArray { + type Error = ArrowError; + + fn try_from(array: StringArray) -> Result { + Self::try_from(&array) + } +} + +impl TryFrom<&StringArray> for JsonArray { + type Error = ArrowError; + + fn try_from(array: &StringArray) -> Result { + encode_json_text_array(array) + } +} + +impl TryFrom for JsonArray { + type Error = ArrowError; + + fn try_from(array: LargeStringArray) -> Result { + Self::try_from(&array) + } +} + +impl TryFrom<&LargeStringArray> for JsonArray { + type Error = ArrowError; + + fn try_from(array: &LargeStringArray) -> Result { + encode_json_text_array(array) + } +} + +fn encode_json_text_array( + array: &GenericStringArray, +) -> Result { + let mut builder = LargeBinaryBuilder::with_capacity(array.len(), array.value_data().len()); + for value in array { + match value { + Some(json_str) => { + let encoded = encode_json(json_str).map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to encode JSON: {}", e)) + })?; + builder.append_value(&encoded); + } + None => builder.append_null(), + } + } + Ok(JsonArray { + inner: builder.finish(), + }) +} + +fn decode_jsonb_array(array: &LargeBinaryArray) -> GenericStringArray { + let mut builder = + GenericStringBuilder::::with_capacity(array.len(), array.value_data().len()); + for value in array { + match value { + Some(jsonb_bytes) => builder.append_value(decode_json(jsonb_bytes)), + None => builder.append_null(), + } + } + builder.finish() +} + +impl TryFrom for JsonArray { + type Error = ArrowError; + + fn try_from(array_ref: ArrayRef) -> Result { + match array_ref.data_type() { + DataType::Utf8 => { + // Downcast is guaranteed to succeed after matching on DataType::Utf8 + let string_array = array_ref + .as_any() + .downcast_ref::() + .expect("DataType::Utf8 array must be StringArray"); + Self::try_from(string_array) + } + DataType::LargeUtf8 => { + // Downcast is guaranteed to succeed after matching on DataType::LargeUtf8 + let large_string_array = array_ref + .as_any() + .downcast_ref::() + .expect("DataType::LargeUtf8 array must be LargeStringArray"); + Self::try_from(large_string_array) + } + dt => Err(ArrowError::InvalidArgumentError(format!( + "Unsupported array type for JSON: {:?}. Expected Utf8 or LargeUtf8", + dt + ))), + } + } +} + +/// Encode JSON string to JSONB format +pub fn encode_json(json_str: &str) -> Result, Box> { + let value = lance_jsonb::parse_value(json_str.as_bytes())?; + Ok(value.to_vec()) +} + +/// Decode JSONB bytes to JSON string +pub fn decode_json(jsonb_bytes: &[u8]) -> String { + let raw_jsonb = lance_jsonb::RawJsonb::new(jsonb_bytes); + raw_jsonb.to_string() +} + +/// Parse a JSONPath expression. +pub fn parse_json_path(path: &str) -> Result, ArrowError> { + lance_jsonb::jsonpath::parse_json_path(path.as_bytes()) + .map_err(|e| ArrowError::InvalidArgumentError(format!("Invalid JSONPath '{path}': {e}"))) +} + +/// Select the value at `path` in a JSONB value. +/// +/// A path matching several values selects them together as one JSON array, +/// so no match is silently dropped. +pub fn select_json_path( + jsonb_bytes: &[u8], + path: &JsonPath<'_>, +) -> Result, ArrowError> { + Selector::new(lance_jsonb::RawJsonb::new(jsonb_bytes)) + .select_value(path) + .map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to select JSONPath {path}: {e}")) + }) +} + +/// Whether `path` matches any value in a JSONB value. +pub fn json_path_exists(jsonb_bytes: &[u8], path: &JsonPath<'_>) -> Result { + Selector::new(lance_jsonb::RawJsonb::new(jsonb_bytes)) + .exists(path) + .map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to match JSONPath {path}: {e}")) + }) +} + +/// Select every value matched by `path` in a JSONB value. +pub fn select_json_path_values( + jsonb_bytes: &[u8], + path: &JsonPath<'_>, +) -> Result, ArrowError> { + Selector::new(lance_jsonb::RawJsonb::new(jsonb_bytes)) + .select_values(path) + .map_err(|e| { + ArrowError::InvalidArgumentError(format!("Failed to select JSONPath {path}: {e}")) + }) +} + +/// Convert an Arrow JSON field to Lance JSON field (with JSONB storage) +pub fn arrow_json_to_lance_json(field: &ArrowField) -> ArrowField { + if is_arrow_json_field(field) { + return field_with_extension(field, DataType::LargeBinary, JSON_EXT_NAME); + } + + let data_type = match field.data_type() { + DataType::Struct(fields) => { + let fields = fields + .iter() + .map(|field| Arc::new(arrow_json_to_lance_json(field))) + .collect::>(); + DataType::Struct(Fields::from(fields)) + } + DataType::List(item) => DataType::List(Arc::new(arrow_json_to_lance_json(item))), + DataType::LargeList(item) => DataType::LargeList(Arc::new(arrow_json_to_lance_json(item))), + DataType::FixedSizeList(item, size) => { + DataType::FixedSizeList(Arc::new(arrow_json_to_lance_json(item)), *size) + } + DataType::Map(entries, keys_sorted) => { + DataType::Map(Arc::new(arrow_json_to_lance_json(entries)), *keys_sorted) + } + _ => return field.clone(), + }; + + field_with_data_type(field, data_type) +} + +/// Convert a Lance JSON field to Arrow JSON field. +pub fn lance_json_to_arrow_json(field: &ArrowField) -> ArrowField { + if is_json_field(field) { + return field_with_extension(field, DataType::Utf8, ARROW_JSON_EXT_NAME); + } + + let data_type = match field.data_type() { + DataType::Struct(fields) => { + let fields = fields + .iter() + .map(|field| Arc::new(lance_json_to_arrow_json(field))) + .collect::>(); + DataType::Struct(Fields::from(fields)) + } + DataType::List(item) => DataType::List(Arc::new(lance_json_to_arrow_json(item))), + DataType::LargeList(item) => DataType::LargeList(Arc::new(lance_json_to_arrow_json(item))), + DataType::FixedSizeList(item, size) => { + DataType::FixedSizeList(Arc::new(lance_json_to_arrow_json(item)), *size) + } + DataType::Map(entries, keys_sorted) => { + DataType::Map(Arc::new(lance_json_to_arrow_json(entries)), *keys_sorted) + } + _ => return field.clone(), + }; + + field_with_data_type(field, data_type) +} + +fn field_with_data_type(field: &ArrowField, data_type: DataType) -> ArrowField { + ArrowField::new(field.name(), data_type, field.is_nullable()) + .with_metadata(field.metadata().clone()) +} + +fn field_with_extension( + field: &ArrowField, + data_type: DataType, + extension_name: &str, +) -> ArrowField { + let mut metadata = field.metadata().clone(); + metadata.insert(ARROW_EXT_NAME_KEY.to_string(), extension_name.to_string()); + ArrowField::new(field.name(), data_type, field.is_nullable()).with_metadata(metadata) +} + +fn convert_json_array( + field: &ArrowField, + array: &ArrayRef, + convert_leaf: &F, +) -> Result<(ArrowField, ArrayRef, bool), ArrowError> +where + F: Fn(&ArrowField, &ArrayRef) -> Result, ArrowError>, +{ + if let Some((field, array)) = convert_leaf(field, array)? { + return Ok((field, array, true)); + } + + match field.data_type() { + DataType::Struct(fields) => { + let struct_array = array.as_struct(); + let mut new_fields = Vec::with_capacity(fields.len()); + let mut new_columns = Vec::with_capacity(fields.len()); + let mut changed = false; + + for (field, column) in fields.iter().zip(struct_array.columns()) { + let (new_field, new_column, field_changed) = + convert_json_array(field, column, convert_leaf)?; + changed |= field_changed; + new_fields.push(Arc::new(new_field)); + new_columns.push(new_column); + } + + if changed { + let fields = Fields::from(new_fields); + let new_field = field_with_data_type(field, DataType::Struct(fields.clone())); + let new_array = + StructArray::new(fields, new_columns, struct_array.nulls().cloned()); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::List(item) => { + let list_array: &ListArray = array.as_list(); + let (new_item, new_values, changed) = + convert_json_array(item, list_array.values(), convert_leaf)?; + if changed { + let new_field = + field_with_data_type(field, DataType::List(Arc::new(new_item.clone()))); + let new_array = ListArray::new( + Arc::new(new_item), + list_array.offsets().clone(), + new_values, + list_array.nulls().cloned(), + ); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::LargeList(item) => { + let list_array: &LargeListArray = array.as_list(); + let (new_item, new_values, changed) = + convert_json_array(item, list_array.values(), convert_leaf)?; + if changed { + let new_field = + field_with_data_type(field, DataType::LargeList(Arc::new(new_item.clone()))); + let new_array = LargeListArray::new( + Arc::new(new_item), + list_array.offsets().clone(), + new_values, + list_array.nulls().cloned(), + ); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::FixedSizeList(item, size) => { + let list_array: &FixedSizeListArray = array.as_fixed_size_list(); + let (new_item, new_values, changed) = + convert_json_array(item, list_array.values(), convert_leaf)?; + if changed { + let new_field = field_with_data_type( + field, + DataType::FixedSizeList(Arc::new(new_item.clone()), *size), + ); + let new_array = FixedSizeListArray::try_new_with_length( + Arc::new(new_item), + *size, + new_values, + list_array.nulls().cloned(), + list_array.len(), + )?; + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + DataType::Map(entries, keys_sorted) => { + let map_array = array + .as_any() + .downcast_ref::() + .expect("DataType::Map array must be MapArray"); + let entries_array = Arc::new(map_array.entries().clone()) as ArrayRef; + let (new_entries, new_entries_array, changed) = + convert_json_array(entries, &entries_array, convert_leaf)?; + if changed { + let entries_struct = new_entries_array + .as_any() + .downcast_ref::() + .expect("Map entries must be StructArray") + .clone(); + let new_field = field_with_data_type( + field, + DataType::Map(Arc::new(new_entries.clone()), *keys_sorted), + ); + let new_array = MapArray::new( + Arc::new(new_entries), + map_array.offsets().clone(), + entries_struct, + map_array.nulls().cloned(), + *keys_sorted, + ); + Ok((new_field, Arc::new(new_array) as ArrayRef, true)) + } else { + Ok((field.clone(), array.clone(), false)) + } + } + _ => Ok((field.clone(), array.clone(), false)), + } +} + +fn convert_arrow_json_array( + field: &ArrowField, + array: &ArrayRef, +) -> Result<(ArrowField, ArrayRef, bool), ArrowError> { + convert_json_array(field, array, &|field, array| { + if is_arrow_json_field(field) { + let json_array = JsonArray::try_from(array.clone())?; + Ok(Some(( + arrow_json_to_lance_json(field), + Arc::new(json_array.into_inner()) as ArrayRef, + ))) + } else { + Ok(None) + } + }) +} + +fn convert_lance_json_array( + field: &ArrowField, + array: &ArrayRef, +) -> Result<(ArrowField, ArrayRef, bool), ArrowError> { + convert_json_array(field, array, &|field, array| { + if is_json_field(field) { + Ok(Some(( + lance_json_to_arrow_json(field), + Arc::new(decode_jsonb_array::(array.as_binary())) as ArrayRef, + ))) + } else { + Ok(None) + } + }) +} + +/// Convert a RecordBatch with Lance JSON columns (JSONB) back to Arrow JSON format (strings) +pub fn convert_lance_json_to_arrow( + batch: &arrow_array::RecordBatch, +) -> Result { + let schema = batch.schema(); + let mut needs_conversion = false; + let mut new_fields = Vec::with_capacity(schema.fields().len()); + let mut new_columns = Vec::with_capacity(batch.num_columns()); + + for (i, field) in schema.fields().iter().enumerate() { + let column = batch.column(i); + let (new_field, new_column, changed) = convert_lance_json_array(field, column)?; + + needs_conversion |= changed; + new_fields.push(new_field); + new_columns.push(new_column); + } + + if needs_conversion { + let new_schema = Arc::new(Schema::new_with_metadata( + new_fields, + schema.metadata().clone(), + )); + RecordBatch::try_new(new_schema, new_columns) + } else { + // No conversion needed, return original batch + Ok(batch.clone()) + } +} + +/// Convert a RecordBatch with Arrow JSON columns to Lance JSON format (JSONB) +pub fn convert_json_columns( + batch: &arrow_array::RecordBatch, +) -> Result { + let schema = batch.schema(); + let mut needs_conversion = false; + let mut new_fields = Vec::with_capacity(schema.fields().len()); + let mut new_columns = Vec::with_capacity(batch.num_columns()); + + for (i, field) in schema.fields().iter().enumerate() { + let column = batch.column(i); + let (new_field, new_column, changed) = convert_arrow_json_array(field, column)?; + + needs_conversion |= changed; + new_fields.push(new_field); + new_columns.push(new_column); + } + + if needs_conversion { + let new_schema = Arc::new(Schema::new_with_metadata( + new_fields, + schema.metadata().clone(), + )); + RecordBatch::try_new(new_schema, new_columns) + } else { + // No conversion needed, return original batch + Ok(batch.clone()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_json_field_creation() { + let field = json_field("data", true); + assert_eq!(field.name(), "data"); + assert_eq!(field.data_type(), &DataType::LargeBinary); + assert!(field.is_nullable()); + assert!(is_json_field(&field)); + } + + #[test] + fn test_json_array_from_strings() { + let json_strings = vec![ + Some(r#"{"name": "Alice", "age": 30}"#), + None, + Some(r#"{"name": "Bob", "age": 25}"#), + ]; + + let array = JsonArray::try_from_iter(json_strings).unwrap(); + assert_eq!(array.len(), 3); + assert!(!array.is_null(0)); + assert!(array.is_null(1)); + assert!(!array.is_null(2)); + + let decoded = array.value(0).unwrap(); + assert!(decoded.contains("Alice")); + } + + #[test] + fn test_json_array_from_string_array() { + let string_array = StringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + None, + ]); + + let json_array = JsonArray::try_from(string_array).unwrap(); + assert_eq!(json_array.len(), 3); + assert!(!json_array.is_null(0)); + assert!(!json_array.is_null(1)); + assert!(json_array.is_null(2)); + } + + #[test] + fn test_json_path_extraction() { + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"user": {"name": "Alice", "age": 30}}"#), + Some(r#"{"user": {"name": "Bob"}}"#), + ]) + .unwrap(); + + let name = json_array.json_path(0, "$.user.name").unwrap(); + assert_eq!(name, Some("\"Alice\"".to_string())); + + let age = json_array.json_path(1, "$.user.age").unwrap(); + assert_eq!(age, None); + + // Several matches are selected together, as the SQL JSON functions do. + let json_array = + JsonArray::try_from_iter(vec![Some(r#"{"a": [{"b": 1}, {"b": 2}]}"#)]).unwrap(); + let bs = json_array.json_path(0, "$.a[*].b").unwrap(); + assert_eq!(bs, Some("[1,2]".to_string())); + } + + #[test] + fn test_json_values_read_either_encoding() { + let docs = vec![Some(r#"{"a":1}"#), None]; + let text: ArrayRef = Arc::new(StringArray::from(docs.clone())); + let jsonb: ArrayRef = Arc::new(JsonArray::try_from_iter(docs).unwrap().into_inner()); + let mut text_field = ArrowField::new("j", DataType::Utf8, true); + text_field.set_metadata(std::collections::HashMap::from([( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + )])); + let jsonb_field = json_field("j", true); + + let from_text = JsonValues::try_new(&text_field, &text).unwrap(); + let from_jsonb = JsonValues::try_new(&jsonb_field, &jsonb).unwrap(); + assert_eq!(from_text.encoding(), JsonEncoding::Text); + assert_eq!(from_jsonb.encoding(), JsonEncoding::Jsonb); + + assert_eq!(&from_text.to_jsonb().unwrap(), jsonb.as_binary::()); + assert_eq!(&from_jsonb.to_jsonb().unwrap(), jsonb.as_binary::()); + assert_eq!(&from_text.to_text(), &text); + let decoded = from_jsonb.to_text(); + let decoded = decoded.as_string::(); + assert_eq!(decoded.value(0), r#"{"a":1}"#); + assert!(decoded.is_null(1)); + + let plain = ArrowField::new("j", DataType::Utf8, true); + assert!(JsonValues::try_new(&plain, &text).is_none()); + } + + #[test] + fn test_convert_json_columns() { + // Create a batch with Arrow JSON column + let json_strings = vec![Some(r#"{"name": "Alice"}"#), Some(r#"{"name": "Bob"}"#)]; + let json_arr = StringArray::from(json_strings); + + // Create field with arrow.json extension + let mut field = ArrowField::new("data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(json_arr) as ArrayRef]).unwrap(); + + // Convert the batch + let converted = convert_json_columns(&batch).unwrap(); + + // Check the converted schema + assert_eq!(converted.num_columns(), 1); + let converted_schema = converted.schema(); + let converted_field = converted_schema.field(0); + assert_eq!(converted_field.data_type(), &DataType::LargeBinary); + assert_eq!( + converted_field.metadata().get(ARROW_EXT_NAME_KEY), + Some(&JSON_EXT_NAME.to_string()) + ); + + // Check the data was converted + let converted_column = converted.column(0); + assert_eq!(converted_column.data_type(), &DataType::LargeBinary); + assert_eq!(converted_column.len(), 2); + + // Verify the data is valid JSONB + let binary_array = converted_column + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..binary_array.len() { + let jsonb_bytes = binary_array.value(i); + let decoded = decode_json(jsonb_bytes); + assert!(decoded.contains("name")); + } + } + + #[test] + fn test_convert_nested_json_columns() { + use arrow_buffer::{OffsetBuffer, ScalarBuffer}; + + let uri_field = Arc::new(ArrowField::new("uri", DataType::Utf8, false)); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + let extra_field = + Arc::new(ArrowField::new("extra", DataType::Utf8, true).with_metadata(metadata)); + let item_fields = Fields::from(vec![uri_field, extra_field]); + + let values = StructArray::new( + item_fields.clone(), + vec![ + Arc::new(StringArray::from(vec![Some("a.jpg"), Some("b.jpg")])) as ArrayRef, + Arc::new(StringArray::from(vec![ + Some(r#"{"codec":"h264"}"#), + None::<&str>, + ])) as ArrayRef, + ], + None, + ); + let item = Arc::new(ArrowField::new("item", DataType::Struct(item_fields), true)); + let media = ListArray::new( + item, + OffsetBuffer::new(ScalarBuffer::from(vec![0, 1, 2])), + Arc::new(values), + None, + ); + let schema = Arc::new(Schema::new(vec![ArrowField::new( + "media", + media.data_type().clone(), + true, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(media) as ArrayRef]).unwrap(); + + assert!(has_arrow_json_fields(batch.schema().field(0))); + + let converted = convert_json_columns(&batch).unwrap(); + let converted_schema = converted.schema(); + let DataType::List(item) = converted_schema.field(0).data_type() else { + panic!("expected list field"); + }; + let DataType::Struct(fields) = item.data_type() else { + panic!("expected struct item"); + }; + assert!(is_json_field(&fields[1])); + + let list_array: &ListArray = converted.column(0).as_list(); + let values = list_array.values().as_struct(); + let extra = values + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(decode_json(extra.value(0)).contains("h264")); + assert!(extra.is_null(1)); + + let logical = convert_lance_json_to_arrow(&converted).unwrap(); + let logical_schema = logical.schema(); + let DataType::List(item) = logical_schema.field(0).data_type() else { + panic!("expected list field"); + }; + let DataType::Struct(fields) = item.data_type() else { + panic!("expected struct item"); + }; + assert!(is_arrow_json_field(&fields[1])); + + let list_array: &ListArray = logical.column(0).as_list(); + let values = list_array.values().as_struct(); + let extra = values + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(extra.value(0).contains("h264")); + assert!(extra.is_null(1)); + } + + #[test] + fn test_convert_fixed_size_list_zero_json_preserves_length() { + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + let item = Arc::new(ArrowField::new("item", DataType::Utf8, true).with_metadata(metadata)); + let values = Arc::new(StringArray::from(Vec::>::new())) as ArrayRef; + let lists = FixedSizeListArray::try_new_with_length(item, 0, values, None, 3).unwrap(); + let schema = Arc::new(Schema::new(vec![ArrowField::new( + "lists", + lists.data_type().clone(), + true, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(lists) as ArrayRef]).unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_rows(), 3); + assert_eq!(converted.column(0).len(), 3); + + let converted_schema = converted.schema(); + let DataType::FixedSizeList(item, size) = converted_schema.field(0).data_type() else { + panic!("expected fixed size list field"); + }; + assert_eq!(*size, 0); + assert!(is_json_field(item)); + + let logical = convert_lance_json_to_arrow(&converted).unwrap(); + assert_eq!(logical.num_rows(), 3); + assert_eq!(logical.column(0).len(), 3); + + let logical_schema = logical.schema(); + let DataType::FixedSizeList(item, size) = logical_schema.field(0).data_type() else { + panic!("expected fixed size list field"); + }; + assert_eq!(*size, 0); + assert!(is_arrow_json_field(item)); + } + + #[test] + fn test_has_json_fields() { + // Test direct JSON field + let json_f = json_field("data", true); + assert!(has_json_fields(&json_f)); + + // Test non-JSON field + let non_json = ArrowField::new("data", DataType::Utf8, true); + assert!(!has_json_fields(&non_json)); + + // Test struct containing JSON field + let struct_field = ArrowField::new( + "struct", + DataType::Struct(vec![json_field("nested_json", true)].into()), + true, + ); + assert!(has_json_fields(&struct_field)); + + // Test struct without JSON field + let struct_no_json = ArrowField::new( + "struct", + DataType::Struct(vec![ArrowField::new("text", DataType::Utf8, true)].into()), + true, + ); + assert!(!has_json_fields(&struct_no_json)); + + // Test List containing JSON field + let list_field = ArrowField::new( + "list", + DataType::List(Arc::new(json_field("item", true))), + true, + ); + assert!(has_json_fields(&list_field)); + + // Test LargeList containing JSON field + let large_list_field = ArrowField::new( + "large_list", + DataType::LargeList(Arc::new(json_field("item", true))), + true, + ); + assert!(has_json_fields(&large_list_field)); + + // Test FixedSizeList containing JSON field + let fixed_list_field = ArrowField::new( + "fixed_list", + DataType::FixedSizeList(Arc::new(json_field("item", true)), 3), + true, + ); + assert!(has_json_fields(&fixed_list_field)); + + // Test Map containing JSON field + let map_field = ArrowField::new( + "map", + DataType::Map( + Arc::new(ArrowField::new( + "entries", + DataType::Struct( + vec![ + ArrowField::new("key", DataType::Utf8, false), + json_field("value", true), + ] + .into(), + ), + false, + )), + false, + ), + true, + ); + assert!(has_json_fields(&map_field)); + } + + #[test] + fn test_json_array_inner() { + let json_array = JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#)]).unwrap(); + let inner = json_array.inner(); + assert_eq!(inner.len(), 1); + } + + #[test] + fn test_json_array_value_null_error() { + let json_array = JsonArray::try_from_iter(vec![None::<&str>]).unwrap(); + let result = json_array.value(0); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("null")); + } + + #[test] + fn test_json_array_value_bytes() { + let json_array = JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#)]).unwrap(); + let bytes = json_array.value_bytes(0); + assert!(!bytes.is_empty()); + } + + #[test] + fn test_json_path_with_null() { + let json_array = + JsonArray::try_from_iter(vec![Some(r#"{"user": {"name": "Alice"}}"#), None::<&str>]) + .unwrap(); + + let result = json_array.json_path(1, "$.user.name").unwrap(); + assert_eq!(result, None); + } + + #[test] + fn test_to_arrow_json() { + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"name": "Alice"}"#), + None::<&str>, + Some(r#"{"name": "Bob"}"#), + ]) + .unwrap(); + + let arrow_json = json_array.to_arrow_json(); + assert_eq!(arrow_json.len(), 3); + assert!(!arrow_json.is_null(0)); + assert!(arrow_json.is_null(1)); + assert!(!arrow_json.is_null(2)); + + let string_array = arrow_json.as_any().downcast_ref::().unwrap(); + assert!(string_array.value(0).contains("Alice")); + assert!(string_array.value(2).contains("Bob")); + } + + #[test] + fn test_json_array_trait_methods() { + let json_array = + JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#), Some(r#"{"b": 2}"#)]).unwrap(); + + // Wrapper methods + assert_eq!(json_array.len(), 2); + assert!(!json_array.is_empty()); + assert!(!json_array.is_null(0)); + + // Underlying Arrow array + assert_eq!(json_array.inner().data_type(), &DataType::LargeBinary); + assert_eq!(json_array.inner().len(), 2); + } + + #[test] + fn test_json_array_empty() { + let json_array = JsonArray::try_from_iter(Vec::>::new()).unwrap(); + assert!(json_array.is_empty()); + assert_eq!(json_array.len(), 0); + } + + #[test] + fn test_try_from_large_string_array() { + let large_string_array = LargeStringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + None, + ]); + + // Test TryFrom<&LargeStringArray> + let json_array = JsonArray::try_from(&large_string_array).unwrap(); + assert_eq!(json_array.len(), 3); + assert!(!json_array.is_null(0)); + assert!(!json_array.is_null(1)); + assert!(json_array.is_null(2)); + + // Test TryFrom (owned) + let large_string_array2 = LargeStringArray::from(vec![Some(r#"{"x": 1}"#)]); + let json_array2 = JsonArray::try_from(large_string_array2).unwrap(); + assert_eq!(json_array2.len(), 1); + } + + #[test] + fn test_try_from_array_ref() { + // Test with Utf8 + let string_array: ArrayRef = Arc::new(StringArray::from(vec![ + Some(r#"{"a": 1}"#), + Some(r#"{"b": 2}"#), + ])); + let json_array = JsonArray::try_from(string_array).unwrap(); + assert_eq!(json_array.len(), 2); + + // Test with LargeUtf8 + let large_string_array: ArrayRef = Arc::new(LargeStringArray::from(vec![ + Some(r#"{"c": 3}"#), + Some(r#"{"d": 4}"#), + ])); + let json_array2 = JsonArray::try_from(large_string_array).unwrap(); + assert_eq!(json_array2.len(), 2); + + // Test with unsupported type + let int_array: ArrayRef = Arc::new(arrow_array::Int32Array::from(vec![1, 2, 3])); + let result = JsonArray::try_from(int_array); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Unsupported")); + } + + #[test] + fn test_arrow_json_to_lance_json_non_json_field() { + // Test that non-JSON fields are returned unchanged + let field = ArrowField::new("text", DataType::Utf8, true); + let converted = arrow_json_to_lance_json(&field); + assert_eq!(converted.data_type(), &DataType::Utf8); + assert_eq!(converted.name(), "text"); + } + + #[test] + fn test_convert_lance_json_to_arrow() { + // Create a batch with Lance JSON column (JSONB) + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"name": "Alice"}"#), + None::<&str>, + Some(r#"{"name": "Bob"}"#), + ]) + .unwrap(); + + let lance_json_field = json_field("data", true); + let schema = Arc::new(Schema::new(vec![lance_json_field])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(json_array.into_inner()) as ArrayRef]) + .unwrap(); + + // Convert back to Arrow JSON + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + + // Check schema + let converted_schema = converted.schema(); + let converted_field = converted_schema.field(0); + assert_eq!(converted_field.data_type(), &DataType::Utf8); + assert_eq!( + converted_field.metadata().get(ARROW_EXT_NAME_KEY), + Some(&ARROW_JSON_EXT_NAME.to_string()) + ); + + // Check data + let string_array = converted + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(!string_array.is_null(0)); + assert!(string_array.is_null(1)); + assert!(!string_array.is_null(2)); + assert!(string_array.value(0).contains("Alice")); + assert!(string_array.value(2).contains("Bob")); + } + + #[test] + fn test_convert_lance_json_to_arrow_empty_batch() { + // Create an empty batch with Lance JSON column + let lance_json_field = json_field("data", true); + let schema = Arc::new(Schema::new(vec![lance_json_field])); + let empty_binary = LargeBinaryBuilder::new().finish(); + let batch = RecordBatch::try_new(schema, vec![Arc::new(empty_binary) as ArrayRef]).unwrap(); + + // Convert back to Arrow JSON + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + assert_eq!(converted.num_rows(), 0); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + } + + #[test] + fn test_convert_lance_json_to_arrow_no_json_columns() { + // Create a batch without JSON columns + let field = ArrowField::new("text", DataType::Utf8, true); + let schema = Arc::new(Schema::new(vec![field])); + let string_array = StringArray::from(vec![Some("hello"), Some("world")]); + let batch = RecordBatch::try_new(schema, vec![Arc::new(string_array) as ArrayRef]).unwrap(); + + // Convert - should return the same batch + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + assert_eq!(converted.num_columns(), 1); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + } + + #[test] + fn test_convert_json_columns_empty_batch() { + // Create an empty batch with Arrow JSON column + let mut field = ArrowField::new("data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let empty_strings = arrow_array::builder::StringBuilder::new().finish(); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(empty_strings) as ArrayRef]).unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_rows(), 0); + assert_eq!( + converted.schema().field(0).data_type(), + &DataType::LargeBinary + ); + } + + #[test] + fn test_convert_json_columns_large_string() { + // Create a batch with Arrow JSON column using LargeUtf8 + let json_strings = LargeStringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + ]); + + let mut field = ArrowField::new("data", DataType::LargeUtf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(json_strings) as ArrayRef]).unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_columns(), 1); + assert_eq!( + converted.schema().field(0).data_type(), + &DataType::LargeBinary + ); + assert_eq!(converted.num_rows(), 2); + } + + #[test] + fn test_convert_json_columns_no_json_columns() { + // Create a batch without JSON columns + let field = ArrowField::new("text", DataType::Utf8, true); + let schema = Arc::new(Schema::new(vec![field])); + let string_array = StringArray::from(vec![Some("hello"), Some("world")]); + let batch = RecordBatch::try_new(schema, vec![Arc::new(string_array) as ArrayRef]).unwrap(); + + // Convert - should return the same batch + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_columns(), 1); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + } + + #[test] + fn test_convert_json_columns_mixed_columns() { + // Create a batch with both JSON and non-JSON columns + let json_strings = StringArray::from(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + ]); + let text_strings = StringArray::from(vec![Some("hello"), Some("world")]); + + let mut json_field = ArrowField::new("json_data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + json_field.set_metadata(metadata); + + let text_field = ArrowField::new("text_data", DataType::Utf8, true); + + let schema = Arc::new(Schema::new(vec![json_field, text_field])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(json_strings) as ArrayRef, + Arc::new(text_strings) as ArrayRef, + ], + ) + .unwrap(); + + let converted = convert_json_columns(&batch).unwrap(); + assert_eq!(converted.num_columns(), 2); + assert_eq!( + converted.schema().field(0).data_type(), + &DataType::LargeBinary + ); + assert_eq!(converted.schema().field(1).data_type(), &DataType::Utf8); + } + + #[test] + fn test_is_arrow_json_field_large_utf8() { + // Test with LargeUtf8 storage type + let mut field = ArrowField::new("data", DataType::LargeUtf8, true); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + assert!(is_arrow_json_field(&field)); + } + + #[test] + fn test_encode_json_invalid() { + // Test encoding invalid JSON + let result = encode_json("not valid json {"); + assert!(result.is_err()); + } + + #[test] + fn test_json_array_from_invalid_json() { + // Test creating JsonArray from invalid JSON strings + let result = JsonArray::try_from_iter(vec![Some("invalid json {")]); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Failed to encode")); + } + + #[test] + fn test_try_from_string_array_invalid_json() { + let string_array = StringArray::from(vec![Some("invalid json {")]); + let result = JsonArray::try_from(string_array); + assert!(result.is_err()); + } + + #[test] + fn test_try_from_large_string_array_invalid_json() { + let large_string_array = LargeStringArray::from(vec![Some("invalid json {")]); + let result = JsonArray::try_from(large_string_array); + assert!(result.is_err()); + } + + #[test] + fn test_convert_lance_json_to_arrow_mixed_columns() { + // Create a batch with both JSON and non-JSON columns + let json_array = JsonArray::try_from_iter(vec![ + Some(r#"{"name": "Alice"}"#), + Some(r#"{"name": "Bob"}"#), + ]) + .unwrap(); + let text_strings = StringArray::from(vec![Some("hello"), Some("world")]); + + let json_f = json_field("json_data", true); + let text_field = ArrowField::new("text_data", DataType::Utf8, true); + + let schema = Arc::new(Schema::new(vec![json_f, text_field])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(json_array.into_inner()) as ArrayRef, + Arc::new(text_strings) as ArrayRef, + ], + ) + .unwrap(); + + let converted = convert_lance_json_to_arrow(&batch).unwrap(); + assert_eq!(converted.num_columns(), 2); + assert_eq!(converted.schema().field(0).data_type(), &DataType::Utf8); + assert_eq!(converted.schema().field(1).data_type(), &DataType::Utf8); + } + + #[test] + fn test_json_path_invalid_path() { + let json_array = JsonArray::try_from_iter(vec![Some(r#"{"a": 1}"#)]).unwrap(); + // Invalid JSONPath syntax should return error + let result = json_array.json_path(0, "invalid path without $"); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Invalid JSONPath")); + } + + #[test] + fn test_convert_json_columns_invalid_storage_type() { + // Create a batch with Arrow JSON field but wrong storage type (Int32 instead of Utf8) + let int_array = arrow_array::Int32Array::from(vec![1, 2, 3]); + + let mut field = ArrowField::new("data", DataType::Int32, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(int_array) as ArrayRef]).unwrap(); + + // This should succeed since Int32 doesn't match is_arrow_json_field check + // (is_arrow_json_field requires Utf8 or LargeUtf8) + let result = convert_json_columns(&batch); + assert!(result.is_ok()); + } + + #[test] + fn test_is_json_field_wrong_extension() { + // LargeBinary field without the correct extension metadata + let field = ArrowField::new("data", DataType::LargeBinary, true); + assert!(!is_json_field(&field)); + + // LargeBinary field with wrong extension name + let mut field2 = ArrowField::new("data", DataType::LargeBinary, true); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + "other.extension".to_string(), + ); + field2.set_metadata(metadata); + assert!(!is_json_field(&field2)); + } + + #[test] + fn test_is_arrow_json_field_wrong_extension() { + // Utf8 field without extension metadata + let field = ArrowField::new("data", DataType::Utf8, true); + assert!(!is_arrow_json_field(&field)); + + // Utf8 field with wrong extension name + let mut field2 = ArrowField::new("data", DataType::Utf8, true); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + "other.extension".to_string(), + ); + field2.set_metadata(metadata); + assert!(!is_arrow_json_field(&field2)); + + // Wrong type entirely + let field3 = ArrowField::new("data", DataType::Int32, true); + assert!(!is_arrow_json_field(&field3)); + } + + #[test] + fn test_convert_json_columns_invalid_json_utf8() { + // Test error propagation when converting invalid JSON (Utf8) + let invalid_json = StringArray::from(vec![Some("invalid json {")]); + + let mut field = ArrowField::new("data", DataType::Utf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(invalid_json) as ArrayRef]).unwrap(); + + let result = convert_json_columns(&batch); + assert!(result.is_err()); + } + + #[test] + fn test_convert_json_columns_invalid_json_large_utf8() { + // Test error propagation when converting invalid JSON (LargeUtf8) + let invalid_json = LargeStringArray::from(vec![Some("invalid json {")]); + + let mut field = ArrowField::new("data", DataType::LargeUtf8, false); + let mut metadata = std::collections::HashMap::new(); + metadata.insert( + ARROW_EXT_NAME_KEY.to_string(), + ARROW_JSON_EXT_NAME.to_string(), + ); + field.set_metadata(metadata); + + let schema = Arc::new(Schema::new(vec![field])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(invalid_json) as ArrayRef]).unwrap(); + + let result = convert_json_columns(&batch); + assert!(result.is_err()); + } + + #[test] + fn test_json_path_on_corrupted_jsonb() { + // Create corrupted JSONB bytes directly + let corrupted_bytes: &[u8] = &[0xFF, 0xFE, 0x00, 0x01, 0x02]; + let corrupted_binary = LargeBinaryArray::from(vec![Some(corrupted_bytes)]); + + // Wrap in JsonArray + let corrupted_json = JsonArray { + inner: corrupted_binary, + }; + + // Try to use json_path on corrupted data - the selector might fail or return unexpected results + // This exercises the code path but may not produce an error depending on jsonb library behavior + let _result = corrupted_json.json_path(0, "$.a"); + // We don't assert on the result as the behavior depends on the jsonb library + } + + #[test] + fn test_decode_json_on_various_inputs() { + // Test decode_json with various inputs + let valid_jsonb = encode_json(r#"{"key": "value"}"#).unwrap(); + let decoded = decode_json(&valid_jsonb); + assert!(decoded.contains("key")); + + // Empty bytes - jsonb library handles this gracefully + let decoded_empty = decode_json(&[]); + // Just verify it doesn't panic + let _ = decoded_empty; + + // Random bytes - jsonb library handles this gracefully + let decoded_random = decode_json(&[0xFF, 0xFE, 0x00]); + // Just verify it doesn't panic + let _ = decoded_random; + } +} diff --git a/python/vendor/lance-arrow/src/lib.rs b/python/vendor/lance-arrow/src/lib.rs new file mode 100644 index 000000000..f26e1f3e3 --- /dev/null +++ b/python/vendor/lance-arrow/src/lib.rs @@ -0,0 +1,3102 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Extend Arrow Functionality +//! +//! To improve Arrow-RS ergonomic + +#![warn(clippy::undocumented_unsafe_blocks)] + +// lance-arrow reinterprets value bytes as native numeric types in +// `FloatArray::as_slice` for `bf16` (rust/lance-arrow/src/bfloat16.rs), which +// requires the host byte order to match the on-disk byte order Lance writes. +// Lance writes little-endian; building on a big-endian target would silently +// produce wrong numeric values. +#[cfg(not(target_endian = "little"))] +compile_error!("lance-arrow only supports little-endian targets"); + +use std::sync::Arc; +use std::{collections::HashMap, ptr::NonNull}; + +use arrow_array::{ + Array, ArrayRef, ArrowNumericType, FixedSizeBinaryArray, FixedSizeListArray, GenericListArray, + LargeListArray, ListArray, MapArray, OffsetSizeTrait, PrimitiveArray, RecordBatch, StructArray, + UInt8Array, UInt32Array, cast::AsArray, +}; +use arrow_array::{ + Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array, new_null_array, +}; +use arrow_buffer::MutableBuffer; +use arrow_data::ArrayDataBuilder; +use arrow_schema::{ArrowError, DataType, Field, Fields, IntervalUnit, Schema, SortOptions}; +use arrow_select::{interleave::interleave, take::take}; +use rand::prelude::*; + +pub mod deepcopy; +pub mod schema; +pub use schema::*; +pub mod bfloat16; +pub mod floats; +use crate::list::ListArrayExt; +pub use floats::*; + +pub mod ipc; +pub mod json; +pub mod list; +pub mod memory; +pub mod scalar; +pub mod stream; +pub mod r#struct; + +/// Arrow extension metadata key for extension name +pub const ARROW_EXT_NAME_KEY: &str = "ARROW:extension:name"; + +/// Arrow extension metadata key for extension metadata +pub const ARROW_EXT_META_KEY: &str = "ARROW:extension:metadata"; + +/// Key used by lance to mark a field as a blob +/// TODO: Use Arrow extension mechanism instead? +pub const BLOB_META_KEY: &str = "lance-encoding:blob"; +/// Arrow extension type name for Lance blob v2 columns +pub const BLOB_V2_EXT_NAME: &str = "lance.blob.v2"; +/// Metadata key for overriding the dedicated blob size threshold (in bytes) +pub const BLOB_DEDICATED_SIZE_THRESHOLD_META_KEY: &str = + "lance-encoding:blob-dedicated-size-threshold"; +/// Metadata key for overriding the inline blob size threshold (in bytes) +pub const BLOB_INLINE_SIZE_THRESHOLD_META_KEY: &str = "lance-encoding:blob-inline-size-threshold"; +/// Metadata key for overriding the maximum size (in bytes) of a packed blob sidecar file +pub const BLOB_PACK_FILE_SIZE_THRESHOLD_META_KEY: &str = + "lance-encoding:blob-pack-file-size-threshold"; + +type Result = std::result::Result; + +pub trait DataTypeExt { + /// Returns true if the data type is binary-like, such as Utf8, Binary, or the large and/or view variants. + fn is_binary_like(&self) -> bool; + + /// Returns true if the data type is a struct. + fn is_struct(&self) -> bool; + + /// Check whether the given Arrow DataType is fixed stride. + /// + /// A fixed stride type has the same byte width for all array elements + /// This includes all PrimitiveType's Boolean, FixedSizeList, FixedSizeBinary, and Decimals + fn is_fixed_stride(&self) -> bool; + + /// Returns true if the [DataType] is a dictionary type. + fn is_dictionary(&self) -> bool; + + /// Returns the byte width of the data type + /// Panics if the data type is not fixed stride. + fn byte_width(&self) -> usize; + + /// Returns the byte width of the data type, if it is fixed stride. + /// Returns None if the data type is not fixed stride. + fn byte_width_opt(&self) -> Option; +} + +impl DataTypeExt for DataType { + fn is_binary_like(&self) -> bool { + use DataType::*; + matches!( + self, + Utf8 | Binary | LargeUtf8 | LargeBinary | Utf8View | BinaryView + ) + } + + fn is_struct(&self) -> bool { + matches!(self, Self::Struct(_)) + } + + fn is_fixed_stride(&self) -> bool { + use DataType::*; + matches!( + self, + Boolean + | UInt8 + | UInt16 + | UInt32 + | UInt64 + | Int8 + | Int16 + | Int32 + | Int64 + | Float16 + | Float32 + | Float64 + | Decimal128(_, _) + | Decimal256(_, _) + | FixedSizeList(_, _) + | FixedSizeBinary(_) + | Duration(_) + | Timestamp(_, _) + | Date32 + | Date64 + | Time32(_) + | Time64(_) + ) + } + + fn is_dictionary(&self) -> bool { + matches!(self, Self::Dictionary(_, _)) + } + + fn byte_width_opt(&self) -> Option { + match self { + Self::Int8 => Some(1), + Self::Int16 => Some(2), + Self::Int32 => Some(4), + Self::Int64 => Some(8), + Self::UInt8 => Some(1), + Self::UInt16 => Some(2), + Self::UInt32 => Some(4), + Self::UInt64 => Some(8), + Self::Float16 => Some(2), + Self::Float32 => Some(4), + Self::Float64 => Some(8), + Self::Date32 => Some(4), + Self::Date64 => Some(8), + Self::Time32(_) => Some(4), + Self::Time64(_) => Some(8), + Self::Timestamp(_, _) => Some(8), + Self::Duration(_) => Some(8), + Self::Decimal128(_, _) => Some(16), + Self::Decimal256(_, _) => Some(32), + Self::Interval(unit) => match unit { + IntervalUnit::YearMonth => Some(4), + IntervalUnit::DayTime => Some(8), + IntervalUnit::MonthDayNano => Some(16), + }, + Self::FixedSizeBinary(s) => Some(*s as usize), + Self::FixedSizeList(dt, s) => dt + .data_type() + .byte_width_opt() + .map(|width| width * *s as usize), + _ => None, + } + } + + fn byte_width(&self) -> usize { + self.byte_width_opt() + .unwrap_or_else(|| panic!("Expecting fixed stride data type, found {:?}", self)) + } +} + +/// Create an [`GenericListArray`] from values and offsets. +/// +/// ``` +/// use arrow_array::{Int32Array, Int64Array, ListArray}; +/// use arrow_array::types::Int64Type; +/// use lance_arrow::try_new_generic_list_array; +/// +/// let offsets = Int32Array::from_iter([0, 2, 7, 10]); +/// let int_values = Int64Array::from_iter(0..10); +/// let list_arr = try_new_generic_list_array(int_values, &offsets).unwrap(); +/// assert_eq!(list_arr, +/// ListArray::from_iter_primitive::(vec![ +/// Some(vec![Some(0), Some(1)]), +/// Some(vec![Some(2), Some(3), Some(4), Some(5), Some(6)]), +/// Some(vec![Some(7), Some(8), Some(9)]), +/// ])) +/// ``` +pub fn try_new_generic_list_array( + values: T, + offsets: &PrimitiveArray, +) -> Result> +where + Offset::Native: OffsetSizeTrait, +{ + let data_type = if Offset::Native::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + values.data_type().clone(), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + values.data_type().clone(), + true, + ))) + }; + let data = ArrayDataBuilder::new(data_type) + .len(offsets.len() - 1) + .add_buffer(offsets.into_data().buffers()[0].clone()) + .add_child_data(values.into_data()) + .build()?; + + Ok(GenericListArray::from(data)) +} + +pub fn fixed_size_list_type(list_width: i32, inner_type: DataType) -> DataType { + DataType::FixedSizeList(Arc::new(Field::new("item", inner_type, true)), list_width) +} + +pub trait FixedSizeListArrayExt { + /// Create an [`FixedSizeListArray`] from values and list size. + /// + /// ``` + /// use arrow_array::{Int64Array, FixedSizeListArray}; + /// use arrow_array::types::Int64Type; + /// use lance_arrow::FixedSizeListArrayExt; + /// + /// let int_values = Int64Array::from_iter(0..10); + /// let fixed_size_list_arr = FixedSizeListArray::try_new_from_values(int_values, 2).unwrap(); + /// assert_eq!(fixed_size_list_arr, + /// FixedSizeListArray::from_iter_primitive::(vec![ + /// Some(vec![Some(0), Some(1)]), + /// Some(vec![Some(2), Some(3)]), + /// Some(vec![Some(4), Some(5)]), + /// Some(vec![Some(6), Some(7)]), + /// Some(vec![Some(8), Some(9)]) + /// ], 2)) + /// ``` + fn try_new_from_values( + values: T, + list_size: i32, + ) -> Result; + + /// Sample `n` rows from the [FixedSizeListArray] + /// + /// ``` + /// use arrow_array::{Int64Array, FixedSizeListArray, Array}; + /// use lance_arrow::FixedSizeListArrayExt; + /// + /// let int_values = Int64Array::from_iter(0..256); + /// let fixed_size_list_arr = FixedSizeListArray::try_new_from_values(int_values, 16).unwrap(); + /// let sampled = fixed_size_list_arr.sample(10).unwrap(); + /// assert_eq!(sampled.len(), 10); + /// assert_eq!(sampled.value_length(), 16); + /// assert_eq!(sampled.values().len(), 160); + /// ``` + fn sample(&self, n: usize) -> Result; + + /// Ensure the [FixedSizeListArray] of Float16, Float32, Float64, + /// Int8, Int16, Int32, Int64, UInt8, UInt32 type to its closest floating point type. + fn convert_to_floating_point(&self) -> Result; +} + +impl FixedSizeListArrayExt for FixedSizeListArray { + fn try_new_from_values(values: T, list_size: i32) -> Result { + let field = Arc::new(Field::new("item", values.data_type().clone(), true)); + let values = Arc::new(values); + + Self::try_new(field, list_size, values, None) + } + + fn sample(&self, n: usize) -> Result { + if n >= self.len() { + return Ok(self.clone()); + } + let mut rng = SmallRng::from_os_rng(); + let chosen = (0..self.len() as u32).choose_multiple(&mut rng, n); + take(self, &UInt32Array::from(chosen), None).map(|arr| arr.as_fixed_size_list().clone()) + } + + fn convert_to_floating_point(&self) -> Result { + match self.data_type() { + DataType::FixedSizeList(field, size) => match field.data_type() { + DataType::Float16 | DataType::Float32 | DataType::Float64 => Ok(self.clone()), + DataType::Int8 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float32, + field.is_nullable(), + )), + *size, + Arc::new(Float32Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int8Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f32)), + )), + self.nulls().cloned(), + )), + DataType::Int16 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float32, + field.is_nullable(), + )), + *size, + Arc::new(Float32Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int16Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f32)), + )), + self.nulls().cloned(), + )), + DataType::Int32 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float32, + field.is_nullable(), + )), + *size, + Arc::new(Float32Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int32Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f32)), + )), + self.nulls().cloned(), + )), + DataType::Int64 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float64, + field.is_nullable(), + )), + *size, + Arc::new(Float64Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to Int64Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f64)), + )), + self.nulls().cloned(), + )), + DataType::UInt8 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float64, + field.is_nullable(), + )), + *size, + Arc::new(Float64Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to UInt8Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f64)), + )), + self.nulls().cloned(), + )), + DataType::UInt32 => Ok(Self::new( + Arc::new(arrow_schema::Field::new( + field.name(), + DataType::Float64, + field.is_nullable(), + )), + *size, + Arc::new(Float64Array::from_iter( + self.values() + .as_any() + .downcast_ref::() + .ok_or(ArrowError::ParseError( + "Fail to cast primitive array to UInt32Type".to_string(), + ))? + .into_iter() + .map(|x| x.map(|y| y as f64)), + )), + self.nulls().cloned(), + )), + data_type => Err(ArrowError::ParseError(format!( + "Expect either floating type or integer got {:?}", + data_type + ))), + }, + data_type => Err(ArrowError::ParseError(format!( + "Expect either FixedSizeList got {:?}", + data_type + ))), + } + } +} + +/// Force downcast of an [`Array`], such as an [`ArrayRef`], to +/// [`FixedSizeListArray`], panic'ing on failure. +pub fn as_fixed_size_list_array(arr: &dyn Array) -> &FixedSizeListArray { + arr.as_any().downcast_ref::().unwrap() +} + +pub trait FixedSizeBinaryArrayExt { + /// Create an [`FixedSizeBinaryArray`] from values and stride. + /// + /// ``` + /// use arrow_array::{UInt8Array, FixedSizeBinaryArray}; + /// use arrow_array::types::UInt8Type; + /// use lance_arrow::FixedSizeBinaryArrayExt; + /// + /// let int_values = UInt8Array::from_iter(0..10); + /// let fixed_size_list_arr = FixedSizeBinaryArray::try_new_from_values(&int_values, 2).unwrap(); + /// assert_eq!(fixed_size_list_arr, + /// FixedSizeBinaryArray::try_from_iter( + /// [[0u8, 1], [2, 3], [4, 5], [6, 7], [8, 9]].into_iter() + /// ).unwrap()) + /// ``` + fn try_new_from_values(values: &UInt8Array, stride: i32) -> Result; +} + +impl FixedSizeBinaryArrayExt for FixedSizeBinaryArray { + fn try_new_from_values(values: &UInt8Array, stride: i32) -> Result { + let data_type = DataType::FixedSizeBinary(stride); + let data = ArrayDataBuilder::new(data_type) + .len(values.len() / stride as usize) + .add_buffer(values.into_data().buffers()[0].clone()) + .build()?; + Ok(Self::from(data)) + } +} + +pub fn as_fixed_size_binary_array(arr: &dyn Array) -> &FixedSizeBinaryArray { + arr.as_any().downcast_ref::().unwrap() +} + +pub fn iter_str_array(arr: &dyn Array) -> Box> + Send + '_> { + match arr.data_type() { + DataType::Utf8 => Box::new(arr.as_string::().iter()), + DataType::LargeUtf8 => Box::new(arr.as_string::().iter()), + DataType::Utf8View => Box::new(arr.as_string_view().iter()), + _ => panic!( + "Expecting Utf8, LargeUtf8 or Utf8View, found {:?}", + arr.data_type() + ), + } +} + +pub fn iter_binary_array( + arr: &dyn Array, +) -> Result> + Send + '_>> { + match arr.data_type() { + DataType::Binary => Ok(Box::new(arr.as_binary::().iter())), + DataType::LargeBinary => Ok(Box::new(arr.as_binary::().iter())), + DataType::BinaryView => Ok(Box::new(arr.as_binary_view().iter())), + DataType::FixedSizeBinary(_) => Ok(Box::new(arr.as_fixed_size_binary().iter())), + data_type => Err(ArrowError::InvalidArgumentError(format!( + "Expecting a binary type, found {data_type}" + ))), + } +} + +/// Extends Arrow's [RecordBatch]. +pub trait RecordBatchExt { + /// Append a new column to this [`RecordBatch`] and returns a new RecordBatch. + /// + /// ``` + /// use std::sync::Arc; + /// use arrow_array::{RecordBatch, Int32Array, StringArray}; + /// use arrow_schema::{Schema, Field, DataType}; + /// use lance_arrow::*; + /// + /// let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])); + /// let int_arr = Arc::new(Int32Array::from(vec![1, 2, 3, 4])); + /// let record_batch = RecordBatch::try_new(schema, vec![int_arr.clone()]).unwrap(); + /// + /// let new_field = Field::new("s", DataType::Utf8, true); + /// let str_arr = Arc::new(StringArray::from(vec!["a", "b", "c", "d"])); + /// let new_record_batch = record_batch.try_with_column(new_field, str_arr.clone()).unwrap(); + /// + /// assert_eq!( + /// new_record_batch, + /// RecordBatch::try_new( + /// Arc::new(Schema::new( + /// vec![ + /// Field::new("a", DataType::Int32, true), + /// Field::new("s", DataType::Utf8, true) + /// ]) + /// ), + /// vec![int_arr, str_arr], + /// ).unwrap() + /// ) + /// ``` + fn try_with_column(&self, field: Field, arr: ArrayRef) -> Result; + + /// Created a new RecordBatch with column at index. + fn try_with_column_at(&self, index: usize, field: Field, arr: ArrayRef) -> Result; + + /// Creates a new [`RecordBatch`] from the provided [`StructArray`]. + /// + /// The fields on the [`StructArray`] need to match this [`RecordBatch`] schema + fn try_new_from_struct_array(&self, arr: StructArray) -> Result; + + /// Merge with another [`RecordBatch`] and returns a new one. + /// + /// Fields are merged based on name. First we iterate the left columns. If a matching + /// name is found in the right then we merge the two columns. If there is no match then + /// we add the left column to the output. + /// + /// To merge two columns we consider the type. If both arrays are struct arrays we recurse. + /// Otherwise we use the left array. + /// + /// Afterwards we add all non-matching right columns to the output. + /// + /// Note: This method likely does not handle nested fields correctly and you may want to consider + /// using [`Self::merge_with_schema`] instead. + /// ``` + /// use std::sync::Arc; + /// use arrow_array::*; + /// use arrow_schema::{Schema, Field, DataType}; + /// use lance_arrow::*; + /// + /// let left_schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])); + /// let int_arr = Arc::new(Int32Array::from(vec![1, 2, 3, 4])); + /// let left = RecordBatch::try_new(left_schema, vec![int_arr.clone()]).unwrap(); + /// + /// let right_schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)])); + /// let str_arr = Arc::new(StringArray::from(vec!["a", "b", "c", "d"])); + /// let right = RecordBatch::try_new(right_schema, vec![str_arr.clone()]).unwrap(); + /// + /// let new_record_batch = left.merge(&right).unwrap(); + /// + /// assert_eq!( + /// new_record_batch, + /// RecordBatch::try_new( + /// Arc::new(Schema::new( + /// vec![ + /// Field::new("a", DataType::Int32, true), + /// Field::new("s", DataType::Utf8, true) + /// ]) + /// ), + /// vec![int_arr, str_arr], + /// ).unwrap() + /// ) + /// ``` + /// + /// TODO: add merge nested fields support. + fn merge(&self, other: &RecordBatch) -> Result; + + /// Create a batch by merging columns between two batches with a given schema. + /// + /// A reference schema is used to determine the proper ordering of nested fields. + /// + /// For each field in the reference schema we look for corresponding fields in + /// the left and right batches. If a field is found in both batches we recursively merge + /// it. + /// + /// If a field is only in the left or right batch we take it as it is. + fn merge_with_schema(&self, other: &RecordBatch, schema: &Schema) -> Result; + + /// Drop one column specified with the name and return the new [`RecordBatch`]. + /// + /// If the named column does not exist, it returns a copy of this [`RecordBatch`]. + fn drop_column(&self, name: &str) -> Result; + + /// Replace a column (specified by name) and return the new [`RecordBatch`]. + fn replace_column_by_name(&self, name: &str, column: Arc) -> Result; + + /// Replace a column schema (specified by name) and return the new [`RecordBatch`]. + fn replace_column_schema_by_name( + &self, + name: &str, + new_data_type: DataType, + column: Arc, + ) -> Result; + + /// Rename a column at a given index. + fn rename_column(&self, index: usize, new_name: &str) -> Result; + + /// Get (potentially nested) column by qualified name. + fn column_by_qualified_name(&self, name: &str) -> Option<&ArrayRef>; + + /// Project the schema over the [RecordBatch]. + fn project_by_schema(&self, schema: &Schema) -> Result; + + /// metadata of the schema. + fn metadata(&self) -> &HashMap; + + /// Add metadata to the schema. + fn add_metadata(&self, key: String, value: String) -> Result { + let mut metadata = self.metadata().clone(); + metadata.insert(key, value); + self.with_metadata(metadata) + } + + /// Replace the schema metadata with the provided one. + fn with_metadata(&self, metadata: HashMap) -> Result; + + /// Take selected rows from the [RecordBatch]. + fn take(&self, indices: &UInt32Array) -> Result; + + /// Create a new RecordBatch with compacted memory after slicing. + fn shrink_to_fit(&self) -> Result; + + /// Helper method to sort the RecordBatch by a column + fn sort_by_column(&self, column: usize, options: Option) -> Result; +} + +impl RecordBatchExt for RecordBatch { + fn try_with_column(&self, field: Field, arr: ArrayRef) -> Result { + let new_schema = Arc::new(self.schema().as_ref().try_with_column(field)?); + let mut new_columns = self.columns().to_vec(); + new_columns.push(arr); + Self::try_new(new_schema, new_columns) + } + + fn try_with_column_at(&self, index: usize, field: Field, arr: ArrayRef) -> Result { + let new_schema = Arc::new(self.schema().as_ref().try_with_column_at(index, field)?); + let mut new_columns = self.columns().to_vec(); + new_columns.insert(index, arr); + Self::try_new(new_schema, new_columns) + } + + fn try_new_from_struct_array(&self, arr: StructArray) -> Result { + let schema = Arc::new(Schema::new_with_metadata( + arr.fields().to_vec(), + self.schema().metadata.clone(), + )); + let batch = Self::from(arr); + batch.with_schema(schema) + } + + fn merge(&self, other: &Self) -> Result { + if self.num_rows() != other.num_rows() { + return Err(ArrowError::InvalidArgumentError(format!( + "Attempt to merge two RecordBatch with different sizes: {} != {}", + self.num_rows(), + other.num_rows() + ))); + } + let left_struct_array: StructArray = self.clone().into(); + let right_struct_array: StructArray = other.clone().into(); + self.try_new_from_struct_array(merge(&left_struct_array, &right_struct_array)) + } + + fn merge_with_schema(&self, other: &RecordBatch, schema: &Schema) -> Result { + if self.num_rows() != other.num_rows() { + return Err(ArrowError::InvalidArgumentError(format!( + "Attempt to merge two RecordBatch with different sizes: {} != {}", + self.num_rows(), + other.num_rows() + ))); + } + let left_struct_array: StructArray = self.clone().into(); + let right_struct_array: StructArray = other.clone().into(); + self.try_new_from_struct_array(merge_with_schema( + &left_struct_array, + &right_struct_array, + schema.fields(), + )) + } + + fn drop_column(&self, name: &str) -> Result { + let mut fields = vec![]; + let mut columns = vec![]; + for i in 0..self.schema().fields.len() { + if self.schema().field(i).name() != name { + fields.push(self.schema().field(i).clone()); + columns.push(self.column(i).clone()); + } + } + Self::try_new( + Arc::new(Schema::new_with_metadata( + fields, + self.schema().metadata().clone(), + )), + columns, + ) + } + + fn rename_column(&self, index: usize, new_name: &str) -> Result { + let mut fields = self.schema().fields().to_vec(); + if index >= fields.len() { + return Err(ArrowError::InvalidArgumentError(format!( + "Index out of bounds: {}", + index + ))); + } + fields[index] = Arc::new(Field::new( + new_name, + fields[index].data_type().clone(), + fields[index].is_nullable(), + )); + Self::try_new( + Arc::new(Schema::new_with_metadata( + fields, + self.schema().metadata().clone(), + )), + self.columns().to_vec(), + ) + } + + fn replace_column_by_name(&self, name: &str, column: Arc) -> Result { + let mut columns = self.columns().to_vec(); + let field_i = self + .schema() + .fields() + .iter() + .position(|f| f.name() == name) + .ok_or_else(|| ArrowError::SchemaError(format!("Field {} does not exist", name)))?; + columns[field_i] = column; + Self::try_new(self.schema(), columns) + } + + fn replace_column_schema_by_name( + &self, + name: &str, + new_data_type: DataType, + column: Arc, + ) -> Result { + let fields = self + .schema() + .fields() + .iter() + .map(|x| { + if x.name() != name { + x.clone() + } else { + let new_field = Field::new(name, new_data_type.clone(), x.is_nullable()); + Arc::new(new_field) + } + }) + .collect::>(); + let schema = Schema::new_with_metadata(fields, self.schema().metadata.clone()); + let mut columns = self.columns().to_vec(); + let field_i = self + .schema() + .fields() + .iter() + .position(|f| f.name() == name) + .ok_or_else(|| ArrowError::SchemaError(format!("Field {} does not exist", name)))?; + columns[field_i] = column; + Self::try_new(Arc::new(schema), columns) + } + + fn column_by_qualified_name(&self, name: &str) -> Option<&ArrayRef> { + let split = name.split('.').collect::>(); + if split.is_empty() { + return None; + } + + self.column_by_name(split[0]) + .and_then(|arr| get_sub_array(arr, &split[1..])) + } + + fn project_by_schema(&self, schema: &Schema) -> Result { + let struct_array: StructArray = self.clone().into(); + self.try_new_from_struct_array(project(&struct_array, schema.fields())?) + } + + fn metadata(&self) -> &HashMap { + self.schema_ref().metadata() + } + + fn with_metadata(&self, metadata: HashMap) -> Result { + let mut schema = self.schema_ref().as_ref().clone(); + schema.metadata = metadata; + Self::try_new(schema.into(), self.columns().into()) + } + + fn take(&self, indices: &UInt32Array) -> Result { + let struct_array: StructArray = self.clone().into(); + let taken = take(&struct_array, indices, None)?; + self.try_new_from_struct_array(taken.as_struct().clone()) + } + + fn shrink_to_fit(&self) -> Result { + // Deep copy the sliced record batch, instead of whole batch + crate::deepcopy::deep_copy_batch_sliced(self) + } + + fn sort_by_column(&self, column: usize, options: Option) -> Result { + if column >= self.num_columns() { + return Err(ArrowError::InvalidArgumentError(format!( + "Column index out of bounds: {}", + column + ))); + } + let column = self.column(column); + let sorted = arrow_ord::sort::sort_to_indices(column, options, None)?; + self.take(&sorted) + } +} + +/// Recursively projects an array to match the target field's structure. +/// This handles reordering fields inside nested List types. +fn project_array(array: &ArrayRef, target_field: &Field) -> Result { + match target_field.data_type() { + DataType::Struct(subfields) => { + let struct_arr = array.as_struct(); + let projected = project(struct_arr, subfields)?; + Ok(Arc::new(projected)) + } + DataType::List(inner_field) => { + let list_arr: &ListArray = array.as_list(); + let projected_values = project_array(list_arr.values(), inner_field.as_ref())?; + Ok(Arc::new(ListArray::new( + inner_field.clone(), + list_arr.offsets().clone(), + projected_values, + list_arr.nulls().cloned(), + ))) + } + DataType::LargeList(inner_field) => { + let list_arr: &LargeListArray = array.as_list(); + let projected_values = project_array(list_arr.values(), inner_field.as_ref())?; + Ok(Arc::new(LargeListArray::new( + inner_field.clone(), + list_arr.offsets().clone(), + projected_values, + list_arr.nulls().cloned(), + ))) + } + DataType::FixedSizeList(inner_field, size) => { + let list_arr = array.as_fixed_size_list(); + let projected_values = project_array(list_arr.values(), inner_field.as_ref())?; + Ok(Arc::new(FixedSizeListArray::new( + inner_field.clone(), + *size, + projected_values, + list_arr.nulls().cloned(), + ))) + } + // A nullable entries field fails MapArray::try_new unconditionally, + // so a (schema-invalid) map declared that way keeps the clone + // fallthrough it always had rather than gaining a new error. + DataType::Map(entries_field, sorted) if !entries_field.is_nullable() => { + let map_arr = array.as_map(); + let DataType::Struct(entry_fields) = entries_field.data_type() else { + return Err(ArrowError::SchemaError(format!( + "Map entries field must be a struct, got {}", + entries_field.data_type() + ))); + }; + let projected_entries = project(map_arr.entries(), entry_fields)?; + // try_new re-checks the entries invariants (a non-null entries + // struct, two entry columns, offset bounds); null keys are ruled + // out one level down, by the struct rebuild against the + // non-nullable key field. + Ok(Arc::new(MapArray::try_new( + entries_field.clone(), + map_arr.offsets().clone(), + projected_entries, + map_arr.nulls().cloned(), + *sorted, + )?)) + } + _ => Ok(array.clone()), + } +} + +fn project(struct_array: &StructArray, fields: &Fields) -> Result { + if fields.is_empty() { + return Ok(StructArray::new_empty_fields( + struct_array.len(), + struct_array.nulls().cloned(), + )); + } + let mut columns: Vec = vec![]; + for field in fields.iter() { + if let Some(col) = struct_array.column_by_name(field.name()) { + let projected = project_array(col, field.as_ref())?; + columns.push(projected); + } else { + return Err(ArrowError::SchemaError(format!( + "field {} does not exist in the RecordBatch", + field.name() + ))); + } + } + // Preserve the struct's validity when projecting + StructArray::try_new(fields.clone(), columns, struct_array.nulls().cloned()) +} + +/// Whether `data_type` has a struct somewhere below it, through lists. +fn holds_struct(data_type: &DataType) -> bool { + match data_type { + DataType::Struct(_) => true, + DataType::List(item) | DataType::LargeList(item) => holds_struct(item.data_type()), + _ => false, + } +} + +/// Merge the values of two lists: structs field by field, nested lists +/// recursively, anything else keeps the left side. +fn merge_list_values(left: &ArrayRef, right: &ArrayRef) -> ArrayRef { + match (left.data_type(), right.data_type()) { + (DataType::Struct(_), DataType::Struct(_)) => { + Arc::new(merge(left.as_struct(), right.as_struct())) + } + (DataType::List(_), DataType::List(_)) + | (DataType::LargeList(_), DataType::LargeList(_)) + if left.data_type() != right.data_type() + && holds_struct(left.data_type()) + && holds_struct(right.data_type()) => + { + merge_list_struct(left, right) + } + _ => left.clone(), + } +} + +fn merge_list_struct_helper( + left: &dyn Array, + right: &dyn Array, +) -> Arc { + let left_list: &GenericListArray = left.as_list(); + let right_list: &GenericListArray = right.as_list(); + let item_name = match left.data_type() { + DataType::List(item) | DataType::LargeList(item) => item.name().clone(), + _ => unreachable!(), + }; + // One side all-null (a placeholder for columns this fragment lacks) has + // no values, so stand in nulls shaped like the other side's. + let null_left = left_list.null_count() == left_list.len(); + let null_right = !null_left && right_list.null_count() == right_list.len(); + let (merged_items, list, items_nullable) = if null_left || null_right { + let not_null = if null_left { right_list } else { left_list }; + let values_len = not_null.values().len(); + let values = |list: &GenericListArray, is_null: bool| { + if is_null { + new_null_array(list.values().data_type(), values_len) + } else { + list.values().clone() + } + }; + let merged = merge_list_values( + &values(left_list, null_left), + &values(right_list, null_right), + ); + (merged, not_null, true) + } else { + if left_list.offsets().inner() != right_list.offsets().inner() { + panic!("Attempt to merge list struct arrays which do not have same offsets"); + } + let merged = merge_list_values(left_list.values(), right_list.values()); + let nullable = match left.data_type() { + DataType::List(item) | DataType::LargeList(item) => item.is_nullable(), + _ => unreachable!(), + }; + (merged, left_list, nullable) + }; + let items_field = Arc::new(Field::new( + item_name, + merged_items.data_type().clone(), + items_nullable, + )); + Arc::new(GenericListArray::::new( + items_field, + list.offsets().clone(), + merged_items, + list.nulls().cloned(), + )) +} + +/// Merge two lists whose items hold structs. Only succeeds if both lists have +/// the same offsets or one of them is all-null; panics otherwise. +fn merge_list_struct(left: &dyn Array, right: &dyn Array) -> Arc { + match (left.data_type(), right.data_type()) { + (DataType::List(_), DataType::List(_)) => merge_list_struct_helper::(left, right), + (DataType::LargeList(_), DataType::LargeList(_)) => { + merge_list_struct_helper::(left, right) + } + _ => unreachable!(), + } +} + +/// Helper function to merge validity buffers from two struct arrays. +/// +/// A row is valid if it is valid in either input. +/// An absent validity buffer means all rows are valid, an all-null buffer acts as the identity for this merge. +fn merge_struct_validity( + left_validity: Option<&arrow_buffer::NullBuffer>, + right_validity: Option<&arrow_buffer::NullBuffer>, +) -> Option { + match (left_validity, right_validity) { + // Fast paths: no computation needed + (None, _) | (_, None) => None, + (Some(left), Some(right)) => { + if left.null_count() == 0 || right.null_count() == 0 { + return None; + } + if left.null_count() == left.len() { + return Some(right.clone()); + } + if right.null_count() == right.len() { + return Some(left.clone()); + } + + let left_buffer = left.inner(); + let right_buffer = right.inner(); + + // Perform bitwise OR directly on BooleanBuffers + // This preserves the correct semantics: 1 = valid, 0 = null + let merged_buffer = left_buffer | right_buffer; + + Some(arrow_buffer::NullBuffer::from(merged_buffer)) + } + } +} + +fn merge_list_child_values( + child_field: &Field, + left_values: ArrayRef, + right_values: ArrayRef, +) -> ArrayRef { + match child_field.data_type() { + DataType::Struct(child_fields) => Arc::new(merge_with_schema( + left_values.as_struct(), + right_values.as_struct(), + child_fields, + )) as ArrayRef, + DataType::List(grandchild) => { + let left_list = left_values + .as_any() + .downcast_ref::() + .expect("left list values should be ListArray"); + let right_list = right_values + .as_any() + .downcast_ref::() + .expect("right list values should be ListArray"); + let merged_values = merge_list_child_values( + grandchild.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = merge_struct_validity(left_list.nulls(), right_list.nulls()); + Arc::new(ListArray::new( + grandchild.clone(), + left_list.offsets().clone(), + merged_values, + merged_validity, + )) as ArrayRef + } + DataType::LargeList(grandchild) => { + let left_list = left_values + .as_any() + .downcast_ref::() + .expect("left list values should be LargeListArray"); + let right_list = right_values + .as_any() + .downcast_ref::() + .expect("right list values should be LargeListArray"); + let merged_values = merge_list_child_values( + grandchild.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = merge_struct_validity(left_list.nulls(), right_list.nulls()); + Arc::new(LargeListArray::new( + grandchild.clone(), + left_list.offsets().clone(), + merged_values, + merged_validity, + )) as ArrayRef + } + DataType::FixedSizeList(grandchild, list_size) => { + let left_list = left_values + .as_any() + .downcast_ref::() + .expect("left list values should be FixedSizeListArray"); + let right_list = right_values + .as_any() + .downcast_ref::() + .expect("right list values should be FixedSizeListArray"); + let merged_values = merge_list_child_values( + grandchild.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = merge_struct_validity(left_list.nulls(), right_list.nulls()); + Arc::new(FixedSizeListArray::new( + grandchild.clone(), + *list_size, + merged_values, + merged_validity, + )) as ArrayRef + } + _ => left_values.clone(), + } +} + +// Helper function to adjust child array validity based on parent struct validity +// When parent struct is null, propagates null to child array +// Optimized with fast paths and SIMD operations +fn adjust_child_validity( + child: &ArrayRef, + parent_validity: Option<&arrow_buffer::NullBuffer>, +) -> ArrayRef { + // Fast path: no parent validity means no adjustment needed + let parent_validity = match parent_validity { + None => return child.clone(), + Some(p) if p.null_count() == 0 => return child.clone(), // No nulls to propagate + Some(p) => p, + }; + + // Fast path: DataType::Null arrays are always entirely null by definition and cannot + // carry an explicit null bitmap (Arrow rejects it). No adjustment is needed. + if child.data_type() == &DataType::Null { + return child.clone(); + } + + let child_validity = child.nulls(); + + // Compute the new validity: child_validity AND parent_validity + let new_validity = match child_validity { + None => { + // Fast path: child has no existing validity, just use parent's + parent_validity.clone() + } + Some(child_nulls) => { + let child_buffer = child_nulls.inner(); + let parent_buffer = parent_validity.inner(); + + // Perform bitwise AND directly on BooleanBuffers + // This preserves the correct semantics: 1 = valid, 0 = null + let merged_buffer = child_buffer & parent_buffer; + + arrow_buffer::NullBuffer::from(merged_buffer) + } + }; + + // ArrayData keeps the child's offset for its value buffers. Its null bitmap + // must cover that offset too, even though the merged validity describes only + // the visible rows. Copy logical bits into an offset-aligned bitmap when needed. + let null_bit_buffer = if child.offset() == 0 && new_validity.inner().offset() == 0 { + new_validity.into_inner().into_inner() + } else { + let mut builder = + arrow_buffer::builder::BooleanBufferBuilder::new(child.offset() + child.len()); + builder.append_n(child.offset(), true); + builder.append_buffer(new_validity.inner()); + builder.build().into_inner() + }; + + // Create new array with adjusted validity + arrow_array::make_array( + arrow_data::ArrayData::try_new( + child.data_type().clone(), + child.len(), + Some(null_bit_buffer), + child.offset(), + child.to_data().buffers().to_vec(), + child.to_data().child_data().to_vec(), + ) + .unwrap(), + ) +} + +fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> StructArray { + let mut fields: Vec = vec![]; + let mut columns: Vec = vec![]; + let right_fields = right_struct_array.fields(); + let right_columns = right_struct_array.columns(); + + // Get the validity buffers from both structs + let left_validity = left_struct_array.nulls(); + let right_validity = right_struct_array.nulls(); + + // Compute merged validity + let merged_validity = merge_struct_validity(left_validity, right_validity); + + // iterate through the fields on the left hand side + for (left_field, left_column) in left_struct_array + .fields() + .iter() + .zip(left_struct_array.columns().iter()) + { + match right_fields + .iter() + .position(|f| f.name() == left_field.name()) + { + // if the field exists on the right hand side, merge them recursively if appropriate + Some(right_index) => { + let right_field = right_fields.get(right_index).unwrap(); + let right_column = right_columns.get(right_index).unwrap(); + // if both fields are struct, merge them recursively + match (left_field.data_type(), right_field.data_type()) { + (DataType::Struct(_), DataType::Struct(_)) => { + let left_sub_array = left_column.as_struct(); + let right_sub_array = right_column.as_struct(); + let merged_sub_array = merge(left_sub_array, right_sub_array); + fields.push(Field::new( + left_field.name(), + merged_sub_array.data_type().clone(), + left_field.is_nullable(), + )); + columns.push(Arc::new(merged_sub_array) as ArrayRef); + } + (DataType::List(left_list), DataType::List(right_list)) + | (DataType::LargeList(left_list), DataType::LargeList(right_list)) + if holds_struct(left_list.data_type()) + && holds_struct(right_list.data_type()) => + { + // Identical inner types: nothing to merge, keep the left column. + if left_list.data_type() == right_list.data_type() { + fields.push(left_field.as_ref().clone()); + columns.push(left_column.clone()); + } else { + // The struct fields differ, so merge them structurally. merge_list_struct + // only succeeds when both lists share offsets or one side is all-null; + // it panics otherwise. + let merged_sub_array = merge_list_struct(&left_column, &right_column); + + fields.push(Field::new( + left_field.name(), + merged_sub_array.data_type().clone(), + left_field.is_nullable(), + )); + columns.push(merged_sub_array); + } + } + // otherwise, just use the field on the left hand side + _ => { + // TODO handle list-of-struct and other types + fields.push(left_field.as_ref().clone()); + // Adjust the column validity: if left struct was null, propagate to child + let adjusted_column = adjust_child_validity(left_column, left_validity); + columns.push(adjusted_column); + } + } + } + None => { + fields.push(left_field.as_ref().clone()); + // Adjust the column validity: if left struct was null, propagate to child + let adjusted_column = adjust_child_validity(left_column, left_validity); + columns.push(adjusted_column); + } + } + } + + // now iterate through the fields on the right hand side + right_fields + .iter() + .zip(right_columns.iter()) + .for_each(|(field, column)| { + // add new columns on the right + if !left_struct_array + .fields() + .iter() + .any(|f| f.name() == field.name()) + { + fields.push(field.as_ref().clone()); + // This field doesn't exist on the left + // We use the right's column but need to adjust for struct validity + let adjusted_column = adjust_child_validity(column, right_validity); + columns.push(adjusted_column); + } + }); + + StructArray::try_new(Fields::from(fields), columns, merged_validity).unwrap() +} + +fn merge_with_schema( + left_struct_array: &StructArray, + right_struct_array: &StructArray, + fields: &Fields, +) -> StructArray { + // Helper function that returns true if both types are struct or both are non-struct + fn same_type_kind(left: &DataType, right: &DataType) -> bool { + match (left, right) { + (DataType::Struct(_), DataType::Struct(_)) => true, + (DataType::Struct(_), _) => false, + (_, DataType::Struct(_)) => false, + _ => true, + } + } + + let mut output_fields: Vec = Vec::with_capacity(fields.len()); + let mut columns: Vec = Vec::with_capacity(fields.len()); + + let left_fields = left_struct_array.fields(); + let left_columns = left_struct_array.columns(); + let right_fields = right_struct_array.fields(); + let right_columns = right_struct_array.columns(); + + // Get the validity buffers from both structs + let left_validity = left_struct_array.nulls(); + let right_validity = right_struct_array.nulls(); + + // Compute merged validity + let merged_validity = merge_struct_validity(left_validity, right_validity); + + for field in fields { + let left_match_idx = left_fields.iter().position(|f| { + f.name() == field.name() && same_type_kind(f.data_type(), field.data_type()) + }); + let right_match_idx = right_fields.iter().position(|f| { + f.name() == field.name() && same_type_kind(f.data_type(), field.data_type()) + }); + + match (left_match_idx, right_match_idx) { + (None, Some(right_idx)) => { + output_fields.push(right_fields[right_idx].as_ref().clone()); + // Adjust validity if the right struct was null + let adjusted_column = + adjust_child_validity(&right_columns[right_idx], right_validity); + columns.push(adjusted_column); + } + (Some(left_idx), None) => { + output_fields.push(left_fields[left_idx].as_ref().clone()); + // Adjust validity if the left struct was null + let adjusted_column = adjust_child_validity(&left_columns[left_idx], left_validity); + columns.push(adjusted_column); + } + (Some(left_idx), Some(right_idx)) => { + match field.data_type() { + DataType::Struct(child_fields) => { + let left_sub_array = left_columns[left_idx].as_struct(); + let right_sub_array = right_columns[right_idx].as_struct(); + let merged_sub_array = + merge_with_schema(left_sub_array, right_sub_array, child_fields); + output_fields.push(Field::new( + field.name(), + merged_sub_array.data_type().clone(), + field.is_nullable(), + )); + columns.push(Arc::new(merged_sub_array) as ArrayRef); + } + DataType::List(child_field) => { + let left_list = left_columns[left_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let right_list = right_columns[right_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let merged_values = merge_list_child_values( + child_field.as_ref(), + left_list.trimmed_values(), + right_list.trimmed_values(), + ); + let merged_validity = + merge_struct_validity(left_list.nulls(), right_list.nulls()); + // `trimmed_values` starts at the first used value, so offsets + // must be shifted to match or `ListArray::new` panics when the + // input list was sliced (e.g. from a filtered batch). + let merged_list = ListArray::new( + child_field.clone(), + left_list.trimmed_offsets(), + merged_values, + merged_validity, + ); + output_fields.push(field.as_ref().clone()); + columns.push(Arc::new(merged_list) as ArrayRef); + } + DataType::LargeList(child_field) => { + let left_list = left_columns[left_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let right_list = right_columns[right_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let merged_values = merge_list_child_values( + child_field.as_ref(), + left_list.trimmed_values(), + right_list.trimmed_values(), + ); + let merged_validity = + merge_struct_validity(left_list.nulls(), right_list.nulls()); + let merged_list = LargeListArray::new( + child_field.clone(), + left_list.trimmed_offsets(), + merged_values, + merged_validity, + ); + output_fields.push(field.as_ref().clone()); + columns.push(Arc::new(merged_list) as ArrayRef); + } + DataType::FixedSizeList(child_field, list_size) => { + let left_list = left_columns[left_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let right_list = right_columns[right_idx] + .as_any() + .downcast_ref::() + .unwrap(); + let merged_values = merge_list_child_values( + child_field.as_ref(), + left_list.values().clone(), + right_list.values().clone(), + ); + let merged_validity = + merge_struct_validity(left_list.nulls(), right_list.nulls()); + let merged_list = FixedSizeListArray::new( + child_field.clone(), + *list_size, + merged_values, + merged_validity, + ); + output_fields.push(field.as_ref().clone()); + columns.push(Arc::new(merged_list) as ArrayRef); + } + _ => { + output_fields.push(left_fields[left_idx].as_ref().clone()); + // For fields that exist in both, use left but adjust validity + let adjusted_column = + adjust_child_validity(&left_columns[left_idx], left_validity); + columns.push(adjusted_column); + } + } + } + (None, None) => { + // The field will not be included in the output + } + } + } + + StructArray::try_new(Fields::from(output_fields), columns, merged_validity).unwrap() +} + +fn get_sub_array<'a>(array: &'a ArrayRef, components: &[&str]) -> Option<&'a ArrayRef> { + if components.is_empty() { + return Some(array); + } + if !matches!(array.data_type(), DataType::Struct(_)) { + return None; + } + let struct_arr = array.as_struct(); + struct_arr + .column_by_name(components[0]) + .and_then(|arr| get_sub_array(arr, &components[1..])) +} + +/// Interleave multiple RecordBatches into a single RecordBatch. +/// +/// Behaves like [`arrow_select::interleave::interleave`], but for RecordBatches. +pub fn interleave_batches( + batches: &[RecordBatch], + indices: &[(usize, usize)], +) -> Result { + let first_batch = batches.first().ok_or_else(|| { + ArrowError::InvalidArgumentError("Cannot interleave zero RecordBatches".to_string()) + })?; + let schema = first_batch.schema(); + let num_columns = first_batch.num_columns(); + let mut columns = Vec::with_capacity(num_columns); + let mut chunks = Vec::with_capacity(batches.len()); + + for i in 0..num_columns { + for batch in batches { + chunks.push(batch.column(i).as_ref()); + } + let new_column = interleave(&chunks, indices)?; + columns.push(new_column); + chunks.clear(); + } + + RecordBatch::try_new(schema, columns) +} + +pub trait BufferExt { + /// Create an `arrow_buffer::Buffer`` from a `bytes::Bytes` object + /// + /// The alignment must be specified (as `bytes_per_value`) since we want to make + /// sure we can safely reinterpret the buffer. + /// + /// If the buffer is properly aligned this will be zero-copy. If not, a copy + /// will be made and an owned buffer returned. + /// + /// If `bytes_per_value` is not a power of two, then we assume the buffer is + /// never going to be reinterpreted into another type and we can safely + /// ignore the alignment. + /// + /// Yes, the method name is odd. It's because there is already a `from_bytes` + /// which converts from `arrow_buffer::bytes::Bytes` (not `bytes::Bytes`) + fn from_bytes_bytes(bytes: bytes::Bytes, bytes_per_value: u64) -> Self; + + /// Allocates a new properly aligned arrow buffer and copies `bytes` into it + /// + /// `size_bytes` can be larger than `bytes` and, if so, the trailing bytes will + /// be zeroed out. + /// + /// # Panics + /// + /// Panics if `size_bytes` is less than `bytes.len()` + fn copy_bytes_bytes(bytes: bytes::Bytes, size_bytes: usize) -> Self; +} + +fn is_pwr_two(n: u64) -> bool { + n & (n - 1) == 0 +} + +impl BufferExt for arrow_buffer::Buffer { + fn from_bytes_bytes(bytes: bytes::Bytes, bytes_per_value: u64) -> Self { + if is_pwr_two(bytes_per_value) && bytes.as_ptr().align_offset(bytes_per_value as usize) != 0 + { + // The original buffer is not aligned, cannot zero-copy + let size_bytes = bytes.len(); + Self::copy_bytes_bytes(bytes, size_bytes) + } else { + // The original buffer is aligned, can zero-copy + // SAFETY: the alignment is correct we can make this conversion + unsafe { + Self::from_custom_allocation( + NonNull::new(bytes.as_ptr() as _).expect("should be a valid pointer"), + bytes.len(), + Arc::new(bytes), + ) + } + } + } + + fn copy_bytes_bytes(bytes: bytes::Bytes, size_bytes: usize) -> Self { + assert!(size_bytes >= bytes.len()); + let mut buf = MutableBuffer::with_capacity(size_bytes); + let to_fill = size_bytes - bytes.len(); + buf.extend(bytes); + buf.extend(std::iter::repeat_n(0_u8, to_fill)); + + // FIX for issue #4512: Shrink buffer to actual size before converting to immutable + // This reduces memory overhead from capacity over-allocation + buf.shrink_to_fit(); + + Self::from(buf) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{ + BinaryArray, BinaryViewArray, BooleanArray, FixedSizeBinaryArray, Float32Array, Int32Array, + LargeBinaryArray, ListArray, NullArray, StringArray, StructArray, new_empty_array, + new_null_array, + }; + use arrow_buffer::OffsetBuffer; + + #[test] + fn test_adjust_child_validity_with_sliced_child() { + let child: ArrayRef = Arc::new(BooleanArray::from_iter((0..1030).map(|index| { + if index == 1027 { + None + } else { + Some(index % 2 == 1) + } + }))); + let child = child.slice(1025, 4); + assert_eq!(child.offset(), 1025); + + let parent_validity = arrow_buffer::NullBuffer::from(vec![true, false, true, true]); + let adjusted = adjust_child_validity(&child, Some(&parent_validity)); + assert_eq!(adjusted.offset(), child.offset()); + let adjusted = adjusted.as_any().downcast_ref::().unwrap(); + assert_eq!( + adjusted.iter().collect::>(), + vec![Some(true), None, None, Some(false)] + ); + } + + #[test] + fn test_adjust_child_validity_with_sliced_parent_bitmap() { + let child: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4])); + let parent_validity: arrow_buffer::NullBuffer = + (0..1030).map(|index| index != 1026).collect(); + let parent_validity = parent_validity.slice(1025, 4); + assert_eq!(parent_validity.inner().offset(), 1025); + + let adjusted = adjust_child_validity(&child, Some(&parent_validity)); + let adjusted = adjusted.as_any().downcast_ref::().unwrap(); + assert_eq!( + adjusted.iter().collect::>(), + vec![Some(1), None, Some(3), Some(4)] + ); + } + + #[test] + fn test_convert_to_floating_point_preserves_inner_nulls() { + // A FixedSizeList with a null inner element must convert to a + // FixedSizeList with the null kept in place. Dropping it would + // shorten the values array and shift every later element (and, when the + // remaining count is not a multiple of the list size, panic). + let values = Int8Array::from(vec![Some(1), None, Some(3), Some(4)]); + let fsl = FixedSizeListArray::new( + Arc::new(Field::new("item", DataType::Int8, true)), + 2, + Arc::new(values), + None, + ); + + let converted = fsl.convert_to_floating_point().unwrap(); + + assert_eq!(converted.len(), 2); + let conv_values = converted + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(conv_values.len(), 4); + assert_eq!(conv_values.value(0), 1.0); + assert!(conv_values.is_null(1)); + assert_eq!(conv_values.value(2), 3.0); + assert_eq!(conv_values.value(3), 4.0); + } + + #[test] + fn test_convert_to_floating_point_preserves_inner_nulls_f64_arm() { + // The Float64-producing arms (Int64/UInt8/UInt32) share the same fix as the + // Float32 arms; cover one representative (UInt8 -> Float64) so both branch + // families are exercised. + let values = UInt8Array::from(vec![Some(10u8), None, Some(30), Some(40)]); + let fsl = FixedSizeListArray::new( + Arc::new(Field::new("item", DataType::UInt8, true)), + 2, + Arc::new(values), + None, + ); + + let converted = fsl.convert_to_floating_point().unwrap(); + + assert_eq!(converted.len(), 2); + let conv_values = converted + .values() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(conv_values.len(), 4); + assert_eq!(conv_values.value(0), 10.0); + assert!(conv_values.is_null(1)); + assert_eq!(conv_values.value(2), 30.0); + assert_eq!(conv_values.value(3), 40.0); + } + + #[test] + fn test_merge_recursive() { + let a_array = Int32Array::from(vec![Some(1), Some(2), Some(3)]); + let e_array = Int32Array::from(vec![Some(4), Some(5), Some(6)]); + let c_array = Int32Array::from(vec![Some(7), Some(8), Some(9)]); + let d_array = StringArray::from(vec![Some("a"), Some("b"), Some("c")]); + + let left_schema = Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new( + "b", + DataType::Struct(vec![Field::new("c", DataType::Int32, true)].into()), + true, + ), + ]); + let left_batch = RecordBatch::try_new( + Arc::new(left_schema), + vec![ + Arc::new(a_array.clone()), + Arc::new(StructArray::from(vec![( + Arc::new(Field::new("c", DataType::Int32, true)), + Arc::new(c_array.clone()) as ArrayRef, + )])), + ], + ) + .unwrap(); + + let right_schema = Schema::new(vec![ + Field::new("e", DataType::Int32, true), + Field::new( + "b", + DataType::Struct(vec![Field::new("d", DataType::Utf8, true)].into()), + true, + ), + ]); + let right_batch = RecordBatch::try_new( + Arc::new(right_schema), + vec![ + Arc::new(e_array.clone()), + Arc::new(StructArray::from(vec![( + Arc::new(Field::new("d", DataType::Utf8, true)), + Arc::new(d_array.clone()) as ArrayRef, + )])) as ArrayRef, + ], + ) + .unwrap(); + + let merged_schema = Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new( + "b", + DataType::Struct( + vec![ + Field::new("c", DataType::Int32, true), + Field::new("d", DataType::Utf8, true), + ] + .into(), + ), + true, + ), + Field::new("e", DataType::Int32, true), + ]); + let merged_batch = RecordBatch::try_new( + Arc::new(merged_schema), + vec![ + Arc::new(a_array) as ArrayRef, + Arc::new(StructArray::from(vec![ + ( + Arc::new(Field::new("c", DataType::Int32, true)), + Arc::new(c_array) as ArrayRef, + ), + ( + Arc::new(Field::new("d", DataType::Utf8, true)), + Arc::new(d_array) as ArrayRef, + ), + ])) as ArrayRef, + Arc::new(e_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = left_batch.merge(&right_batch).unwrap(); + assert_eq!(result, merged_batch); + } + + #[test] + fn test_merge_with_schema() { + fn test_batch(names: &[&str], types: &[DataType]) -> (Schema, RecordBatch) { + let fields: Fields = names + .iter() + .zip(types) + .map(|(name, ty)| Field::new(name.to_string(), ty.clone(), false)) + .collect(); + let schema = Schema::new(vec![Field::new( + "struct", + DataType::Struct(fields.clone()), + false, + )]); + let children = types.iter().map(new_empty_array).collect::>(); + let batch = RecordBatch::try_new( + Arc::new(schema.clone()), + vec![Arc::new(StructArray::new(fields, children, None)) as ArrayRef], + ); + (schema, batch.unwrap()) + } + + let (_, left_batch) = test_batch(&["a", "b"], &[DataType::Int32, DataType::Int64]); + let (_, right_batch) = test_batch(&["c", "b"], &[DataType::Int32, DataType::Int64]); + let (output_schema, _) = test_batch( + &["b", "a", "c"], + &[DataType::Int64, DataType::Int32, DataType::Int32], + ); + + // If we use merge_with_schema the schema is respected + let merged = left_batch + .merge_with_schema(&right_batch, &output_schema) + .unwrap(); + assert_eq!(merged.schema().as_ref(), &output_schema); + + // If we use merge we get first-come first-serve based on the left batch + let (naive_schema, _) = test_batch( + &["a", "b", "c"], + &[DataType::Int32, DataType::Int64, DataType::Int32], + ); + let merged = left_batch.merge(&right_batch).unwrap(); + assert_eq!(merged.schema().as_ref(), &naive_schema); + } + + #[test] + fn test_merge_list_struct() { + let x_field = Arc::new(Field::new("x", DataType::Int32, true)); + let y_field = Arc::new(Field::new("y", DataType::Int32, true)); + let x_struct_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone()])), + true, + )); + let y_struct_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![y_field.clone()])), + true, + )); + let both_struct_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone(), y_field.clone()])), + true, + )); + let left_schema = Schema::new(vec![Field::new( + "list_struct", + DataType::List(x_struct_field.clone()), + true, + )]); + let right_schema = Schema::new(vec![Field::new( + "list_struct", + DataType::List(y_struct_field.clone()), + true, + )]); + let both_schema = Schema::new(vec![Field::new( + "list_struct", + DataType::List(both_struct_field.clone()), + true, + )]); + + let x = Arc::new(Int32Array::from(vec![1])); + let y = Arc::new(Int32Array::from(vec![2])); + let x_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone()]), + vec![x.clone()], + None, + )); + let y_struct = Arc::new(StructArray::new( + Fields::from(vec![y_field.clone()]), + vec![y.clone()], + None, + )); + let both_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone(), y_field.clone()]), + vec![x.clone(), y], + None, + )); + let both_null_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field, y_field]), + vec![x, Arc::new(new_null_array(&DataType::Int32, 1))], + None, + )); + let offsets = OffsetBuffer::from_lengths([1]); + let x_s_list = ListArray::new(x_struct_field, offsets.clone(), x_struct, None); + let y_s_list = ListArray::new(y_struct_field, offsets.clone(), y_struct, None); + let both_list = ListArray::new( + both_struct_field.clone(), + offsets.clone(), + both_struct, + None, + ); + let both_null_list = ListArray::new(both_struct_field, offsets, both_null_struct, None); + let x_batch = + RecordBatch::try_new(Arc::new(left_schema), vec![Arc::new(x_s_list)]).unwrap(); + let y_batch = RecordBatch::try_new( + Arc::new(right_schema.clone()), + vec![Arc::new(y_s_list.clone())], + ) + .unwrap(); + let merged = x_batch.merge(&y_batch).unwrap(); + let expected = + RecordBatch::try_new(Arc::new(both_schema.clone()), vec![Arc::new(both_list)]).unwrap(); + assert_eq!(merged, expected); + + let y_null_list = new_null_array(y_s_list.data_type(), 1); + let y_null_batch = + RecordBatch::try_new(Arc::new(right_schema), vec![Arc::new(y_null_list.clone())]) + .unwrap(); + let expected = + RecordBatch::try_new(Arc::new(both_schema), vec![Arc::new(both_null_list)]).unwrap(); + let merged = x_batch.merge(&y_null_batch).unwrap(); + assert_eq!(merged, expected); + } + + #[test] + fn test_merge_all_null_list_adds_nested_child() { + // An all-null placeholder (what a fragment reader merges in for children + // missing from its files) adds `b` to a struct below one or two lists. + let strukt = |cols: Vec<(&str, ArrayRef)>| -> ArrayRef { + let fields = cols + .iter() + .map(|(name, col)| Field::new(*name, col.data_type().clone(), true)) + .collect::>(); + Arc::new(StructArray::new( + fields.into(), + cols.into_iter().map(|(_, col)| col).collect(), + None, + )) + }; + // Two rows: `[values]` and null. + let list = |values: ArrayRef, large: bool| -> ArrayRef { + let field = Arc::new(Field::new("item", values.data_type().clone(), true)); + let lengths = [values.len(), 0]; + let nulls = Some(arrow_buffer::NullBuffer::from(vec![true, false])); + if large { + Arc::new(LargeListArray::new( + field, + OffsetBuffer::from_lengths(lengths), + values, + nulls, + )) + } else { + Arc::new(ListArray::new( + field, + OffsetBuffer::from_lengths(lengths), + values, + nulls, + )) + } + }; + let a = || Arc::new(Int32Array::from(vec![7])) as ArrayRef; + let b = || new_null_array(&DataType::Utf8, 1); + for large in [false, true] { + // list>>, built with or without `t`. + let under_list = |inner: ArrayRef, with_t: bool| { + let mut cols = vec![("in", inner)]; + if with_t { + cols.insert(0, ("t", Arc::new(Int32Array::from(vec![1])) as ArrayRef)); + } + list(strukt(cols), large) + }; + // list>> + let under_two_lists = |inner: ArrayRef, _: bool| { + let inner_list: ArrayRef = if large { + let field = Arc::new(Field::new("item", inner.data_type().clone(), true)); + Arc::new(LargeListArray::new( + field, + OffsetBuffer::from_lengths([1]), + inner, + None, + )) + } else { + let field = Arc::new(Field::new("item", inner.data_type().clone(), true)); + Arc::new(ListArray::new( + field, + OffsetBuffer::from_lengths([1]), + inner, + None, + )) + }; + list(inner_list, large) + }; + let shapes: [&dyn Fn(ArrayRef, bool) -> ArrayRef; 2] = [&under_list, &under_two_lists]; + for shape in shapes { + let data = shape(strukt(vec![("a", a())]), true); + let expected = shape(strukt(vec![("a", a()), ("b", b())]), true); + let placeholder = + new_null_array(shape(strukt(vec![("b", b())]), false).data_type(), 2); + let batch = |col: ArrayRef| { + RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "c", + col.data_type().clone(), + true, + )])), + vec![col], + ) + .unwrap() + }; + let expected = batch(expected); + // Either side may be the placeholder; field order follows the left. + for merged in [ + batch(data.clone()) + .merge(&batch(placeholder.clone())) + .unwrap(), + batch(placeholder.clone()) + .merge(&batch(data.clone())) + .unwrap(), + ] { + let merged = merged.project_by_schema(expected.schema_ref()).unwrap(); + assert_eq!(merged, expected, "large={large}"); + } + } + } + } + + #[test] + fn test_merge_list_struct_identical_schema() { + // Merging two batches whose `List` columns have identical types + // should yield a single column equal to the input (there is nothing to + // merge), not a struct with the field pushed twice. + let x_field = Arc::new(Field::new("x", DataType::Int32, true)); + let item_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone()])), + true, + )); + let schema = Arc::new(Schema::new(vec![Field::new( + "list_struct", + DataType::List(item_field.clone()), + true, + )])); + + let build_list = |values: Vec| { + let len = values.len(); + let item_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone()]), + vec![Arc::new(Int32Array::from(values))], + None, + )); + ListArray::new( + item_field.clone(), + OffsetBuffer::from_lengths([len]), + item_struct, + None, + ) + }; + + // Distinct values so the equality assertion proves the left column is kept, + // not that some column with the same values happens to be present. + let left = + RecordBatch::try_new(schema.clone(), vec![Arc::new(build_list(vec![1, 2]))]).unwrap(); + let right = RecordBatch::try_new(schema, vec![Arc::new(build_list(vec![3, 4]))]).unwrap(); + + let merged = left.merge(&right).unwrap(); + + // Exactly one column, equal to the left input: the field must not be duplicated. + assert_eq!(merged.num_columns(), 1); + assert_eq!(merged, left); + } + + #[test] + fn test_merge_nested_list_struct_identical_schema() { + // A `List` nested inside a struct reaches the identical-type + // short-circuit through the recursive `merge` call. The recursion must + // keep the field exactly once, equal to the left input. + let x_field = Arc::new(Field::new("x", DataType::Int32, true)); + let item_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![x_field.clone()])), + true, + )); + let companies_field = Arc::new(Field::new( + "companies", + DataType::List(item_field.clone()), + true, + )); + let schema = Arc::new(Schema::new(vec![Field::new( + "outer", + DataType::Struct(Fields::from(vec![companies_field.clone()])), + true, + )])); + + let build_outer = |x: i32| { + // One list row: [{x}]. + let item_struct = Arc::new(StructArray::new( + Fields::from(vec![x_field.clone()]), + vec![Arc::new(Int32Array::from(vec![x]))], + None, + )); + let companies = Arc::new(ListArray::new( + item_field.clone(), + OffsetBuffer::from_lengths([1]), + item_struct, + None, + )); + StructArray::new( + Fields::from(vec![companies_field.clone()]), + vec![companies], + None, + ) + }; + + // Distinct values so equality proves the left column is kept. + let left = RecordBatch::try_new(schema.clone(), vec![Arc::new(build_outer(10))]).unwrap(); + let right = RecordBatch::try_new(schema, vec![Arc::new(build_outer(20))]).unwrap(); + + let merged = left.merge(&right).unwrap(); + + // The recursive identical-type merge keeps exactly one `companies` field, + // with no double-push inside the nested struct. + assert_eq!(merged.column(0).as_struct().num_columns(), 1); + assert_eq!(merged, left); + } + + #[test] + fn test_byte_width_opt() { + assert_eq!(DataType::Int32.byte_width_opt(), Some(4)); + assert_eq!(DataType::Int64.byte_width_opt(), Some(8)); + assert_eq!(DataType::Float32.byte_width_opt(), Some(4)); + assert_eq!(DataType::Float64.byte_width_opt(), Some(8)); + assert_eq!(DataType::Utf8.byte_width_opt(), None); + assert_eq!(DataType::Binary.byte_width_opt(), None); + assert_eq!( + DataType::List(Arc::new(Field::new("item", DataType::Int32, true))).byte_width_opt(), + None + ); + assert_eq!( + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 3) + .byte_width_opt(), + Some(12) + ); + assert_eq!( + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 4) + .byte_width_opt(), + Some(16) + ); + assert_eq!( + DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Utf8, true)), 5) + .byte_width_opt(), + None + ); + } + + #[test] + fn test_take_record_batch() { + let schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Utf8, true), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from_iter_values(0..20)), + Arc::new(StringArray::from_iter_values( + (0..20).map(|i| format!("str-{}", i)), + )), + ], + ) + .unwrap(); + let taken = batch.take(&(vec![1_u32, 5_u32, 10_u32].into())).unwrap(); + assert_eq!( + taken, + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from(vec![1, 5, 10])), + Arc::new(StringArray::from(vec!["str-1", "str-5", "str-10"])), + ], + ) + .unwrap() + ) + } + + #[test] + fn test_schema_project_by_schema() { + let metadata = [("key".to_string(), "value".to_string())]; + let schema = Arc::new( + Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Utf8, true), + ]) + .with_metadata(metadata.clone().into()), + ); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from_iter_values(0..20)), + Arc::new(StringArray::from_iter_values( + (0..20).map(|i| format!("str-{}", i)), + )), + ], + ) + .unwrap(); + + // Empty schema + let empty_schema = Schema::empty(); + let empty_projected = batch.project_by_schema(&empty_schema).unwrap(); + let expected_schema = empty_schema.with_metadata(metadata.clone().into()); + assert_eq!( + empty_projected, + RecordBatch::from(StructArray::new_empty_fields(batch.num_rows(), None)) + .with_schema(Arc::new(expected_schema)) + .unwrap() + ); + + // Re-ordered schema + let reordered_schema = Schema::new(vec![ + Field::new("b", DataType::Utf8, true), + Field::new("a", DataType::Int32, true), + ]); + let reordered_projected = batch.project_by_schema(&reordered_schema).unwrap(); + let expected_schema = Arc::new(reordered_schema.with_metadata(metadata.clone().into())); + assert_eq!( + reordered_projected, + RecordBatch::try_new( + expected_schema, + vec![ + Arc::new(StringArray::from_iter_values( + (0..20).map(|i| format!("str-{}", i)), + )), + Arc::new(Int32Array::from_iter_values(0..20)), + ], + ) + .unwrap() + ); + + // Sub schema + let sub_schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]); + let sub_projected = batch.project_by_schema(&sub_schema).unwrap(); + let expected_schema = Arc::new(sub_schema.with_metadata(metadata.into())); + assert_eq!( + sub_projected, + RecordBatch::try_new( + expected_schema, + vec![Arc::new(Int32Array::from_iter_values(0..20))], + ) + .unwrap() + ); + } + + #[test] + fn test_project_rebuilds_sliced_map() { + // A sliced MapArray keeps its full entries array behind sliced + // offsets and validity; the Map projection arm must rebuild it + // without renormalizing either. + let entry_fields = Fields::from(vec![ + Field::new("key", DataType::Utf8, false), + Field::new("value", DataType::Int32, true), + ]); + let entries_field = Arc::new(Field::new( + "entries", + DataType::Struct(entry_fields.clone()), + false, + )); + let entries = StructArray::new( + entry_fields, + vec![ + Arc::new(StringArray::from(vec!["k0", "k1", "k2"])) as ArrayRef, + Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef, + ], + None, + ); + let map = MapArray::new( + entries_field.clone(), + OffsetBuffer::new(vec![0, 1, 1, 3].into()), + entries, + Some(arrow_buffer::NullBuffer::from(vec![true, false, true])), + false, + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "m", + DataType::Map(entries_field, false), + true, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(map) as ArrayRef]).unwrap(); + + // Rows 1..3: a null slot and a two-entry slot, offsets not zero-based. + let projected = batch + .slice(1, 2) + .project_by_schema(schema.as_ref()) + .unwrap(); + let map = projected.column(0).as_map(); + assert!(map.is_null(0)); + assert!(map.is_valid(1)); + assert_eq!(map.value_length(1), 2); + assert_eq!( + map.value(1) + .column(1) + .as_primitive::() + .values(), + &[2, 3] + ); + } + + #[test] + fn test_project_preserves_struct_validity() { + // Test that projecting a struct array preserves its validity (fix for issue #4385) + let fields = Fields::from(vec![ + Field::new("id", DataType::Int32, false), + Field::new("value", DataType::Float32, true), + ]); + + // Create a struct array with validity + let id_array = Int32Array::from(vec![1, 2, 3]); + let value_array = Float32Array::from(vec![Some(1.0), Some(2.0), Some(3.0)]); + let struct_array = StructArray::new( + fields.clone(), + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(value_array) as ArrayRef, + ], + Some(vec![true, false, true].into()), // Second struct is null + ); + + // Project the struct array + let projected = project(&struct_array, &fields).unwrap(); + + // Verify the validity is preserved + assert_eq!(projected.null_count(), 1); + assert!(!projected.is_null(0)); + assert!(projected.is_null(1)); + assert!(!projected.is_null(2)); + } + + #[test] + fn test_merge_struct_with_different_validity() { + // Test case from Weston's review comment + // File 1 has height field with some nulls + let height_array = Int32Array::from(vec![Some(500), None, Some(600), None]); + let left_fields = Fields::from(vec![Field::new("height", DataType::Int32, true)]); + let left_struct = StructArray::new( + left_fields, + vec![Arc::new(height_array) as ArrayRef], + Some(vec![true, false, true, false].into()), // Rows 2 and 4 are null structs + ); + + // File 2 has width field with some nulls + let width_array = Int32Array::from(vec![Some(300), Some(200), None, None]); + let right_fields = Fields::from(vec![Field::new("width", DataType::Int32, true)]); + let right_struct = StructArray::new( + right_fields, + vec![Arc::new(width_array) as ArrayRef], + Some(vec![true, true, false, false].into()), // Rows 3 and 4 are null structs + ); + + // Merge the two structs + let merged = merge(&left_struct, &right_struct); + + // Expected: + // Row 1: both non-null -> {width: 300, height: 500} + // Row 2: left null, right non-null -> {width: 200, height: null} + // Row 3: left non-null, right null -> {width: null, height: 600} + // Row 4: both null -> null struct + + assert_eq!(merged.null_count(), 1); // Only row 4 is null + assert!(!merged.is_null(0)); + assert!(!merged.is_null(1)); + assert!(!merged.is_null(2)); + assert!(merged.is_null(3)); + + // Check field values + let height_col = merged.column_by_name("height").unwrap(); + let height_values = height_col.as_any().downcast_ref::().unwrap(); + assert_eq!(height_values.value(0), 500); + assert!(height_values.is_null(1)); // height is null when left struct was null + assert_eq!(height_values.value(2), 600); + + let width_col = merged.column_by_name("width").unwrap(); + let width_values = width_col.as_any().downcast_ref::().unwrap(); + assert_eq!(width_values.value(0), 300); + assert_eq!(width_values.value(1), 200); + assert!(width_values.is_null(2)); // width is null when right struct was null + + // An all-null validity buffer is data, not a placeholder meaning "this side has no + // validity": merging two of them keeps the rows null. + let all_null_left = StructArray::new( + Fields::from(vec![Field::new("height", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![None, None])) as ArrayRef], + Some(vec![false, false].into()), + ); + let all_null_right = StructArray::new( + Fields::from(vec![Field::new("width", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![None, None])) as ArrayRef], + Some(vec![false, false].into()), + ); + + let merged = merge(&all_null_left, &all_null_right); + assert_eq!(merged.null_count(), 2); + + // An all-null side is the identity of the merge, so the other side decides each row. + let partial_left = StructArray::new( + Fields::from(vec![Field::new("height", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef], + Some(vec![true, false].into()), + ); + let merged = merge(&partial_left, &all_null_right); + assert!(!merged.is_null(0)); + assert!(merged.is_null(1)); + + // A missing validity buffer means all rows are valid, which absorbs an all-null side. + let all_valid_left = StructArray::new( + Fields::from(vec![Field::new("height", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef], + None, + ); + let merged = merge(&all_valid_left, &all_null_right); + assert_eq!(merged.null_count(), 0); + + // An explicit all-valid buffer has the same semantics as a missing buffer. + let all_valid: arrow_buffer::NullBuffer = vec![true, true].into(); + let partial: arrow_buffer::NullBuffer = vec![true, false].into(); + assert!(merge_struct_validity(Some(&all_valid), Some(&partial)).is_none()); + assert!(merge_struct_validity(Some(&partial), Some(&all_valid)).is_none()); + } + + #[test] + fn test_merge_null_typed_column_with_parent_validity() { + // Reproduces ENT-990: panic in adjust_child_validity when a Null-typed column + // exists on one side and the parent struct has null rows. + // Arrow's Null type has no null bitmap, so passing one to ArrayData::try_new panics. + let left_struct = StructArray::new( + Fields::from(vec![Field::new("a", DataType::Int32, true)]), + vec![Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef], + Some(vec![true, false].into()), + ); + let right_struct = StructArray::new( + Fields::from(vec![Field::new("b", DataType::Null, true)]), + vec![Arc::new(NullArray::new(2)) as ArrayRef], + Some(vec![true, false].into()), + ); + + // Previously panicked: "Arrays of type Null cannot contain a null bitmask" + let merged = merge(&left_struct, &right_struct); + assert_eq!(merged.len(), 2); + let b_col = merged.column_by_name("b").unwrap(); + // DataType::Null implies all-null by definition; no null bitmap is stored. + assert_eq!(b_col.data_type(), &DataType::Null); + assert_eq!(b_col.len(), 2); + } + + #[test] + fn test_merge_with_schema_with_nullable_struct_list_schema_mismatch() { + // left_list setup + let left_company_id = Arc::new(Int32Array::from(vec![None, None])); + let left_count = Arc::new(Int32Array::from(vec![None, None])); + let left_struct = Arc::new(StructArray::new( + Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("count", DataType::Int32, true), + ]), + vec![left_company_id, left_count], + None, + )); + let left_list = Arc::new(ListArray::new( + Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([2]), + left_struct, + None, + )); + + // Right List Setup + let right_company_name = Arc::new(StringArray::from(vec!["Google", "Microsoft"])); + let right_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new("company_name", DataType::Utf8, true)]), + vec![right_company_name], + None, + )); + let right_list = Arc::new(ListArray::new( + Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([2]), + right_struct, + None, + )); + + let target_fields = Fields::from(vec![Field::new( + "companies", + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("company_name", DataType::Utf8, true), + Field::new("count", DataType::Int32, true), + ])), + true, + ))), + true, + )]); + + let left_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "companies", + left_list.data_type().clone(), + true, + )])), + vec![left_list as ArrayRef], + ) + .unwrap(); + + let right_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "companies", + right_list.data_type().clone(), + true, + )])), + vec![right_list as ArrayRef], + ) + .unwrap(); + + let merged = left_batch + .merge_with_schema(&right_batch, &Schema::new(target_fields.to_vec())) + .unwrap(); + + // Verify the merged structure + let merged_list = merged + .column_by_name("companies") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let merged_struct = merged_list.values().as_struct(); + + // Should have all 3 fields + assert_eq!(merged_struct.num_columns(), 3); + assert!(merged_struct.column_by_name("company_id").is_some()); + assert!(merged_struct.column_by_name("company_name").is_some()); + assert!(merged_struct.column_by_name("count").is_some()); + + // Verify values + let company_id = merged_struct + .column_by_name("company_id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(company_id.is_null(0)); + assert!(company_id.is_null(1)); + + let company_name = merged_struct + .column_by_name("company_name") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(company_name.value(0), "Google"); + assert_eq!(company_name.value(1), "Microsoft"); + + let count = merged_struct + .column_by_name("count") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(count.is_null(0)); + assert!(count.is_null(1)); + } + + #[test] + fn test_merge_struct_lists() { + test_merge_struct_lists_generic::(); + } + + #[test] + fn test_merge_struct_large_lists() { + test_merge_struct_lists_generic::(); + } + + fn test_merge_struct_lists_generic() { + // left_list setup + let left_company_id = Arc::new(Int32Array::from(vec![ + Some(1), + Some(2), + Some(3), + Some(4), + Some(5), + Some(6), + Some(7), + Some(8), + Some(9), + Some(10), + Some(11), + Some(12), + Some(13), + Some(14), + Some(15), + Some(16), + Some(17), + Some(18), + Some(19), + Some(20), + ])); + let left_count = Arc::new(Int32Array::from(vec![ + Some(10), + Some(20), + Some(30), + Some(40), + Some(50), + Some(60), + Some(70), + Some(80), + Some(90), + Some(100), + Some(110), + Some(120), + Some(130), + Some(140), + Some(150), + Some(160), + Some(170), + Some(180), + Some(190), + Some(200), + ])); + let left_struct = Arc::new(StructArray::new( + Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("count", DataType::Int32, true), + ]), + vec![left_company_id, left_count], + None, + )); + + let left_list = Arc::new(GenericListArray::::new( + Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([3, 1]), + left_struct.clone(), + None, + )); + + let left_list_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new( + "companies", + if O::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(left_struct.fields().clone()), + true, + ))) + }, + true, + )]), + vec![left_list as ArrayRef], + None, + )); + + // right_list setup + let right_company_name = Arc::new(StringArray::from(vec![ + "Google", + "Microsoft", + "Apple", + "Facebook", + ])); + let right_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new("company_name", DataType::Utf8, true)]), + vec![right_company_name], + None, + )); + let right_list = Arc::new(GenericListArray::::new( + Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + )), + OffsetBuffer::from_lengths([3, 1]), + right_struct.clone(), + None, + )); + + let right_list_struct = Arc::new(StructArray::new( + Fields::from(vec![Field::new( + "companies", + if O::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(right_struct.fields().clone()), + true, + ))) + }, + true, + )]), + vec![right_list as ArrayRef], + None, + )); + + // prepare schema + let target_fields = Fields::from(vec![Field::new( + "companies", + if O::IS_LARGE { + DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("company_name", DataType::Utf8, true), + Field::new("count", DataType::Int32, true), + ])), + true, + ))) + } else { + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("company_id", DataType::Int32, true), + Field::new("company_name", DataType::Utf8, true), + Field::new("count", DataType::Int32, true), + ])), + true, + ))) + }, + true, + )]); + + // merge left_list and right_list + let merged_array = merge_with_schema(&left_list_struct, &right_list_struct, &target_fields); + assert_eq!(merged_array.len(), 2); + } + + #[test] + fn test_merge_with_schema_sliced_list_struct() { + test_merge_with_schema_sliced_list_struct_generic::(); + } + + #[test] + fn test_merge_with_schema_sliced_large_list_struct() { + test_merge_with_schema_sliced_list_struct_generic::(); + } + + // Regression for #6580: merge_with_schema panicked when the left list was a + // sliced view whose offsets did not start at zero (common after a filtered + // scan). Cloning those offsets alongside `trimmed_values` produced offsets + // larger than the trimmed child, panicking in `(Large)ListArray::new`. + fn test_merge_with_schema_sliced_list_struct_generic() { + let make_list_dtype = |item_field: Arc| { + if O::IS_LARGE { + DataType::LargeList(item_field) + } else { + DataType::List(item_field) + } + }; + + // Build a List with two rows of 5 items each, then slice away + // the first row so the remaining list's offsets start at 5, not 0. + let struct_fields_a = Fields::from(vec![Field::new("a", DataType::Int32, true)]); + let left_values = Arc::new(StructArray::new( + struct_fields_a.clone(), + vec![Arc::new(Int32Array::from_iter_values(0..10)) as ArrayRef], + None, + )); + let full_list = GenericListArray::::new( + Arc::new(Field::new("item", DataType::Struct(struct_fields_a), true)), + OffsetBuffer::::from_lengths([5, 5]), + left_values, + None, + ); + let sliced_left = full_list.slice(1, 1); + assert_eq!(sliced_left.offsets()[0].as_usize(), 5); + assert_eq!(sliced_left.offsets()[1].as_usize(), 10); + + let struct_fields_b = Fields::from(vec![Field::new("b", DataType::Int32, true)]); + let right_values = Arc::new(StructArray::new( + struct_fields_b.clone(), + vec![Arc::new(Int32Array::from_iter_values(100..105)) as ArrayRef], + None, + )); + let right_list = GenericListArray::::new( + Arc::new(Field::new("item", DataType::Struct(struct_fields_b), true)), + OffsetBuffer::::from_lengths([5]), + right_values, + None, + ); + + let target_item_field = Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + ])), + true, + )); + let target_fields = Fields::from(vec![Field::new( + "items", + make_list_dtype(target_item_field), + true, + )]); + + let left_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "items", + sliced_left.data_type().clone(), + true, + )])), + vec![Arc::new(sliced_left) as ArrayRef], + ) + .unwrap(); + let right_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "items", + right_list.data_type().clone(), + true, + )])), + vec![Arc::new(right_list) as ArrayRef], + ) + .unwrap(); + + let merged = left_batch + .merge_with_schema(&right_batch, &Schema::new(target_fields.to_vec())) + .unwrap(); + + let merged_list = merged + .column_by_name("items") + .unwrap() + .as_any() + .downcast_ref::>() + .unwrap(); + assert_eq!(merged_list.len(), 1); + assert_eq!(merged_list.value_length(0).as_usize(), 5); + let merged_struct = merged_list.values().as_struct(); + assert_eq!(merged_struct.num_columns(), 2); + let a = merged_struct + .column_by_name("a") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + // After shifting offsets to zero, values 5..10 should be first. + let a_vals: Vec = a.iter().map(|v| v.unwrap()).collect(); + assert_eq!(a_vals, vec![5, 6, 7, 8, 9]); + } + + #[test] + fn test_project_by_schema_list_struct_reorder() { + // Test that project_by_schema correctly reorders fields inside List + // This is a regression test for issue #5702 + + // Source schema with inner struct fields in order: c, b, a + let source_inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("c", DataType::Utf8, true), + Field::new("b", DataType::Utf8, true), + Field::new("a", DataType::Utf8, true), + ])); + let source_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "data", + DataType::List(Arc::new(Field::new( + "item", + source_inner_struct.clone(), + true, + ))), + true, + ), + ])); + + // Create source data with c, b, a order + let c_array = StringArray::from(vec!["c1", "c2"]); + let b_array = StringArray::from(vec!["b1", "b2"]); + let a_array = StringArray::from(vec!["a1", "a2"]); + let inner_struct = StructArray::from(vec![ + ( + Arc::new(Field::new("c", DataType::Utf8, true)), + Arc::new(c_array) as ArrayRef, + ), + ( + Arc::new(Field::new("b", DataType::Utf8, true)), + Arc::new(b_array) as ArrayRef, + ), + ( + Arc::new(Field::new("a", DataType::Utf8, true)), + Arc::new(a_array) as ArrayRef, + ), + ]); + + let list_array = ListArray::new( + Arc::new(Field::new("item", source_inner_struct, true)), + OffsetBuffer::from_lengths([1, 1]), + Arc::new(inner_struct), + None, + ); + + let batch = RecordBatch::try_new( + source_schema, + vec![Arc::new(Int32Array::from(vec![1, 2])), Arc::new(list_array)], + ) + .unwrap(); + + // Target schema with inner struct fields in order: a, b, c + let target_inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Utf8, true), + Field::new("c", DataType::Utf8, true), + ])); + let target_schema = Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "data", + DataType::List(Arc::new(Field::new("item", target_inner_struct, true))), + true, + ), + ]); + + // Project should reorder the inner struct fields + let projected = batch.project_by_schema(&target_schema).unwrap(); + + // Verify the schema is correct + assert_eq!(projected.schema().as_ref(), &target_schema); + + // Verify the data is correct by checking inner struct field order + let projected_list = projected.column(1).as_list::(); + let projected_struct = projected_list.values().as_struct(); + + // Fields should now be in order: a, b, c + assert_eq!( + projected_struct.column_by_name("a").unwrap().as_ref(), + &StringArray::from(vec!["a1", "a2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column_by_name("b").unwrap().as_ref(), + &StringArray::from(vec!["b1", "b2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column_by_name("c").unwrap().as_ref(), + &StringArray::from(vec!["c1", "c2"]) as &dyn Array + ); + + // Also verify positional access matches expected order (a=0, b=1, c=2) + assert_eq!( + projected_struct.column(0).as_ref(), + &StringArray::from(vec!["a1", "a2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column(1).as_ref(), + &StringArray::from(vec!["b1", "b2"]) as &dyn Array + ); + assert_eq!( + projected_struct.column(2).as_ref(), + &StringArray::from(vec!["c1", "c2"]) as &dyn Array + ); + } + + #[test] + fn test_project_by_schema_nested_list_struct() { + // Test deeply nested List>> projection + let inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("y", DataType::Int32, true), + Field::new("x", DataType::Int32, true), + ])); + let source_schema = Arc::new(Schema::new(vec![Field::new( + "outer", + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("b", DataType::Utf8, true), + Field::new( + "inner_list", + DataType::List(Arc::new(Field::new("item", inner_struct.clone(), true))), + true, + ), + Field::new("a", DataType::Utf8, true), + ])), + true, + ))), + true, + )])); + + // Create deeply nested data + let y_array = Int32Array::from(vec![1, 2]); + let x_array = Int32Array::from(vec![3, 4]); + let innermost_struct = StructArray::from(vec![ + ( + Arc::new(Field::new("y", DataType::Int32, true)), + Arc::new(y_array) as ArrayRef, + ), + ( + Arc::new(Field::new("x", DataType::Int32, true)), + Arc::new(x_array) as ArrayRef, + ), + ]); + let inner_list = ListArray::new( + Arc::new(Field::new("item", inner_struct.clone(), true)), + OffsetBuffer::from_lengths([2]), + Arc::new(innermost_struct), + None, + ); + + let b_array = StringArray::from(vec!["b1"]); + let a_array = StringArray::from(vec!["a1"]); + let middle_struct = StructArray::from(vec![ + ( + Arc::new(Field::new("b", DataType::Utf8, true)), + Arc::new(b_array) as ArrayRef, + ), + ( + Arc::new(Field::new( + "inner_list", + DataType::List(Arc::new(Field::new("item", inner_struct, true))), + true, + )), + Arc::new(inner_list) as ArrayRef, + ), + ( + Arc::new(Field::new("a", DataType::Utf8, true)), + Arc::new(a_array) as ArrayRef, + ), + ]); + + let outer_list = ListArray::new( + Arc::new(Field::new("item", middle_struct.data_type().clone(), true)), + OffsetBuffer::from_lengths([1]), + Arc::new(middle_struct), + None, + ); + + let batch = + RecordBatch::try_new(source_schema, vec![Arc::new(outer_list) as ArrayRef]).unwrap(); + + // Target schema with reordered fields at all levels + let target_inner_struct = DataType::Struct(Fields::from(vec![ + Field::new("x", DataType::Int32, true), // x before y now + Field::new("y", DataType::Int32, true), + ])); + let target_schema = Schema::new(vec![Field::new( + "outer", + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(Fields::from(vec![ + Field::new("a", DataType::Utf8, true), // a before b now + Field::new( + "inner_list", + DataType::List(Arc::new(Field::new("item", target_inner_struct, true))), + true, + ), + Field::new("b", DataType::Utf8, true), + ])), + true, + ))), + true, + )]); + + let projected = batch.project_by_schema(&target_schema).unwrap(); + + // Verify schema + assert_eq!(projected.schema().as_ref(), &target_schema); + + // Verify deeply nested data is reordered correctly + let outer_list = projected.column(0).as_list::(); + let middle_struct = outer_list.values().as_struct(); + + // Middle struct should have a first, then inner_list, then b + assert_eq!( + middle_struct.column(0).as_ref(), + &StringArray::from(vec!["a1"]) as &dyn Array + ); + assert_eq!( + middle_struct.column(2).as_ref(), + &StringArray::from(vec!["b1"]) as &dyn Array + ); + + // Inner list's struct should have x first, then y + let inner_list = middle_struct.column(1).as_list::(); + let innermost_struct = inner_list.values().as_struct(); + assert_eq!( + innermost_struct.column(0).as_ref(), + &Int32Array::from(vec![3, 4]) as &dyn Array + ); + assert_eq!( + innermost_struct.column(1).as_ref(), + &Int32Array::from(vec![1, 2]) as &dyn Array + ); + } + + #[test] + fn test_iter_binary_array_accepts_binary_variants() { + let binary = BinaryArray::from(vec![b"a".as_slice(), b"bc"]); + assert_eq!( + iter_binary_array(&binary).unwrap().collect::>(), + vec![Some(b"a".as_slice()), Some(b"bc".as_slice())] + ); + + let large_binary = LargeBinaryArray::from(vec![b"x".as_slice(), b"yz"]); + assert_eq!( + iter_binary_array(&large_binary) + .unwrap() + .collect::>(), + vec![Some(b"x".as_slice()), Some(b"yz".as_slice())] + ); + + let binary_view = BinaryViewArray::from(vec![b"1".as_slice(), b"23"]); + assert_eq!( + iter_binary_array(&binary_view).unwrap().collect::>(), + vec![Some(b"1".as_slice()), Some(b"23".as_slice())] + ); + + let fixed_size = + FixedSizeBinaryArray::try_from_iter([b"abcd", b"efgh"].into_iter()).unwrap(); + assert_eq!( + iter_binary_array(&fixed_size).unwrap().collect::>(), + vec![Some(b"abcd".as_slice()), Some(b"efgh".as_slice())] + ); + } + + #[test] + fn test_iter_binary_array_rejects_non_binary() { + let int_array = Int32Array::from(vec![1, 2, 3]); + let Err(error) = iter_binary_array(&int_array) else { + panic!("expected an error for non-binary array"); + }; + assert!(error.to_string().contains("Expecting a binary type")); + } +} diff --git a/python/vendor/lance-arrow/src/list.rs b/python/vendor/lance-arrow/src/list.rs new file mode 100644 index 000000000..750b54c93 --- /dev/null +++ b/python/vendor/lance-arrow/src/list.rs @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::sync::Arc; + +use arrow_array::{Array, BooleanArray, GenericListArray, OffsetSizeTrait}; +use arrow_buffer::{BooleanBufferBuilder, OffsetBuffer, ScalarBuffer}; +use arrow_schema::Field; + +pub trait ListArrayExt { + /// Filters out masked null items from the list array + /// + /// It is legal for a list array to have a null entry with a non-zero length. The + /// values inside the entry are "garbage" and should be ignored. This function + /// filters the values array to remove the garbage values. + /// + /// The output list will always have zero-length nulls. + fn filter_garbage_nulls(&self) -> Self; + /// Returns a copy of the list's values array that has been sliced to size + /// + /// It is legal for a list array's offsets to not start with zero. It's also legal + /// for a list array's offsets to not extend to the entire values array. This function + /// behaves similarly to `values()` except it slices the array so that it starts at + /// the first list offset and ends at the last list offset. + fn trimmed_values(&self) -> Arc; + /// The offset type of the underlying list array. + type Offset: OffsetSizeTrait; + /// Returns offsets shifted so the first offset is zero, matching + /// [`Self::trimmed_values`]. + /// + /// Sliced list arrays (e.g. a filtered batch) keep offsets that reference the + /// original values buffer, so combining them with trimmed values produces + /// offsets that exceed the values length. Use this together with + /// `trimmed_values` when constructing a new list array. + fn trimmed_offsets(&self) -> OffsetBuffer; +} + +impl ListArrayExt for GenericListArray { + fn filter_garbage_nulls(&self) -> Self { + if self.is_empty() { + return self.clone(); + } + let Some(validity) = self.nulls().cloned() else { + return self.clone(); + }; + + let mut should_keep = BooleanBufferBuilder::new(self.values().len()); + + // Handle case where offsets do not start at 0 + let preamble_len = self.offsets().first().unwrap().to_usize().unwrap(); + should_keep.append_n(preamble_len, false); + + let mut new_offsets: Vec = Vec::with_capacity(self.len() + 1); + new_offsets.push(OffsetSize::zero()); + let mut cur_len = OffsetSize::zero(); + for (offset, is_valid) in self.offsets().windows(2).zip(validity.iter()) { + let len = offset[1] - offset[0]; + if is_valid { + cur_len += len; + should_keep.append_n(len.to_usize().unwrap(), true); + new_offsets.push(cur_len); + } else { + should_keep.append_n(len.to_usize().unwrap(), false); + new_offsets.push(cur_len); + } + } + + // Offsets may not reference entire values buffer + let trailer = self.values().len() - should_keep.len(); + should_keep.append_n(trailer, false); + + let should_keep = should_keep.finish(); + let should_keep = BooleanArray::new(should_keep, None); + let new_values = arrow_select::filter::filter(self.values(), &should_keep).unwrap(); + let new_offsets = ScalarBuffer::from(new_offsets); + let new_offsets = OffsetBuffer::new(new_offsets); + + Self::new( + Arc::new(Field::new( + "item", + self.value_type(), + self.values().is_nullable(), + )), + new_offsets, + new_values, + Some(validity), + ) + } + + fn trimmed_values(&self) -> Arc { + let first_value = self + .offsets() + .first() + .map(|v| v.to_usize().unwrap()) + .unwrap_or(0); + let last_value = self + .offsets() + .last() + .map(|v| v.to_usize().unwrap()) + .unwrap_or(0); + self.values().slice(first_value, last_value - first_value) + } + + type Offset = OffsetSize; + + fn trimmed_offsets(&self) -> OffsetBuffer { + let offsets = self.offsets(); + let Some(&first) = offsets.first() else { + return offsets.clone(); + }; + if first == OffsetSize::zero() { + return offsets.clone(); + } + let shifted: Vec = offsets.iter().map(|&o| o - first).collect(); + OffsetBuffer::new(ScalarBuffer::from(shifted)) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{ListArray, UInt64Array}; + use arrow_buffer::{BooleanBuffer, NullBuffer, OffsetBuffer, ScalarBuffer}; + use arrow_schema::{DataType, Field}; + + use super::ListArrayExt; + + #[test] + fn test_filter_garbage_nulls() { + let items = UInt64Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let offsets = ScalarBuffer::::from(vec![2, 5, 8, 9]); + let offsets = OffsetBuffer::new(offsets); + let list_validity = NullBuffer::new(BooleanBuffer::from(vec![true, false, true])); + let list_arr = ListArray::new( + Arc::new(Field::new("item", DataType::UInt64, true)), + offsets, + Arc::new(items), + Some(list_validity.clone()), + ); + + let filtered = list_arr.filter_garbage_nulls(); + + let expected_items = UInt64Array::from(vec![2, 3, 4, 8]); + let offsets = ScalarBuffer::::from(vec![0, 3, 3, 4]); + let expected = ListArray::new( + Arc::new(Field::new("item", DataType::UInt64, false)), + OffsetBuffer::new(offsets), + Arc::new(expected_items), + Some(list_validity), + ); + + assert_eq!(filtered, expected); + } + + #[test] + fn test_trim_values() { + let items = UInt64Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let offsets = ScalarBuffer::::from(vec![2, 5, 6, 8, 9]); + let offsets = OffsetBuffer::new(offsets); + let list_arr = ListArray::new( + Arc::new(Field::new("item", DataType::UInt64, true)), + offsets, + Arc::new(items), + None, + ); + let list_arr = list_arr.slice(1, 2); + + let trimmed = list_arr.trimmed_values(); + + let expected_items = UInt64Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + let expected_items = expected_items.slice(5, 3); + + assert_eq!(trimmed.as_ref(), &expected_items); + } +} diff --git a/python/vendor/lance-arrow/src/memory.rs b/python/vendor/lance-arrow/src/memory.rs new file mode 100644 index 000000000..1038a3f91 --- /dev/null +++ b/python/vendor/lance-arrow/src/memory.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::collections::HashSet; + +use arrow_array::{Array, RecordBatch}; +use arrow_data::ArrayData; + +/// Counts memory used by buffers of Arrow arrays and RecordBatches. +/// +/// This is meant to capture how much memory is being used by the Arrow data +/// structures as they are. It does not represent the memory used if the data +/// were to be serialized and then deserialized. In particular: +/// +/// * This does not double count memory used by buffers shared by multiple +/// arrays or batches. Round-tripped data may use more memory because of this. +/// * This counts the **total** size of the buffers, even if the array is a slice. +/// Round-tripped data may use less memory because of this. +#[derive(Default)] +pub struct MemoryAccumulator { + seen: HashSet, + total: usize, +} + +impl MemoryAccumulator { + pub fn record_array(&mut self, array: &dyn Array) { + let data = array.to_data(); + self.record_array_data(&data); + } + + fn record_array_data(&mut self, data: &ArrayData) { + for buffer in data.buffers() { + let ptr = buffer.as_ptr(); + if self.seen.insert(ptr as usize) { + self.total += buffer.capacity(); + } + } + + if let Some(nulls) = data.nulls() { + let null_buf = nulls.inner().inner(); + let ptr = null_buf.as_ptr(); + if self.seen.insert(ptr as usize) { + self.total += null_buf.capacity(); + } + } + + for child in data.child_data() { + self.record_array_data(child); + } + } + + pub fn record_batch(&mut self, batch: &RecordBatch) { + for array in batch.columns() { + self.record_array(array); + } + } + + pub fn total(&self) -> usize { + self.total + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::Int32Array; + use arrow_schema::{DataType, Field, Schema}; + + use super::*; + + #[test] + fn test_memory_accumulator() { + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + let slice = batch.slice(1, 2); + + let mut acc = MemoryAccumulator::default(); + + // Should record whole buffer, not just slice + acc.record_batch(&slice); + assert_eq!(acc.total(), 3 * std::mem::size_of::()); + + // Should not double count + acc.record_batch(&slice); + assert_eq!(acc.total(), 3 * std::mem::size_of::()); + } +} diff --git a/python/vendor/lance-arrow/src/scalar.rs b/python/vendor/lance-arrow/src/scalar.rs new file mode 100644 index 000000000..412253d12 --- /dev/null +++ b/python/vendor/lance-arrow/src/scalar.rs @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use arrow_array::{ArrayRef, UInt64Array, make_array}; +use arrow_buffer::Buffer; +use arrow_data::ArrayDataBuilder; +use arrow_schema::{ArrowError, DataType}; +use arrow_select::take::take; + +use crate::DataTypeExt; + +type Result = std::result::Result; + +pub const INLINE_VALUE_MAX_BYTES: usize = 32; + +pub fn extract_scalar_value(array: &ArrayRef, idx: usize) -> Result { + if idx >= array.len() { + return Err(ArrowError::InvalidArgumentError( + "Scalar index out of bounds".to_string(), + )); + } + + take(array.as_ref(), &UInt64Array::from(vec![idx as u64]), None) +} + +fn read_u32(buf: &[u8], offset: &mut usize) -> Result { + if *offset + 4 > buf.len() { + return Err(ArrowError::InvalidArgumentError( + "Invalid scalar value buffer: unexpected EOF".to_string(), + )); + } + let bytes = [ + buf[*offset], + buf[*offset + 1], + buf[*offset + 2], + buf[*offset + 3], + ]; + *offset += 4; + Ok(u32::from_le_bytes(bytes)) +} + +fn read_bytes<'a>(buf: &'a [u8], offset: &mut usize, len: usize) -> Result<&'a [u8]> { + if *offset + len > buf.len() { + return Err(ArrowError::InvalidArgumentError( + "Invalid scalar value buffer: unexpected EOF".to_string(), + )); + } + let slice = &buf[*offset..*offset + len]; + *offset += len; + Ok(slice) +} + +fn write_u32(out: &mut Vec, v: u32) { + out.extend_from_slice(&v.to_le_bytes()); +} + +fn write_bytes(out: &mut Vec, bytes: &[u8]) { + out.extend_from_slice(bytes); +} + +pub fn encode_scalar_value_buffer(scalar: &ArrayRef) -> Result> { + if scalar.len() != 1 || scalar.null_count() != 0 { + return Err(ArrowError::InvalidArgumentError( + "Scalar value buffer must be a single non-null value".to_string(), + )); + } + let data = scalar.to_data(); + if data.offset() != 0 { + return Err(ArrowError::InvalidArgumentError( + "Scalar value buffer must have offset=0".to_string(), + )); + } + if !data.child_data().is_empty() { + return Err(ArrowError::InvalidArgumentError( + "Scalar value buffer does not support nested types".to_string(), + )); + } + + // Minimal format (RFC): store the Arrow value buffers for a length-1 array. + // Null bitmap and child data are intentionally not supported here. + // + // | u32 num_buffers | + // | u32 buffer_0_len | ... | u32 buffer_{n-1}_len | + // | buffer_0 bytes | ... | buffer_{n-1} bytes | + let mut out = Vec::with_capacity(128); + let buffers = data.buffers(); + write_u32(&mut out, buffers.len() as u32); + for b in buffers { + write_u32(&mut out, b.len() as u32); + } + for b in buffers { + write_bytes(&mut out, b.as_slice()); + } + Ok(out) +} + +pub fn decode_scalar_from_value_buffer( + data_type: &DataType, + value_buffer: &[u8], +) -> Result { + if matches!( + data_type, + DataType::Struct(_) | DataType::FixedSizeList(_, _) + ) { + return Err(ArrowError::InvalidArgumentError(format!( + "Scalar value buffer does not support nested data type {:?}", + data_type + ))); + } + + let mut offset = 0; + let num_buffers = read_u32(value_buffer, &mut offset)? as usize; + let buffer_lens = (0..num_buffers) + .map(|_| read_u32(value_buffer, &mut offset).map(|l| l as usize)) + .collect::>>()?; + + let mut buffers = Vec::with_capacity(num_buffers); + for len in buffer_lens { + let bytes = read_bytes(value_buffer, &mut offset, len)?; + buffers.push(Buffer::from_vec(bytes.to_vec())); + } + + if offset != value_buffer.len() { + return Err(ArrowError::InvalidArgumentError( + "Invalid scalar value buffer: trailing bytes".to_string(), + )); + } + + let mut builder = ArrayDataBuilder::new(data_type.clone()) + .len(1) + .null_count(0); + for b in buffers { + builder = builder.add_buffer(b); + } + Ok(make_array(builder.build()?)) +} + +pub fn decode_scalar_from_inline_value( + data_type: &DataType, + inline_value: &[u8], +) -> Result { + // I expect our input to be safe here, but I added some debug_assert_eq statements just in case. + // If they are triggered, we may need to change them to return actual errors. + // + // Boolean values are bit-packed in Arrow and therefore are not "fixed-stride" in bytes. + // As a result, `byte_width_opt()` returns `None` for `DataType::Boolean`, even though a + // length-1 scalar can be represented inline using a single byte (matching `try_inline_value`). + if matches!(data_type, DataType::Boolean) { + debug_assert_eq!( + inline_value.len(), + 1, + "Invalid boolean inline scalar length (expected 1 byte, got {})", + inline_value.len() + ); + } else if let Some(byte_width) = data_type.byte_width_opt() { + debug_assert_eq!( + inline_value.len(), + byte_width, + "Inline constant length mismatch for {:?}: expected {} bytes but got {}", + data_type, + byte_width, + inline_value.len() + ); + } + + let data = ArrayDataBuilder::new(data_type.clone()) + .len(1) + .null_count(0) + .add_buffer(Buffer::from_vec(inline_value.to_vec())) + .build()?; + Ok(make_array(data)) +} + +pub fn try_inline_value(scalar: &ArrayRef) -> Option> { + if scalar.null_count() != 0 || scalar.len() != 1 { + return None; + } + let data = scalar.to_data(); + if !data.child_data().is_empty() { + return None; + } + if data.buffers().len() != 1 { + return None; + } + let bytes = data.buffers()[0].as_slice(); + if bytes.len() > INLINE_VALUE_MAX_BYTES { + return None; + } + Some(bytes.to_vec()) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{ + BooleanArray, DictionaryArray, FixedSizeBinaryArray, Int8Array, Int32Array, StringArray, + cast::AsArray, types::Int8Type, + }; + + use super::*; + + #[test] + fn test_extract_scalar_value() { + let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])); + let scalar = extract_scalar_value(&array, 2).unwrap(); + assert_eq!(scalar.len(), 1); + assert_eq!( + scalar + .as_primitive::() + .value(0), + 3 + ); + } + + #[test] + fn test_extract_scalar_value_from_full_dictionary() { + let values = Arc::new(StringArray::from( + (0..=i8::MAX) + .map(|value| format!("value-{value}")) + .collect::>(), + )); + let keys = Int8Array::from((0..=i8::MAX).collect::>()); + let array: ArrayRef = Arc::new(DictionaryArray::::new(keys, values)); + + let scalar = extract_scalar_value(&array, i8::MAX as usize).unwrap(); + + let scalar = scalar.as_dictionary::(); + assert_eq!(scalar.len(), 1); + assert_eq!(scalar.key(0), Some(i8::MAX as usize)); + assert_eq!(scalar.values().len(), i8::MAX as usize + 1); + } + + #[test] + fn test_scalar_value_buffer_utf8_round_trip() { + let scalar: ArrayRef = Arc::new(StringArray::from(vec!["hello"])); + let buf = encode_scalar_value_buffer(&scalar).unwrap(); + let decoded = decode_scalar_from_value_buffer(&DataType::Utf8, &buf).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded.null_count(), 0); + assert_eq!(decoded.as_string::().value(0), "hello"); + } + + #[test] + fn test_scalar_value_buffer_fixed_size_binary_round_trip() { + let val = vec![0xABu8; 33]; + let scalar: ArrayRef = Arc::new( + FixedSizeBinaryArray::try_from_sparse_iter_with_size( + std::iter::once(Some(val.as_slice())), + 33, + ) + .unwrap(), + ); + let buf = encode_scalar_value_buffer(&scalar).unwrap(); + let decoded = + decode_scalar_from_value_buffer(&DataType::FixedSizeBinary(33), &buf).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded.as_fixed_size_binary().value(0), val.as_slice()); + } + + #[test] + fn test_inline_value_boolean_round_trip() { + let scalar: ArrayRef = Arc::new(BooleanArray::from_iter([Some(true)])); + let inline = try_inline_value(&scalar).unwrap(); + let decoded = decode_scalar_from_inline_value(&DataType::Boolean, &inline).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded.null_count(), 0); + assert!(decoded.as_boolean().value(0)); + } + + #[test] + fn test_scalar_value_buffer_rejects_nested_type() { + let field = Arc::new(arrow_schema::Field::new("item", DataType::Int32, false)); + let list: ArrayRef = Arc::new(arrow_array::FixedSizeListArray::new( + field, + 2, + Arc::new(Int32Array::from(vec![1, 2])), + None, + )); + let scalar = list.slice(0, 1); + assert!(encode_scalar_value_buffer(&scalar).is_err()); + } + + #[test] + fn test_decode_scalar_from_value_buffer_rejects_nested_type() { + let buf = Vec::::new(); + let res = + decode_scalar_from_value_buffer(&DataType::Struct(arrow_schema::Fields::empty()), &buf); + assert!(res.is_err()); + } + + #[test] + fn test_decode_scalar_from_value_buffer_trailing_bytes() { + // num_buffers = 0, plus an extra byte + let mut bytes = Vec::new(); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.push(1); + let res = decode_scalar_from_value_buffer(&DataType::Int32, &bytes); + assert!(res.is_err()); + } +} diff --git a/python/vendor/lance-arrow/src/schema.rs b/python/vendor/lance-arrow/src/schema.rs new file mode 100644 index 000000000..0489dd584 --- /dev/null +++ b/python/vendor/lance-arrow/src/schema.rs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Extension to arrow schema + +use arrow_schema::{ArrowError, DataType, Field, FieldRef, Schema}; + +use crate::{ARROW_EXT_NAME_KEY, BLOB_META_KEY, BLOB_V2_EXT_NAME}; + +pub enum Indentation { + OneLine, + MultiLine(u8), +} + +impl Indentation { + fn value(&self) -> String { + match self { + Self::OneLine => "".to_string(), + Self::MultiLine(spaces) => " ".repeat(*spaces as usize), + } + } + + fn deepen(&self) -> Self { + match self { + Self::OneLine => Self::OneLine, + Self::MultiLine(spaces) => Self::MultiLine(spaces + 2), + } + } +} + +/// Extends the functionality of [arrow_schema::Field]. +pub trait FieldExt { + /// Create a compact string representation of the field + /// + /// This is intended for display purposes and not for serialization + fn to_compact_string(&self, indent: Indentation) -> String; + + /// Check if the field is marked as a packed struct + fn is_packed_struct(&self) -> bool; + + /// Check if the field is marked as a blob + fn is_blob(&self) -> bool; + + /// Check if the field is marked as a blob + fn is_blob_v2(&self) -> bool; +} + +impl FieldExt for Field { + fn to_compact_string(&self, indent: Indentation) -> String { + let mut result = format!("{}: ", self.name().clone()); + match self.data_type() { + DataType::Struct(fields) => { + result += "{"; + result += &indent.value(); + for (field_idx, field) in fields.iter().enumerate() { + result += field.to_compact_string(indent.deepen()).as_str(); + if field_idx < fields.len() - 1 { + result += ","; + } + result += indent.value().as_str(); + } + result += "}"; + } + DataType::List(field) + | DataType::LargeList(field) + | DataType::ListView(field) + | DataType::LargeListView(field) => { + result += "["; + result += field.to_compact_string(indent.deepen()).as_str(); + result += "]"; + } + DataType::FixedSizeList(child, dimension) => { + result += &format!( + "[{}; {}]", + child.to_compact_string(indent.deepen()), + dimension + ); + } + DataType::Dictionary(key_type, value_type) => { + result += &value_type.to_string(); + result += "@"; + result += &key_type.to_string(); + } + _ => { + result += &self.data_type().to_string(); + } + } + if self.is_nullable() { + result += "?"; + } + result + } + + // Check if field has metadata `packed` set to true, this check is case insensitive. + fn is_packed_struct(&self) -> bool { + let field_metadata = self.metadata(); + const PACKED_KEYS: [&str; 2] = ["packed", "lance-encoding:packed"]; + PACKED_KEYS.iter().any(|key| { + field_metadata + .get(*key) + .map(|value| value.eq_ignore_ascii_case("true")) + .unwrap_or(false) + }) + } + + fn is_blob(&self) -> bool { + let field_metadata = self.metadata(); + field_metadata.get(BLOB_META_KEY).is_some() + || field_metadata + .get(ARROW_EXT_NAME_KEY) + .map(|value| value == BLOB_V2_EXT_NAME) + .unwrap_or(false) + } + + fn is_blob_v2(&self) -> bool { + let field_metadata = self.metadata(); + field_metadata + .get(ARROW_EXT_NAME_KEY) + .map(|value| value == BLOB_V2_EXT_NAME) + .unwrap_or(false) + } +} + +/// Extends the functionality of [arrow_schema::Schema]. +pub trait SchemaExt { + /// Create a new [`Schema`] with one extra field. + fn try_with_column(&self, field: Field) -> std::result::Result; + + fn try_with_column_at( + &self, + index: usize, + field: Field, + ) -> std::result::Result; + + fn field_names(&self) -> Vec<&String>; + + fn without_column(&self, column_name: &str) -> Schema; + + /// Create a compact string representation of the schema + /// + /// This is intended for display purposes and not for serialization + fn to_compact_string(&self, indent: Indentation) -> String; +} + +impl SchemaExt for Schema { + fn try_with_column(&self, field: Field) -> std::result::Result { + if self.column_with_name(field.name()).is_some() { + return Err(ArrowError::SchemaError(format!( + "Can not append column {} on schema: {:?}", + field.name(), + self + ))); + }; + let mut fields: Vec = self.fields().iter().cloned().collect(); + fields.push(FieldRef::new(field)); + Ok(Self::new_with_metadata(fields, self.metadata.clone())) + } + + fn try_with_column_at( + &self, + index: usize, + field: Field, + ) -> std::result::Result { + if self.column_with_name(field.name()).is_some() { + return Err(ArrowError::SchemaError(format!( + "Failed to modify schema: Inserting column {} would create a duplicate column in schema: {:?}", + field.name(), + self + ))); + }; + let mut fields: Vec = self.fields().iter().cloned().collect(); + fields.insert(index, FieldRef::new(field)); + Ok(Self::new_with_metadata(fields, self.metadata.clone())) + } + + /// Project the schema to remove the given column. + /// + /// This only works on top-level fields right now. If a field does not exist, + /// the schema will be returned as is. + fn without_column(&self, column_name: &str) -> Schema { + let fields: Vec = self + .fields() + .iter() + .filter(|f| f.name() != column_name) + .cloned() + .collect(); + Self::new_with_metadata(fields, self.metadata.clone()) + } + + fn field_names(&self) -> Vec<&String> { + self.fields().iter().map(|f| f.name()).collect() + } + + fn to_compact_string(&self, indent: Indentation) -> String { + let mut result = "{".to_string(); + result += &indent.value(); + for (field_idx, field) in self.fields.iter().enumerate() { + result += field.to_compact_string(indent.deepen()).as_str(); + if field_idx < self.fields.len() - 1 { + result += ","; + } + result += indent.value().as_str(); + } + result += "}"; + result + } +} diff --git a/python/vendor/lance-arrow/src/stream.rs b/python/vendor/lance-arrow/src/stream.rs new file mode 100644 index 000000000..c5e55f093 --- /dev/null +++ b/python/vendor/lance-arrow/src/stream.rs @@ -0,0 +1,554 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Utilities for working with streams of [`RecordBatch`]. + +use arrow_array::RecordBatch; +use arrow_schema::{ArrowError, SchemaRef}; +use futures::stream::{self, Stream, StreamExt}; +use std::pin::Pin; + +use crate::deepcopy::deep_copy_batch_sliced; + +/// Rechunks a stream of [`RecordBatch`] so that each output batch has +/// approximately `target_bytes` of array data. +/// +/// Small input batches are accumulated (by concatenation) until at least +/// `min_bytes` of data has been collected. If the resulting batch exceeds +/// `max_bytes`, it is sliced into roughly equal pieces of ~`max_bytes` +/// (assuming uniform row sizes). +pub fn rechunk_stream_by_size( + input: S, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, +) -> impl Stream> +where + S: Stream>, + E: From, +{ + rechunk_stream_by_size_inner(input, input_schema, min_bytes, max_bytes, false) +} + +/// Like [`rechunk_stream_by_size`] but deep-copies slices so that +/// `get_array_memory_size` reflects the true size of each output batch. +/// +/// After a normal `RecordBatch::slice`, the backing buffers are shared with +/// the original batch, so `get_array_memory_size` still reports the full +/// parent size. This variant deep-copies every slice produced during the +/// splitting phase, which allows the stream to detect and re-split slices +/// that still exceed `max_bytes` (e.g. because a single row is much larger +/// than average). +/// +/// The deep copy is a last resort and potentially expensive for large +/// batches. However, it is only performed when a batch actually needs to be +/// sliced — batches that are already within the target range pass through at +/// zero cost. Use this only when the hard cap on `max_bytes` is a +/// correctness requirement, not merely a performance hint. +pub fn rechunk_stream_by_size_deep_copy( + input: S, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, +) -> impl Stream> +where + S: Stream>, + E: From, +{ + rechunk_stream_by_size_inner(input, input_schema, min_bytes, max_bytes, true) +} + +fn rechunk_stream_by_size_inner( + input: S, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, + deep_copy: bool, +) -> impl Stream> +where + S: Stream>, + E: From, +{ + stream::try_unfold( + RechunkState { + input: Box::pin(input), + accumulated: Vec::new(), + acc_bytes: 0, + done: false, + input_schema, + min_bytes, + max_bytes, + deep_copy, + }, + |mut state| async move { + if state.done && state.accumulated.is_empty() { + return Ok(None); + } + + // Pull batches until we reach the byte target or exhaust input. + // Always pull at least one batch so that min_bytes=0 works. + while !state.done && (state.accumulated.is_empty() || state.acc_bytes < state.min_bytes) + { + match state.input.next().await { + Some(Ok(batch)) => { + state.acc_bytes += batch.get_array_memory_size(); + state.accumulated.push(batch); + } + Some(Err(e)) => return Err(e), + None => { + state.done = true; + } + } + } + + if state.accumulated.is_empty() { + return Ok(None); + } + + // Fast path: if the first accumulated batch already meets the + // byte threshold, deliver it directly instead of concatenating + // everything together (which would just get sliced back apart). + if state.accumulated.len() > 1 + && state.accumulated[0].get_array_memory_size() >= state.min_bytes + { + let b = state.accumulated.remove(0); + state.acc_bytes -= b.get_array_memory_size(); + return Ok(Some((b, state))); + } + + let batch = if state.accumulated.len() == 1 { + state.accumulated.pop().unwrap() + } else { + let b = + arrow_select::concat::concat_batches(&state.input_schema, &state.accumulated) + .map_err(E::from)?; + state.accumulated.clear(); + b + }; + state.acc_bytes = 0; + + // Slice the batch into ~max_bytes pieces assuming uniform row sizes. + let mut slices = + slice_batch(batch, state.max_bytes, state.deep_copy).map_err(E::from)?; + + if slices.len() == 1 { + Ok(Some((slices.pop().unwrap(), state))) + } else { + let first = slices.remove(0); + + // Stash leftover slices for subsequent iterations. + for a in &slices { + state.acc_bytes += a.get_array_memory_size(); + } + state.accumulated = slices; + + Ok(Some((first, state))) + } + }, + ) +} + +/// Slice a batch into pieces of at most `max_bytes`. +/// +/// When `deep_copy` is false, slices share buffers with the original batch +/// and `get_array_memory_size` will still report the parent buffer size. +/// This is fine when the caller only needs approximate sizing. +/// +/// When `deep_copy` is true, each slice is deep-copied so that +/// `get_array_memory_size` reflects the true size. If a deep-copied slice +/// still exceeds `max_bytes` (due to non-uniform row sizes), it is +/// recursively split until every piece is within budget or contains only a +/// single row. +fn slice_batch( + batch: RecordBatch, + max_bytes: usize, + deep_copy: bool, +) -> Result, ArrowError> { + let batch_bytes = batch.get_array_memory_size(); + let num_rows = batch.num_rows(); + + if batch_bytes <= max_bytes { + return Ok(vec![batch]); + } + + if num_rows <= 1 { + // A single row cannot be split further, but the size just measured may + // belong to its source buffer rather than to the row: + // `get_array_memory_size` reports whole buffers, and a slice shares + // them. Returning it uncopied hands the caller that inflated figure -- + // a 100 KB row inside a 200 MB buffer measures as 200 MB, and a caller + // budgeting on it concludes the row cannot fit anywhere. + if deep_copy { + return Ok(vec![deep_copy_batch_sliced(&batch)?]); + } + return Ok(vec![batch]); + } + + let rows_per_chunk = (max_bytes as u64 * num_rows as u64 / batch_bytes as u64).max(1) as usize; + + let mut result = Vec::new(); + let mut offset = 0; + while offset < num_rows { + let len = rows_per_chunk.min(num_rows - offset); + let slice = batch.slice(offset, len); + if deep_copy { + let copied = deep_copy_batch_sliced(&slice)?; + // Recurse: the deep-copied slice has accurate sizes, so if it + // still exceeds max_bytes we can split further. + result.extend(slice_batch(copied, max_bytes, true)?); + } else { + result.push(slice); + } + offset += len; + } + + Ok(result) +} + +/// Internal state for [`rechunk_stream`]. +/// +/// Kept as a named struct so the `try_unfold` closure stays readable. +struct RechunkState { + input: Pin>, + accumulated: Vec, + acc_bytes: usize, + done: bool, + input_schema: SchemaRef, + min_bytes: usize, + max_bytes: usize, + deep_copy: bool, +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::sync::Arc; + + use arrow_array::Int32Array; + use arrow_schema::{DataType, Field, Schema}; + use futures::executor::block_on; + + /// A single row that shares a large source buffer must report its own + /// size, not the buffer's. Callers budget on this figure, and an inflated + /// one makes a small row look impossible to place. + #[test] + fn a_single_row_slice_reports_its_own_size() { + use arrow_array::LargeStringArray; + + let row = "x".repeat(100 * 1024); + let values: Vec<&str> = (0..2000).map(|_| row.as_str()).collect(); + let schema = Arc::new(Schema::new(vec![Field::new( + "text", + DataType::LargeUtf8, + false, + )])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(LargeStringArray::from(values))]).unwrap(); + let whole = batch.get_array_memory_size(); + + let one_row = batch.slice(7, 1); + assert_eq!( + one_row.get_array_memory_size(), + whole, + "a slice shares its source buffer, which is the reason this test exists" + ); + + // Budget far below the row so the split recurses to the single-row floor. + let chunks = slice_batch(one_row, 1024, true).unwrap(); + assert_eq!(chunks.len(), 1); + let measured = chunks[0].get_array_memory_size(); + assert_eq!(chunks[0].num_rows(), 1); + assert!( + measured < whole / 100, + "single row still measured as {measured} bytes against a {whole} byte source" + ); + } + + fn make_batch(num_rows: usize) -> RecordBatch { + let schema = test_schema(); + let values: Vec = (0..num_rows as i32).collect(); + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(values))]).unwrap() + } + + fn test_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])) + } + + fn collect_rechunked( + batches: Vec, + min_bytes: usize, + max_bytes: usize, + ) -> Vec { + let input = stream::iter(batches.into_iter().map(Ok::<_, ArrowError>)); + let rechunked = rechunk_stream_by_size(input, test_schema(), min_bytes, max_bytes); + block_on(rechunked.collect::>()) + .into_iter() + .map(|r| r.unwrap()) + .collect() + } + + fn total_rows(batches: &[RecordBatch]) -> usize { + batches.iter().map(|b| b.num_rows()).sum() + } + + #[test] + fn test_empty_stream() { + let result = collect_rechunked(vec![], 100, 200); + assert!(result.is_empty()); + } + + #[test] + fn test_single_batch_passthrough() { + let batch = make_batch(100); + let bytes = batch.get_array_memory_size(); + // Batch is between min and max — should pass through as-is. + let result = collect_rechunked(vec![batch], bytes / 2, bytes * 2); + assert_eq!(result.len(), 1); + assert_eq!(result[0].num_rows(), 100); + } + + #[test] + fn test_small_batches_concatenated() { + let one_batch_bytes = make_batch(10).get_array_memory_size(); + let batches: Vec<_> = (0..8).map(|_| make_batch(10)).collect(); + // min = 5 batches worth, max = 10 batches worth. + let result = collect_rechunked(batches, one_batch_bytes * 5, one_batch_bytes * 10); + assert_eq!(total_rows(&result), 80); + // Should have been concatenated into fewer batches than the 8 inputs. + assert!( + result.len() < 8, + "expected fewer output batches, got {}", + result.len() + ); + } + + #[test] + fn test_large_batch_sliced() { + let batch = make_batch(1000); + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], bytes / 8, bytes / 4); + assert_eq!(total_rows(&result), 1000); + assert!( + result.len() >= 4, + "expected at least 4 slices, got {}", + result.len() + ); + } + + #[test] + fn test_sliced_leftovers_are_not_recombined() { + // Key test for the fast-path optimisation. When a large batch is + // sliced, leftover slices should be delivered one-at-a-time without + // being concatenated back together. We verify this by checking that + // every output buffer pointer falls inside the original batch's + // allocation (i.e. they are all zero-copy slices, not fresh copies). + let batch = make_batch(1000); + let bytes = batch.get_array_memory_size(); + let orig_data = batch.column(0).to_data(); + let orig_buf = &orig_data.buffers()[0]; + let orig_start = orig_buf.as_ptr() as usize; + let orig_end = orig_start + orig_buf.len(); + + let result = collect_rechunked(vec![batch], bytes / 8, bytes / 4); + + assert_eq!(total_rows(&result), 1000); + assert!(result.len() >= 4); + + for (i, b) in result.iter().enumerate() { + let ptr = b.column(0).to_data().buffers()[0].as_ptr() as usize; + assert!( + ptr >= orig_start && ptr < orig_end, + "slice {i} buffer at {ptr:#x} is outside the original allocation \ + [{orig_start:#x}, {orig_end:#x}) — it was re-concatenated" + ); + } + } + + #[test] + fn test_flush_remainder_on_stream_end() { + // Data below min_bytes should still be flushed when the stream ends. + let batch = make_batch(10); + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], bytes * 100, bytes * 200); + assert_eq!(result.len(), 1); + assert_eq!(result[0].num_rows(), 10); + } + + #[test] + fn test_large_then_small_batches() { + // After a large batch is fully drained, subsequent small batches + // should be accumulated normally. + let large = make_batch(1000); + let small_bytes = make_batch(10).get_array_memory_size(); + let batches = vec![ + large, + make_batch(10), + make_batch(10), + make_batch(10), + make_batch(10), + make_batch(10), + ]; + let result = collect_rechunked(batches, small_bytes * 3, small_bytes * 100); + assert_eq!(total_rows(&result), 1050); + // The large batch should appear (possibly sliced) followed by + // concatenated small batches, so we should have fewer output batches + // than the 6 inputs. + assert!(result.len() < 6); + } + + #[test] + fn test_row_preservation_across_slicing() { + // Verify that every input row appears exactly once in the output + // and in the correct order after slicing. + let batch = make_batch(237); // odd count to exercise remainder slice + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], bytes / 8, bytes / 5); + + assert_eq!(total_rows(&result), 237); + + let values: Vec = result + .iter() + .flat_map(|b| { + b.column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .iter() + .copied() + }) + .collect(); + let expected: Vec = (0..237).collect(); + assert_eq!(values, expected); + } + + #[test] + fn test_min_bytes_zero_still_yields_all_rows() { + // When min_bytes=0, the stream should still yield every batch. + // This is the "chop only, don't coalesce" use case. + let batches: Vec<_> = (0..5).map(|_| make_batch(100)).collect(); + let batch_bytes = batches[0].get_array_memory_size(); + let result = collect_rechunked(batches, 0, batch_bytes * 2); + assert_eq!(total_rows(&result), 500); + } + + #[test] + fn test_min_bytes_zero_slices_oversized() { + // min_bytes=0 with a small max_bytes should still slice large batches. + let batch = make_batch(1000); + let bytes = batch.get_array_memory_size(); + let result = collect_rechunked(vec![batch], 0, bytes / 4); + assert_eq!(total_rows(&result), 1000); + assert!( + result.len() >= 4, + "expected at least 4 slices, got {}", + result.len() + ); + } + + /// Build a batch with one variable-length string column. + /// Every row is `small_size` bytes except the row at index `big_row_idx` + /// which is `big_size` bytes. + fn make_variable_batch( + num_rows: usize, + small_size: usize, + big_row_idx: usize, + big_size: usize, + ) -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)])); + let values: Vec = (0..num_rows) + .map(|i| { + if i == big_row_idx { + "X".repeat(big_size) + } else { + "x".repeat(small_size) + } + }) + .collect(); + let array = arrow_array::StringArray::from(values); + RecordBatch::try_new(schema, vec![Arc::new(array)]).unwrap() + } + + fn variable_schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)])) + } + + fn collect_rechunked_variable( + batches: Vec, + min_bytes: usize, + max_bytes: usize, + ) -> Vec { + let input = stream::iter(batches.into_iter().map(Ok::<_, ArrowError>)); + let rechunked = + rechunk_stream_by_size_deep_copy(input, variable_schema(), min_bytes, max_bytes); + block_on(rechunked.collect::>()) + .into_iter() + .map(|r| r.unwrap()) + .collect() + } + + #[test] + fn test_oversized_row_at_end() { + // 100 rows: 99 small (64 bytes each) + 1 large (100KiB) at the end. + let batch = make_variable_batch(100, 64, 99, 100 * 1024); + let max_bytes = 64 * 1024; + let result = collect_rechunked_variable(vec![batch], 0, max_bytes); + assert_eq!(total_rows(&result), 100); + for (i, b) in result.iter().enumerate() { + let size = b.get_array_memory_size(); + assert!( + size <= max_bytes || b.num_rows() == 1, + "batch {i} has {size} bytes (max {max_bytes}) and {} rows", + b.num_rows() + ); + } + } + + #[test] + fn test_oversized_row_at_start() { + // 100 rows: 1 large (100KiB) at the start + 99 small (64 bytes each). + let batch = make_variable_batch(100, 64, 0, 100 * 1024); + let max_bytes = 64 * 1024; + let result = collect_rechunked_variable(vec![batch], 0, max_bytes); + assert_eq!(total_rows(&result), 100); + for (i, b) in result.iter().enumerate() { + let size = b.get_array_memory_size(); + assert!( + size <= max_bytes || b.num_rows() == 1, + "batch {i} has {size} bytes (max {max_bytes}) and {} rows", + b.num_rows() + ); + } + } + + #[test] + fn test_oversized_row_in_middle() { + // 100 rows: 1 large (100KiB) in the middle + 99 small (64 bytes each). + let batch = make_variable_batch(100, 64, 50, 100 * 1024); + let max_bytes = 64 * 1024; + let result = collect_rechunked_variable(vec![batch], 0, max_bytes); + assert_eq!(total_rows(&result), 100); + for (i, b) in result.iter().enumerate() { + let size = b.get_array_memory_size(); + assert!( + size <= max_bytes || b.num_rows() == 1, + "batch {i} has {size} bytes (max {max_bytes}) and {} rows", + b.num_rows() + ); + } + } + + #[test] + fn test_error_propagation() { + let input = stream::iter(vec![ + Ok(make_batch(10)), + Err(ArrowError::ComputeError("boom".into())), + Ok(make_batch(10)), + ]); + let rechunked = rechunk_stream_by_size(input, test_schema(), 1, usize::MAX); + let results: Vec> = block_on(rechunked.collect()); + assert!(results.iter().any(|r| r.is_err())); + } +} diff --git a/python/vendor/lance-arrow/src/struct.rs b/python/vendor/lance-arrow/src/struct.rs new file mode 100644 index 000000000..ed4b6288e --- /dev/null +++ b/python/vendor/lance-arrow/src/struct.rs @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Extension to arrow struct arrays + +use arrow_array::{Array, StructArray, cast::AsArray, make_array}; +use arrow_buffer::NullBuffer; +use arrow_data::{ArrayData, ArrayDataBuilder}; +use arrow_schema::{ArrowError, DataType}; + +pub trait StructArrayExt { + /// Removes the offset / length of the struct array by pushing it into the children + /// + /// In arrow-rs when slice is called it recursively slices the children. + /// In arrow-cpp when slice is called it just sets the offset/length of + /// the struct array and leaves the children as-is + /// + /// Both are legal approaches (╥﹏╥) + /// + /// This method helps reduce complexity by folding into the arrow-rs approach + fn normalize_slicing(&self) -> Result + where + Self: Sized; + + /// Structs are allowed to mask valid items. For example, a struct array might be: + /// + /// [ {"items": [1, 2, 3]}, NULL, {"items": NULL}] + /// + /// However, the underlying items array might be: [[1, 2, 3], [4, 5], NULL] + /// + /// The [4, 5] list is masked out because the struct array is null. + /// + /// The struct validity would be [true, false, true] and the list validity would be [true, true, false] + /// + /// This method pushes nulls down into all children. In the above example the list validity would become + /// [true, false, false]. + /// + /// This method is not recursive. If a child is a struct array it will not push that child's nulls down. + /// + /// This method does not remove garbage lists. It only updates the validity so a future call to + /// [crate::list::ListArrayExt::filter_garbage_nulls] will remove the garbage lists (without + /// this pushdown it would not) + fn pushdown_nulls(&self) -> Result + where + Self: Sized; +} + +fn normalized_struct_array_data(data: ArrayData) -> Result { + let parent_offset = data.offset(); + let parent_len = data.len(); + let modified_children = data + .child_data() + .iter() + .map(|d| { + let d = normalized_struct_array_data(d.clone())?; + let offset = d.offset(); + let len = d.len(); + if len < parent_len + parent_offset { + return Err(ArrowError::InvalidArgumentError(format!( + "Child array {} has length {} which is less than the parent length {} plus the parent offset {}", + d.data_type(), + len, + parent_len, + parent_offset + ))); + } + let new_offset = offset + parent_offset; + d.into_builder().offset(new_offset) + .len(parent_len) + .build() + }) + .collect::, _>>()?; + ArrayDataBuilder::new(data.data_type().clone()) + .len(parent_len) + .offset(0) + .buffers(data.buffers().to_vec()) + .child_data(modified_children) + .build() +} + +impl StructArrayExt for StructArray { + fn normalize_slicing(&self) -> Result + where + Self: Sized, + { + if self.offset() == 0 && self.columns().iter().all(|c| c.len() == self.len()) { + return Ok(self.clone()); + } + + let data = normalized_struct_array_data(self.to_data())?; + Ok(Self::from(data)) + } + + fn pushdown_nulls(&self) -> Result + where + Self: Sized, + { + let Some(validity) = self.nulls() else { + return Ok(self.clone()); + }; + let data = self.to_data(); + let children = data + .child_data() + .iter() + .map(|c| { + if c.data_type() == &DataType::Null { + // A Null array is already null in every slot, and arrow-rs rejects + // a validity buffer on it. + Ok(c.clone()) + } else if let Some(child_validity) = c.nulls() { + let new_validity = child_validity.inner() & validity.inner(); + c.clone() + .into_builder() + .nulls(Some(NullBuffer::from(new_validity))) + .build() + } else { + Ok(c.clone() + .into_builder() + .nulls(Some(validity.clone())) + .build()?) + } + }) + .collect::, _>>()?; + let arr = make_array(data.into_builder().child_data(children).build()?); + Ok(arr.as_struct().clone()) + } +} + +#[cfg(test)] +mod tests { + use arrow_array::{ + Array, Int32Array, NullArray, StructArray, cast::AsArray, make_array, types::Int32Type, + }; + use arrow_buffer::NullBuffer; + use arrow_schema::{DataType, Field, Fields}; + use std::sync::Arc; + + use crate::r#struct::StructArrayExt; + + #[test] + fn test_normalize_slicing_no_offset() { + let x = Int32Array::from(vec![1, 2, 3]); + let y = Int32Array::from(vec![4, 5, 6]); + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("x", DataType::Int32, true), + Field::new("y", DataType::Int32, true), + ]), + vec![Arc::new(x), Arc::new(y)], + None, + ); + + let normalized = struct_array.normalize_slicing().unwrap(); + assert_eq!(normalized, struct_array); + } + + #[test] + fn test_arrow_rs_slicing() { + let x = Int32Array::from(vec![1, 2, 3, 4]); + let y = Int32Array::from(vec![5, 6, 7, 8]); + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("x", DataType::Int32, true), + Field::new("y", DataType::Int32, true), + ]), + vec![Arc::new(x), Arc::new(y)], + None, + ); + + // Slicing with arrow-rs propagates the slicing to the children so there should + // be no change needed to the struct array + let sliced = struct_array.slice(1, 2); + let normalized = sliced.normalize_slicing().unwrap(); + + assert_eq!(normalized, sliced); + } + + #[test] + fn test_arrow_cpp_slicing() { + let x = Int32Array::from(vec![1, 2, 3, 4]); + let y = Int32Array::from(vec![5, 6, 7, 8]); + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("x", DataType::Int32, true), + Field::new("y", DataType::Int32, true), + ]), + vec![Arc::new(x), Arc::new(y)], + None, + ); + + let data = struct_array.to_data(); + let sliced = data.into_builder().offset(1).len(2).build().unwrap(); + let sliced = make_array(sliced); + let normalized = sliced.as_struct().clone().normalize_slicing().unwrap(); + + assert_eq!(normalized, struct_array.slice(1, 2)); + } + + #[test] + fn test_pushdown_nulls_with_null_typed_child() { + // `pa.Table.from_pylist([{"s": {"a": 1, "b": None}}, {"s": None}])` infers a + // struct with a Null-typed child. Arrow forbids a validity buffer on a Null + // array, so the struct's nulls must not be pushed into it. + let struct_array = StructArray::new( + Fields::from(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Null, true), + ]), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3])), + Arc::new(NullArray::new(3)), + ], + Some(NullBuffer::from(vec![true, false, true])), + ); + + let pushed = struct_array.pushdown_nulls().unwrap(); + + assert_eq!(pushed.nulls(), struct_array.nulls()); + assert_eq!( + pushed.column(0).as_primitive::(), + &Int32Array::from(vec![Some(1), None, Some(3)]) + ); + assert_eq!(pushed.column(1).data_type(), &DataType::Null); + assert_eq!(pushed.column(1).logical_null_count(), 3); + } +} diff --git a/rust/lancedb/tests/nullable_struct_merge.rs b/rust/lancedb/tests/nullable_struct_merge.rs new file mode 100644 index 000000000..c245b1c2c --- /dev/null +++ b/rust/lancedb/tests/nullable_struct_merge.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use arrow_array::{Array, ArrayRef, BooleanArray, Int32Array, RecordBatch, StructArray}; +use arrow_buffer::NullBuffer; +use arrow_schema::{DataType, Field, Schema}; +use lance_arrow::RecordBatchExt; + +#[test] +fn merge_nullable_struct_with_sliced_boolean_child() { + let left_struct = StructArray::new( + vec![Field::new("id", DataType::Int32, false)].into(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as ArrayRef], + None, + ); + + // BooleanArray retains its offset when sliced. The merged child bitmap must + // cover that offset as well as the four visible rows. + let boolean_child: ArrayRef = Arc::new(BooleanArray::from_iter((0..1030).map(|index| { + if index == 1027 { + None + } else { + Some(index % 2 == 1) + } + }))); + let boolean_child = boolean_child.slice(1025, 4); + assert_eq!(boolean_child.offset(), 1025); + let right_struct = StructArray::new( + vec![Field::new("flag", DataType::Boolean, true)].into(), + vec![boolean_child], + Some(NullBuffer::from(vec![true, false, true, true])), + ); + + let left_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "nested", + left_struct.data_type().clone(), + true, + )])), + vec![Arc::new(left_struct)], + ) + .unwrap(); + let right_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "nested", + right_struct.data_type().clone(), + true, + )])), + vec![Arc::new(right_struct)], + ) + .unwrap(); + + let merged = left_batch.merge(&right_batch).unwrap(); + let nested = merged.column_by_name("nested").unwrap(); + let nested = nested.as_any().downcast_ref::().unwrap(); + let flag = nested.column_by_name("flag").unwrap(); + let flag = flag.as_any().downcast_ref::().unwrap(); + assert_eq!( + flag.iter().collect::>(), + vec![Some(true), None, None, Some(false)] + ); +} From 55897d7c3b03c6b94b461161abc1b28d34903fde Mon Sep 17 00:00:00 2001 From: Yingzi Zhang <164733623+LindseyZ1205@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:26:43 -0400 Subject: [PATCH 033/180] fix(python): preserve Arrow schema when merging reranker scores (#4332) Fixes #4331 With `return_score="all"`, model rerankers reconstruct merged rows without their Arrow schema. This changes fixed-size float32 vectors into variable-length float64 lists, loses metadata, and can overflow valid uint64 row IDs. Unify the original input schemas before inserting placeholder scores, then use the unified schema when reconstructing the merged table. Row merging and reranking behavior stay the same. Capturing the schema first also preserves float64 scores without conflicting with the float32 null placeholders. Validation: - New regression cases: 5 failures and 5 passing controls before the fix; all 10 pass afterward. - Reranker, hybrid-query and TypeSafe reranker tests: 150 passed, 17 skipped. Optional live model/API tests were not run. - The fake-client tests that use random metadata passed again with seeds 7 and 41. - Repository-wide Ruff lint/format checks, configured Pyright check and applicable pre-commit hooks pass. - Tests used the locally built Rust/Python extension and the repository's locked uv environment. No Rust code changed. AI disclosure: I used Codex for investigation, implementation, tests, local checks, and drafting this description. --- python/python/lancedb/rerankers/base.py | 5 +- python/python/tests/test_rerankers.py | 108 ++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/rerankers/base.py b/python/python/lancedb/rerankers/base.py index 4af938a1e..e1bc7f0dd 100644 --- a/python/python/lancedb/rerankers/base.py +++ b/python/python/lancedb/rerankers/base.py @@ -241,6 +241,7 @@ class Reranker(ABC): This op is slower than just keeping relevance score but can be useful for debugging. """ + combined_schema = pa.unify_schemas([vector_results.schema, fts_results.schema]) # add nulls to fts results for _distance if "_distance" not in fts_results.column_names: fts_results = fts_results.append_column( @@ -265,7 +266,9 @@ class Reranker(ABC): else: vector_results_dict[key] = value - combined = pa.Table.from_pylist(list(vector_results_dict.values())) + combined = pa.Table.from_pylist( + list(vector_results_dict.values()), schema=combined_schema + ) return combined def _keep_relevance_score(self, combined_results: pa.Table): diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index 850b477a0..d5ee6b6a4 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -785,6 +785,114 @@ def test_empty_hybrid_result_reranker(): assert "_rowid" in result.column_names +@pytest.mark.parametrize("return_score", ["relevance", "all"]) +@pytest.mark.parametrize("first_row_id", [1, 2**63]) +@pytest.mark.parametrize("score_type", [pa.float32(), pa.float64()]) +def test_model_reranker_preserves_arrow_schema( + mocker, return_score, first_row_id, score_type +): + common_schema = pa.schema( + [ + pa.field("_rowid", pa.uint64()), + pa.field("text", pa.string()), + pa.field("vector", pa.list_(pa.float32(), 2)), + ], + metadata={b"source": b"reranker-test"}, + ) + vector_results = pa.Table.from_pylist( + [ + { + "_rowid": first_row_id, + "text": "vector", + "vector": [1, 0], + "_distance": 0.1, + }, + { + "_rowid": first_row_id + 1, + "text": "both", + "vector": [0, 1], + "_distance": 0.2, + }, + ], + schema=common_schema.append(pa.field("_distance", score_type)), + ) + fts_results = pa.Table.from_pylist( + [ + { + "_rowid": first_row_id + 1, + "text": "both", + "vector": [0, 1], + "_score": 0.9, + }, + { + "_rowid": first_row_id + 2, + "text": "fts", + "vector": [1, 1], + "_score": 0.8, + }, + ], + schema=common_schema.append(pa.field("_score", score_type)), + ) + reranker = CohereReranker(return_score=return_score) + reranker._client = mocker.Mock() + reranker._client.rerank.return_value.results = [ + mocker.Mock(index=index, relevance_score=score) + for index, score in [(2, 0.9), (1, 0.8), (0, 0.7)] + ] + + result = reranker.rerank_hybrid("query", vector_results, fts_results) + + assert result.select(common_schema.names).schema.equals( + common_schema, check_metadata=True + ) + assert result["_rowid"].to_pylist() == [ + first_row_id + 2, + first_row_id + 1, + first_row_id, + ] + assert result["text"].to_pylist() == ["fts", "both", "vector"] + if return_score == "all": + assert ( + result["_distance"] + .combine_chunks() + .equals(pa.array([None, 0.2, 0.1], type=score_type)) + ) + assert ( + result["_score"] + .combine_chunks() + .equals(pa.array([0.8, 0.9, None], type=score_type)) + ) + + +@pytest.mark.parametrize("return_score", ["relevance", "all"]) +def test_model_reranker_empty_results_preserve_schema(mocker, return_score): + common_schema = pa.schema( + [ + ("_rowid", pa.uint64()), + ("text", pa.string()), + ("vector", pa.list_(pa.float32(), 2)), + ], + metadata={b"source": b"reranker-test"}, + ) + vector_results = pa.Table.from_pylist( + [], schema=common_schema.append(pa.field("_distance", pa.float32())) + ) + fts_results = pa.Table.from_pylist( + [], schema=common_schema.append(pa.field("_score", pa.float32())) + ) + reranker = CohereReranker(return_score=return_score) + reranker._client = mocker.Mock() + + result = reranker.rerank_hybrid("query", vector_results, fts_results) + + assert len(result) == 0 + assert result.select(common_schema.names).schema.equals( + common_schema, check_metadata=True + ) + assert result.schema.field("_relevance_score").type == pa.float32() + reranker._client.rerank.assert_not_called() + + def test_cross_encoder_reranker_return_all(tmp_path): pytest.importorskip("sentence_transformers") reranker = CrossEncoderReranker(return_score="all") From 7f932b8552c22355902829be1c5615a867d1bd45 Mon Sep 17 00:00:00 2001 From: Prince Jain Date: Thu, 22 Oct 2026 23:15:26 +0530 Subject: [PATCH 034/180] fix(nodejs): reject listNamespaces limit above i32::MAX instead of wrapping (#4584) ## Summary Fixes #4583. `Connection::list_namespaces` narrowed `Option` to `i32` with an unchecked `as` cast, so a JavaScript `limit` between 2^31 and 2^32 - 1 (e.g. `3000000000`) wrapped negative before reaching `ListNamespacesRequest`. The server received a negative page size instead of a clear client-side error. Replaced the cast with a `checked_limit` helper using `i32::try_from`, returning `napi::Error::from_reason` on overflow, matching the existing `try_from` validation used for `limit` elsewhere in the same file. ## Tests Unit tests cover the wrap case (`u32` values above `i32::MAX` reject), the boundary (`i32::MAX` passes), and `None`/zero passthrough. `cargo test -p lancedb-nodejs` passes 8/8 and `pnpm build` compiles the binding and TypeScript definitions cleanly. --- nodejs/src/connection.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 58ec9859a..67c4706e4 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -673,7 +673,7 @@ impl Connection { let req = ListNamespacesRequest { id: namespace_path, page_token, - limit: limit.map(|l| l as i32), + limit: checked_limit(limit)?, ..Default::default() }; let resp = self @@ -787,3 +787,33 @@ impl Connection { .default_error() } } + +fn checked_limit(limit: Option) -> napi::Result> { + limit + .map(i32::try_from) + .transpose() + .map_err(|_| napi::Error::from_reason("limit must not exceed 2147483647")) +} + +#[cfg(test)] +mod tests { + use super::checked_limit; + + #[test] + fn checked_limit_rejects_values_above_i32_max() { + // u32 values above i32::MAX wrapped negative through `as i32`, + // sending a negative page size to the server. + assert!(checked_limit(Some(3_000_000_000)).is_err()); + assert!(checked_limit(Some(u32::MAX)).is_err()); + } + + #[test] + fn checked_limit_passes_boundary_and_missing_values() { + assert_eq!( + checked_limit(Some(i32::MAX as u32)).unwrap(), + Some(i32::MAX) + ); + assert_eq!(checked_limit(Some(0)).unwrap(), Some(0)); + assert_eq!(checked_limit(None).unwrap(), None); + } +} From 62d83f2ea2b43fcf1d37869bbaf06883fe768882 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 23 Oct 2026 02:19:32 +0800 Subject: [PATCH 035/180] fix(python): expect oidc credential-type header on refreshed tokens (#4632) ## Summary #3971 added `test_zero_lifetime_token_is_refreshed`, but its expected headers omit `x-lancedb-credential-type: oidc`, which `OAuthProvider.get_headers()` has emitted since #2631/#4070. The test fails against current main and breaks the PR CI matrix for every open PR. ## Changes - Align the two zap assertions in `test_zero_lifetime_token_is_refreshed` with the provider contract (see `test_token_refresh` and `test_sync_method`). ## Tests - `pytest python/tests/test_header_provider.py -q` --- python/python/tests/test_header_provider.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/python/python/tests/test_header_provider.py b/python/python/tests/test_header_provider.py index e50ff3270..9d19e7bef 100644 --- a/python/python/tests/test_header_provider.py +++ b/python/python/tests/test_header_provider.py @@ -128,8 +128,14 @@ class TestOAuthProvider: provider = OAuthProvider(fetcher, refresh_buffer_seconds=0) - assert provider.get_headers() == {"Authorization": "Bearer token1"} - assert provider.get_headers() == {"Authorization": "Bearer token2"} + assert provider.get_headers() == { + "Authorization": "Bearer token1", + "x-lancedb-credential-type": "oidc", + } + assert provider.get_headers() == { + "Authorization": "Bearer token2", + "x-lancedb-credential-type": "oidc", + } assert call_count == 2 def test_missing_access_token(self): From a0946282ca57a58e18b8cea9a50be39195b3323a Mon Sep 17 00:00:00 2001 From: Mohammad Hijjawi <51020382+MohammadHijjawi97@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:42:06 +0100 Subject: [PATCH 036/180] fix(python): return original scores from hybrid search with normalize="rank" (#4343) ## Summary With `rerank(..., normalize="rank")`, a hybrid query returns ranks (1.0, 2.0, 3.0, ...) in the `_distance` and `_score` columns instead of the real vector distances and BM25 scores. `_combine_hybrid_results` converted both result sets to ranks first, and only then captured `original_distances` / `original_scores`. So the step that restores the original values after reranking put the ranks back. With `normalize="score"`, the real values are returned as expected. Repro (RRFReranker(return_score="all"), vector distances 0 / 25 / 100): | normalize | `_distance` returned | `_score` returned | | --- | --- | --- | | `"score"` | 0.0, 25.0, 100.0 | 0.47, 0.67, None | | `"rank"` (before) | 1.0, 2.0, 3.0 | 1.0, 2.0, None | | `"rank"` (after) | 0.0, 25.0, 100.0 | 0.47, 0.67, None | ## Changes - Capture the original `_distance` / `_score` columns before converting them to ranks, then normalize the ranked column. The reranker input is unchanged; only the values restored afterwards are fixed. `AsyncHybridQuery` uses the same function, so both sync and async are covered. ## Test plan - [x] New `test_hybrid_return_all_restores_original_scores` in `test_rerankers.py`, parametrized over `score` / `rank`: the `rank` case fails before the fix and passes after - [x] `pytest python/tests/test_rerankers.py python/tests/test_hybrid_query.py` - [x] `ruff format --check` / `ruff check` I have no local Rust toolchain, so I ran the tests against the released 0.39.0 native module with the changed Python files overlaid. The changed functions are identical between 0.39.0 and main. Co-authored-by: Xuanwo --- python/python/lancedb/query.py | 20 +++++++++----- python/python/tests/test_rerankers.py | 40 +++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index fe8c33861..9d7610f72 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2575,10 +2575,6 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): with_row_ids: bool, offset: Optional[int] = None, ) -> pa.Table: - if norm == "rank": - vector_results = LanceHybridQueryBuilder._rank(vector_results, "_distance") - fts_results = LanceHybridQueryBuilder._rank(fts_results, "_score") - # If both result sets are empty (e.g. after hard filtering), # return early to avoid errors in reranking or score restoration. if vector_results.num_rows == 0 and fts_results.num_rows == 0: @@ -2605,15 +2601,23 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): original_score_row_ids = None # normalize the scores to be between 0 and 1, 0 being most relevant # We check whether the results (vector and FTS) are empty, because when - # they are, they often are missing the _rowid column, which causes an error + # they are, they often are missing the _rowid column, which causes an error. + # The original values are captured before any rank conversion so that + # they can be restored after reranking. if vector_results.num_rows > 0: distance_i = vector_results.column_names.index("_distance") original_distances = vector_results.column(distance_i) original_distance_row_ids = vector_results.column("_rowid") + if norm == "rank": + vector_results = LanceHybridQueryBuilder._rank( + vector_results, "_distance" + ) vector_results = vector_results.set_column( distance_i, vector_results.field(distance_i), - LanceHybridQueryBuilder._normalize_scores(original_distances), + LanceHybridQueryBuilder._normalize_scores( + vector_results.column(distance_i) + ), ) # In fts higher scores represent relevance. Not inverting them here as @@ -2622,10 +2626,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): score_i = fts_results.column_names.index("_score") original_scores = fts_results.column(score_i) original_score_row_ids = fts_results.column("_rowid") + if norm == "rank": + fts_results = LanceHybridQueryBuilder._rank(fts_results, "_score") fts_results = fts_results.set_column( score_i, fts_results.field(score_i), - LanceHybridQueryBuilder._normalize_scores(original_scores), + LanceHybridQueryBuilder._normalize_scores(fts_results.column(score_i)), ) results = reranker.rerank_hybrid(fts_query, vector_results, fts_results) diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index d5ee6b6a4..743669367 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -785,6 +785,46 @@ def test_empty_hybrid_result_reranker(): assert "_rowid" in result.column_names +@pytest.mark.parametrize("norm", ["score", "rank"]) +def test_hybrid_return_all_restores_original_scores(norm): + from lancedb.query import LanceHybridQueryBuilder + + vector_results = pa.table( + { + "text": ["a", "b", "c"], + "_rowid": pa.array([0, 1, 2], type=pa.uint64()), + "_distance": pa.array([0.5, 2.5, 10.0], type=pa.float32()), + } + ) + fts_results = pa.table( + { + "text": ["b", "a"], + "_rowid": pa.array([1, 0], type=pa.uint64()), + "_score": pa.array([3.25, 1.75], type=pa.float32()), + } + ) + + result = LanceHybridQueryBuilder._combine_hybrid_results( + fts_results=fts_results, + vector_results=vector_results, + norm=norm, + fts_query="query", + reranker=RRFReranker(return_score="all"), + limit=10, + with_row_ids=True, + ) + + # The raw distances and scores are returned, not the normalized values + # or ranks used for reranking. + rows = {row["_rowid"]: row for row in result.to_pylist()} + assert rows[0]["_distance"] == 0.5 + assert rows[1]["_distance"] == 2.5 + assert rows[2]["_distance"] == 10.0 + assert rows[0]["_score"] == 1.75 + assert rows[1]["_score"] == 3.25 + assert rows[2]["_score"] is None + + @pytest.mark.parametrize("return_score", ["relevance", "all"]) @pytest.mark.parametrize("first_row_id", [1, 2**63]) @pytest.mark.parametrize("score_type", [pa.float32(), pa.float64()]) From 5f9a8af27c66d8730b9e7cf3c29cac1f2bd237cf Mon Sep 17 00:00:00 2001 From: Mohammad Hijjawi <51020382+MohammadHijjawi97@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:42:21 +0100 Subject: [PATCH 037/180] fix(python): keep embedding functions registered without an alias readable (#4356) `EmbeddingFunctionRegistry.register()` documents that the class name is used when no alias is given, and it does register the class under that name. But it stored the alias itself (`None`) as `__embedding_function_registry_alias__`, which is what `function_to_metadata()` writes into the table schema. A table using such a function gets `"name": null` in its `embedding_functions` metadata, and any later read of the functions fails: ```python @get_registry().register() class MyEmbed(TextEmbeddingFunction): ... f = MyEmbed.create() class Schema(LanceModel): text: str = f.SourceField() vector: Vector(4) = f.VectorField() tbl = db.create_table("t", schema=Schema) tbl.add([{"text": "hi"}]) # KeyError: None tbl.search("hi") # KeyError: None ``` This stores the key the class is registered under instead, so the class name round-trips. For aliased classes the key is the alias, so their metadata is unchanged. The TypeScript registry already falls back to `ctor.name` in the same way. Added `test_embedding_function_registered_without_alias`, which creates a table with such a function, reopens it, and adds a row. It fails with `KeyError` before the change. `test_embeddings.py`, `test_pydantic.py`, `test_table.py` and `test_db.py` pass, and `ruff format --check` / `ruff check` are clean. --- python/python/lancedb/embeddings/registry.py | 4 ++- python/python/tests/test_embeddings.py | 31 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/embeddings/registry.py b/python/python/lancedb/embeddings/registry.py index 1dc7ffcb8..3b940fe2e 100644 --- a/python/python/lancedb/embeddings/registry.py +++ b/python/python/lancedb/embeddings/registry.py @@ -73,7 +73,9 @@ class EmbeddingFunctionRegistry: raise KeyError(f"{cls.__name__} was already registered") key = alias or cls.__name__ self._functions[key] = cls - cls.__embedding_function_registry_alias__ = alias + # Store the name the class is registered under, so the table + # metadata written for it can be looked up again when reading. + cls.__embedding_function_registry_alias__ = key return cls return decorator diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index c42172f77..51907f141 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -64,6 +64,37 @@ def test_embedding_function(tmp_path): assert np.allclose(actual, expected) +def test_embedding_function_registered_without_alias(tmp_path): + registry = EmbeddingFunctionRegistry.get_instance() + + @registry.register() + class NoAliasEmbeddingFunction(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [np.array([1.0, 2.0]) for _ in texts] + + assert registry.get("NoAliasEmbeddingFunction") is NoAliasEmbeddingFunction + + func = NoAliasEmbeddingFunction.create() + + class Schema(LanceModel): + text: str = func.SourceField() + vector: Vector(2) = func.VectorField() + + db = lancedb.connect(tmp_path) + db.create_table("test", schema=Schema) + + # The class name is written to the table metadata, so the function can be + # resolved again when the table is reopened. + table = lancedb.connect(tmp_path).open_table("test") + table.add([{"text": "hello"}]) + conf = table.embedding_functions["vector"] + assert isinstance(conf.function, NoAliasEmbeddingFunction) + assert table.to_arrow()["vector"].to_pylist() == [[1.0, 2.0]] + + def test_instructor_ndims_uses_instruction(): instructor = get_registry().get("instructor").create() model = MagicMock() From 712a8b86995397de03ae1c0389f68824505f80a5 Mon Sep 17 00:00:00 2001 From: Mohammad Hijjawi <51020382+MohammadHijjawi97@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:42:36 +0100 Subject: [PATCH 038/180] fix(python): write plain Enum fields of a LanceModel as their values (#4357) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since #3232, `pydantic_to_schema` maps an `Enum` field to the Arrow type of its values, including enums without a `str`/`int` mixin. Writing such models still failed: `model_to_dict()` returns `model.model_dump()`, which keeps the Enum members, and Arrow can only convert members that are also `str`/`int` instances. ```python class Color(Enum): RED = "red" class Item(LanceModel): color: Color tbl = db.create_table("items", schema=Item) tbl.add([Item(color=Color.RED)]) # pyarrow.lib.ArrowTypeError: Expected bytes, got a 'Color' object ``` `create_table(data=[...])` fails the same way, and int-valued enums raise `ArrowInvalid`. `model_to_dict()` now replaces Enum members with their values, including in nested models and lists. Lists of plain scalars (vectors in particular) are returned without being walked, so the per-row cost stays about the same as `model_dump()` alone (21.3µs vs 20.3µs for a 1536-dim model). Reading back is unchanged: Pydantic already validates the stored value into the Enum member. Added `test_plain_enum_values_are_written`, which covers str and int valued enums, `Optional` and `List` fields, and an Enum inside a nested model, and checks that `to_pydantic` round-trips the rows. It fails with the `ArrowTypeError` above before the change. `test_pydantic.py`, `test_embeddings.py`, `test_table.py` and `test_db.py` pass, and `ruff format --check` / `ruff check` are clean. --- python/python/lancedb/pydantic.py | 18 +++++++++- python/python/tests/test_pydantic.py | 49 ++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index 313c514c3..8fe3c1c93 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -524,4 +524,20 @@ def get_extras(field_info: FieldInfo, key: str) -> Any: def model_to_dict(model: pydantic.BaseModel) -> dict[str, Any]: """Convert a Pydantic model to a dictionary.""" - return model.model_dump() + return _enum_members_to_values(model.model_dump()) + + +def _enum_members_to_values(value: Any) -> Any: + # model_dump() keeps Enum members, and Arrow cannot convert a member of a + # plain Enum (one without a str or int mixin). Write its value instead, + # which is what the Arrow type of the field is derived from. + if isinstance(value, Enum): + return value.value + if isinstance(value, dict): + return {k: _enum_members_to_values(v) for k, v in value.items()} + if isinstance(value, (list, tuple)) and value: + # Skip lists of plain scalars, such as vectors, without walking them. + if isinstance(value[0], (int, float, str, bytes)): + return value + return [_enum_members_to_values(v) for v in value] + return value diff --git a/python/python/tests/test_pydantic.py b/python/python/tests/test_pydantic.py index 81674d735..24fb7ee89 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -733,3 +733,52 @@ def test_enum_types(): assert schema.field("priority").type == pa.int64() assert schema.field("opt_status").type == pa.dictionary(pa.int32(), pa.utf8()) assert schema.field("opt_status").nullable + + +def test_plain_enum_values_are_written(mem_db): + """Members of an Enum without a str/int mixin are written as their values.""" + + class Color(Enum): + RED = "red" + BLUE = "blue" + + class Priority(Enum): + LOW = 1 + HIGH = 2 + + class Tag(LanceModel): + color: Color + + class TestModel(LanceModel): + color: Color + priority: Priority + opt_color: Optional[Color] = None + colors: List[Color] + tag: Tag + vector: Vector(2) + + rows = [ + TestModel( + color=Color.RED, + priority=Priority.HIGH, + opt_color=Color.BLUE, + colors=[Color.BLUE, Color.RED], + tag=Tag(color=Color.BLUE), + vector=[1.0, 2.0], + ), + TestModel( + color=Color.BLUE, + priority=Priority.LOW, + colors=[], + tag=Tag(color=Color.RED), + vector=[3.0, 4.0], + ), + ] + tbl = mem_db.create_table("test", schema=TestModel) + tbl.add(rows) + + assert tbl.to_arrow().select(["color", "priority", "opt_color"]).to_pylist() == [ + {"color": "red", "priority": 2, "opt_color": "blue"}, + {"color": "blue", "priority": 1, "opt_color": None}, + ] + assert tbl.search().to_pydantic(TestModel) == rows From 4bdc8c3c0015c54587445409ad10619481843273 Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 02:42:51 +0800 Subject: [PATCH 039/180] fix: wait for the submitted remote index job (#4428) Addresses the client-side waiting portion of #4402. When create_index returns a job ID, wait_timeout now waits for that submission rather than an already-ready index with the same name. It propagates JobFailed / JobCancelled and bounds job polling by the requested timeout. Older servers without job IDs keep name-based waiting, calls without wait_timeout remain fire-and-forget, and the existing two-hour maximum is preserved. The job wrapper is shared with create_index_async; no synchronous server-side config validation is added. Rebased on main 81d52a98, preserving the new materialized-view SQL constructor. Validation on Linux / Rust 1.97, exact head 61122f92: - All five new native HTTP-mock tests pass (DONE/FAILED/CANCELLED, pending deadline, legacy response, no wait, maximum timeout). On unchanged current-main production the job-tracking and deadline regressions fail by returning early against the old index. - All 274 remote-table tests pass, no failures/skips. - cargo fmt --all -- --check and Clippy --lib --tests -- -D warnings pass. Tests and Clippy used --offline --profile ci --locked -p lancedb --no-default-features --features remote. The affected package was rebuilt from each selected source root; dependency caches were reused. This is Rust mocked-HTTP coverage, not live-cloud, Python/Node binding, full-workspace or performance qualification. --- rust/lancedb/src/index/waiter.rs | 2 +- rust/lancedb/src/remote/table.rs | 194 +++++++++++++++++++++++++++++-- 2 files changed, 185 insertions(+), 11 deletions(-) diff --git a/rust/lancedb/src/index/waiter.rs b/rust/lancedb/src/index/waiter.rs index f201ed6c3..eeef22c98 100644 --- a/rust/lancedb/src/index/waiter.rs +++ b/rust/lancedb/src/index/waiter.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use tokio::time::sleep; const DEFAULT_SLEEP_MS: u64 = 1000; -const MAX_WAIT: Duration = Duration::from_secs(2 * 60 * 60); +pub(crate) const MAX_WAIT: Duration = Duration::from_secs(2 * 60 * 60); /// Poll the table using list_indices() and index_stats() until all of the indices have 0 un-indexed rows. /// Will return Error::Timeout if the columns are not fully indexed within the timeout. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 1c569f6e5..c3b6e7b73 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -16,7 +16,7 @@ use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; use crate::index::scalar::FtsQuery; -use crate::index::waiter::wait_for_index; +use crate::index::waiter::{MAX_WAIT, wait_for_index}; use crate::job::Job; use crate::materialized_view::{ MaterializedViewDefinition, MaterializedViewInfo, RefreshMaterializedViewResult, @@ -650,13 +650,42 @@ impl RemoteTable { .and_then(|body| extract_job_id(&body)); if let Some(wait_timeout) = index.wait_timeout { - let index_name = index.name.unwrap_or_else(|| format!("{}_idx", column)); - self.wait_for_index(&[&index_name], wait_timeout).await?; + if let Some(job_id) = &job_id { + if wait_timeout > MAX_WAIT { + return Err(Error::InvalidInput { + message: format!("timeout must be less than {:?}", MAX_WAIT), + }); + } + // An older same-named index may still be ready while its + // replacement is building. Wait for this submission instead. + tokio::time::timeout(wait_timeout, self.index_job(job_id.clone()).wait()) + .await + .map_err(|_| Error::Timeout { + message: format!( + "timed out waiting for index job {:?} after {:?}", + job_id, wait_timeout + ), + })??; + } else { + // Older servers do not return a job ID. + let index_name = index.name.unwrap_or_else(|| format!("{}_idx", column)); + self.wait_for_index(&[&index_name], wait_timeout).await?; + } } Ok(job_id) } + fn index_job(&self, job_id: String) -> Job { + Job::new(Box::new(FreshnessJob { + inner: RemoteJob::new(self.client.clone(), job_id), + freshness: self.freshness.clone(), + version: self.version.clone(), + tracked_result: TrackedJobResult::None, + freshness_request: self.snapshot_freshness_headers(), + })) + } + pub(super) fn new_with_sql_client( client: RestfulLanceDbClient, name: String, @@ -3101,13 +3130,7 @@ impl BaseTable for RemoteTable { async fn create_index_async(&self, index: IndexBuilder) -> Result { Ok(match self.submit_create_index(index).await? { - Some(job_id) => Job::new(Box::new(FreshnessJob { - inner: RemoteJob::new(self.client.clone(), job_id), - freshness: self.freshness.clone(), - version: self.version.clone(), - tracked_result: TrackedJobResult::None, - freshness_request: self.snapshot_freshness_headers(), - })), + Some(job_id) => self.index_job(job_id), None => Job::new_done(), }) } @@ -8000,6 +8023,157 @@ mod tests { assert_eq!(err.to_string(), "Job job-err failed: preempted (in commit)"); } + // The name-based endpoint deliberately exposes an already-ready old index. + // A replacement must wait on the new job, not mistake that index for success. + fn index_wait_fixture( + job_id: Option<&'static str>, + terminal_state: &'static str, + ) -> ( + Table, + Arc, + Arc, + ) { + let job_polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let index_polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let jobs = job_polls.clone(); + let indices = index_polls.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let body = match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + return http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(); + } + "/v1/table/my_table/create_index/" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + // Replacement is the default and omitted from the wire body. + assert!(body.get("replace").is_none()); + match job_id { + Some(id) => json!({"job_id": id}), + None => json!({}), + } + } + "/v1/jobs/describe" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], json!(job_id.unwrap())); + let poll = jobs.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + json!({ + "job_id": job_id.unwrap(), + "job_state": if poll == 0 { "IN_PROGRESS" } else { terminal_state }, + "failure": {"phase": "build", "message": "invalid index config", + "retryable": false} + }) + } + "/v1/table/my_table/index/list/" => { + indices.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + json!({"indexes": [{"index_name": "a_idx", "columns": ["a"], + "index_uuid": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "index_status": "done"}]}) + } + "/v1/table/my_table/index/a_idx/stats/" => json!({ + "num_indexed_rows": 100, "num_unindexed_rows": 0, "index_type": "BTREE" + }), + path => panic!("Unexpected path: {path}"), + }; + http::Response::builder() + .status(200) + .body(body.to_string()) + .unwrap() + }); + (table, job_polls, index_polls) + } + + #[tokio::test] + async fn test_create_index_wait_timeout_tracks_job() { + for state in ["DONE", "FAILED", "CANCELLED"] { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), state); + let result = table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_secs(2)) + .execute() + .await; + match state { + "DONE" => result.unwrap(), + "FAILED" => match result.unwrap_err() { + Error::JobFailed { job_id, failure } => { + assert_eq!(job_id.as_deref(), Some("new-index-job")); + assert_eq!(failure.message.as_deref(), Some("invalid index config")); + assert_eq!(failure.phase.as_deref(), Some("build")); + } + error => panic!("Expected job failure, got {error:?}"), + }, + "CANCELLED" => assert!(matches!(result, Err(Error::JobCancelled { .. }))), + _ => unreachable!(), + } + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 2); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + } + + #[tokio::test] + async fn test_create_index_wait_timeout_bounds_job_polling() { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), "IN_PROGRESS"); + let error = table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_millis(10)) + .execute() + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { message } if message.contains("new-index-job"))); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn test_create_index_wait_timeout_legacy_fallback() { + let (table, jobs, indices) = index_wait_fixture(None, "DONE"); + table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_secs(2)) + .execute() + .await + .unwrap(); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_create_index_wait_timeout_absent_does_not_poll() { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), "IN_PROGRESS"); + table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .execute() + .await + .unwrap(); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn test_create_index_wait_timeout_preserves_maximum() { + let (table, jobs, indices) = index_wait_fixture(Some("new-index-job"), "DONE"); + let error = table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(true) + .wait_timeout(Duration::from_secs(2 * 60 * 60 + 1)) + .execute() + .await + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. })); + assert_eq!(jobs.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!(indices.load(std::sync::atomic::Ordering::SeqCst), 0); + } + /// Servers that return no job id (e.g. an empty create-index response) /// yield an already-done job. #[tokio::test] From e489d0cd7b272bab25066c25a951fd2bac8f8c15 Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 02:43:07 +0800 Subject: [PATCH 040/180] fix: return errors for unsupported remote alteration types (#4430) RemoteTable::alter_columns currently unwraps the JsonDataType conversion. A valid Arrow input that the remote wire format cannot represent (for example Utf8View, BinaryView, or a struct containing Utf8View) therefore panics instead of returning an error. Propagate conversion/serialization failures as Error::InvalidInput, including the column path. Unsupported inputs are rejected before any HTTP request; supported alteration payloads are unchanged. This does not add server support for view types or change server HTTP-error classification. Three new native Rust cases reproduce the panic on unchanged production and return InvalidInput with the fix. The existing supported-type cases remain passing. Validation at head 88184ea, Linux/Rust 1.97.0, locked offline dependencies: - cargo test --offline --profile ci --locked -p lancedb --no-default-features --features remote --lib remote::table::tests:: (269 passed) - cargo clippy --offline --profile ci --locked -p lancedb --no-default-features --features remote --lib --tests -- -D warnings - cargo fmt --all -- --check Current main merges cleanly; the intervening remote-table change is unrelated nprobes validation. Live Cloud, rebuilt Python/Node bindings and full-workspace integration were not tested. AI-assisted; native regression and before/after results independently checked. --- rust/lancedb/src/remote/table.rs | 37 +++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index c3b6e7b73..9e2641c22 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3736,16 +3736,25 @@ impl BaseTable for RemoteTable { value["rename"] = serde_json::Value::String(rename.clone()); } if let Some(data_type) = &alteration.data_type { - let json_data_type = JsonDataType::try_from(data_type).unwrap(); - let json_data_type = serde_json::to_value(&json_data_type).unwrap(); - value["data_type"] = json_data_type; + let json_data_type = + JsonDataType::try_from(data_type).map_err(|err| Error::InvalidInput { + message: format!( + "Cannot serialize data type for column '{}': {err}", + alteration.path + ), + })?; + value["data_type"] = serde_json::to_value(&json_data_type).map_err(|err| { + Error::InvalidInput { + message: format!("Cannot serialize column alteration: {err}"), + } + })?; } if let Some(nullable) = &alteration.nullable { value["nullable"] = serde_json::Value::Bool(*nullable); } - value + Ok(value) }) - .collect::>(); + .collect::>>()?; let mut body = serde_json::json!({ "alterations": body }); self.apply_branch_body(&mut body); let request = self @@ -5067,6 +5076,24 @@ mod tests { } } + #[rstest] + #[case::string_view(DataType::Utf8View)] + #[case::binary_view(DataType::BinaryView)] + #[case::nested_view(DataType::Struct(vec![Field::new("value", DataType::Utf8View, true)].into()))] + #[tokio::test] + async fn test_alter_columns_unsupported_type(#[case] data_type: DataType) { + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("an unserializable alteration must not reach the server") + }); + let err = table + .alter_columns(&[ColumnAlteration::new("value".into()).cast_to(data_type)]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); + assert!(err.to_string().contains("value")); + assert!(err.to_string().contains("Unsupported type")); + } + #[rstest] #[case(true)] #[case(false)] From cc9f01ae2622d2a3726608b4ff875d4478daffd4 Mon Sep 17 00:00:00 2001 From: Preston Zhao Date: Thu, 22 Oct 2026 13:43:21 -0500 Subject: [PATCH 041/180] fix(node): accept exist_ok in createTable (#4432) TypeScript CreateTableOptions.mode omitted exist_ok even though createTable already forwards that mode to the native client. closes: #2900 --------- Co-authored-by: Preston Zhao <195942578+canyang25@users.noreply.github.com> --- docs/src/js/interfaces/CreateTableOptions.md | 5 ++++- nodejs/__test__/connection.test.ts | 14 ++++++++++++++ nodejs/lancedb/connection.ts | 5 ++++- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/src/js/interfaces/CreateTableOptions.md b/docs/src/js/interfaces/CreateTableOptions.md index f46cf3722..e6119e74c 100644 --- a/docs/src/js/interfaces/CreateTableOptions.md +++ b/docs/src/js/interfaces/CreateTableOptions.md @@ -65,7 +65,7 @@ then no error will be raised. ### mode ```ts -mode: "overwrite" | "create"; +mode: "overwrite" | "create" | "exist_ok"; ``` The mode to use when creating the table. @@ -76,6 +76,9 @@ happen. Any provided data will be ignored. If this is set to "overwrite" then any existing table will be replaced. +If this is set to "exist_ok" then an existing table is opened and any +provided data is ignored. + *** ### schema? diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index 895c2a7c5..1167ae34a 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -117,6 +117,20 @@ describe("given a connection", () => { await expect(tbl.countRows()).resolves.toBe(1); }); + it("should keep the existing table when mode is exist_ok", async () => { + const created = await db.createTable("test", [{ id: 1 }, { id: 2 }], { + mode: "exist_ok", + }); + await expect(created.countRows()).resolves.toBe(2); + + const reopened = await db.createTable("test", [{ id: 9 }], { + mode: "exist_ok", + }); + await expect(reopened.countRows()).resolves.toBe(2); + const rows = (await reopened.query().toArray()) as { id: number }[]; + expect(rows.map((row) => row.id).sort()).toEqual([1, 2]); + }); + it("should respect limit and page token when listing tables", async () => { const db = await connect(tmpDir.name); diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 11341a8c6..4ed511b86 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -53,8 +53,11 @@ export interface CreateTableOptions { * happen. Any provided data will be ignored. * * If this is set to "overwrite" then any existing table will be replaced. + * + * If this is set to "exist_ok" then an existing table is opened and any + * provided data is ignored. */ - mode: "create" | "overwrite"; + mode: "create" | "overwrite" | "exist_ok"; /** * If this is true and the table already exists and the mode is "create" * then no error will be raised. From 13df747f180da94c3a487067e2a8cec8839a5158 Mon Sep 17 00:00:00 2001 From: Preston Zhao Date: Thu, 22 Oct 2026 13:43:36 -0500 Subject: [PATCH 042/180] fix(python): return the session supplied to LanceDBConnection (#4433) LanceDBConnection.session read AsyncConnection.session, but AsyncConnection has no session attribute, so access raised AttributeError. Store the session passed to the constructor and return that object. Assisted by Cursor (Grok). Co-authored-by: Preston Zhao <195942578+canyang25@users.noreply.github.com> --- python/python/lancedb/db.py | 11 ++++++++++- python/python/tests/test_db.py | 3 +++ python/python/tests/test_session.py | 10 ++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index e1e5d270a..a74763afb 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1300,6 +1300,10 @@ class LanceDBConnection(DBConnection): self.storage_options = storage_options self._manifest_enabled = manifest_enabled self._namespace_client_properties = namespace_client_properties + # The native connection does not expose the Python Session wrapper. + # Keep the object supplied by the caller so this property stays + # synchronous for debugger inspection. + self._session = session if _inner is not None: self._conn = _inner # Native-derived wrappers resolve this in their async reconstruction @@ -1366,7 +1370,12 @@ class LanceDBConnection(DBConnection): @property def session(self) -> Optional[Session]: - return self._conn.session + """Return the session supplied when this connection was opened. + + None when the caller did not pass a session, including connections + reconstructed with :meth:`from_inner`. + """ + return self._session @property def uri(self) -> str: diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 7d37910a3..af63987aa 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -86,6 +86,7 @@ def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeyp assert members["uri"] == str(tmp_path) assert members["read_consistency_interval"] is None + assert members["session"] is None assert repr(db) == f"LanceDBConnection(uri={str(tmp_path)!r})" assert repr(table) == f"LanceTable(name='test', _conn={db!r})" @@ -105,6 +106,8 @@ def test_read_consistency_interval_does_not_use_background_loop(tmp_path, monkey assert db.read_consistency_interval == consistency_interval assert db_from_inner.read_consistency_interval == consistency_interval + assert db.session is None + assert db_from_inner.session is None def test_ingest_pd(tmp_path): diff --git a/python/python/tests/test_session.py b/python/python/tests/test_session.py index 8923477c7..d0bc54210 100644 --- a/python/python/tests/test_session.py +++ b/python/python/tests/test_session.py @@ -36,3 +36,13 @@ def test_session_cache_configuration(tmp_path): assert final_cache_size > initial_cache_size # Cache should have grown assert final_cache_items >= initial_cache_items # Items should not decrease assert initial_cache_size < index_cache_size + metadata_cache_size + + +def test_connection_session_returns_supplied_session(tmp_path): + """Sync connections must expose the session they were opened with.""" + db = lancedb.connect(tmp_path) + assert db.session is None + + session = lancedb.Session() + db = lancedb.connect(tmp_path, session=session) + assert db.session is session From 1e313d3c0d828d04f6c7cb3036d896942c48c86c Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:43:50 +0800 Subject: [PATCH 043/180] fix(python): parse decimal exponent literals exactly (#4449) Decimal literals such as Decimal("1E-7") and Decimal("1E+3") currently raise ValueError while building an expression. Parse the coefficient and exponent exactly, and normalize representable negative scales to zero so both typed filters and predicate.to_sql() queries preserve the value. Checked arithmetic bounds the Decimal128 coefficient to 38 digits, preserves existing scale limits, and rejects nonfinite or overflowing values. This does not add Decimal256 literal support. Added 21 cases covering actual Arrow-backed table queries, SQL queries, zero, signed exponents, precision boundaries, and errors. Both Python 3.11 and 3.13 expression suites pass 123 tests; the baseline fails 10 of the new cases. Python binding Rust tests pass 13; official make doctest passes 77 with 6 skips; Ruff, Rustfmt, hooks, Pyright and workspace/tests/all-features Clippy with -D warnings pass. A fresh environment restored from the original dependency freeze passes the full required suite: 1528 passed, 37 skipped, 68 deselected (143.51s); while optional Torch suites have the same baseline remote mock-server ordering failure. Tested against f4544628; observed official main d864e719 contains one Catalog API commit without expr or Cargo.lock changes. AI assistance: gpt-6.1-sol assisted implementation and local validation; all reported checks were actually executed. --- python/python/tests/test_expr.py | 61 ++++++++++++++++++++++++++++++++ python/src/expr.rs | 58 ++++++++++++++++++++++++------ 2 files changed, 109 insertions(+), 10 deletions(-) diff --git a/python/python/tests/test_expr.py b/python/python/tests/test_expr.py index 0f49231f1..6cfc09922 100644 --- a/python/python/tests/test_expr.py +++ b/python/python/tests/test_expr.py @@ -80,6 +80,67 @@ class TestExprConstruction: e = lit(d) assert isinstance(e, Expr) + @pytest.mark.parametrize( + "value, decimal_type", + [ + ("1E-7", pa.decimal128(12, 7)), + ("-1.23E-7", pa.decimal128(12, 9)), + ("1E+3", pa.decimal128(12, 0)), + ("-1.23E+5", pa.decimal128(12, 0)), + ("0E-7", pa.decimal128(12, 7)), + ("-0E+3", pa.decimal128(12, 0)), + ("1E-38", pa.decimal128(38, 38)), + ("1E+37", pa.decimal128(38, 0)), + ("1.234567890123456789012345678901234567E+37", pa.decimal128(38, 0)), + ("0E+128", pa.decimal128(1, 0)), + ], + ) + def test_lit_decimal_exponent_query(self, tmp_path, value, decimal_type): + expected = Decimal(value) + table = lancedb.connect(tmp_path).create_table( + "decimals", + pa.table( + { + "id": [1, 2], + # Arrow's Python ingestion rejects 0E+128 even though its + # numeric value is representable. Store canonical zero to + # exercise the expression literal independently of ingestion. + "price": pa.array( + [Decimal(0) if expected.is_zero() else expected, None], + type=decimal_type, + ), + } + ), + ) + predicate = col("price") == lit(expected) + result = table.search().where(predicate).to_arrow() + assert result["id"].to_pylist() == [1] + assert result["price"].to_pylist() == [expected] + # Exercise the SQL serializer and parser as well as the typed query path. + sql_result = table.search().where(predicate.to_sql()).to_arrow() + assert sql_result["id"].to_pylist() == [1] + assert sql_result["price"].to_pylist() == [expected] + + @pytest.mark.parametrize( + "value", + [ + "NaN", + "sNaN", + "Infinity", + "-Infinity", + "1E-39", + "1E+38", + "1E+129", + "1E+1000000000", + "0E+129", + "12345678901234567890123456789012345678E+1", + "9" * 39, + ], + ) + def test_lit_decimal_unrepresentable_raises(self, value): + with pytest.raises(ValueError): + lit(Decimal(value)) + class TestExprOperators: def test_eq_operator(self): diff --git a/python/src/expr.rs b/python/src/expr.rs index 79b448fdf..bb779bc1d 100644 --- a/python/src/expr.rs +++ b/python/src/expr.rs @@ -240,22 +240,60 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult { fn parse_decimal(s: &str) -> PyResult<(i128, u8, i8)> { let s = s.trim(); - let dot_pos = s.find('.'); - let scale = if let Some(pos) = dot_pos { - (s.len() - pos - 1) as i8 - } else { - 0 + let (mantissa, exponent) = match s.split_once(['e', 'E']) { + Some((mantissa, exponent)) => ( + mantissa, + exponent.parse::().map_err(|e| { + PyValueError::new_err(format!("failed to parse decimal exponent: {}", e)) + })?, + ), + None => (s, 0), }; + let fractional_digits = mantissa.find('.').map_or(0, |pos| mantissa.len() - pos - 1); + // Keep the coefficient intact instead of expanding an exponent into zeros. + // Arrow Decimal128 has at most 38 digits and an i8 scale (at most 38). + let mut scale = i64::try_from(fractional_digits) + .ok() + .and_then(|fractional_digits| fractional_digits.checked_sub(exponent)) + .and_then(|scale| i8::try_from(scale).ok()) + .filter(|scale| *scale <= 38) + .ok_or_else(|| PyValueError::new_err("decimal scale is outside Decimal128 range"))?; - let digits = s.replace('.', ""); - let val = digits + let digits = mantissa.replace('.', ""); + let mut val = digits .parse::() .map_err(|e| PyValueError::new_err(format!("failed to parse decimal digits: {}", e)))?; - // Precision is total number of digits - let precision = digits.trim_start_matches('-').len() as u8; + // Positive scale cannot exceed precision, including for tiny values such as 1E-38. + let mut precision = digits + .trim_start_matches('-') + .len() + .max(usize::try_from(scale).unwrap_or(0)); + if scale < 0 { + // Arrow cannot cast SQL text to a decimal with negative scale. Normalize + // positive exponents within Decimal128's bounded coefficient range. + if val != 0 { + let shift = -i16::from(scale) as u32; + precision += shift as usize; + if precision > 38 { + return Err(PyValueError::new_err( + "decimal precision exceeds Decimal128 maximum of 38", + )); + } + val = 10_i128 + .checked_pow(shift) + .and_then(|factor| val.checked_mul(factor)) + .ok_or_else(|| PyValueError::new_err("decimal coefficient exceeds i128 range"))?; + } + scale = 0; + } + if precision > 38 { + return Err(PyValueError::new_err( + "decimal precision exceeds Decimal128 maximum of 38", + )); + } - Ok((val, precision, scale)) + Ok((val, precision as u8, scale)) } /// Call an arbitrary registered SQL function by name. From fcd26c425a8657501b9a438fd8ab35f086bc5943 Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:44:05 +0800 Subject: [PATCH 044/180] fix(python): preserve integer Vector and MultiVector values (#4450) When `Vector` or `MultiVector` declares an integer Arrow value type, Pydantic currently validates every element as a float. This silently rounds integers above `2**53`, and converts `uint64`'s maximum value into an out-of-range float before table insertion. Use Pydantic's integer schema for integer Arrow value types in both validators. Floating-point types retain the existing validation. Tests exercise model serialization and real local table creation, insertion, and reads for signed and unsigned integer boundaries and floating-point controls, plus dimensions and optional/nullability behavior. Fractional floats are rejected for integer declarations; integral floats remain accepted. This does not extend ANN index support. Validation on macOS arm64, with the current main native extension built using Rust 1.97.0: - Python 3.11.14 and 3.13.11, Pydantic 2.13.5: full `pytest -m "not slow and not s3_test" -q python/tests` suite: **1,537 passed, 37 skipped, 68 deselected** on each runtime. Comparable unchanged-main baselines: **1,521 passed, 37 skipped, 68 deselected** each. - Added cases on unchanged main: **8 failed, 8 passed**; complete `test_pydantic.py` after the fix: **40 passed** on each runtime. - Documentation tests with the existing embeddings dependencies in an isolated environment, Python 3.11.14: **77 passed, 6 skipped**, matching the unchanged-main baseline. The workflow's Linux/Python 3.13 doctest matrix was not reproduced locally. - Repository Ruff lint/format, Pyright, all applicable pre-commit hooks, compile checks, and `git diff --check` passed. Eight public SDK table round trips passed on each final installed wheel runtime. Slow, credential-dependent S3 integration tests, the remaining OS/runtime matrix, and the minimum Pydantic/PyArrow dependency matrix were not run locally. The native extension was built from unchanged current main; the final local wheel repack contains the verified Python change with that identical native extension. A separate candidate maturin packaging attempt triggered Rust recompilation and was stopped, so an official candidate distribution build was not completed. The project requires Pydantic `>=2.7.4,<3`; Pydantic v1 support was removed in #3990. AI assistance: developed and verified with **gpt-6.1-sol**. --- python/python/lancedb/pydantic.py | 12 +++++- python/python/tests/test_pydantic.py | 61 ++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index 8fe3c1c93..bb70c9a67 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -127,7 +127,11 @@ def Vector( core_schema.list_schema( min_length=dim, max_length=dim, - items_schema=core_schema.float_schema(), + items_schema=( + core_schema.int_schema() + if pa.types.is_integer(value_type) + else core_schema.float_schema() + ), ), ) @@ -208,7 +212,11 @@ def MultiVector( items_schema=core_schema.list_schema( min_length=dim, max_length=dim, - items_schema=core_schema.float_schema(), + items_schema=( + core_schema.int_schema() + if pa.types.is_integer(value_type) + else core_schema.float_schema() + ), ), ), ) diff --git a/python/python/tests/test_pydantic.py b/python/python/tests/test_pydantic.py index 24fb7ee89..6717bbc32 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -415,6 +415,67 @@ def test_nullable_vector(): assert schema == pa.schema([pa.field("vec", pa.list_(pa.float32(), 16), True)]) +@pytest.mark.parametrize("vector_type", [Vector, MultiVector]) +@pytest.mark.parametrize( + "value_type, values", + [ + (pa.int64(), [-(2**53 + 1), 2**53 + 3]), + (pa.uint64(), [2**53 + 1, 2**64 - 1]), + (pa.int8(), [-128, 127]), + (pa.uint8(), [0, 255]), + (pa.float32(), [1.25, 2.5]), + (pa.float64(), [1.25, 2.5]), + ], +) +def test_typed_vector_round_trip(tmp_path, vector_type, value_type, values): + import lancedb + + annotation = vector_type(2, value_type=value_type) + expected = [values, values] if vector_type is MultiVector else values + + class Row(LanceModel): + id: int + payload: annotation + + row = Row(id=1, payload=expected) + table = lancedb.connect(tmp_path).create_table("typed_vectors", [row], schema=Row) + table.add([Row(id=2, payload=expected)]) + assert table.schema == Row.to_arrow_schema() + assert table.search().to_arrow().to_pylist() == [ + {"id": 1, "payload": expected}, + {"id": 2, "payload": expected}, + ] + assert json.loads(row.model_dump_json())["payload"] == expected + + +@pytest.mark.parametrize("vector_type", [Vector, MultiVector]) +@pytest.mark.parametrize("nullable", [False, True]) +def test_integer_vector_validation(vector_type, nullable): + annotation = vector_type(2, value_type=pa.int64(), nullable=nullable) + + class Row(LanceModel): + payload: annotation + + def shape(values): + return [values] if vector_type is MultiVector else values + + assert Row.to_arrow_schema().field("payload").nullable is nullable + assert Row(payload=shape([1.0, -2.0])).model_dump()["payload"] == shape([1, -2]) + with pytest.raises(pydantic.ValidationError, match="valid integer"): + Row(payload=shape([1.5, 2])) + with pytest.raises(pydantic.ValidationError): + Row(payload=shape([1])) + with pytest.raises(pydantic.ValidationError): + Row(payload=shape([1, 2, 3])) + with pytest.raises(pydantic.ValidationError): + Row(payload=None) + + class OptionalRow(LanceModel): + payload: Optional[annotation] = None + + assert OptionalRow(payload=None).payload is None + + def test_bare_vector_raises_clear_error(): namespace = { "__name__": "test_model_without_pyarrow", From 92ada619d2c5aac50c987534a4ebaafd295828c2 Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:44:20 +0800 Subject: [PATCH 045/180] fix(python): preserve metadata during vector schema inference (#4451) Creating a table from an Arrow `list` or `large_list` vector field infers a fixed-size vector type, but currently drops that field's metadata. Descriptions and tags such as `lancedb:description` and `lancedb:tag:model` disappear even though the input field carries them. Preserve the original field metadata while replacing its inferred type. Tests use public synchronous and asynchronous table creation, reopening, and reads for floating-point and integer inference, checking the complete schema and row values. Existing dtype inference and nullability remain unchanged. Validation on macOS arm64 with an official native extension built from main `d864e719` using Rust 1.97.0: - Python 3.11.14 and 3.13.11: full `pytest -m "not slow and not s3_test" -q -rs python/tests`: **1,533 passed, 37 skipped, 68 deselected** each, wall times 331.464 s and 416.308 s. - Added public SDK cases on unchanged main: **12 failed**; after the fix: **12 passed** on each runtime. Final installed distributions passed **8 public SDK round trips** each, including fixed-size fields and fields without metadata. - Documentation tests on Python 3.11.14: **77 passed, 6 skipped**. Ruff lint/format, Pyright (**0 errors**), applicable pre-commit hooks (**4 passed, 2 without matching files**), compile checks and `git diff --check` passed. - Comparable unchanged-main full baselines from the same day, native extension and dependency versions: **1,521 passed, 37 skipped, 68 deselected** on each runtime. These were reused rather than rerun. The final local wheel is an explicitly verified repack of the official main wheel, replacing only `table.py` and `RECORD`; all production Python files match the tested source and the native extension is unchanged. No candidate Rust rebuild was performed. Slow/S3 integration tests, the remaining OS/runtime and minimum-dependency matrices, and the workflow's Linux/Python 3.13 doctest job were not run locally. The existing Rust migration draft #2970 and issues #3216/#3222 do not fix this metadata loss in the current Python path; a future migration should preserve the same metadata. During final verification main advanced to `81d52a98` through #4373 and the beta.13 version bump. Neither modified the two files here; the local native and full-suite validation above remain explicitly based on `d864e719`, and the updated native changes have not been tested locally. AI assistance: developed and verified with **gpt-6.1-sol**. --- python/python/lancedb/table.py | 1 + python/python/tests/test_table.py | 52 +++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 35ec7a466..9b96a1b2a 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -5404,6 +5404,7 @@ def _infer_target_schema( field.name, # preserve original field name target_type, nullable=field.nullable, + metadata=field.metadata, ) schema = schema.set(i, new_field) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index b241adb0a..b2d499933 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4507,6 +4507,58 @@ async def test_alter_columns_rejects_invalid_async( assert await table.schema() == initial_schema +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("list_type", [pa.list_, pa.large_list]) +@pytest.mark.parametrize( + "value_type, values, inferred_type", + [ + (pa.float64(), [1.25, 2.5], pa.float32()), + (pa.int32(), [0, 255], pa.uint8()), + (pa.int32(), [-1, 256], pa.float32()), + ], +) +async def test_inferred_vector_field_metadata( + tmp_db: DBConnection, + tmp_db_async: AsyncConnection, + asynchronous, + list_type, + value_type, + values, + inferred_type, +): + metadata = { + "lancedb:description": "Embedding values", + "lancedb:tag:model": "test-model", + } + schema = pa.schema( + [ + pa.field( + "vector", list_type(value_type), nullable=False, metadata=metadata + ), + pa.field("text", pa.string(), metadata={"description": "Source text"}), + ], + metadata={"description": "Source dataset"}, + ) + rows = [{"vector": values, "text": "first"}, {"vector": values, "text": "second"}] + data = pa.Table.from_pylist(rows, schema=schema) + if asynchronous: + await tmp_db_async.create_table("vector_metadata", data=data) + table = await tmp_db_async.open_table("vector_metadata") + actual_schema = await table.schema() + actual_data = await table.to_arrow() + else: + tmp_db.create_table("vector_metadata", data=data) + table = tmp_db.open_table("vector_metadata") + actual_schema = table.schema + actual_data = table.to_arrow() + expected_schema = schema.set( + 0, schema.field("vector").with_type(pa.list_(inferred_type, 2)) + ) + assert actual_schema.equals(expected_schema, check_metadata=True) + assert actual_data.to_pylist() == rows + + def test_update_field_metadata(mem_db: DBConnection): data = pa.table({"id": [0, 1], "category": ["a", "b"]}) table = mem_db.create_table("my_table", data=data) From b9ef048abbf62840befb3727efb6f0e2ed5932ca Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 02:44:34 +0800 Subject: [PATCH 046/180] fix: validate Python read consistency intervals (#4454) Negative `read_consistency_interval` values currently reach Rust's panicking `Duration::from_secs_f64` conversion. For example: ```python from datetime import timedelta import lancedb lancedb.connect("./db", read_consistency_interval=timedelta(seconds=-1)) ``` Validate the interval with `Duration::try_from_secs_f64` at the three native connection entry points and return `ValueError` before constructing the connection or async future. `None`, zero and positive intervals retain their behavior. The raw native binding also rejects NaN, infinity and overflow; the public Python API still accepts `timedelta`, not floats. Tests cover public sync/async connections, native namespace connections, real Python namespace clients, the three raw binding entry points and valid-value controls. Validation on Python 3.12 / Rust 1.97: - Same 26 regression cases against separately built native baseline and candidate: baseline 22 failed / 4 passed; candidate 26 passed. - Existing basic connection and background-loop regression tests pass. - `cargo fmt --all -- --check`, Ruff check/format and `git diff --check` pass. The native builds used the unchanged repository `ci` profile and Cargo.lock with `--no-default-features --features remote,lancedb/metrics-otel,pyo3/extension-module`. Python runtime and focused test dependency versions came from `python/uv.lock`. Source-tree tests used a minimal distribution-version metadata fixture derived from the unchanged Cargo/pyproject manifests; both imported module origins and native versions were checked in fresh processes. This is not a complete Maturin packaging, cloud backend or full Python suite result. No GPU was used. AI-assisted diagnosis, implementation and validation. Signed-off-by: Xucheng Zhou --- .../tests/test_read_consistency_interval.py | 83 +++++++++++++++++++ python/src/connection.rs | 18 +++- 2 files changed, 98 insertions(+), 3 deletions(-) create mode 100644 python/python/tests/test_read_consistency_interval.py diff --git a/python/python/tests/test_read_consistency_interval.py b/python/python/tests/test_read_consistency_interval.py new file mode 100644 index 000000000..bc69775ea --- /dev/null +++ b/python/python/tests/test_read_consistency_interval.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta + +import lancedb +import pytest +from lance_namespace import connect as connect_namespace_client +from lancedb import _lancedb +from lancedb.namespace import LanceNamespaceDBConnection + + +@pytest.mark.parametrize("seconds", [-1.0, -0.000001]) +@pytest.mark.parametrize("kind", ["sync", "namespace", "namespace_async", "client"]) +def test_negative_read_consistency_interval(tmp_path, seconds, kind): + interval = timedelta(seconds=seconds) + with pytest.raises(ValueError, match="read_consistency_interval"): + if kind == "sync": + lancedb.connect(tmp_path, read_consistency_interval=interval) + elif kind == "client": + client = connect_namespace_client("dir", {"root": str(tmp_path)}) + LanceNamespaceDBConnection(client, read_consistency_interval=interval) + else: + connect = ( + lancedb.connect_namespace + if kind == "namespace" + else lancedb.connect_namespace_async + ) + connect("dir", {"root": str(tmp_path)}, read_consistency_interval=interval) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("seconds", [-1.0, -0.000001]) +async def test_negative_async_read_consistency_interval(tmp_path, seconds): + with pytest.raises(ValueError, match="read_consistency_interval"): + await lancedb.connect_async( + tmp_path, read_consistency_interval=timedelta(seconds=seconds) + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("seconds", [float("nan"), float("inf"), -float("inf"), 1e30]) +@pytest.mark.parametrize("kind", ["connect", "namespace", "client"]) +async def test_binding_rejects_invalid_read_consistency_interval( + tmp_path, seconds, kind +): + with pytest.raises(ValueError, match="read_consistency_interval"): + if kind == "connect": + await _lancedb.connect(str(tmp_path), read_consistency_interval=seconds) + elif kind == "namespace": + _lancedb.connect_namespace( + "dir", {"root": str(tmp_path)}, read_consistency_interval=seconds + ) + else: + client = connect_namespace_client("dir", {"root": str(tmp_path)}) + _lancedb.connect_namespace_client(client, read_consistency_interval=seconds) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "interval", [None, timedelta(0), timedelta(microseconds=1), timedelta(seconds=5)] +) +async def test_valid_read_consistency_intervals(tmp_path, interval): + db = lancedb.connect(tmp_path / "sync", read_consistency_interval=interval) + assert db.read_consistency_interval == interval + db.close() + + db = await lancedb.connect_async( + tmp_path / "async", read_consistency_interval=interval + ) + assert await db.get_read_consistency_interval() == interval + db.close() + + db = lancedb.connect_namespace( + "dir", {"root": str(tmp_path / "namespace")}, read_consistency_interval=interval + ) + assert db.read_consistency_interval == interval + db.close() + + client = connect_namespace_client("dir", {"root": str(tmp_path / "client")}) + db = LanceNamespaceDBConnection(client, read_consistency_interval=interval) + assert db.read_consistency_interval == interval + db.close() diff --git a/python/src/connection.rs b/python/src/connection.rs index 7e20f5f99..baeb29780 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -49,6 +49,18 @@ impl Connection { } } +fn parse_read_consistency_interval(interval: Option) -> PyResult> { + interval + .map(|seconds| { + Duration::try_from_secs_f64(seconds).map_err(|_| { + PyValueError::new_err( + "read_consistency_interval must be finite, non-negative, and within the supported range", + ) + }) + }) + .transpose() +} + fn parse_namespace_client_pushdown_operations( operations: Option>, ) -> PyResult> { @@ -1077,6 +1089,7 @@ pub fn connect( namespace_client_properties: Option>, oauth_config: Option, ) -> PyResult> { + let read_consistency_interval = parse_read_consistency_interval(read_consistency_interval)?; future_into_py(py, async move { let mut builder = lancedb::connect(&uri); if let Some(api_key) = api_key { @@ -1095,7 +1108,6 @@ pub fn connect( #[cfg(not(feature = "remote"))] let _ = sql_host_override; if let Some(read_consistency_interval) = read_consistency_interval { - let read_consistency_interval = Duration::from_secs_f64(read_consistency_interval); builder = builder.read_consistency_interval(read_consistency_interval); } if let Some(storage_options) = storage_options { @@ -1144,7 +1156,7 @@ pub fn connect_namespace_client( namespace_client_impl: Option, namespace_client_properties: Option>, ) -> PyResult { - let read_consistency_interval = read_consistency_interval.map(Duration::from_secs_f64); + let read_consistency_interval = parse_read_consistency_interval(read_consistency_interval)?; let namespace_client_pushdown_operations = parse_namespace_client_pushdown_operations(namespace_client_pushdown_operations)?; let ns_properties = namespace_client_properties.unwrap_or_default(); @@ -1201,7 +1213,7 @@ pub fn connect_namespace( session: Option, namespace_client_pushdown_operations: Option>, ) -> PyResult { - let read_consistency_interval = read_consistency_interval.map(Duration::from_secs_f64); + let read_consistency_interval = parse_read_consistency_interval(read_consistency_interval)?; let namespace_client_pushdown_operations = parse_namespace_client_pushdown_operations(namespace_client_pushdown_operations)?; From a12aef2a8ce39b7d85c28033bd7eff0d1e60b1da Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 02:44:48 +0800 Subject: [PATCH 047/180] fix: return a Python error when querying a closed table (#4455) `AsyncTable.query()` unwraps the native closed-table error, so querying a closed table raises `PanicException` instead of the documented `RuntimeError`. `AsyncTable.head()` reaches the same path. Propagate `inner_ref()`'s error through `PyResult` instead. Add regressions for closed `query()` and `head()`, with `count_rows()`, repeated close, and normal open-table queries as controls. Validation against separately built native bindings: - Before: 2 regression failures (`PanicException`), 2 controls passed. - After: all 4 regressions passed. - Existing query tests plus the basic database test: 102 passed, 1 skipped on each arm (Torch is not installed). - `cargo fmt --all -- --check`, Ruff, and `git diff --check` passed. The native build used the locked Cargo dependencies with `remote,lancedb/metrics-otel,pyo3/extension-module`. This is source-tree native testing, not a complete wheel-packaging or cloud-service test. Signed-off-by: Xucheng Zhou --- .../python/tests/test_closed_table_query.py | 32 +++++++++++++++++++ python/src/table.rs | 4 +-- 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 python/python/tests/test_closed_table_query.py diff --git a/python/python/tests/test_closed_table_query.py b/python/python/tests/test_closed_table_query.py new file mode 100644 index 000000000..2ff3a8e98 --- /dev/null +++ b/python/python/tests/test_closed_table_query.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest +from lancedb.db import AsyncConnection + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["count_rows", "query", "head"]) +async def test_closed_table_queries_raise_runtime_error( + mem_db_async: AsyncConnection, operation +): + table = await mem_db_async.create_table("closed_query", data=[{"id": 0}]) + assert (await table.query().to_arrow()).to_pylist() == [{"id": 0}] + table.close() + table.close() + assert not table.is_open() + + with pytest.raises(RuntimeError, match="Table closed_query is closed"): + if operation == "query": + table.query() + else: + await getattr(table, operation)() + + +@pytest.mark.asyncio +async def test_open_table_queries(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table("open_query", data=[{"id": 0}]) + assert await table.count_rows() == 1 + assert (await table.query().to_arrow()).to_pylist() == [{"id": 0}] + assert (await table.head()).to_pylist() == [{"id": 0}] + table.close() diff --git a/python/src/table.rs b/python/src/table.rs index c1d23d151..27ed8be8b 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1428,8 +1428,8 @@ impl Table { }) } - pub fn query(&self) -> Query { - Query::new(self.inner_ref().unwrap().query()) + pub fn query(&self) -> PyResult { + Ok(Query::new(self.inner_ref()?.query())) } #[getter] From 7a3709b3768f3d1a496e1baf5832493de25e6c87 Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 02:45:02 +0800 Subject: [PATCH 048/180] fix(remote): preserve request IDs in multipart response errors (#4456) Keep the request ID when a multipart create/complete response has a missing or incorrectly typed `upload_id`/`version`. These errors currently use an empty ID, unlike JSON parse errors, so callers lose the ID needed to correlate the failed request. Add six cases through `Table.add(...).write_parallelism(2).execute()`, capturing the actual outgoing `x-request-id`: four missing/wrong-type cases fail on unchanged main, while two invalid-JSON controls already pass. After the fix all six pass, and all 15 multipart tests pass. Native Linux validation (locked dependencies, `ci` profile): - `cargo test --offline --profile ci --locked -p lancedb --no-default-features --features remote --lib remote::table::tests::test_multipart_write`: 15 passed. - `cargo fmt --all -- --check`: passed. - `cargo clippy --offline --profile ci --locked -p lancedb --no-default-features --features remote --lib --tests -- -D warnings`: passed. The committed source bytes match the tested source. HTTP endpoints are mocked; this does not claim a live Cloud or full-repository test run. --- rust/lancedb/src/remote/table.rs | 69 ++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 4 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 9e2641c22..84c1b3fef 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1277,7 +1277,7 @@ impl RemoteTable { let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse multipart create response: {}", e).into(), - request_id, + request_id: request_id.clone(), status_code: None, })?; parsed["upload_id"] @@ -1285,7 +1285,7 @@ impl RemoteTable { .map(|s| s.to_string()) .ok_or_else(|| Error::Http { source: "Missing upload_id in multipart create response".into(), - request_id: String::new(), + request_id, status_code: None, }) } @@ -1304,12 +1304,12 @@ impl RemoteTable { let body = response.text().await.err_to_http(request_id.clone())?; let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("Failed to parse multipart complete response: {}", e).into(), - request_id, + request_id: request_id.clone(), status_code: None, })?; let version = parsed["version"].as_u64().ok_or_else(|| Error::Http { source: "Missing version in multipart complete response".into(), - request_id: String::new(), + request_id, status_code: None, })?; Ok(AddResult { version }) @@ -12596,6 +12596,67 @@ mod tests { ); } + #[rstest] + #[case("create", "{}")] + #[case("create", r#"{"upload_id": 1}"#)] + #[case("create", "not json")] + #[case("complete", "{}")] + #[case("complete", r#"{"version": "invalid"}"#)] + #[case("complete", "not json")] + #[tokio::test] + async fn test_multipart_write_error_preserves_request_id( + #[case] failed_stage: &str, + #[case] body: &str, + ) { + let failed_stage = failed_stage.to_string(); + let body = body.to_string(); + let request_id = Arc::new(std::sync::Mutex::new(String::new())); + let observed_request_id = request_id.clone(); + let table = Table::new_with_handler_version( + "my_table", + semver::Version::new(0, 4, 0), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/describe/" { + return simple_describe_response(); + } + if path == format!("/v1/table/my_table/multipart_write/{failed_stage}") { + *observed_request_id.lock().unwrap() = request.headers()["x-request-id"] + .to_str() + .unwrap() + .to_string(); + return http::Response::builder() + .status(200) + .body(body.clone()) + .unwrap(); + } + let response = match path { + "/v1/table/my_table/multipart_write/create" => r#"{"upload_id":"upload-1"}"#, + "/v1/table/my_table/insert/" => r#"{"version":1}"#, + "/v1/table/my_table/multipart_write/abort" => "", + _ => panic!("Unexpected request path: {path}"), + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }, + ); + let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap(); + let error = table + .add(vec![batch]) + .write_parallelism(2) + .execute() + .await + .unwrap_err(); + let expected = request_id.lock().unwrap(); + assert!(!expected.is_empty()); + match error { + Error::Http { request_id, .. } => assert_eq!(request_id, *expected), + other => panic!("Expected Http error, got {other:?}"), + } + } + #[tokio::test] async fn test_multipart_write_progress() { let callback_count = Arc::new(AtomicUsize::new(0)); From 9c161869e1b90f3e7733ff851d113f04935c309f Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 02:45:19 +0800 Subject: [PATCH 049/180] fix(node): respect transformers tokenizer option (#4457) ## Summary `tokenizer` is a documented option, but initialization always passed the model name to `AutoTokenizer.from_pretrained`. Preserve the resolved tokenizer option, fall back to the model name when it is omitted, and identify the selected tokenizer in loading errors. Add five initialization regressions covering default model/tokenizer selection, an explicit tokenizer, registry variables, and tokenizer loading errors. They run in native Node child processes so the real ESM import works without changing Jest/CI flags. Model loaders are mocked and local/remote model access is disabled; these tests do not download models or test inference. ## Validation - Before: three regressions fail and two default-selection controls pass. After: all five pass. - New tests plus the existing registry and embedding-registry suites: 48 passed. - TypeScript compilation, changed-file Biome checks, and `pnpm run docs` pass; generated tracked docs are unchanged. - Checked with Node 24.14.1 / pnpm 11.1.1 on Linux, both with default Jest flags and the Linux CI ESM flag. The native binding and declarations came from the official `0.40.0-beta.13` packages, with registry integrity verified. Rebuilding Rust from source timed out during Cargo metadata resolution, before compilation; no Rust code is changed. --- .../fixtures/transformers_tokenizer.cjs | 66 +++++++++++++++++++ nodejs/__test__/transformers.test.ts | 26 ++++++++ nodejs/lancedb/embedding/transformers.ts | 6 +- 3 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 nodejs/__test__/fixtures/transformers_tokenizer.cjs create mode 100644 nodejs/__test__/transformers.test.ts diff --git a/nodejs/__test__/fixtures/transformers_tokenizer.cjs b/nodejs/__test__/fixtures/transformers_tokenizer.cjs new file mode 100644 index 000000000..bf30cc229 --- /dev/null +++ b/nodejs/__test__/fixtures/transformers_tokenizer.cjs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const assert = require("node:assert/strict"); +const { + TransformersEmbeddingFunction, +} = require("../../dist/embedding/transformers"); +const { getRegistry } = require("../../dist/embedding/registry"); + +async function main() { + const transformers = await import("@huggingface/transformers"); + // Never fetch a real model, including if a loader mock stops intercepting. + transformers.env.allowRemoteModels = false; + transformers.env.allowLocalModels = false; + const modelCalls = []; + const tokenizerCalls = []; + const testCase = Number(process.argv[2]); + const defaults = "Xenova/all-MiniLM-L6-v2"; + const cases = [ + [{}, defaults, defaults], + [{ model: "test/model" }, "test/model", "test/model"], + [ + { model: "test/model", tokenizer: "test/tokenizer" }, + "test/model", + "test/tokenizer", + ], + [ + { model: "test/model", tokenizer: "$var:tokenizer" }, + "test/model", + "test/tokenizer", + ], + [ + { model: "test/model", tokenizer: "test/tokenizer" }, + "test/model", + "test/tokenizer", + ], + ]; + assert.ok( + Number.isInteger(testCase) && testCase >= 0 && testCase < cases.length, + ); + transformers.AutoModel.from_pretrained = async (...args) => { + modelCalls.push(args); + return {}; + }; + transformers.AutoTokenizer.from_pretrained = async (...args) => { + tokenizerCalls.push(args); + if (testCase === 4) throw new Error("missing tokenizer"); + return {}; + }; + getRegistry().setVar("tokenizer", "test/tokenizer"); + const [options, model, tokenizer] = cases[testCase]; + const fn = new TransformersEmbeddingFunction(options); + if (testCase === 4) { + await assert.rejects(fn.init(), /error loading tokenizer test\/tokenizer/); + } else { + await fn.init(); + } + assert.deepEqual(modelCalls, [[model, { dtype: "fp32" }]]); + assert.deepEqual(tokenizerCalls, [[tokenizer]]); + assert.deepEqual(fn.toJSON(), options); +} + +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/nodejs/__test__/transformers.test.ts b/nodejs/__test__/transformers.test.ts new file mode 100644 index 000000000..ac66c1499 --- /dev/null +++ b/nodejs/__test__/transformers.test.ts @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { execFileSync } from "node:child_process"; +import { resolve } from "node:path"; + +describe("Transformers embedding tokenizer selection", () => { + // Run init's native ESM import outside Jest's CommonJS sandbox, like a user. + // The fixture mocks model loading and forbids local/remote model access. + test.each([ + ["default model", 0], + ["default tokenizer", 1], + ["custom tokenizer", 2], + ["tokenizer registry variable", 3], + ["tokenizer loading error", 4], + ])("handles %s", (_name, testCase) => { + execFileSync( + process.execPath, + [ + resolve(__dirname, "fixtures", "transformers_tokenizer.cjs"), + String(testCase), + ], + { stdio: "pipe", timeout: 15_000 }, + ); + }); +}); diff --git a/nodejs/lancedb/embedding/transformers.ts b/nodejs/lancedb/embedding/transformers.ts index 06043ea7c..7e57bc6bc 100644 --- a/nodejs/lancedb/embedding/transformers.ts +++ b/nodejs/lancedb/embedding/transformers.ts @@ -38,6 +38,7 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction< #model?: import("@huggingface/transformers").PreTrainedModel; #tokenizer?: import("@huggingface/transformers").PreTrainedTokenizer; #modelName: XenovaTransformerOptions["model"]; + #tokenizerName: string; #initialized = false; #tokenizerOptions: XenovaTransformerOptions["tokenizerOptions"]; #ndims?: number; @@ -58,6 +59,7 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction< this.#ndims = options.ndims; this.#modelName = modelName; + this.#tokenizerName = options.tokenizer ?? modelName; } async init() { @@ -86,11 +88,11 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction< } try { this.#tokenizer = await transformers.AutoTokenizer.from_pretrained( - this.#modelName, + this.#tokenizerName, ); } catch (e) { throw new Error( - `error loading tokenizer for ${this.#modelName}. Make sure you are using a wasm compatible model:\nReason: ${e}`, + `error loading tokenizer ${this.#tokenizerName}. Make sure you are using a wasm compatible model:\nReason: ${e}`, ); } this.#initialized = true; From e1e87e1cae05a39ccb736c516405649c1ce92380 Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:45:36 +0800 Subject: [PATCH 050/180] fix(python): preserve logical rows from Hugging Face datasets (#4461) Hugging Face `select`, `filter`, and `shuffle` can retain a physical Arrow table while storing logical row selection/order in an indices table. Ingesting the physical table then silently writes excluded rows or the wrong order and can lose duplicate selections. Read indexed datasets through bounded Arrow-format iteration, and keep the existing direct batch path for datasets without indices. Apply the same conversion to sync/async table creation and additions, including DatasetDict splits. The conversion does not mutate the user's formatting settings. Regression coverage includes reordered/duplicate selections, filtering, shuffling, empty selections, projected numpy/pandas/Arrow formatting, DatasetDicts, rescanning, and bounded batches. Validation on base d864e7198fe55a4e5fbe747fee574737fa102aab with its byte-identical native/config: - Python 3.11 full CI test selection: 1564 passed, 36 skipped, 68 deselected; 162.51s pytest /171.68s wall. - Python 3.13 full CI test selection: 1521 passed, 37 skipped, 68 deselected; 160.32s pytest /163.74s wall. Optional HF tests were skipped in this environment. - Python 3.13 complete doctest command: 71 passed, 6 skipped; 8.42s pytest /12.14s wall. - Python 3.11 HF regression module from a candidate wheel: 43 passed; the same regression module on the unchanged baseline gives 24 failed /19 passed. - Ruff check/format, repository pre-commit hooks, pyright with the source import path, and `git diff --check` passed. This is a Python-only change. Native binaries were reused from the verified baseline; no new native build or external-service integration tests were run. The separate schema-metadata preservation change in #4451 addresses a different conversion defect. The target branch currently includes newer native changes than the verified base. Latest-main native compatibility, Linux CI, and remote-service tests remain for CI/maintainer validation. Prepared with AI assistance (gpt-6.1-sol). --- python/python/lancedb/scannable.py | 20 ++++- python/python/lancedb/table.py | 6 +- python/python/tests/test_huggingface.py | 103 ++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 5 deletions(-) diff --git a/python/python/lancedb/scannable.py b/python/python/lancedb/scannable.py index baf8e0c2b..9a6f71a5d 100644 --- a/python/python/lancedb/scannable.py +++ b/python/python/lancedb/scannable.py @@ -276,6 +276,14 @@ def _from_iterable(data: Iterator) -> Scannable: _registered_modules: set[str] = set() +def _hf_batches(data): + if data._indices is None: + yield from data.data.to_batches() + else: + for table in data.with_format("arrow").iter(batch_size=1000): + yield from table.to_batches() + + def _register_optional_converters(): """Register converters for optional dependencies that are already imported.""" @@ -323,7 +331,15 @@ def _register_optional_converters(): def _from_hf_dataset(data: HFDataset) -> Scannable: table = data.data.table # Access underlying Arrow table return Scannable( - schema=table.schema, num_rows=len(data), reader=table.to_reader + schema=table.schema, + num_rows=len(data), + reader=( + table.to_reader + if data._indices is None + else lambda: pa.RecordBatchReader.from_batches( + table.schema, _hf_batches(data) + ) + ), ) @to_scannable.register(HFDatasetDict) @@ -335,7 +351,7 @@ def _register_optional_converters(): def gen(): for split_name, dataset in data.items(): - for batch in dataset.data.to_batches(): + for batch in _hf_batches(dataset): split_arr = pa.array( [split_name] * len(batch), type=pa.string() ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 9b96a1b2a..f9cfac6e1 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -28,7 +28,7 @@ from typing import ( ) from urllib.parse import urlparse -from lancedb.scannable import _register_optional_converters, to_scannable +from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable from . import __version__ from ._blob import ( @@ -400,7 +400,7 @@ def _into_pyarrow_reader( if _check_for_hugging_face(data): if isinstance(data, datasets.Dataset): schema = data.features.arrow_schema - return pa.RecordBatchReader.from_batches(schema, data.data.to_batches()) + return pa.RecordBatchReader.from_batches(schema, _hf_batches(data)) elif isinstance(data, datasets.dataset_dict.DatasetDict): schema = _schema_from_hf(data, None) if "split" not in schema.names: @@ -1195,7 +1195,7 @@ def _to_batches_with_split(data): with an extra `split` column """ for key, dataset in data.items(): - for batch in dataset.data.to_batches(): + for batch in _hf_batches(dataset): table = pa.Table.from_batches([batch]) if "split" not in table.column_names: table = table.append_column( diff --git a/python/python/tests/test_huggingface.py b/python/python/tests/test_huggingface.py index 9b597bbc9..91421b79c 100644 --- a/python/python/tests/test_huggingface.py +++ b/python/python/tests/test_huggingface.py @@ -129,3 +129,106 @@ def test_generator(tmp_path: Path): assert len(tbl) == 2 assert tbl.schema == ds.features.arrow_schema + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("operation", ["create", "add"]) +@pytest.mark.parametrize( + "selection", + ["normal", "contiguous", "selected", "duplicates", "filtered", "shuffled", "empty"], +) +async def test_write_selected_hf_dataset(tmp_path, asynchronous, operation, selection): + source = datasets.Dataset.from_dict({"id": list(range(5)), "text": list("abcde")}) + data = { + "normal": source, + "contiguous": source.select(range(1, 4)), + "selected": source.select([4, 1]), + "duplicates": source.select([2, 2, 0]), + "filtered": source.filter(lambda row: row["id"] % 2 == 1), + "shuffled": source.shuffle(seed=42), + "empty": source.select([]), + }[selection] + expected = data.to_list() + if asynchronous: + db = await lancedb.connect_async(tmp_path) + if operation == "create": + table = await db.create_table("selected", data) + else: + table = await db.create_table("selected", schema=data.features.arrow_schema) + await table.add(data) + actual = await table.to_arrow() + else: + db = lancedb.connect(tmp_path) + if operation == "create": + table = db.create_table("selected", data) + else: + table = db.create_table("selected", schema=data.features.arrow_schema) + table.add(data) + actual = table.to_arrow() + assert actual.to_pylist() == expected + assert actual.schema.equals(data.features.arrow_schema, check_metadata=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("operation", ["create", "add"]) +async def test_write_selected_hf_splits(tmp_path, asynchronous, operation): + source = datasets.Dataset.from_dict({"id": list(range(5)), "text": list("abcde")}) + data = datasets.DatasetDict( + { + "train": source.select([4, 1]), + "test": source.select([3, 0, 2]), + "empty": source.select([]), + } + ) + expected = [ + dict(row, split=split) + for split, dataset in data.items() + for row in dataset.to_list() + ] + schema = source.features.arrow_schema.append(pa.field("split", pa.string())) + if asynchronous: + db = await lancedb.connect_async(tmp_path) + if operation == "create": + table = await db.create_table("splits", data) + else: + table = await db.create_table("splits", schema=schema) + await table.add(data) + actual = await table.to_arrow() + else: + db = lancedb.connect(tmp_path) + if operation == "create": + table = db.create_table("splits", data) + else: + table = db.create_table("splits", schema=schema) + table.add(data) + actual = table.to_arrow() + assert actual.to_pylist() == expected + assert actual.schema.equals(schema, check_metadata=True) + + +@pytest.mark.parametrize("format_type", [None, "numpy", "pandas", "arrow"]) +@pytest.mark.parametrize("empty", [False, True]) +def test_selected_hf_reader_is_rescannable(format_type, empty): + from lancedb.scannable import _register_optional_converters, to_scannable + + source = datasets.Dataset.from_dict( + {"id": list(range(2105)), "text": [str(i) for i in range(2105)]} + ) + indices = [] if empty else list(reversed(range(2105))) + [1, 1] + data = source.select(indices).with_format(format_type, columns=["id"]) + original_format = data.format + expected = source.select(indices).to_list() + _register_optional_converters() + scannable = to_scannable(data) + assert scannable.rescannable + assert scannable.num_rows == len(expected) + for _ in range(2): + batches = list(scannable.reader()) + if not empty: + assert all(batch.num_rows <= 1000 for batch in batches) + actual = pa.Table.from_batches(batches, schema=scannable.schema) + assert actual.to_pylist() == expected + assert actual.schema.equals(data.features.arrow_schema, check_metadata=True) + assert data.format == original_format From 8552fd2f5b8213ce6be5fdd9d3cdfe7978f10a1d Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:45:51 +0800 Subject: [PATCH 051/180] fix(python): prevent embedding aliases from replacing registered functions (#4462) Registering a different embedding class under an existing alias silently replaced the original class. A deterministic real local SDK table reproduction changed the top result for the same query from alpha to beta after reopening the persisted table. Check the resolved key before inserting a class. Preserve repeated registration of the same class under the same nonempty explicit alias as idempotent, as existing SDK tests rely on it. Repeated implicit class-name registration, including an empty alias, still raises KeyError. Failed registration preserves the mapping and class metadata. Existing embedding tests receive isolated registry mappings; test_util.py remains unchanged. Eight regression cases cover different-class alias collisions, alias/class-name collisions, implicit and empty-alias duplicates, equal class names under distinct aliases, explicit-alias idempotence, and real local creation/reopening/search. This is independent of #4356, which fixes no-alias serialization. Validation on 52a1ccee5a5b8dbfff8568abafb57099c55383b9: - Original registry plus eight new cases: 4 failed, 4 passed; Python 3.11.14; exit 1; 2.902604 s. Candidate plus full utility module: 83 passed, 1 skipped; exit 0; 3.144414 s. - Python 3.11.14 full official non-slow/non-S3 suite: 1532 passed, 36 skipped, 68 deselected; exit 0; 152.631543 s. - Python 3.13.11 full official non-slow/non-S3 suite: 1529 passed, 37 skipped, 68 deselected; exit 0; 163.970571 s. - Official Python 3.13 doctest with existing compatible embeddings/torch/mlx dependencies: 71 passed, 6 skipped; exit 0; 9.635034 s. - Pyright with matching interpreter/source path: 0 errors, 0 warnings; exit 0; 4.299743 s. - Repository Ruff 0.9.9 check and format: exit 0; 157 files already formatted; 0.047418 s and 0.016815 s. Pre-commit changed files: four hooks passed, two inapplicable skipped; exit 0; 0.406136 s. git diff --check passed. Base is official d864e7198fe55a4e5fbe747fee574737fa102aab with its verified matching native extension reused read-only. All 174 native/config paths are unchanged from that base. Latest main bbc4aebe55b69471fa1bd7655599b8d2e3f9352c has byte-identical registry production code; its complete native build was not run. Verification was macOS arm64, with optional dependency/service skips above; Linux/Windows CI remains remote verification. Exact commands, cwd, identities, raw logs and intermediate failures are in the local manifest. The earlier strict same-class check caused 13 utility failures and was corrected in production; it is not described as a baseline failure. Reproduction commands after preparing the repository's declared environment (from repository root unless noted): ```sh PYTHONPATH=python/python .venv/bin/python -m pytest python/python/tests -m 'not slow and not s3_test' -q -rs -p no:cacheprovider PYTHONPATH=python/python .venv/bin/python -m pytest --doctest-modules python/python/lancedb -q --tb=short (cd python && PYTHONPATH=python ../.venv/bin/pyright --pythonpath ../.venv/bin/python) .venv/bin/ruff check . .venv/bin/ruff format --check . .venv/bin/python -m pre_commit run --files python/python/lancedb/embeddings/registry.py python/python/tests/test_embedding_registry.py python/python/tests/test_embeddings.py git diff --check ``` These relative commands describe reproducible source/cwd equivalents. The recorded local runs used absolute paths to existing Python 3.11.14/3.13.11 environments, a verified matching reused native extension, and read-only compatible optional-dependency cache paths for the 3.13 doctest, rather than a newly installed `.venv`. Full tests used separate task-private working directories and `--basetemp` directories to avoid cross-run database collisions. Implemented with assistance from gpt-6.1-sol; the final diff was reviewed locally by the collaborating agents. --- python/python/lancedb/embeddings/registry.py | 6 +- .../python/tests/test_embedding_registry.py | 88 +++++++++++++++++++ python/python/tests/test_embeddings.py | 6 ++ 3 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 python/python/tests/test_embedding_registry.py diff --git a/python/python/lancedb/embeddings/registry.py b/python/python/lancedb/embeddings/registry.py index 3b940fe2e..728ff36da 100644 --- a/python/python/lancedb/embeddings/registry.py +++ b/python/python/lancedb/embeddings/registry.py @@ -69,9 +69,11 @@ class EmbeddingFunctionRegistry: def decorator(cls): if not issubclass(cls, EmbeddingFunction): raise TypeError("Must be a subclass of EmbeddingFunction") - if cls.__name__ in self._functions: - raise KeyError(f"{cls.__name__} was already registered") key = alias or cls.__name__ + if key in self._functions and ( + not alias or self._functions[key] is not cls + ): + raise KeyError(f"{key} was already registered") self._functions[key] = cls # Store the name the class is registered under, so the table # metadata written for it can be looked up again when reading. diff --git a/python/python/tests/test_embedding_registry.py b/python/python/tests/test_embedding_registry.py new file mode 100644 index 000000000..07c10bd7e --- /dev/null +++ b/python/python/tests/test_embedding_registry.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +import pytest +from lancedb.embeddings.base import TextEmbeddingFunction +from lancedb.embeddings.registry import EmbeddingFunctionRegistry, get_registry +from lancedb.pydantic import LanceModel, Vector + + +class FirstEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [[1.0, 0.0] if text == "alpha" else [0.0, 1.0] for text in texts] + + +class SecondEmbedding(FirstEmbedding): + def generate_embeddings(self, texts): + return [[0.0, 1.0] if text == "alpha" else [1.0, 0.0] for text in texts] + + +@pytest.mark.parametrize( + "first_alias,second_alias,second_class", + [ + ("shared", "shared", SecondEmbedding), + (None, "FirstEmbedding", SecondEmbedding), + ("SecondEmbedding", None, SecondEmbedding), + (None, None, FirstEmbedding), + ("", "", FirstEmbedding), + ], +) +def test_duplicate_registration_preserves_original( + first_alias, second_alias, second_class +): + registry = EmbeddingFunctionRegistry() + registry.register(first_alias)(FirstEmbedding) + key = first_alias or "FirstEmbedding" + original_alias = FirstEmbedding.__embedding_function_registry_alias__ + second_attributes = dict(second_class.__dict__) + with pytest.raises(KeyError, match=f"{key} was already registered"): + registry.register(second_alias)(second_class) + assert registry.get(key) is FirstEmbedding + assert FirstEmbedding.__embedding_function_registry_alias__ == original_alias + assert dict(second_class.__dict__) == second_attributes + + +def test_class_name_does_not_collide_with_distinct_alias(): + registry = EmbeddingFunctionRegistry() + registry.register()(FirstEmbedding) + same_name = type("FirstEmbedding", (SecondEmbedding,), {}) + registry.register("separate")(same_name) + assert registry.get("FirstEmbedding") is FirstEmbedding + assert registry.get("separate") is same_name + + +def test_same_class_explicit_alias_registration_is_idempotent(): + registry = EmbeddingFunctionRegistry() + assert registry.register("shared")(FirstEmbedding) is FirstEmbedding + attributes = dict(FirstEmbedding.__dict__) + assert registry.register("shared")(FirstEmbedding) is FirstEmbedding + assert registry.get("shared") is FirstEmbedding + assert dict(FirstEmbedding.__dict__) == attributes + + +def test_alias_collision_does_not_change_persisted_table(tmp_path, monkeypatch): + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + alias = "test-alias-collision-persisted-table" + registry.register(alias)(FirstEmbedding) + function = FirstEmbedding.create(max_retries=0) + + class Row(LanceModel): + text: str = function.SourceField() + vector: Vector(2) = function.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table( + "rows", schema=Row, data=[{"text": "alpha"}, {"text": "beta"}] + ) + assert table.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + assert registry.register(alias)(FirstEmbedding) is FirstEmbedding + with pytest.raises(KeyError, match=f"{alias} was already registered"): + registry.register(alias)(SecondEmbedding) + reopened = lancedb.connect(tmp_path).open_table("rows") + assert isinstance(reopened.embedding_functions["vector"].function, FirstEmbedding) + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 51907f141..d6d128845 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -23,6 +23,12 @@ from lancedb.embeddings.utils import retry from lancedb.pydantic import LanceModel, Vector +@pytest.fixture(autouse=True) +def isolated_embedding_registry(monkeypatch): + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + + def mock_embed_func(input_data): return [np.random.randn(128).tolist() for _ in range(len(input_data))] From 554dc01f4d653f95bf044059e1f88ad7e3e71457 Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:46:06 +0800 Subject: [PATCH 052/180] fix(python): preserve custom embedding field metadata (#4463) `SourceField(json_schema_extra={...})` and `VectorField(json_schema_extra={...})` currently raise `TypeError` because the helper supplies the same `Field` keyword twice. Explicit `None` also fails. This prevents users from adding ordinary Pydantic JSON schema metadata to embedding fields. Copy and merge the supplied dictionary before attaching the helper's internal embedding identity. Caller dictionaries remain unchanged, and reserved embedding keys retain the real function. Other `Field` arguments keep their existing behavior. This change covers dictionaries and `None`; callable `json_schema_extra` remains unsupported by the existing embedding metadata reader and is outside this fix. The 11 regression cases exercise both helpers, empty/custom/None metadata, reserved-key collisions, other Field arguments, and a deterministic local embedding model through JSON schema generation, table creation, reopening, and search. On the original source, 9 fail and 2 controls pass; the candidate passes all 11 on Python 3.11 and 3.13. Validation uses read-only reused environments and the native extension built for d864e719. The production helper is byte-identical to current main bbc4aebe before this fix; no current-main native rebuild was performed. The branch contains only this helper fix and its regression test, independently based on d864e719. Reproducible checkout commands below assume the documented environment is installed as `.venv`; the actual local runs used existing interpreters through absolute paths and isolated generated-data working directories: ```sh PYTHONPATH=python/python .venv/bin/python -m pytest python/python/tests -m 'not slow and not s3_test' -q -rs -p no:cacheprovider PYTHONPATH=python/python .venv/bin/python -m pytest --doctest-modules python/python/lancedb -q --tb=short (cd python && PYTHONPATH=python ../.venv/bin/pyright --pythonpath ../.venv/bin/python) git diff --check .venv/bin/ruff check . .venv/bin/ruff format --check . .venv/bin/python -m pre_commit run --files python/python/lancedb/embeddings/base.py python/python/tests/test_embedding_field_metadata.py ``` Doctests require the repository's tests/dev/embeddings dependencies, including mlx on this platform. All checks below ran against frozen head 3fa6820. Implemented with assistance from gpt-6.1-sol; the final diff was reviewed locally. Frozen-head validation (all exit 0): - Python 3.11 full: 1535 passed, 36 skipped, 68 deselected; 190.272415 seconds wall time. - Python 3.13 full: 1532 passed, 37 skipped, 68 deselected; 249.289778 seconds wall time. - Python 3.13 doctests: 71 passed, 6 skipped; 10.391002 seconds wall time. - Pyright: 0 errors, 0 warnings; 4.884641 seconds wall time. - pre-commit: 4 passed, 2 skipped; 0.747764 seconds wall time. - Repository Ruff check: passed; 0.078177 seconds wall time. - Repository Ruff format: 157 files already formatted; 0.034561 seconds wall time. --- python/python/lancedb/embeddings/base.py | 8 +- .../tests/test_embedding_field_metadata.py | 84 +++++++++++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 python/python/tests/test_embedding_field_metadata.py diff --git a/python/python/lancedb/embeddings/base.py b/python/python/lancedb/embeddings/base.py index f26a940df..96ca6556c 100644 --- a/python/python/lancedb/embeddings/base.py +++ b/python/python/lancedb/embeddings/base.py @@ -239,7 +239,9 @@ class EmbeddingFunction(BaseModel, ABC): Creates a pydantic Field that can automatically annotate the source column for this embedding function """ - return Field(json_schema_extra={"source_column_for": self}, **kwargs) + json_schema_extra = dict(kwargs.pop("json_schema_extra", None) or {}) + json_schema_extra["source_column_for"] = self + return Field(json_schema_extra=json_schema_extra, **kwargs) def VectorField(self, **kwargs): """ @@ -250,7 +252,9 @@ class EmbeddingFunction(BaseModel, ABC): static type checkers. LanceDB will infer the fixed vector dimension from this embedding function. """ - return Field(json_schema_extra={"vector_column_for": self}, **kwargs) + json_schema_extra = dict(kwargs.pop("json_schema_extra", None) or {}) + json_schema_extra["vector_column_for"] = self + return Field(json_schema_extra=json_schema_extra, **kwargs) def __eq__(self, __value: object) -> bool: if not hasattr(__value, "__dict__"): diff --git a/python/python/tests/test_embedding_field_metadata.py b/python/python/tests/test_embedding_field_metadata.py new file mode 100644 index 000000000..68754ee35 --- /dev/null +++ b/python/python/tests/test_embedding_field_metadata.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import copy + +import lancedb +import pytest +from lancedb.embeddings.base import TextEmbeddingFunction +from lancedb.embeddings.registry import get_registry +from lancedb.pydantic import LanceModel, Vector + + +class LocalEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [[1.0, 0.0] if text == "alpha" else [0.0, 1.0] for text in texts] + + +@pytest.mark.parametrize( + "method,tag", + [("SourceField", "source_column_for"), ("VectorField", "vector_column_for")], +) +@pytest.mark.parametrize("extra", [None, {}, {"x-purpose": "retrieval"}]) +def test_embedding_field_preserves_extra_metadata(method, tag, extra): + function = LocalEmbedding.create(max_retries=0) + original = copy.deepcopy(extra) + field = getattr(function, method)(json_schema_extra=extra) + assert extra == original + assert field.json_schema_extra[tag] is function + for key, value in (extra or {}).items(): + assert field.json_schema_extra[key] == value + + +@pytest.mark.parametrize( + "method,tag", + [("SourceField", "source_column_for"), ("VectorField", "vector_column_for")], +) +def test_extra_metadata_cannot_replace_embedding_identity(method, tag): + function = LocalEmbedding.create(max_retries=0) + supplied = {tag: "caller value", "x-purpose": "retrieval"} + field = getattr(function, method)(json_schema_extra=supplied) + assert supplied[tag] == "caller value" + assert field.json_schema_extra[tag] is function + assert field.json_schema_extra["x-purpose"] == "retrieval" + + +@pytest.mark.parametrize("method", ["SourceField", "VectorField"]) +def test_embedding_field_preserves_other_field_arguments(method): + function = LocalEmbedding.create(max_retries=0) + field = getattr(function, method)(title="Custom title", description="Custom field") + assert field.title == "Custom title" + assert field.description == "Custom field" + + +def test_extra_metadata_preserves_schema_and_local_embedding(tmp_path, monkeypatch): + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + registry.register("test-embedding-field-extra")(LocalEmbedding) + function = LocalEmbedding.create(max_retries=0) + + class Row(LanceModel): + text: str = function.SourceField(json_schema_extra={"x-purpose": "source"}) + vector: Vector(2) = function.VectorField( + json_schema_extra={"x-purpose": "embedding"} + ) + + json_schema = Row.model_json_schema() + assert json_schema["properties"]["text"]["x-purpose"] == "source" + assert json_schema["properties"]["vector"]["x-purpose"] == "embedding" + configs = Row.parse_embedding_functions() + assert len(configs) == 1 + assert configs[0].function is function + assert configs[0].source_column == "text" + assert configs[0].vector_column == "vector" + db = lancedb.connect(tmp_path) + table = db.create_table( + "rows", schema=Row, data=[{"text": "alpha"}, {"text": "beta"}] + ) + assert table.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + reopened = lancedb.connect(tmp_path).open_table("rows") + assert isinstance(reopened.embedding_functions["vector"].function, LocalEmbedding) + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" From 694942a1e0dcc85927ecb6c6362fb4003af8a50a Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:46:21 +0800 Subject: [PATCH 053/180] fix(python): convert tuple and NumPy datetime update values (#4464) `Table.update` and `AsyncTable.update` convert Python values into SQL literals. Tuple arrays and `numpy.datetime64` values currently raise `NotImplementedError`, even when the same values can be ingested into the corresponding local Arrow columns. Register tuples with the existing recursive list converter and format NumPy timestamps as complete nanosecond ISO strings with an explicit UTC offset. `NaT` becomes SQL NULL; subnanosecond units raise an explicit error rather than silently losing precision. Regression tests exercise local synchronous and asynchronous create/update/Arrow reads, date and timestamp units, nanosecond precision, NULL, and existing list/ndarray/Python datetime behavior. Nested and empty tuple arrays are compared with equivalent lists on the actual SDK: successful results must match, and the matching d864 native engine's existing list limitations must produce the same stable error without changing either table. This does not change SQL map handling. Implemented with assistance from gpt-6.1-sol; final diff reviewed locally. Local verification uses Python 3.11.14 and 3.13.11 in existing read-only development environments with the native extension matching base d864e7198fe55a4e5fbe747fee574737fa102aab. The current main `util.py` is byte-identical to that base; current-main native code has not been rebuilt. Slow tests, S3 tests, remote production services and other operating systems are not validated here. Reproducible commands after preparing the repository's documented development environment (these relative `.venv` examples describe equivalent commands; the local runs use absolute read-only environment paths and fresh task-private working directories): ```sh PYTHONPATH=python/python .venv/bin/python -m pytest python/python/tests/test_util_update_values.py -q -p no:cacheprovider PYTHONPATH=python/python .venv/bin/python -m pytest python/python/tests -m 'not slow and not s3_test' -q -rs -p no:cacheprovider PYTHONPATH=python/python .venv/bin/python -m pytest --doctest-modules python/python/lancedb -q --tb=short (cd python && PYTHONPATH=python ../.venv/bin/pyright --pythonpath ../.venv/bin/python) .venv/bin/ruff check . .venv/bin/ruff format --check . .venv/bin/python -m pre_commit run --files python/python/lancedb/util.py python/python/tests/test_util_update_values.py git diff --check d864e7198fe55a4e5fbe747fee574737fa102aab HEAD ``` Frozen commit `33e74d0ed3d90a20419816a3f1fc15ff038db452` passed all local gates: Python 3.11.14 full suite 1,590 passed / 36 skipped / 68 deselected; Python 3.13.11 full suite 1,587 passed / 37 skipped / 68 deselected. All 66 added SDK cases passed on both runtimes. Python 3.13 doctests: 71 passed / 6 skipped. Pyright: 0 errors / 0 warnings. Ruff, formatting, applicable pre-commit hooks, two-file syntax/import checks and the PR merge-base diff check exited 0. Exact local argv/runtime/wall metadata and raw logs are retained in the acceptance manifest. The follow-up addresses the non-UTC timestamp issue reported in review: an update previously changed the epoch ingested by Arrow (New York +5 hours, Tokyo -9 hours). On the published original head, 4 non-UTC sync/async SDK regressions failed and 12 naive/UTC/NaT controls passed (exit 1; wall 3.713 seconds). Formatting with `timezone="UTC"` emits a Z suffix and preserves the ingested nanosecond instant independently of the destination timezone. This is consistent with the Arrow-aligned epoch convention in merged #3775. The original 50 cases also remain green. Full-suite wall times were 158.619 seconds (3.11) and 163.631 seconds (3.13), both exit 0. --- python/python/lancedb/util.py | 12 +- .../python/tests/test_util_update_values.py | 215 ++++++++++++++++++ 2 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 python/python/tests/test_util_update_values.py diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index f1a652924..a043f0c8d 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -426,7 +426,8 @@ def _(value: date): @value_to_sql.register(list) -def _(value: list): +@value_to_sql.register(tuple) +def _(value: Union[list, tuple]): return "[" + ", ".join(map(value_to_sql, value)) + "]" @@ -471,6 +472,15 @@ def _(value: np.floating): return value_to_sql(float(value)) +@value_to_sql.register(np.datetime64) +def _(value: np.datetime64): + if np.isnat(value): + return value_to_sql(None) + if np.datetime_data(value.dtype)[0] in ("ps", "fs", "as"): + raise ValueError("SQL timestamps cannot preserve sub-nanosecond precision") + return value_to_sql(str(np.datetime_as_string(value, unit="ns", timezone="UTC"))) + + def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted diff --git a/python/python/tests/test_util_update_values.py b/python/python/tests/test_util_update_values.py new file mode 100644 index 000000000..fdef867da --- /dev/null +++ b/python/python/tests/test_util_update_values.py @@ -0,0 +1,215 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import date, datetime + +import lancedb +import numpy as np +import pyarrow as pa +import pytest + + +ARRAY_VALUES = [ + ((1.0, 2.0), [1.0, 2.0]), + ([1.0, 2.0], [1.0, 2.0]), + (np.array([1.0, 2.0]), [1.0, 2.0]), + (None, None), +] + + +@pytest.mark.parametrize("value,expected", ARRAY_VALUES) +def test_update_array_values(tmp_path, value, expected): + dtype = pa.list_(pa.float64()) + db = lancedb.connect(tmp_path) + table = db.create_table( + "values", pa.table({"array": pa.array([[0.0, 0.0]], type=dtype)}) + ) + table.update(values={"array": value}) + assert table.to_arrow()["array"].to_pylist() == [expected] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("value,expected", ARRAY_VALUES) +async def test_update_array_values_async(tmp_path, value, expected): + dtype = pa.list_(pa.float64()) + db = await lancedb.connect_async(tmp_path) + table = await db.create_table( + "values", pa.table({"array": pa.array([[0.0, 0.0]], type=dtype)}) + ) + await table.update({"array": value}) + assert (await table.to_arrow())["array"].to_pylist() == [expected] + + +TIME_VALUES = [ + np.datetime64("2025", "Y"), + np.datetime64("2025-01", "M"), + np.datetime64("2025-01-02", "D"), + np.datetime64("2025-01-02T03", "h"), + np.datetime64("2025-01-02T03:04", "m"), + np.datetime64("2025-01-02T03:04:05", "s"), + np.datetime64("2025-01-02T03:04:05.123", "ms"), + np.datetime64("2025-01-02T03:04:05.123456", "us"), + np.datetime64("2025-01-02T03:04:05.123456789", "ns"), + np.datetime64("NaT", "ns"), + datetime(2025, 1, 2, 3, 4, 5, 123456), + None, +] + + +def expected_time(value): + if value is None or isinstance(value, np.datetime64) and np.isnat(value): + return None + return int(np.datetime64(value, "ns").astype(np.int64)) + + +@pytest.mark.parametrize("value", TIME_VALUES) +def test_update_timestamp_values(tmp_path, value): + db = lancedb.connect(tmp_path) + data = pa.table({"time": pa.array([datetime(2025, 1, 1)], type=pa.timestamp("ns"))}) + table = db.create_table("times", data) + table.update(values={"time": value}) + assert table.to_arrow()["time"].cast(pa.int64()).to_pylist() == [ + expected_time(value) + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("value", TIME_VALUES) +async def test_update_timestamp_values_async(tmp_path, value): + db = await lancedb.connect_async(tmp_path) + data = pa.table({"time": pa.array([datetime(2025, 1, 1)], type=pa.timestamp("ns"))}) + table = await db.create_table("times", data) + await table.update({"time": value}) + assert (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() == [ + expected_time(value) + ] + + +@pytest.mark.parametrize("values", [[[1, 2], [3, 4]], []]) +def test_nested_array_tuple_matches_list(tmp_path, values): + db = lancedb.connect(tmp_path) + data = pa.table( + {"array": pa.array([[[0, 0]]], type=pa.list_(pa.list_(pa.int64())))} + ) + control = db.create_table("list_values", data) + candidate = db.create_table("tuple_values", data) + tuples = tuple(tuple(value) for value in values) + try: + control.update(values={"array": values}) + except ValueError as error: + reason = ( + "Expected a literal value in array" if values else "concat requires input" + ) + assert reason in str(error) + with pytest.raises(ValueError, match=reason): + candidate.update(values={"array": tuples}) + assert control.to_arrow().equals(data) + assert candidate.to_arrow().equals(data) + else: + candidate.update(values={"array": tuples}) + assert candidate.to_arrow().equals(control.to_arrow()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("values", [[[1, 2], [3, 4]], []]) +async def test_nested_array_tuple_matches_list_async(tmp_path, values): + db = await lancedb.connect_async(tmp_path) + data = pa.table( + {"array": pa.array([[[0, 0]]], type=pa.list_(pa.list_(pa.int64())))} + ) + control = await db.create_table("list_values", data) + candidate = await db.create_table("tuple_values", data) + tuples = tuple(tuple(value) for value in values) + try: + await control.update({"array": values}) + except ValueError as error: + reason = ( + "Expected a literal value in array" if values else "concat requires input" + ) + assert reason in str(error) + with pytest.raises(ValueError, match=reason): + await candidate.update({"array": tuples}) + assert (await control.to_arrow()).equals(data) + assert (await candidate.to_arrow()).equals(data) + else: + await candidate.update({"array": tuples}) + assert (await candidate.to_arrow()).equals(await control.to_arrow()) + + +@pytest.mark.parametrize("unit", ["ps", "fs", "as"]) +def test_subnanosecond_update_does_not_round(tmp_path, unit): + db = lancedb.connect(tmp_path) + data = pa.table({"time": pa.array([datetime(1970, 1, 1)], type=pa.timestamp("ns"))}) + table = db.create_table("precise", data) + with pytest.raises(ValueError, match="cannot preserve sub-nanosecond precision"): + table.update(values={"time": np.datetime64(1, unit)}) + assert table.to_arrow()["time"].cast(pa.int64()).to_pylist() == [0] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("unit", ["ps", "fs", "as"]) +async def test_subnanosecond_update_does_not_round_async(tmp_path, unit): + db = await lancedb.connect_async(tmp_path) + data = pa.table({"time": pa.array([datetime(1970, 1, 1)], type=pa.timestamp("ns"))}) + table = await db.create_table("precise", data) + with pytest.raises(ValueError, match="cannot preserve sub-nanosecond precision"): + await table.update({"time": np.datetime64(1, unit)}) + assert (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() == [0] + + +@pytest.mark.parametrize("unit", ["Y", "M", "W", "D"]) +def test_update_numpy_date_column(tmp_path, unit): + value = np.datetime64("2025-01-02", unit) + db = lancedb.connect(tmp_path) + table = db.create_table( + "dates", pa.table({"day": pa.array([date(1970, 1, 1)], type=pa.date32())}) + ) + table.update(values={"day": value}) + assert table.to_arrow()["day"].to_pylist() == [value.astype("datetime64[D]").item()] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("unit", ["Y", "M", "W", "D"]) +async def test_update_numpy_date_column_async(tmp_path, unit): + value = np.datetime64("2025-01-02", unit) + db = await lancedb.connect_async(tmp_path) + table = await db.create_table( + "dates", pa.table({"day": pa.array([date(1970, 1, 1)], type=pa.date32())}) + ) + await table.update({"day": value}) + assert (await table.to_arrow())["day"].to_pylist() == [ + value.astype("datetime64[D]").item() + ] + + +@pytest.mark.parametrize("timezone", [None, "UTC", "America/New_York", "Asia/Tokyo"]) +@pytest.mark.parametrize( + "value", + [np.datetime64("2025-01-02T03:04:05.123456789", "ns"), np.datetime64("NaT", "ns")], +) +def test_update_numpy_timestamp_matches_arrow_ingestion(tmp_path, timezone, value): + dtype = pa.timestamp("ns", tz=timezone) + ingested = pa.array(np.array([value]), type=dtype) + db = lancedb.connect(tmp_path) + table = db.create_table("timestamps", pa.table({"time": ingested})) + expected = table.to_arrow()["time"].cast(pa.int64()).to_pylist() + table.update(values={"time": value}) + assert table.to_arrow()["time"].cast(pa.int64()).to_pylist() == expected + + +@pytest.mark.asyncio +@pytest.mark.parametrize("timezone", [None, "UTC", "America/New_York", "Asia/Tokyo"]) +@pytest.mark.parametrize( + "value", + [np.datetime64("2025-01-02T03:04:05.123456789", "ns"), np.datetime64("NaT", "ns")], +) +async def test_update_numpy_timestamp_matches_arrow_ingestion_async( + tmp_path, timezone, value +): + dtype = pa.timestamp("ns", tz=timezone) + ingested = pa.array(np.array([value]), type=dtype) + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("timestamps", pa.table({"time": ingested})) + expected = (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() + await table.update({"time": value}) + assert (await table.to_arrow())["time"].cast(pa.int64()).to_pylist() == expected From 57a6cce6819913adfca2852bb795a1ec0dd4641c Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:46:34 +0800 Subject: [PATCH 054/180] fix(python): omit excluded model fields from persistence (#4465) LanceDB serializes Pydantic rows with `model_dump()`, which omits `Field(exclude=True)`, but currently constructs an Arrow schema containing those same fields. Creating a local table therefore fails when an excluded field is non-nullable, including defaulted transient fields and nested models. Filter unconditionally excluded fields when converting model schemas, including nested structs. Skip excluded source/vector fields when deriving embedding configuration so persistent metadata does not refer to absent columns. Keep `field_names()` as model-field reflection. Tests exercise implicit and explicit schemas, synchronous and asynchronous create/add/reopen/readback, nested fields, defaults and default factories, retained fields, and local deterministic embeddings. Excluded values are not persisted; `to_pydantic` restores declared defaults. Conditional exclusion and readback of required excluded fields without defaults are outside this change. Implemented with assistance from gpt-6.1-sol; final diff reviewed locally. Local validation reuses the native extension matching official base d864e7198fe55a4e5fbe747fee574737fa102aab. The current-main Pydantic module is byte-identical to that base, but current-main native code has not been rebuilt. Slow/S3 tests, remote services, and other operating systems were not validated. Reproducible commands after preparing the documented development environment (relative `.venv` examples are equivalent commands; actual local runs use absolute read-only environments and fresh task-private working directories): ```sh PYTHONPATH=python/python .venv/bin/python -m pytest python/python/tests/test_pydantic_excluded_fields.py -q -p no:cacheprovider PYTHONPATH=python/python .venv/bin/python -m pytest python/python/tests -m 'not slow and not s3_test' -q -rs -p no:cacheprovider PYTHONPATH=python/python .venv/bin/python -m pytest --doctest-modules python/python/lancedb -q --tb=short (cd python && PYTHONPATH=python ../.venv/bin/pyright --pythonpath ../.venv/bin/python) .venv/bin/ruff check . .venv/bin/ruff format --check . .venv/bin/python -m pre_commit run --files python/python/lancedb/pydantic.py python/python/tests/test_pydantic_excluded_fields.py git diff --check d864e7198fe55a4e5fbe747fee574737fa102aab HEAD ``` Final frozen-source results: - EXCLUDE_TARGET_COMPLETE_ORIGINAL_RED: Python 3.11.14, exit 1, 1.900076000019908 seconds, {"failed"=>7}. - EXCLUDE_TARGET_EMBEDDING: Python 3.11.14, exit 0, 1.3686820000002626 seconds, {"passed"=>7}. - EXCLUDE_TARGET313: Python 3.13.11, exit 0, 1.7214069999754429 seconds, {"passed"=>7}. - EXCLUDE_FULL311: Python 3.11.14, exit 0, 217.56785399999353 seconds, {"passed"=>1531, "skipped"=>36, "deselected"=>68, "warnings"=>251}. - EXCLUDE_FULL313: Python 3.13.11, exit 0, 197.93847399999504 seconds, {"passed"=>1528, "skipped"=>37, "deselected"=>68, "warnings"=>251}. - EXCLUDE_DOCTEST313: Python 3.13.11, exit 0, 11.8951390000002 seconds, {"passed"=>71, "skipped"=>6, "warnings"=>2}. - EXCLUDE_PYRIGHT: Python 3.13.11, exit 0, 5.808195000019623 seconds, {"warnings"=>0, "errors"=>0}. - EXCLUDE_PRECOMMIT: Python 3.11.14, exit 0, 0.5624079999979585 seconds, {"passed"=>4, "skipped"=>2}. - EXCLUDE_RUFF_FINAL: Ruff 0.9.9, exit 0, 0.06722099997568876 seconds, {}. - EXCLUDE_FORMAT_FINAL: Ruff 0.9.9, exit 0, 0.033322000002954155 seconds, {"files_formatted"=>157}. - EXCLUDE_SYNTAX: Python 3.11.14, exit 0, 0.031629999983124435 seconds, {"files_compiled"=>2}. - EXCLUDE_DIFF_CHECK: Git, exit 0, 0.024460999993607402 seconds, {}. --- python/python/lancedb/pydantic.py | 9 +- .../tests/test_pydantic_excluded_fields.py | 128 ++++++++++++++++++ 2 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 python/python/tests/test_pydantic_excluded_fields.py diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index bb70c9a67..db8723a99 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -268,7 +268,9 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType: def _pydantic_model_to_fields(model: pydantic.BaseModel) -> List[pa.Field]: return [ - _pydantic_to_field(name, field) for name, field in model.model_fields.items() + _pydantic_to_field(name, field) + for name, field in model.model_fields.items() + if field.exclude is not True ] @@ -501,6 +503,9 @@ class LanceModel(pydantic.BaseModel): vec_and_function = [] for name, field_info in cls.safe_get_fields().items(): + if field_info.exclude is True: + continue + func = get_extras(field_info, "vector_column_for") if func is not None: vec_and_function.append([name, func]) @@ -508,6 +513,8 @@ class LanceModel(pydantic.BaseModel): configs = [] for vec, func in vec_and_function: for source, field_info in cls.safe_get_fields().items(): + if field_info.exclude is True: + continue src_func = get_extras(field_info, "source_column_for") if src_func is func: # note we can't use == here since the function is a pydantic diff --git a/python/python/tests/test_pydantic_excluded_fields.py b/python/python/tests/test_pydantic_excluded_fields.py new file mode 100644 index 000000000..5f1fd1adb --- /dev/null +++ b/python/python/tests/test_pydantic_excluded_fields.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +import pytest +from pydantic import BaseModel, Field +from lancedb.pydantic import LanceModel + + +class Details(BaseModel): + label: str + transient: str = Field(default="nested default", exclude=True) + + +class Row(LanceModel): + id: int + details: Details + transient: str = Field(default="local default", exclude=True) + generated: list[str] = Field(default_factory=lambda: ["local"], exclude=True) + retained: str = Field(default="persisted", exclude=False) + + +def rows(): + return [ + Row( + id=i, + details=Details(label=str(i), transient="private"), + transient="private", + generated=["private"], + ) + for i in (1, 2) + ] + + +def assert_schema(schema): + assert schema.names == ["id", "details", "retained"] + assert [field.name for field in schema.field("details").type] == ["label"] + assert Row.field_names() == ["id", "details", "transient", "generated", "retained"] + + +def assert_restored(restored): + assert sorted(row.id for row in restored) == [1, 2] + for row in restored: + assert row.transient == "local default" + assert row.generated == ["local"] + assert row.details.transient == "nested default" + assert row.details.label == str(row.id) + assert row.retained == "persisted" + + +@pytest.mark.parametrize("explicit_schema", [False, True]) +def test_excluded_fields_round_trip(tmp_path, explicit_schema): + data = rows() + kwargs = {"schema": Row} if explicit_schema else {} + db = lancedb.connect(tmp_path) + table = db.create_table("rows", data=data[:1], **kwargs) + table.add(data[1:]) + assert_schema(table.schema) + reopened = lancedb.connect(tmp_path).open_table("rows") + assert_restored(reopened.search().to_pydantic(Row)) + assert data[0].transient == "private" + assert data[0].generated == ["private"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("explicit_schema", [False, True]) +async def test_excluded_fields_round_trip_async(tmp_path, explicit_schema): + data = rows() + kwargs = {"schema": Row} if explicit_schema else {} + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("rows", data=data[:1], **kwargs) + await table.add(data[1:]) + assert_schema(await table.schema()) + reopened_db = await lancedb.connect_async(tmp_path) + reopened = await reopened_db.open_table("rows") + assert_restored(await reopened.query().to_pydantic(Row)) + assert data[0].details.transient == "private" + + +@pytest.mark.parametrize("excluded", ["transient", "source", "vector"]) +def test_excluded_fields_keep_embedding_metadata_consistent( + tmp_path, monkeypatch, excluded +): + from lancedb.embeddings.base import TextEmbeddingFunction + from lancedb.embeddings.registry import get_registry + from lancedb.pydantic import Vector + + calls = [] + + class LocalEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + calls.extend(texts) + return [[1.0, 0.0] for _ in texts] + + registry = get_registry() + monkeypatch.setattr(registry, "_functions", registry._functions.copy()) + registry.register("test-excluded-fields")(LocalEmbedding) + function = LocalEmbedding.create(max_retries=0) + + class EmbeddedRow(LanceModel): + text: str = function.SourceField(default="alpha", exclude=excluded == "source") + vector: Vector(2) = function.VectorField( + default_factory=lambda: [1.0, 0.0], exclude=excluded == "vector" + ) + transient: str = Field(default="local", exclude=True) + + configs = EmbeddedRow.parse_embedding_functions() + assert len(configs) == (1 if excluded == "transient" else 0) + db = lancedb.connect(tmp_path) + data = [{"text": "alpha"}] if excluded == "transient" else [EmbeddedRow()] + table = db.create_table("embeddings", schema=EmbeddedRow, data=data) + assert "transient" not in table.schema.names + assert ("text" in table.schema.names) == (excluded != "source") + assert ("vector" in table.schema.names) == (excluded != "vector") + reopened = lancedb.connect(tmp_path).open_table("embeddings") + assert len(reopened.embedding_functions) == len(configs) + restored = reopened.search().to_pydantic(EmbeddedRow) + assert restored[0].text == "alpha" + assert restored[0].vector == [1.0, 0.0] + assert restored[0].transient == "local" + if excluded == "transient": + assert calls == ["alpha"] + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + else: + assert calls == [] From 036f4ec53fac660b7703fe707dbcd7c5b405e020 Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 03:13:31 +0800 Subject: [PATCH 055/180] fix(node): preserve options when namespace is omitted (#4479) The namespace overloads allow `undefined` to select the root namespace, but overload dispatch treats it as the legacy options argument and discards the trailing options. For example, `createTable(name, data, undefined, { mode: "overwrite" })` raises an already-exists error instead of overwriting. Preserve the trailing options for `createTable`, `createEmptyTable`, `tableNames`, and `listTables` when the namespace is omitted. Legacy options-object calls and explicit namespace arrays keep their existing behavior. Adds native-database regressions for overwrite, existOk, and both listing APIs, parameterized over `undefined` and `[]`. Validation on Windows / Node 24.19.0: - Before the fix: all five omitted-namespace cases failed; all five explicit-root controls passed. - Current TypeScript source with official, integrity-verified 0.41.0-beta.0 native binaries: the entire connection test file passed, 47/47 (transpile-only). - The same fix replayed onto the matching 0.41.0-beta.0 source: TypeScript compilation, strict ts-jest connection tests (47/47), and TypeDoc passed. - Biome check/format on both changed files and diff whitespace checks passed. No Rust changes. A complete current-main native rebuild remains for CI: released declarations predate the unrelated lazy-iterator APIs, so current-main typechecking against those declarations reports six pre-existing iterator signature errors. Signed-off-by: Xucheng Zhou Co-authored-by: Xuanwo --- nodejs/__test__/connection.test.ts | 60 ++++++++++++++++++++++++++++++ nodejs/lancedb/connection.ts | 8 ++-- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index 1167ae34a..355b86ccb 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -117,6 +117,66 @@ describe("given a connection", () => { await expect(tbl.countRows()).resolves.toBe(1); }); + describe.each([undefined, []])("root namespace %p", (namespacePath) => { + it("should preserve createTable options after the namespace", async () => { + await db.createTable("test", [{ id: 1 }, { id: 2 }]); + + const table = await db.createTable("test", [{ id: 3 }], namespacePath, { + mode: "overwrite", + }); + + const rows = await table.query().toArray(); + expect(rows.map((row) => row.id)).toEqual([3]); + }); + + it("should preserve createEmptyTable overwrite after the namespace", async () => { + await db.createTable("test", [{ id: 1 }]); + const schema = new Schema([new Field("id", new Float64(), true)]); + + const table = await db.createEmptyTable("test", schema, namespacePath, { + mode: "overwrite", + }); + + await expect(table.countRows()).resolves.toBe(0); + }); + + it("should preserve createEmptyTable existOk after the namespace", async () => { + await db.createTable("test", [{ id: 1 }]); + const schema = new Schema([new Field("id", new Float64(), true)]); + + const table = await db.createEmptyTable("test", schema, namespacePath, { + existOk: true, + }); + + await expect(table.countRows()).resolves.toBe(1); + }); + + it("should preserve tableNames options after the namespace", async () => { + for (const name of ["a", "b", "c"]) { + await db.createTable(name, [{ id: 1 }]); + } + + await expect( + db.tableNames(namespacePath, { limit: 1, startAfter: "a" }), + ).resolves.toEqual(["b"]); + }); + + it("should preserve listTables options after the namespace", async () => { + for (const name of ["a", "b", "c"]) { + await db.createTable(name, [{ id: 1 }]); + } + + const first = await db.listTables(namespacePath, { limit: 1 }); + expect(first.tables).toEqual(["a"]); + expect(first.pageToken).toBeDefined(); + + const second = await db.listTables(namespacePath, { + limit: 1, + pageToken: first.pageToken, + }); + expect(second.tables).toEqual(["b"]); + }); + }); it("should keep the existing table when mode is exist_ok", async () => { const created = await db.createTable("test", [{ id: 1 }, { id: 2 }], { mode: "exist_ok", diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 4ed511b86..f866d1ecd 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -720,7 +720,7 @@ export class LocalConnection extends Connection { } else { // First argument is options object (backwards compatibility) namespacePath = undefined; - tableNamesOptions = namespacePathOrOptions; + tableNamesOptions = namespacePathOrOptions ?? options; } return this.inner.tableNames( @@ -831,7 +831,7 @@ export class LocalConnection extends Connection { : undefined; const listTablesOptions = Array.isArray(namespacePathOrOptions) ? options - : namespacePathOrOptions; + : (namespacePathOrOptions ?? options); return this.inner.listTables( namespacePath ?? [], @@ -942,7 +942,7 @@ export class LocalConnection extends Connection { } else { // Third argument is options object (backwards compatibility) namespacePath = undefined; - createOptions = namespacePathOrOptions; + createOptions = namespacePathOrOptions ?? options; } return this._createTableImpl(name, data, namespacePath, createOptions); @@ -989,7 +989,7 @@ export class LocalConnection extends Connection { } else { // Third argument is options object (backwards compatibility) namespacePath = undefined; - createOptions = namespacePathOrOptions; + createOptions = namespacePathOrOptions ?? options; } let mode: string = createOptions?.mode ?? "create"; From 13d54db59411029f6c80755b7453090e17beb417 Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 03:13:46 +0800 Subject: [PATCH 056/180] fix(node): preserve caller-owned storage options (#4480) `getStorageOptions` writes typed creation options back into the caller's `storageOptions` object. This makes frozen options throw and causes overrides to leak into later calls that reuse the storage map. For example, using `{ storageOptions: shared, enableV2ManifestPaths: true }` changes `shared.newTableEnableV2ManifestPaths` to `"true"`. A subsequent creation with just `{ storageOptions: shared }` then uses V2 manifest paths even if `shared` originally requested `"false"`. Merge the typed overrides into a local map instead. Their existing precedence, key normalization, and undefined/default behavior remain unchanged. This affects both `createTable` and `createEmptyTable`; no native/Rust changes. Adds six native-database regressions covering frozen creation options, frozen nested storage options with conflicting defaults, and cross-call reuse for both APIs. Validation (Linux x64 / Node 24.19.0 / official 0.41.0-beta.0 native library): - Before: all six new regressions fail; an existing namespace storage-options control passes. - After: the full connection test file passes, 43/43 (current TypeScript source, transpile-only). - Same fix on the matching 0.41.0-beta.0 source: TypeScript compilation, strict ts-jest connection tests (43/43), and TypeDoc with warnings-as-errors pass. - Biome on changed files and whitespace checks pass. A current-main native rebuild was not run. Released native declarations predate six unrelated lazy-iterator signatures; current-main typechecking reports the same six errors before and after this fix (only downstream line coordinates shift). ### Connection entry-point follow-up The same ownership problem occurs in `connect(uri, options)` and `connectNamespace`: normalization assigns a new storage map into the caller's options. Copy the options before normalization instead. The `connect(options)` overload already copies its input and is retained as a control. Nine added native-database cases cover frozen outer options (with/without storage options) and repeated reuse, including table creation and row-count checks. Before this entry-point fix, the URI/namespace cases fail (6), while the object-overload controls pass (3). Afterward the complete connection file passes 52/52 on current TypeScript with the official 0.41.0-beta.0 native library. Applying the entry-point fix to matching-release source also passes strict TypeScript, strict ts-jest (52/52), and TypeDoc. Biome passes on both newly changed files. The same six current-main/released-native lazy-iterator declaration errors remain unchanged. No Rust/native rebuild or GPU claim is added. --------- Signed-off-by: Xucheng Zhou --- nodejs/__test__/connection.test.ts | 144 +++++++++++++++++++++++++++++ nodejs/lancedb/connection.ts | 23 ++--- nodejs/lancedb/index.ts | 17 ++-- 3 files changed, 164 insertions(+), 20 deletions(-) diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index 355b86ccb..e32e7e626 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -36,6 +36,87 @@ describe("when connecting", () => { }); }); +describe.each([ + [ + "URI overload", + (uri: string, options: { storageOptions?: Record }) => + connect(uri, options), + ], + [ + "object overload", + async ( + uri: string, + options: { storageOptions?: Record }, + ) => { + const input = { uri, ...options }; + if (Object.isFrozen(options)) { + Object.freeze(input); + } + const db = await connect(input); + expect(input).toEqual({ uri, ...options }); + expect(input.storageOptions).toBe(options.storageOptions); + return db; + }, + ], + [ + "namespace", + (uri: string, options: { storageOptions?: Record }) => + connectNamespace("dir", { root: uri }, options), + ], +])("%s connection options", (_name, open) => { + let tmpDir: tmp.DirResult; + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => tmpDir.removeCallback()); + + it("should accept frozen options without storage options", async () => { + const options = Object.freeze({}); + const db = await open(tmpDir.name, options); + try { + await db.createTable("frozen", [{ id: 1 }]); + await expect(db.tableNames()).resolves.toContain("frozen"); + expect(options).toEqual({}); + } finally { + await db.close(); + } + }); + + it("should accept frozen options with storage options", async () => { + const storageOptions = Object.freeze({ + newTableDataStorageVersion: "stable", + }); + const options = Object.freeze({ storageOptions }); + const db = await open(tmpDir.name, options); + try { + const table = await db.createTable("frozen", [{ id: 1 }]); + await expect(table.countRows()).resolves.toBe(1); + expect(options.storageOptions).toBe(storageOptions); + expect(storageOptions).toEqual({ newTableDataStorageVersion: "stable" }); + } finally { + await db.close(); + } + }); + + it("should preserve reused options and their storage options", async () => { + const storageOptions = { newTableDataStorageVersion: "stable" }; + const options = { storageOptions }; + for (let i = 0; i < 2; i++) { + const db = await open(tmpDir.name, options); + try { + const table = await db.createTable(`reused_${i}`, [{ id: i }]); + await expect(table.countRows()).resolves.toBe(1); + expect(options.storageOptions).toBe(storageOptions); + expect(storageOptions).toEqual({ + newTableDataStorageVersion: "stable", + }); + } finally { + await db.close(); + } + } + }); +}); + describe("given a connection", () => { let tmpDir: tmp.DirResult; let db: Connection; @@ -367,6 +448,69 @@ describe("given a connection", () => { }); }); + describe.each(["createTable", "createEmptyTable"] as const)( + "%s storage options", + (method) => { + const schema = new Schema([new Field("id", new Float64(), true)]); + + it("should accept frozen creation options without storage options", async () => { + const options = Object.freeze({ + dataStorageVersion: "stable", + enableV2ManifestPaths: true, + }); + const table = + method === "createTable" + ? await db.createTable("frozen_options", [{ id: 1 }], options) + : await db.createEmptyTable("frozen_options", schema, options); + expect(await (table as LocalTable).usesV2ManifestPaths()).toBe(true); + expect(options).not.toHaveProperty("storageOptions"); + }); + + it("should accept frozen storage options and preserve override precedence", async () => { + const storageOptions = Object.freeze({ + newTableDataStorageVersion: "legacy", + newTableEnableV2ManifestPaths: "false", + }); + const options = Object.freeze({ + storageOptions, + dataStorageVersion: "stable", + enableV2ManifestPaths: true, + }); + const table = + method === "createTable" + ? await db.createTable("frozen_storage", [{ id: 1 }], options) + : await db.createEmptyTable("frozen_storage", schema, options); + expect(await (table as LocalTable).usesV2ManifestPaths()).toBe(true); + expect(options.storageOptions).toBe(storageOptions); + expect(storageOptions).toEqual({ + newTableDataStorageVersion: "legacy", + newTableEnableV2ManifestPaths: "false", + }); + }); + + it("should not retain a previous override when reusing storage options", async () => { + const storageOptions = { newTableEnableV2ManifestPaths: "false" }; + const create = async (name: string, enableV2ManifestPaths?: boolean) => + method === "createTable" + ? db.createTable(name, [{ id: 1 }], { + storageOptions, + enableV2ManifestPaths, + }) + : db.createEmptyTable(name, schema, { + storageOptions, + enableV2ManifestPaths, + }); + const first = await create("override", true); + expect(await (first as LocalTable).usesV2ManifestPaths()).toBe(true); + const second = await create("without_override"); + expect(await (second as LocalTable).usesV2ManifestPaths()).toBe(false); + expect(storageOptions).toEqual({ + newTableEnableV2ManifestPaths: "false", + }); + }); + }, + ); + it("should be able to migrate tables to the V2 manifest paths", async () => { const db = await connect(tmpDir.name); const table = (await db.createEmptyTable( diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index f866d1ecd..44fde96f1 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -893,23 +893,24 @@ export class LocalConnection extends Connection { private getStorageOptions( options?: Partial, ): Record | undefined { + let storageOptions = options?.storageOptions; if (options?.dataStorageVersion !== undefined) { - if (options.storageOptions === undefined) { - options.storageOptions = {}; - } - options.storageOptions["newTableDataStorageVersion"] = - options.dataStorageVersion; + storageOptions = { + ...storageOptions, + newTableDataStorageVersion: options.dataStorageVersion, + }; } if (options?.enableV2ManifestPaths !== undefined) { - if (options.storageOptions === undefined) { - options.storageOptions = {}; - } - options.storageOptions["newTableEnableV2ManifestPaths"] = - options.enableV2ManifestPaths ? "true" : "false"; + storageOptions = { + ...storageOptions, + newTableEnableV2ManifestPaths: options.enableV2ManifestPaths + ? "true" + : "false", + }; } - return cleanseStorageOptions(options?.storageOptions); + return cleanseStorageOptions(storageOptions); } async createTable( diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 1057e2d53..4ad8b2a93 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -420,10 +420,10 @@ export async function connect( throw new Error("uri is required"); } - finalOptions = (finalOptions as ConnectionOptions) ?? {}; - (finalOptions).storageOptions = cleanseStorageOptions( - (finalOptions).storageOptions, - ); + finalOptions = { + ...finalOptions, + storageOptions: cleanseStorageOptions(finalOptions.storageOptions), + }; // Create native header provider if one was provided let nativeProvider: NativeJsHeaderProvider | undefined; @@ -630,11 +630,10 @@ export async function connectNamespace( properties = configOrProperties as Record; } - const finalOptions: ConnectNamespaceOptions = (options ?? - {}) as ConnectNamespaceOptions; - finalOptions.storageOptions = cleanseStorageOptions( - finalOptions.storageOptions, - ); + const finalOptions: ConnectNamespaceOptions = { + ...options, + storageOptions: cleanseStorageOptions(options?.storageOptions), + }; const nativeConn = await LanceDbConnection.newWithNamespace( implName, From e256b3c2cfc49f45c74d4ac5e31a2e60b6a40efa Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 03:14:03 +0800 Subject: [PATCH 057/180] fix(python): honor namespace table storage options (#4483) Follow-up on current main `7b3ba4c4` (merge commit `0b0475c1`): resolved the test import conflict, preserving both upstream imports and the original `warnings` import. The final PR diff is still limited to the same storage-option helper/call sites and regression class. AST comparisons preserve every upstream test definition and the original regression class/helper; both changed files compile and pass Ruff 0.15.1 check/format. Fresh locked-environment runtime validation was attempted with `uv run --locked --extra tests --extra dev pytest python/tests/test_namespace.py -q`, but dependency setup failed downloading the locked `pylance==14.0.0b12` wheel due a network connection error. No current-main native test result is claimed. Repository-wide Ruff reports 49 findings and 11 formatting differences in unchanged upstream docs/web-tests files; these were left outside this PR. CI approval and a human review are still pending. --- Original implementation and historical validation (before the main merge): Namespace-backed `create_table` accepts `data_storage_version` and `enable_v2_manifest_paths`, but neither sync nor async creation forwards them. The requested format/manifest settings are silently ignored. Normalize these deprecated arguments into the existing `new_table_*` storage options, matching ordinary connections. Explicit arguments take precedence; the caller's dictionary is not mutated. No Rust or native interface changes. Regression tests inspect persisted tables, including sync/async creation, populated/empty tables, stable/legacy formats, both manifest settings and explicit-option precedence. Validation on Linux/Python 3.12, based on current main `d3390a9`: - Rebuilt the exact-main native extension and reused that identical extension in separate baseline/candidate environments; only the candidate Python namespace wrapper differs. Dependencies came from the unchanged `uv.lock`. - Same complete `test_namespace.py`: baseline 16 regression failures and 39 passing controls; candidate **55 passed**, no skips/errors. - Ruff check/format and diff whitespace checks passed. This validates the local directory-namespace path, not a live Cloud service or the complete repository CI suite. Signed-off-by: Xucheng Zhou --- python/python/lancedb/namespace.py | 32 +++++++ python/python/tests/test_namespace.py | 120 ++++++++++++++++++++++++++ 2 files changed, 152 insertions(+) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index f8675ebb5..a5d88eb1f 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -11,6 +11,7 @@ through a namespace abstraction. from __future__ import annotations import sys +import warnings from typing import Any, Dict, Iterable, List, Optional, Union from uuid import UUID @@ -82,6 +83,31 @@ from ._lancedb import Session _MAX_QUERY_K = 2**31 - 1 +def _create_table_storage_options( + storage_options: Optional[Dict[str, str]], + data_storage_version: Optional[str], + enable_v2_manifest_paths: Optional[bool], +) -> Optional[Dict[str, str]]: + if data_storage_version is None and enable_v2_manifest_paths is None: + return storage_options + options = dict(storage_options or {}) + for name, value in ( + ("data_storage_version", data_storage_version), + ("enable_v2_manifest_paths", enable_v2_manifest_paths), + ): + if value is not None: + warnings.warn( + f"setting {name} directly on create_table is deprecated. " + "Use storage_options instead.", + DeprecationWarning, + stacklevel=3, + ) + options[f"new_table_{name}"] = ( + str(value).lower() if isinstance(value, bool) else value + ) + return options + + def _query_to_namespace_request( table_id: List[str], query: "Query", @@ -587,6 +613,9 @@ class LanceNamespaceDBConnection(DBConnection): if mode.lower() not in ["create", "overwrite"]: raise ValueError("mode must be either 'create' or 'overwrite'") validate_table_name(name) + storage_options = _create_table_storage_options( + storage_options, data_storage_version, enable_v2_manifest_paths + ) async_table = LOOP.run( self._inner.create_table( name, @@ -1230,6 +1259,9 @@ class AsyncLanceNamespaceDBConnection: if mode.lower() not in ["create", "overwrite"]: raise ValueError("mode must be either 'create' or 'overwrite'") validate_table_name(name) + storage_options = _create_table_storage_options( + storage_options, data_storage_version, enable_v2_manifest_paths + ) table = await self._inner.create_table( name, data, diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 520a6992d..b55da4d57 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -6,6 +6,7 @@ import tempfile import shutil import importlib +import warnings import http.server import json import threading @@ -25,6 +26,125 @@ PUSHDOWN_DATA = pa.table( ) +class TestNamespaceCreateTableOptions: + @pytest.mark.parametrize("version", ["legacy", "stable"]) + @pytest.mark.parametrize("empty", [False, True]) + def test_deprecated_storage_version(self, tmp_path, version, empty): + db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "namespace")}) + data = None if empty else [{"id": 1}] + schema = pa.schema([("id", pa.int64())]) + other_version = "stable" if version == "legacy" else "legacy" + options = {"new_table_data_storage_version": other_version} + control = lancedb.connect(tmp_path / "control").create_table( + "test", + data=data, + schema=schema, + storage_options={"new_table_data_storage_version": version}, + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = db.create_table( + "test", + data=data, + schema=schema, + storage_options=options, + data_storage_version=version, + ) + + assert ( + table.to_lance().data_storage_version + == control.to_lance().data_storage_version + ) + assert table.to_arrow().to_pylist() == ([] if empty else data) + assert options == {"new_table_data_storage_version": other_version} + assert any("data_storage_version" in str(w.message) for w in caught) + + @pytest.mark.asyncio + @pytest.mark.parametrize("version", ["legacy", "stable"]) + @pytest.mark.parametrize("empty", [False, True]) + async def test_deprecated_storage_version_async(self, tmp_path, version, empty): + root = str(tmp_path / "namespace") + db = lancedb.connect_namespace_async("dir", {"root": root}) + data = None if empty else [{"id": 1}] + schema = pa.schema([("id", pa.int64())]) + other_version = "stable" if version == "legacy" else "legacy" + options = {"new_table_data_storage_version": other_version} + control = lancedb.connect(tmp_path / "control").create_table( + "test", + data=data, + schema=schema, + storage_options={"new_table_data_storage_version": version}, + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = await db.create_table( + "test", + data=data, + schema=schema, + storage_options=options, + data_storage_version=version, + ) + + reopened = lancedb.connect_namespace("dir", {"root": root}).open_table("test") + assert ( + reopened.to_lance().data_storage_version + == control.to_lance().data_storage_version + ) + assert (await table.to_arrow()).to_pylist() == ([] if empty else data) + assert options == {"new_table_data_storage_version": other_version} + assert any("data_storage_version" in str(w.message) for w in caught) + + @pytest.mark.parametrize("enabled", [False, True]) + @pytest.mark.parametrize("empty", [False, True]) + def test_deprecated_manifest_paths(self, tmp_path, enabled, empty): + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + data = None if empty else [{"id": 1}] + options = {"new_table_enable_v2_manifest_paths": str(not enabled).lower()} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = db.create_table( + "test", + data=data, + schema=pa.schema([("id", pa.int64())]), + storage_options=options, + enable_v2_manifest_paths=enabled, + ) + + assert table.uses_v2_manifest_paths() == enabled + assert table.to_arrow().to_pylist() == ([] if empty else data) + assert db.open_table("test").uses_v2_manifest_paths() == enabled + assert options == { + "new_table_enable_v2_manifest_paths": str(not enabled).lower() + } + assert any("enable_v2_manifest_paths" in str(w.message) for w in caught) + + @pytest.mark.asyncio + @pytest.mark.parametrize("enabled", [False, True]) + @pytest.mark.parametrize("empty", [False, True]) + async def test_deprecated_manifest_paths_async(self, tmp_path, enabled, empty): + db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) + data = None if empty else [{"id": 1}] + options = {"new_table_enable_v2_manifest_paths": str(not enabled).lower()} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + table = await db.create_table( + "test", + data=data, + schema=pa.schema([("id", pa.int64())]), + storage_options=options, + enable_v2_manifest_paths=enabled, + ) + + assert await table.uses_v2_manifest_paths() == enabled + assert (await table.to_arrow()).to_pylist() == ([] if empty else data) + reopened = await db.open_table("test") + assert await reopened.uses_v2_manifest_paths() == enabled + assert options == { + "new_table_enable_v2_manifest_paths": str(not enabled).lower() + } + assert any("enable_v2_manifest_paths" in str(w.message) for w in caught) + + def _ipc_file(table: pa.Table = PUSHDOWN_DATA) -> bytes: sink = pa.BufferOutputStream() with pa.ipc.new_file(sink, table.schema) as writer: From b205e7c628c327a10f778a8d6db217c63da96e97 Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 03:14:17 +0800 Subject: [PATCH 058/180] fix(node): prevent table listing limits from wrapping (#4492) ## Summary Prevent large JavaScript table-listing limits from wrapping during the native `u32` conversion. With two tables, `limit: 2 ** 32` currently returns no tables and `2 ** 32 + 1` returns only one. Validate nonnegative safe integers using the existing helper and clamp valid limits above `u32::MAX` before calling the native binding. Apply the same normalization to `tableNames` and `listTables`, including namespace overloads. Undefined, zero, small limits and `u32::MAX` keep their existing behavior. ## Validation Built the real Node native extension from main `0aa842b17f13d1f8ffd2851bc57c222bc5a376ba` with the repository's `pnpm build`, using locked dependencies and reusable build caches. No mocked/released native extension or disabled TypeScript diagnostics. With identical regression tests and that native library in fresh Jest processes: - Baseline: 40 passed, 8 failed; candidate: **48 passed**, no failures. - Both arms: `pnpm run tsc` and `pnpm run docs` passed. - Changed-file Biome check passed. Tests cover wrapping limits, invalid numbers, zero/small/u32 limits, defaults and both overload forms. Validation is the focused connection suite, not the complete repository suite. No performance claim. AI-assisted implementation and verification; the patch and exact tested source bytes were reviewed before publication. Signed-off-by: aden Co-authored-by: aden --- nodejs/__test__/connection.test.ts | 50 ++++++++++++++++++++++++++++++ nodejs/lancedb/connection.ts | 11 +++++-- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index e32e7e626..bbd0c3c52 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -336,6 +336,56 @@ describe("given a connection", () => { expect(seen).toEqual(created); }); + it.each([2 ** 32, 2 ** 32 + 1, Number.MAX_SAFE_INTEGER])( + "should not wrap a large table listing limit %s", + async (limit) => { + await db.createTable("a", [{ id: 1 }]); + await db.createTable("b", [{ id: 2 }]); + for (const names of [ + db.tableNames({ limit }), + db.tableNames([], { limit }), + ]) { + await expect(names).resolves.toEqual(["a", "b"]); + } + for (const page of [ + db.listTables({ limit }), + db.listTables([], { limit }), + ]) { + await expect(page).resolves.toEqual({ tables: ["a", "b"] }); + } + }, + ); + + it.each([ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + ])("should reject an invalid table listing limit %s", async (limit) => { + await expect(db.tableNames({ limit })).rejects.toThrow(/limit/); + await expect(db.tableNames([], { limit })).rejects.toThrow(/limit/); + await expect(db.listTables({ limit })).rejects.toThrow(/limit/); + await expect(db.listTables([], { limit })).rejects.toThrow(/limit/); + }); + + it("should preserve zero, small and unsigned-32-bit table listing limits", async () => { + await db.createTable("a", [{ id: 1 }]); + await db.createTable("b", [{ id: 2 }]); + for (const [limit, names] of [ + [0, []], + [1, ["a"]], + [2 ** 32 - 1, ["a", "b"]], + ] as const) { + await expect(db.tableNames({ limit })).resolves.toEqual(names); + const page = await db.listTables({ limit }); + expect(page.tables).toEqual(names); + } + await expect(db.tableNames()).resolves.toEqual(["a", "b"]); + await expect(db.listTables()).resolves.toEqual({ tables: ["a", "b"] }); + }); + it("should list all names and use a default page size of 100", async () => { const names = Array.from( { length: 130 }, diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 44fde96f1..c93414fab 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -726,7 +726,7 @@ export class LocalConnection extends Connection { return this.inner.tableNames( namespacePath ?? [], tableNamesOptions?.startAfter, - tableNamesOptions?.limit, + normalizeTableListingLimit(tableNamesOptions?.limit), ); } @@ -836,7 +836,7 @@ export class LocalConnection extends Connection { return this.inner.listTables( namespacePath ?? [], listTablesOptions?.pageToken, - listTablesOptions?.limit, + normalizeTableListingLimit(listTablesOptions?.limit), ); } @@ -1107,6 +1107,13 @@ export class LocalConnection extends Connection { } } +function normalizeTableListingLimit(limit?: number): number | undefined { + validateNonNegativeInteger(limit, "limit"); + // The native binding takes u32: larger JS numbers otherwise wrap to zero or + // a smaller page size. A listing limit is an upper bound, so saturate it. + return limit === undefined ? undefined : Math.min(limit, 0xffffffff); +} + /** * Takes storage options and makes all the keys snake case. */ From 3d883af674924a7e7266da19d9ce1d774298f74c Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 03:14:31 +0800 Subject: [PATCH 059/180] fix(python): propagate invalid index wait_timeout errors (#4495) Invalid `wait_timeout` values currently reach `Duration::extract(...).unwrap()` in both native index-creation bindings. A normal Python argument error becomes `pyo3_runtime.PanicException`, which is not caught by `except Exception`. Propagate the extraction error with `map(...).transpose()?` before constructing the index operation. Valid `None` and `timedelta` behavior is unchanged. Tests cover both `create_index` and `create_index_async`, three invalid types, valid `None`/`timedelta`, and no index created after rejection. Validation against main `0aa842b`, Python 3.12, uv-locked dependencies, freshly compiled PyO3 extension for each arm: - Unmodified source: 6 new regressions fail with `PanicException`; 6 controls pass. - Fixed source: 12/12 pass; broader index-creation regression selection: 18/18 pass. - `cargo fmt --all --check`, Ruff check/format, and diff check pass. The broader selection includes the 12 cases above. No cloud, full-suite, or performance claim. Signed-off-by: Xucheng Zhou --- python/python/tests/test_table.py | 19 +++++++++++++++++++ python/src/table.rs | 8 ++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index b2d499933..238ee5330 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1633,6 +1633,25 @@ def test_create_index_async_returns_done_job(mem_db: DBConnection): job.cancel() +@pytest.mark.parametrize("method", ["create_index", "create_index_async"]) +@pytest.mark.parametrize("wait_timeout", ["invalid", 1, []]) +def test_create_index_invalid_wait_timeout(mem_db: DBConnection, method, wait_timeout): + table = mem_db.create_table("invalid_timeout", [{"id": 1}]) + with pytest.raises(TypeError): + getattr(table, method)("id", config=BTree(), wait_timeout=wait_timeout) + assert table.list_indices() == [] + + +@pytest.mark.parametrize("method", ["create_index", "create_index_async"]) +@pytest.mark.parametrize("wait_timeout", [None, timedelta(seconds=1)]) +def test_create_index_valid_wait_timeout(mem_db: DBConnection, method, wait_timeout): + table = mem_db.create_table("valid_timeout", [{"id": 1}]) + result = getattr(table, method)("id", config=BTree(), wait_timeout=wait_timeout) + if result is not None: + result.wait() + assert len(table.list_indices()) == 1 + + @patch("lancedb.table.AsyncTable.create_index") def test_create_index_method(mock_create_index, mem_db: DBConnection): table = mem_db.create_table( diff --git a/python/src/table.rs b/python/src/table.rs index 27ed8be8b..e77c58578 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1134,7 +1134,9 @@ impl Table { train: Option, ) -> PyResult> { let index = extract_index_params(&index)?; - let timeout = wait_timeout.map(|t| t.extract::().unwrap()); + let timeout = wait_timeout + .map(|t| t.extract::()) + .transpose()?; let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); @@ -1165,7 +1167,9 @@ impl Table { train: Option, ) -> PyResult> { let index = extract_index_params(&index)?; - let timeout = wait_timeout.map(|t| t.extract::().unwrap()); + let timeout = wait_timeout + .map(|t| t.extract::()) + .transpose()?; let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); From 93f054bcc5b02927720cdcd52fd7b1cc13c9a731 Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 03:14:45 +0800 Subject: [PATCH 060/180] fix(rust): finish query streams after a zero-duration timeout (#4506) A positive query timeout emits one error and then ends, but `Duration::ZERO` leaves `TimeoutStream` in `NotStarted`, returning the same error on every subsequent poll. Transition the zero-duration path to `Completed` before returning its error. The initial error is unchanged. Extend both timeout tests to check that subsequent polls return `None`; the normal-completion test is unchanged. This affects callers that continue polling after an error, not `try_collect`, which already stops at the first error. Validation: - `cargo fmt --all` and `cargo fmt --all --check`: pass. - Mechanically extracted the unchanged implementation and three upstream timeout tests into a native Rust test binary using real cached Arrow 58.4.0, DataFusion 54.1.0, futures 0.3.32 and Tokio 1.53.1 libraries (matching the current lock). With the new assertions, baseline: 2 pass / 1 fail; fix: 3 pass. - Full-crate `cargo test --locked --offline --features remote -p lancedb --lib test_timeout_stream` could not start because this environment lacks the newly locked Lance `v14.0.0-beta.10` checkout. The component comparison is not a claim that the full Cargo suite passed; CI still needs to validate integration. Signed-off-by: Xucheng Zhou --- rust/lancedb/src/utils/mod.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index 20f209f2e..ebf3f697b 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -686,7 +686,9 @@ impl Stream for TimeoutStream { match &mut self.state { TimeoutState::NotStarted { timeout } => { if timeout.is_zero() { - return std::task::Poll::Ready(Some(Err(Self::timeout_error(timeout)))); + let err = Self::timeout_error(timeout); + self.state = TimeoutState::Completed; + return std::task::Poll::Ready(Some(Err(err))); } let deadline = Box::pin(tokio::time::sleep(*timeout)); self.state = TimeoutState::Started { @@ -1159,6 +1161,8 @@ mod tests { .to_string() .contains("Query timeout") ); + assert!(timeout_stream.next().await.is_none()); + assert!(timeout_stream.next().await.is_none()); } #[tokio::test] @@ -1178,6 +1182,8 @@ mod tests { let result = timeout_stream.next().await.unwrap(); assert!(result.is_err()); assert!(result.unwrap_err().to_string().contains("Query timeout")); + assert!(timeout_stream.next().await.is_none()); + assert!(timeout_stream.next().await.is_none()); } #[tokio::test] From d826b6115a0ca30998d9aa1bfb83d01e8f65bf4b Mon Sep 17 00:00:00 2001 From: Aviral Saxena Date: Fri, 23 Oct 2026 00:45:01 +0530 Subject: [PATCH 061/180] fix(rust): explain client-side model files when remote tokenize fails (#4519) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses option 2 of #4440. tokenize() builds the FTS analyzer on the client. For jieba/* and lindera/* that needs model files under LANCE_LANGUAGE_MODEL_HOME, and when they’re missing you only got lance’s raw Invalid directory path: ... error, even though server-side search works. Now, if a jieba/* or lindera/* tokenizer can’t be built, the error keeps the original cause and adds that tokenize() runs on the client, which directory the files need to be in, and that for remote tables they must match the server’s. I also updated the tokenize docs (Rust, Python, TS, generated JS docs) to say a mismatch can’t be detected, so tokens may differ from the server’s index. Behavior when the files exist is unchanged. Detecting a mismatch needs a server-side tokenize endpoint (option 1), so I left it out. The hint isn’t limited to remote tables, since Table::as_native is slated for removal and the wording fits local tables too. Tests: Rust test with mocked jieba/default index_details and an empty model dir, one checking other tokenizer errors don’t get the hint, and Python sync/async tests. --- docs/src/js/classes/Table.md | 6 +- nodejs/lancedb/table.ts | 6 +- python/python/lancedb/remote/table.py | 8 +- python/python/lancedb/table.py | 18 +++- python/python/tests/test_remote_db.py | 73 +++++++++++++++ rust/lancedb/src/remote/table.rs | 125 ++++++++++++++++++++++++++ rust/lancedb/src/table.rs | 34 +++++-- 7 files changed, 257 insertions(+), 13 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index b41ade302..7cf87c405 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1298,7 +1298,11 @@ Specify exactly one of `column` or `indexName`. Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in the client process from index metadata. For remote tables, this means the -same tokenizer model files must also exist locally. +same tokenizer model files must also exist locally (under +`LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A +mismatch cannot be detected: the returned tokens may differ from what the +server's index produces. If the model files are missing, an error naming +the tokenizer is raised. #### Parameters diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 0c79e6a7e..4ae1aefb8 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -989,7 +989,11 @@ export abstract class Table { * * Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in * the client process from index metadata. For remote tables, this means the - * same tokenizer model files must also exist locally. + * same tokenizer model files must also exist locally (under + * `LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A + * mismatch cannot be detected: the returned tokens may differ from what the + * server's index produces. If the model files are missing, an error naming + * the tokenizer is raised. */ abstract tokenize( query: string, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 96b988911..86e8fb8a0 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -279,8 +279,12 @@ class RemoteTable(Table): """Tokenize a query using the tokenizer configured on an FTS index. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata, so the same tokenizer - model files must exist locally. + rebuilt in the client process from index metadata. For remote tables, + this means the same tokenizer model files must also exist locally + (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the + server uses. A mismatch cannot be detected: the returned tokens may + differ from what the server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ return LOOP.run( self._table.tokenize(query, column=column, index_name=index_name) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index f9cfac6e1..124fa34b5 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2558,7 +2558,11 @@ class Table(ABC): Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are rebuilt in the client process from index metadata. For remote tables, - this means the same tokenizer model files must also exist locally. + this means the same tokenizer model files must also exist locally + (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the + server uses. A mismatch cannot be detected: the returned tokens may + differ from what the server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ @abstractmethod @@ -4813,7 +4817,11 @@ class LanceTable(Table): Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are rebuilt in the client process from index metadata. For remote tables, - this means the same tokenizer model files must also exist locally. + this means the same tokenizer model files must also exist locally + (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the + server uses. A mismatch cannot be detected: the returned tokens may + differ from what the server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ return LOOP.run( self._table.tokenize(query, column=column, index_name=index_name) @@ -7505,7 +7513,11 @@ class AsyncTable: Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are rebuilt in the client process from index metadata. For remote tables, - this means the same tokenizer model files must also exist locally. + this means the same tokenizer model files must also exist locally + (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the + server uses. A mismatch cannot be detected: the returned tokens may + differ from what the server's index produces. If the model files are + missing, an error naming the tokenizer is raised. """ return await self._inner.tokenize(query, column=column, index_name=index_name) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 80bd10289..a45e1aaef 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1793,6 +1793,79 @@ def test_table_wait_for_index_timeout(): table.wait_for_index(["id_idx"], timedelta(seconds=1)) +def _jieba_fts_handler(request): + """Serve a table with a ``jieba/default`` FTS index and no other state.""" + if request.path == "/v1/table/test/describe/": + body = { + "version": 1, + "schema": { + "fields": [ + {"name": "text", "type": {"type": "string"}, "nullable": True} + ] + }, + } + elif request.path == "/v1/table/test/index/list/": + index_details = { + "base_tokenizer": "jieba/default", + "language": "English", + "with_position": False, + "max_token_length": 40, + "lower_case": True, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + } + body = { + "indexes": [ + { + "index_name": "text_idx", + "columns": ["text"], + "index_type": "FTS", + "index_details": json.dumps(index_details), + } + ] + } + else: + request.send_response(404) + request.end_headers() + return + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(body).encode()) + + +_MODEL_FILES_ERROR = ( + r"(?s)Invalid directory path.*" + r"full text search index 'text_idx'.*" + r"tokenize\(\) runs on the client.*'jieba/default'.*" + r"LANCE_LANGUAGE_MODEL_HOME.*match the files the server uses" +) + + +def test_remote_tokenize_model_backed_without_model_files(tmp_path, monkeypatch): + monkeypatch.setenv("LANCE_LANGUAGE_MODEL_HOME", str(tmp_path)) + with mock_lancedb_connection(_jieba_fts_handler) as db: + table = db.open_table("test") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + table.tokenize("我们是中国人", index_name="text_idx") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + table.tokenize("我们是中国人", column="text") + + +@pytest.mark.asyncio +async def test_remote_tokenize_model_backed_without_model_files_async( + tmp_path, monkeypatch +): + monkeypatch.setenv("LANCE_LANGUAGE_MODEL_HOME", str(tmp_path)) + async with mock_lancedb_connection_async(_jieba_fts_handler) as db: + table = await db.open_table("test") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + await table.tokenize("我们是中国人", index_name="text_idx") + with pytest.raises(ValueError, match=_MODEL_FILES_ERROR): + await table.tokenize("我们是中国人", column="text") + + def test_stats(): stats = { "total_bytes": 38, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 84c1b3fef..b722dc4a1 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -8871,6 +8871,131 @@ mod tests { ); } + #[tokio::test] + #[serial_test::serial(language_model_env)] + async fn test_tokenize_model_backed_tokenizer_without_model_files() { + let model_home = tempfile::tempdir().unwrap(); + // SAFETY: This is only called in tests, serialized on the env key. + unsafe { + std::env::set_var("LANCE_LANGUAGE_MODEL_HOME", model_home.path()); + } + let schema = Schema::new(vec![Field::new("text", DataType::Utf8, false)]); + let index_details = serde_json::json!({ + "base_tokenizer": "jieba/default", + "language": "English", + "with_position": false, + "max_token_length": 40, + "lower_case": true, + "stem": false, + "remove_stop_words": false, + "ascii_folding": false, + }) + .to_string(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(), + "/v1/table/my_table/index/list/" => { + let body = serde_json::json!({ + "indexes": [ + { + "index_name": "text_idx", + "columns": ["text"], + "index_type": "FTS", + "index_details": index_details, + }, + ] + }); + http::Response::builder() + .status(200) + .body(serde_json::to_string(&body).unwrap()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), + } + }); + + let result = table.tokenize("我们是中国人", "text_idx").await; + // SAFETY: This is only called in tests, serialized on the env key. + unsafe { + std::env::remove_var("LANCE_LANGUAGE_MODEL_HOME"); + } + + let err = result.unwrap_err(); + let Error::InvalidInput { message } = err else { + panic!("expected InvalidInput, got {err:?}"); + }; + // The original cause and the index context are preserved... + assert!(message.contains("Invalid directory path"), "{message}"); + assert!( + message.contains("full text search index 'text_idx'"), + "{message}" + ); + // ...and the message explains that this is a client-side limitation. + assert!( + message.contains("tokenize() runs on the client"), + "{message}" + ); + assert!(message.contains("'jieba/default'"), "{message}"); + assert!(message.contains("LANCE_LANGUAGE_MODEL_HOME"), "{message}"); + assert!( + message.contains("match the files the server uses"), + "{message}" + ); + } + + #[tokio::test] + async fn test_tokenize_unknown_tokenizer_error_has_no_model_files_hint() { + let schema = Schema::new(vec![Field::new("text", DataType::Utf8, false)]); + let index_details = serde_json::json!({ + "base_tokenizer": "no_such_tokenizer", + "language": "English", + "with_position": false, + "max_token_length": 40, + "lower_case": true, + "stem": false, + "remove_stop_words": false, + "ascii_folding": false, + }) + .to_string(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(), + "/v1/table/my_table/index/list/" => { + let body = serde_json::json!({ + "indexes": [ + { + "index_name": "text_idx", + "columns": ["text"], + "index_type": "FTS", + "index_details": index_details, + }, + ] + }); + http::Response::builder() + .status(200) + .body(serde_json::to_string(&body).unwrap()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), + } + }); + + let err = table.tokenize("hello", "text_idx").await.unwrap_err(); + let message = err.to_string(); + assert!( + !message.contains("tokenize() runs on the client"), + "{message}" + ); + } + #[tokio::test] async fn test_tokenize_requires_existing_index_name() { let schema = Schema::new(vec![Field::new("text", DataType::Utf8, false)]); diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 39e6f1911..3123eb776 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2264,7 +2264,11 @@ impl Table { /// /// Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in /// the client process from index metadata. For remote tables, this means the - /// same tokenizer model files must also exist locally. + /// same tokenizer model files must also exist locally, and must match the + /// files the server uses: the client cannot detect a mismatch, so it may + /// return tokens the server's index never produces. If the model files are + /// missing, this returns an error naming the tokenizer and + /// `LANCE_LANGUAGE_MODEL_HOME`. pub async fn tokenize(&self, query: &str, index_name: &str) -> Result> { let indices = self.inner.list_indices().await?; let matches = indices @@ -2298,7 +2302,8 @@ impl Table { /// The column must have exactly one FTS index. Model-backed tokenizers such /// as `jieba/*` and `lindera/*` are rebuilt in the client process from /// index metadata. For remote tables, this means the same tokenizer model - /// files must also exist locally. + /// files must also exist locally, and must match the files the server uses + /// (see [`Self::tokenize`]). pub async fn tokenize_with_column(&self, query: &str, column: &str) -> Result> { let schema = self.inner.schema().await?; let (column, _) = resolve_arrow_field_path(schema.as_ref(), column)?; @@ -2354,13 +2359,30 @@ impl Table { ), } })?; + let model_backed_tokenizer = serde_json::from_str::(details) + .ok() + .and_then(|details| { + let tokenizer = details.get("base_tokenizer")?.as_str()?.to_string(); + (tokenizer.starts_with("jieba/") || tokenizer.starts_with("lindera/")) + .then_some(tokenizer) + }); tokenize(query, ¶ms).map_err(|err| match err { - Error::InvalidInput { message } => Error::InvalidInput { - message: format!( + Error::InvalidInput { message } => { + let mut message = format!( "{} for full text search index '{}' for {}", message, index.name, selector_description - ), - }, + ); + if let Some(tokenizer) = model_backed_tokenizer { + message.push_str(&format!( + ". tokenize() runs on the client: the '{}' tokenizer is rebuilt \ + in this process from the index metadata, so its model files must \ + be available under LANCE_LANGUAGE_MODEL_HOME and, for remote \ + tables, match the files the server uses", + tokenizer + )); + } + Error::InvalidInput { message } + } err => err, }) } From b6d15558ec8df6c15f25b1012e330802b4d1f830 Mon Sep 17 00:00:00 2001 From: Christopher Krah Date: Thu, 22 Oct 2026 21:18:52 +0200 Subject: [PATCH 062/180] fix(python): stop retrying a missing API key or provider package (#4521) `retry_with_exponential_backoff` retries every exception except an auth error (`python/python/lancedb/embeddings/utils.py:298-318`). For Cohere, Gemini, Jina and VoyageAI a missing API key raises from `api_key_not_found_help`, and a missing provider package raises `ImportError` everywhere. Neither can succeed on a retry, yet both sleep through all seven rounds and then surface wrapped in `Exception("Maximum number of retries...")`. Before, on `142d032`, a VoyageAI function with no key set (script below, `time.sleep` recorded, `random.seed(0)`): ``` $ python lance_retry_deterministic.py python/python raised: Exception('Maximum number of retries (7) exceeded.', ValueError('Please set the VOYAGEAI_API_KEY environment v attempts: 8 sleeps: [4, 13, 37, 93, 280, 788, 2811] slept 4026 s before a missing-API-key error surfaced ``` After: ``` $ python lance_retry_deterministic.py python/python raised: MissingApiKeyError('Please set the VOYAGEAI_API_KEY environment variable.') attempts: 1 sleeps: [] ```
lance_retry_deterministic.py ```python # loads the pure-Python embeddings package from the tree, native extension stubbed import os, random, sys, time, types TREE = sys.argv[1] pkg = types.ModuleType("lancedb"); pkg.__path__ = [TREE + "/lancedb"]; sys.modules["lancedb"] = pkg native = types.ModuleType("lancedb._lancedb"); native.__getattr__ = lambda name: None sys.modules["lancedb._lancedb"] = native import pyarrow as pa from lancedb.embeddings import get_registry random.seed(0) os.environ.pop("VOYAGE_API_KEY", None) slept = [] time.sleep = slept.append func = get_registry().get("voyageai").create(name="voyage-3") try: func.compute_source_embeddings_with_retry(pa.array(["hello"])) except Exception as e: print("raised:", repr(e)[:110]) print("attempts:", len(slept) + 1, "sleeps:", [round(s) for s in slept]) print("slept %.0f s before a missing-API-key error surfaced" % sum(slept)) ```
The message names the wrong variable: `voyageai.py:501` reads `VOYAGE_API_KEY`. I left that for a separate fix. `api_key_not_found_help` now raises `MissingApiKeyError`, a `ValueError` subclass, so existing `except ValueError` callers still catch it. That error and `ImportError` join the 401 exemption from #2995. A plain `ValueError` is still retried, because `bedrock.py:171` wraps boto3 throttling in one. No issue exists for this. OpenAI is not covered: with no key, `openai.OpenAI()` raises `OpenAIError`, which has no status code, so it still retries. I can follow up on that. ### Verification ``` # lance_stub: an empty stand-in for lancedb._lancedb, loaded from the source tree $ pytest -p lance_stub --noconftest python/tests/test_embeddings.py -k "retry or 401 or deterministic" -q 5 passed, 23 deselected in 0.59s # utils.py from 142d032, tests kept: 2 failed, 3 passed, 23 deselected in 0.74s $ pytest -p lance_stub --noconftest python/tests/test_voyageai_embeddings.py -q 18 passed in 0.18s # not run: the full suite or pyright; the native extension did not build here ``` Baseline on `142d032` has 2 of these tests. The new ones cover a missing key, a missing package, and a wrapped throttling error that must still retry. ruff 0.16.10 check and format are clean. @wjones127 you merged the 401 change. Is a `ValueError` subclass the way you want to mark this? Co-authored-by: Xuanwo --- python/python/lancedb/embeddings/utils.py | 13 ++++++- python/python/tests/test_embeddings.py | 45 +++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/embeddings/utils.py b/python/python/lancedb/embeddings/utils.py index f76c9b1a5..fb2a94ecb 100644 --- a/python/python/lancedb/embeddings/utils.py +++ b/python/python/lancedb/embeddings/utils.py @@ -320,6 +320,11 @@ def _is_non_retryable_error(error: Exception) -> bool: if error.status_code in (401, 403): return True + # A missing API key or a missing optional dependency fails the same way on + # every attempt + if isinstance(error, (MissingApiKeyError, ImportError)): + return True + return False @@ -337,9 +342,15 @@ def url_retrieve(url: str): raise ConnectionError("could not download {} due to {}".format(url, err)) +class MissingApiKeyError(ValueError): + """Raised when an embedding provider's API key is not set.""" + + def api_key_not_found_help(provider): logging.error("Could not find API key for %s", provider) - raise ValueError(f"Please set the {provider.upper()}_API_KEY environment variable.") + raise MissingApiKeyError( + f"Please set the {provider.upper()}_API_KEY environment variable." + ) def is_flash_attn_2_available(): diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index d6d128845..2438bfe80 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -633,6 +633,51 @@ def test_openai_no_retry_on_401(mock_sleep): assert mock_sleep.call_count == 0 +@patch("time.sleep") +@pytest.mark.parametrize( + "error", + [ + pytest.param("missing_key", id="missing-api-key"), + pytest.param(ImportError("No module named 'voyageai'"), id="missing-package"), + ], +) +def test_no_retry_on_deterministic_errors(mock_sleep, error): + from lancedb.embeddings.utils import ( + api_key_not_found_help, + retry_with_exponential_backoff, + ) + + def func(): + if error == "missing_key": + api_key_not_found_help("voyageai") + raise error + + mock_func = MagicMock(side_effect=func) + wrapped_func = retry_with_exponential_backoff(mock_func, max_retries=3) + + with pytest.raises((ValueError, ImportError)): + wrapped_func() + + assert mock_func.call_count == 1 + assert mock_sleep.call_count == 0 + + +@patch("time.sleep") +def test_retry_on_wrapped_provider_error(mock_sleep): + """Providers such as Bedrock wrap throttling in a plain ValueError.""" + from lancedb.embeddings.utils import retry_with_exponential_backoff + + mock_func = MagicMock( + side_effect=[ + ValueError("Error raised by boto3 client: ThrottlingException"), + [0.1], + ] + ) + wrapped_func = retry_with_exponential_backoff(mock_func, max_retries=3) + + assert wrapped_func() == [0.1] + assert mock_func.call_count == 2 + assert mock_sleep.call_count == 1 def test_openai_bad_request_partial_batch_recovery(): # Regression test for issue #1677 From 9f4cd1618bddf1041c8ebdaa0b0ccb33656dc57c Mon Sep 17 00:00:00 2001 From: adenzhou1350 Date: Fri, 23 Oct 2026 03:19:06 +0800 Subject: [PATCH 063/180] fix(python): handle empty batch iterables with a schema (#4538) ## Summary `create_table(data=iter(()), schema=...)` currently raises `RuntimeError: coroutine raised StopIteration`, although an empty list with the same schema works. A tuple of batches also fails because the helper calls `next()` before obtaining an iterator. Normalize the iterable once and use the supplied schema for an empty reader. Without a schema, raise a clear `ValueError`. Nonempty schema inference and batch casting are unchanged. Tests cover synchronous/asynchronous creation, empty/nonempty iterators and tuples, and schema-aware `add()` sanitization. The default schema-less `add()` rejection is deliberately unchanged. ## Validation - Built the current Rust/PyO3 extension from base `9f37f392` with the repository's `ci` profile; both Python-only arms use the same verified extension and locked Python dependency versions. - Complete `python/tests/test_table.py` + `python/tests/test_scannable.py`: **268 passed, 0 skipped**. The unchanged production code with identical tests has **24 failures / 244 passes**. - Both arms used four-CPU affinity. An initial unrestricted-affinity run exhausted thread creation under the private memory limit; that failed attempt is not counted as a pass. - Package-wide Ruff check/format pass. Repository-wide checks still report pre-existing findings in unchanged `docs/web-tests`; those files are not modified here. AI-assisted change, reproduced against unchanged production code and validated with a native source build. This does not claim the full repository/platform matrix or a performance improvement. Signed-off-by: Xucheng Zhou --- python/python/lancedb/table.py | 15 +++++-- python/python/tests/test_table.py | 75 +++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 124fa34b5..c7de4161d 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -469,7 +469,7 @@ def _into_pyarrow_reader( ): return data.collect().to_arrow().to_reader() elif isinstance(data, Iterable): - return _iterator_to_reader(data) + return _iterator_to_reader(data, schema) else: raise TypeError( f"Unknown data type {type(data)}. " @@ -479,10 +479,19 @@ def _into_pyarrow_reader( ) -def _iterator_to_reader(data: Iterable) -> pa.RecordBatchReader: +def _iterator_to_reader( + data: Iterable, schema: Optional[pa.Schema] = None +) -> pa.RecordBatchReader: # Each batch is treated as it's own reader, mainly so we can # re-use the _into_pyarrow_reader logic. - first = _into_pyarrow_reader(next(data)) + data = iter(data) + try: + first_batch = next(data) + except StopIteration: + if schema is None: + raise ValueError("Cannot create table from empty iterable without a schema") + return pa.RecordBatchReader.from_batches(schema, []) + first = _into_pyarrow_reader(first_batch) schema = first.schema def gen(): diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 238ee5330..e23b478f5 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4847,6 +4847,81 @@ def test_stats(mem_db: DBConnection): assert stats_with_index["fragment_stats"]["num_fragments"] == 1 +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.parametrize("with_schema", [False, True]) +def test_create_table_recordbatch_iterable( + mem_db: DBConnection, iterable_type, empty, with_schema +): + schema = pa.schema([pa.field("id", pa.int64())]) + batches = [] if empty else [pa.RecordBatch.from_pydict({"id": [1]}, schema)] + data = iterable_type(batches) + if empty and not with_schema: + with pytest.raises(ValueError, match="empty iterable without a schema"): + mem_db.create_table("test", data=data) + return + + table = mem_db.create_table( + "test", data=data, schema=schema if with_schema else None + ) + assert table.schema == schema + assert table.to_arrow().to_pylist() == ([] if empty else [{"id": 1}]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.parametrize("with_schema", [False, True]) +async def test_create_table_recordbatch_iterable_async( + mem_db_async: AsyncConnection, iterable_type, empty, with_schema +): + schema = pa.schema([pa.field("id", pa.int64())]) + batches = [] if empty else [pa.RecordBatch.from_pydict({"id": [1]}, schema)] + data = iterable_type(batches) + if empty and not with_schema: + with pytest.raises(ValueError, match="empty iterable without a schema"): + await mem_db_async.create_table("test", data=data) + return + + table = await mem_db_async.create_table( + "test", data=data, schema=schema if with_schema else None + ) + assert await table.schema() == schema + assert (await table.to_arrow()).to_pylist() == ([] if empty else [{"id": 1}]) + + +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"]) +def test_add_empty_recordbatch_iterable( + mem_db: DBConnection, iterable_type, on_bad_vectors +): + table = mem_db.create_table("test", [{"id": 1}]) + if on_bad_vectors == "error": + # The default scannable path still requires an input schema. This + # fix does not change its validation policy for schema-less input. + with pytest.raises(ValueError, match="empty iterator"): + table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + else: + # Sanitization has the existing table schema available. + table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + assert table.to_arrow().to_pylist() == [{"id": 1}] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("iterable_type", [iter, tuple]) +@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"]) +async def test_add_empty_recordbatch_iterable_async( + mem_db_async: AsyncConnection, iterable_type, on_bad_vectors +): + table = await mem_db_async.create_table("test", [{"id": 1}]) + if on_bad_vectors == "error": + with pytest.raises(ValueError, match="empty iterator"): + await table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + else: + await table.add(iterable_type([]), on_bad_vectors=on_bad_vectors) + assert (await table.to_arrow()).to_pylist() == [{"id": 1}] + + def test_create_table_empty_list_with_schema(mem_db: DBConnection): """Test creating table with empty list data and schema From 2d54630a3c8cfc1faaec67289c864bba66578d2a Mon Sep 17 00:00:00 2001 From: Avanish Garg Date: Fri, 23 Oct 2026 00:52:24 +0530 Subject: [PATCH 064/180] fix(python): stop retrying permanent embedding errors and cap the backoff delay (#4542) Permanent embedding errors (HTTP 400/404/422 and other 4xx) were retried the full `max_retries` times with an uncapped, multiplicatively jittered backoff, so a typo'd model name looked like a hang of about an hour (median 50 min of sleeping with a 404; see the issue for the repro and numbers). Changes (`python/python/lancedb/embeddings/utils.py`, `embeddings/base.py`): - An HTTP status in 4xx other than 408/409/429 is raised immediately. The status is read from `status_code`, `http_status`, `response.status_code`, an integer `code` (google-api-core, urllib) or a botocore `response["ResponseMetadata"]["HTTPStatusCode"]`. AWS throttling reported as 400 stays retryable (matched by error code). `AuthenticationError` by name is unchanged. - Still retried: 408, 409, 429, >=500, and anything without a recognisable status (connection errors, timeouts, custom exceptions), so existing custom embedding functions behave as before. - New keyword `max_delay=60` (last in the signature, default keeps call sites working). `delay = min(delay * base, max_delay)` with equal jitter `delay/2 + random() * delay/2`. With defaults the waits are [1,2], [2,4], [4,8], [8,16], [16,32], [30,60], [30,60] s, worst case about 182 s instead of up to 2.5 h. - The "Maximum number of retries" exception now has `from e`. The `max_retries` comment in `base.py` describes the rules. Not changed: `embeddings/openai.py` (it swallows `BadRequestError`; open #4154/#4005/#3152 cover it), Retry-After handling (the code never used it), and the "C Data interface error" wrapping from the native layer (the original message is now included in it). Behaviour changes to be aware of: every 4xx except 408/409/429 fails fast, including 401/403 coming through `response.status_code` (requests/httpx), which used to be retried; a provider that signals transient failures with a 4xx and no AWS-style code is no longer retried; the first retry waits 1-2 s instead of 2-4 s. Tests (`python/python/tests/test_embeddings.py`): 48 new cases (23 test functions): permanent errors are not retried, transient errors are, botocore-style errors, the delay is capped, exact exponential growth without jitter, jitter bounds, no float overflow for a large `max_retries`, the original error is attached, and end to end through `table.add` and `table.search` with a stub function (one call and no sleep). On `main` 23 of them fail with the change stashed; the rest are guards that must not change. `test_embeddings.py`: 61 passed, 4 skipped. `ruff format`/`ruff check` are clean on the touched files. Verification caveat: `main`'s Python layer needs a newer native module than the 0.40.0 wheel, so the tests were run with the wheel's native module preloaded through a small shim (the same shim ran the baseline on `main`); a wider run of embeddings/pydantic/query/table tests has the same 36 failures before and after (that mismatch). Not run: real provider APIs (a fake OpenAI-style server was used), Node or Rust code. Fixes #4541 Co-authored-by: Xuanwo --- python/python/lancedb/embeddings/base.py | 8 +- python/python/lancedb/embeddings/utils.py | 103 +++++++-- python/python/tests/test_embeddings.py | 263 ++++++++++++++++++++++ 3 files changed, 354 insertions(+), 20 deletions(-) diff --git a/python/python/lancedb/embeddings/base.py b/python/python/lancedb/embeddings/base.py index 96ca6556c..c11914fab 100644 --- a/python/python/lancedb/embeddings/base.py +++ b/python/python/lancedb/embeddings/base.py @@ -38,9 +38,11 @@ class EmbeddingFunction(BaseModel, ABC): 3. ndims() which returns the number of dimensions of the vector column """ - max_retries: int = ( - 7 # Setting 0 disables retires. Maybe this should not be enabled by default, - ) + # Maximum number of retries for transient errors (rate limits, 5xx responses, + # connection errors, ...), with exponential backoff capped at 60 seconds between + # attempts. Permanent errors (HTTP 4xx other than 408/409/429) are never retried. + # Setting 0 disables retries. + max_retries: int = 7 _ndims: int = PrivateAttr() _original_args: dict = PrivateAttr() diff --git a/python/python/lancedb/embeddings/utils.py b/python/python/lancedb/embeddings/utils.py index fb2a94ecb..ff8fc6a18 100644 --- a/python/python/lancedb/embeddings/utils.py +++ b/python/python/lancedb/embeddings/utils.py @@ -241,15 +241,30 @@ def retry_with_exponential_backoff( exponential_base: float = 2, jitter: bool = True, max_retries: int = 7, + max_delay: float = 60, ): """Retry a function with exponential backoff. + Only errors that may succeed when repeated are retried. Errors that carry an + HTTP status code are retried when the status is 408, 409, 429 or >= 500; any + other 4xx status (for example 400, 401, 403, 404 or 422) is a permanent failure + that is raised immediately. Errors without a recognisable status code (for + example connection errors, timeouts, or exceptions raised by a custom embedding + function) are retried. + + The delay before the n-th retry is ``initial_delay * exponential_base ** n``, + never more than ``max_delay``. With ``jitter`` enabled, a random amount of up to + half of that delay is removed ("equal jitter"), so the actual wait is always in + the range ``[delay / 2, delay]``. + Args: func (function): The function to be retried. initial_delay (float): Initial delay in seconds (default is 1). exponential_base (float): The base for exponential backoff (default is 2). jitter (bool): Whether to add jitter to the delay (default is True). max_retries (int): Maximum number of retries (default is 7). + max_delay (float): Maximum delay between two attempts, in seconds + (default is 60). Returns: function: The decorated function. @@ -265,13 +280,12 @@ def retry_with_exponential_backoff( try: return func(*args, **kwargs) - # Currently retrying on all exceptions as there is no way to know the - # format of the error msgs used by different APIs. We'll log the error - # and say that it is assumed that if this portion errors out, it's due - # to rate limit but the user should check the error message to be sure. + # Errors are retried unless they are known to be permanent (see + # `_is_non_retryable_error`). Custom embedding functions can raise + # arbitrary exceptions, so unknown errors are assumed to be transient. except Exception as e: # noqa: PERF203 - # Don't retry on authentication errors (e.g., OpenAI 401) - # These are permanent failures that won't be fixed by retrying + # Don't retry permanent failures (e.g., OpenAI 401 or 404). They + # won't be fixed by retrying and would only delay the real error. if _is_non_retryable_error(e): raise @@ -280,24 +294,72 @@ def retry_with_exponential_backoff( if num_retries > max_retries: raise Exception( f"Maximum number of retries ({max_retries}) exceeded.", e - ) + ) from e - delay *= exponential_base * (1 + jitter * random.random()) + delay = min(delay * exponential_base, max_delay) + sleep_for = delay + if jitter: + sleep_for = delay / 2 + random.random() * delay / 2 logging.warning( "Error occurred: %s \n Retrying in %s seconds (retry %s of %s) \n", e, - delay, + sleep_for, num_retries, max_retries, ) - time.sleep(delay) + time.sleep(sleep_for) return wrapper +# HTTP statuses in the 4xx range that are worth retrying: request timeout, +# conflict (the OpenAI SDK treats it as transient) and rate limiting. +_RETRYABLE_CLIENT_STATUSES = (408, 409, 429) + +# AWS error codes that are reported with a 4xx status but are transient. +_RETRYABLE_AWS_ERROR_CODES = ( + "Throttl", + "TooManyRequests", + "RequestLimitExceeded", + "ProvisionedThroughputExceeded", + "ModelNotReady", + "ModelTimeout", +) + + +def _get_http_status(error: Exception): + """Best-effort extraction of an HTTP status code from an exception. + + Provider SDKs expose it in different ways: ``status_code`` (openai, cohere), + ``http_status`` (voyageai), ``response.status_code`` (requests, httpx), + ``code`` (google-api-core, urllib) or ``response["ResponseMetadata"]`` + (botocore). Returns None if no status can be found. + """ + candidates = [ + getattr(error, "status_code", None), + getattr(error, "http_status", None), + ] + response = getattr(error, "response", None) + if isinstance(response, dict): + candidates.append(response.get("ResponseMetadata", {}).get("HTTPStatusCode")) + else: + candidates.append(getattr(response, "status_code", None)) + candidates.append(getattr(error, "code", None)) + + for status in candidates: + if isinstance(status, int) and not isinstance(status, bool): + if 100 <= status <= 599: + return status + return None + + def _is_non_retryable_error(error: Exception) -> bool: """Check if an error should not be retried. + An error is non-retryable if it is an authentication error or if it carries an + HTTP client-error status (4xx) other than 408, 409 and 429. Errors without a + recognisable status are treated as retryable. + Args: error: The exception to check @@ -314,18 +376,25 @@ def _is_non_retryable_error(error: Exception) -> bool: if error_type == "AuthenticationError": return True - # Check for other common non-retryable HTTP status codes - # 401 Unauthorized, 403 Forbidden - if hasattr(error, "status_code"): - if error.status_code in (401, 403): - return True - # A missing API key or a missing optional dependency fails the same way on # every attempt if isinstance(error, (MissingApiKeyError, ImportError)): return True - return False + status = _get_http_status(error) + if status is None or not 400 <= status < 500: + return False + if status in _RETRYABLE_CLIENT_STATUSES: + return False + + # AWS reports throttling with a 400 status; the error code tells them apart. + response = getattr(error, "response", None) + if isinstance(response, dict): + aws_code = str(response.get("Error", {}).get("Code", "")) + if aws_code.startswith(_RETRYABLE_AWS_ERROR_CODES): + return False + + return True def url_retrieve(url: str): diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 2438bfe80..129fa6742 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -633,6 +633,269 @@ def test_openai_no_retry_on_401(mock_sleep): assert mock_sleep.call_count == 0 +class _HttpStatusError(Exception): + """Stand-in for provider SDK errors (openai, cohere, ...) with a status code.""" + + def __init__(self, status_code, message="error"): + super().__init__(message) + self.status_code = status_code + + +class _ResponseStatusError(Exception): + """Stand-in for requests/httpx errors, which expose `response.status_code`.""" + + def __init__(self, status_code): + super().__init__(f"HTTP {status_code}") + self.response = MagicMock(status_code=status_code) + + +def _run_with_retry(side_effect, **kwargs): + """Run a function through the retry helper with a mocked `time.sleep`. + + Returns (mock_func, sleeps, error). + """ + from lancedb.embeddings.utils import retry_with_exponential_backoff + + mock_func = MagicMock(side_effect=side_effect) + sleeps = [] + error = None + with patch("time.sleep", side_effect=sleeps.append): + try: + retry_with_exponential_backoff(mock_func, **kwargs)() + except Exception as e: + error = e + return mock_func, sleeps, error + + +@pytest.mark.parametrize("status", [400, 401, 403, 404, 405, 410, 413, 422]) +@pytest.mark.parametrize("make_error", [_HttpStatusError, _ResponseStatusError]) +def test_retry_does_not_retry_permanent_http_errors(status, make_error): + err = make_error(status) + mock_func, sleeps, error = _run_with_retry(err, max_retries=7) + + assert error is err + assert mock_func.call_count == 1 + assert sleeps == [] + + +@pytest.mark.parametrize("status", [408, 409, 429, 500, 502, 503, 504]) +@pytest.mark.parametrize("make_error", [_HttpStatusError, _ResponseStatusError]) +def test_retry_retries_transient_http_errors(status, make_error): + mock_func, sleeps, error = _run_with_retry( + [make_error(status), make_error(status), "result"], max_retries=7 + ) + + assert error is None + assert mock_func.call_count == 3 + assert len(sleeps) == 2 + + +@pytest.mark.parametrize( + "exc", + [ + ConnectionError("connection reset"), + TimeoutError("timed out"), + OSError("network is unreachable"), + ValueError("custom embedding function failure"), + RuntimeError("boom"), + Exception("plain exception"), + ], +) +def test_retry_retries_errors_without_http_status(exc): + mock_func, sleeps, error = _run_with_retry([exc, exc, "result"], max_retries=7) + + assert error is None + assert mock_func.call_count == 3 + assert len(sleeps) == 2 + + +def test_retry_error_status_attributes_of_other_types_are_ignored(): + # `code` is a string for openai errors ("model_not_found"), and arbitrary + # exceptions may carry unrelated numeric attributes. Neither is an HTTP status. + class WeirdError(Exception): + code = "model_not_found" + status_code = None + + class ExitCodeError(Exception): + code = 2 + + for exc in (WeirdError("a"), ExitCodeError("b")): + mock_func, sleeps, error = _run_with_retry(exc, max_retries=2) + assert mock_func.call_count == 3 + assert len(sleeps) == 2 + + +def test_retry_botocore_style_errors(): + # botocore ClientError exposes `response["ResponseMetadata"]["HTTPStatusCode"]`. + # Bedrock reports throttling with a 400, which must stay retryable. + class ClientError(Exception): + def __init__(self, status, code): + super().__init__(code) + self.response = { + "ResponseMetadata": {"HTTPStatusCode": status}, + "Error": {"Code": code}, + } + + throttled = ClientError(400, "ThrottlingException") + mock_func, sleeps, error = _run_with_retry([throttled, "result"], max_retries=3) + assert error is None + assert mock_func.call_count == 2 + + invalid = ClientError(400, "ValidationException") + mock_func, sleeps, error = _run_with_retry(invalid, max_retries=3) + assert error is invalid + assert mock_func.call_count == 1 + assert sleeps == [] + + +def test_retry_authentication_error_by_name_not_retried(): + class AuthenticationError(Exception): + pass + + mock_func, sleeps, error = _run_with_retry(AuthenticationError("bad key")) + assert isinstance(error, AuthenticationError) + assert mock_func.call_count == 1 + assert sleeps == [] + + +def test_retry_gives_up_after_max_retries_with_original_error_attached(): + original = _HttpStatusError(503, "overloaded") + mock_func, sleeps, error = _run_with_retry(original, max_retries=3) + + assert mock_func.call_count == 4 + assert len(sleeps) == 3 + assert "Maximum number of retries (3) exceeded" in str(error) + assert error.args[1] is original + assert error.__cause__ is original + + +def test_retry_delay_is_capped_by_max_delay(): + # Default settings (7 retries, 60s cap): the old implementation could sleep for + # up to ~47 minutes in a single retry and hours in total. + exc = _HttpStatusError(503) + for seed in range(50): + import random + + random.seed(seed) + _, sleeps, _ = _run_with_retry(exc) + assert len(sleeps) == 7 + assert max(sleeps) <= 60 + assert sum(sleeps) <= 7 * 60 + + # Custom cap + _, sleeps, _ = _run_with_retry(exc, max_retries=10, max_delay=5) + assert len(sleeps) == 10 + assert max(sleeps) <= 5 + + +def test_retry_delay_without_jitter_is_exact_exponential_then_capped(): + _, sleeps, _ = _run_with_retry( + _HttpStatusError(500), + initial_delay=1, + exponential_base=2, + jitter=False, + max_retries=8, + max_delay=30, + ) + assert sleeps == [2, 4, 8, 16, 30, 30, 30, 30] + + +def test_retry_jitter_is_bounded(): + # Each wait is within [delay / 2, delay], where delay grows by exponential_base + # per retry (no random factor is compounded across retries). + exc = _HttpStatusError(500) + for seed in range(50): + import random + + random.seed(seed) + _, sleeps, _ = _run_with_retry(exc, max_retries=8, max_delay=100) + for i, slept in enumerate(sleeps): + delay = min(2 ** (i + 1), 100) + assert delay / 2 <= slept <= delay + + # Extremes of the random source map to the ends of the range + with patch("random.random", return_value=0.0): + _, sleeps, _ = _run_with_retry(exc, max_retries=3) + assert sleeps == [1, 2, 4] + with patch("random.random", return_value=1.0): + _, sleeps, _ = _run_with_retry(exc, max_retries=3) + assert sleeps == [2, 4, 8] + + +def test_retry_large_max_retries_does_not_overflow(): + _, sleeps, _ = _run_with_retry(_HttpStatusError(503), max_retries=1500) + assert len(sleeps) == 1500 + assert max(sleeps) <= 60 + + +def _register_failing_embedding(name, error): + """Register an embedding function that always raises `error`. + + Returns the class and a list that records every call. The function is + re-created from table metadata, so the call count has to live outside of it. + """ + calls = [] + + @register(name) + class FailingEmbeddingFunction(TextEmbeddingFunction): + def ndims(self): + return 4 + + def generate_embeddings(self, texts): + calls.append(len(texts)) + raise error + + return FailingEmbeddingFunction, calls + + +@pytest.mark.parametrize("status", [400, 404, 422]) +def test_permanent_embedding_error_is_not_retried(tmp_path, status): + """A permanent provider error (e.g. a misspelled model name) must surface + immediately from both `table.add` and `table.search` instead of being retried + with minutes of backoff.""" + error = _HttpStatusError(status, "The model `typo-embed` does not exist") + cls, calls = _register_failing_embedding(f"failing-embedding-{status}", error) + func = cls.create() # default max_retries=7 + + class Schema(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("t", schema=Schema) + + with patch("time.sleep") as mock_sleep: + with pytest.raises(Exception, match="The model `typo-embed` does not exist"): + table.add([{"text": "hello"}]) + assert len(calls) == 1 + + with pytest.raises(_HttpStatusError, match="does not exist"): + table.search("hello").limit(1).to_list() + assert len(calls) == 2 + + mock_sleep.assert_not_called() + + +def test_transient_embedding_error_is_retried_in_table_add(tmp_path): + cls, calls = _register_failing_embedding( + "failing-embedding-503", _HttpStatusError(503) + ) + func = cls.create(max_retries=2) + + class Schema(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("t", schema=Schema) + + with patch("time.sleep") as mock_sleep: + with pytest.raises(Exception, match="Maximum number of retries"): + table.add([{"text": "hello"}]) + + assert len(calls) == 3 + assert mock_sleep.call_count == 2 + assert all(call.args[0] <= 60 for call in mock_sleep.call_args_list) @patch("time.sleep") @pytest.mark.parametrize( "error", From bc4c32b779de70c4c62a8411ea7eca1c165c9f7e Mon Sep 17 00:00:00 2001 From: Avanish Garg Date: Fri, 23 Oct 2026 00:52:39 +0530 Subject: [PATCH 065/180] fix: keep tagged versions when pruning in optimize (#4544) `optimize()` fails once a tagged version is older than the cleanup cutoff, although the docs say tagged versions are exempt from cleanup, and the failed prune also skips the index-optimize step (repro and numbers in the issue). Change: `OptimizeAction::Prune` already exposes `error_if_tagged_old_versions: Option`, so no new API. `cleanup_old_versions` and `cleanup_old_versions_before` in `rust/lancedb/src/table/optimize.rs` now use `unwrap_or(false)`, which covers `OptimizeAction::Prune`, `OptimizeAction::All` and `optimize_prune_before`. The Python and Node bindings pass `None`, which now means "retain tagged versions"; I left `python/src/table.rs` and `nodejs/src/table.rs` untouched (this also avoids a conflict with #3870, which edits that region). `Some(true)` still opts in to the error. Doc comments updated; the sentence in `docs/web/management/table.mdx` is accurate once this lands. Tests: Rust `test_optimize_prune_retains_tagged_versions` (`Some(true)` still errors; the default retains the tag; `optimize_prune_before`; `checkout_tag` plus a data read), a Python sync test with a scalar index (index step runs, a second optimize works, untagged versions are pruned, `checkout("release-1")` works), a Python async test and a Node test. **What I could and could not verify (please read):** - I could NOT compile Rust here (not enough disk), so `cargo check`, `cargo test`, the Python/Node binding builds and therefore the fixed-path assertions of the new Rust, Python and Node tests have not been run. This is why the PR is a draft; I will mark it ready once CI is green and fix whatever it finds. - Ran: both new Python tests fail on the released 0.40.0 wheel with the exact error above (so they do catch the bug); pylance 13.0.0 confirms the semantics (`cleanup_old_versions(error_if_tagged_old_versions=False)` removes the untagged versions and keeps the tagged one, still readable with `lance.dataset(version="keep")`); in Lance v14.0.0-beta.7 `cleanup.rs` the policy field is `bool`, the builder default is `true`, and Lance's own `auto_cleanup_hook` uses `Some(false)`; `rustfmt --edition 2024 --check` passes on `optimize.rs`. - The Rust and Node tests rely on timestamp ordering (`nextMillisecond()`, `days(0)`/`now()`), so they could be flaky: tell me if you prefer another approach. Behaviour change: anyone who relied on the error to learn that a tag blocks cleanup now gets a silent retain. Not changed: the deprecated sync `LanceTable.cleanup_old_versions` calls pylance directly and still errors on tagged versions (the keyword may not exist in the oldest supported pylance); `freshness.rs:1377` and `refresh.rs:1077` still pass `None` (I did not check what those paths do with tagged versions). Fixes #4543 --- nodejs/__test__/table.test.ts | 15 +++++ python/python/tests/test_table.py | 51 ++++++++++++++ rust/lancedb/src/table/optimize.rs | 105 +++++++++++++++++++++++++++-- 3 files changed, 167 insertions(+), 4 deletions(-) diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 7d10f8b59..84340c72c 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3742,6 +3742,21 @@ describe("when optimizing a dataset", () => { expect(stats.prune.oldVersionsRemoved).toBe(2); }); + it("retains tagged versions older than the cleanup cutoff", async () => { + await (await table.tags()).create("keep", 1); + await table.add([{ id: 3 }]); + + const cutoff = await nextMillisecond(); + const stats = await table.optimize({ cleanupOlderThan: cutoff }); + // Versions 2 and 3 are pruned, tagged version 1 is retained + expect(stats.prune.oldVersionsRemoved).toBe(2); + + await table.checkout("keep"); + expect(await table.countRows()).toBe(1); + await table.checkoutLatest(); + expect(await table.countRows()).toBe(3); + }); + it("delete unverified", async () => { const version = await table.version(); const versionFile = `${tmpDir.name}/${table.name}.lance/_versions/${String( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e23b478f5..b55abfa7e 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4792,6 +4792,57 @@ def test_optimize_warns_on_zero_cleanup_sync(mem_db: DBConnection): assert all("concurrent" in str(w.message) for w in seen) +def test_optimize_retains_tagged_versions(tmp_db: DBConnection): + # A tagged version older than the cleanup cutoff must be retained, not make + # optimize() fail part-way (after compaction, before the index step). + table = tmp_db.create_table( + "test", data=pa.table({"id": list(range(100)), "text": ["a"] * 100}) + ) + table.create_index("id", config=BTree()) + table.tags.create("release-1", table.version) + tagged_version = table.version + for i in range(3): + table.add(pa.table({"id": [1000 + i], "text": ["new"]})) + assert table.stats()["fragment_stats"]["num_fragments"] == 4 + assert table.index_stats("id_idx").num_unindexed_rows == 3 + sleep(1.1) + + table.optimize(cleanup_older_than=timedelta(seconds=1)) + + # The index step ran after the prune step + assert table.index_stats("id_idx").num_unindexed_rows == 0 + # It stays optimizable + table.optimize(cleanup_older_than=timedelta(seconds=1)) + assert table.stats()["fragment_stats"]["num_fragments"] == 1 + + # Untagged old versions were pruned, the tagged one was retained + versions = [v["version"] for v in table.list_versions()] + assert tagged_version in versions + for added in range(tagged_version + 1, tagged_version + 4): + assert added not in versions + assert len(table) == 103 + + table.checkout("release-1") + assert len(table) == 100 + assert table.to_arrow().num_rows == 100 + + +@pytest.mark.asyncio +async def test_optimize_retains_tagged_versions_async(tmp_db_async: AsyncConnection): + table = await tmp_db_async.create_table("test", data=[{"x": [1]}]) + await table.tags.create("keep", await table.version()) + await table.add(data=[{"x": [2]}]) + await table.add(data=[{"x": [3]}]) + sleep(1.1) + + stats = await table.optimize(cleanup_older_than=timedelta(seconds=1)) + assert stats.prune.old_versions_removed >= 1 + + await table.checkout("keep") + assert await table.count_rows() == 1 + assert await table.query().to_arrow() == pa.table({"x": [[1]]}) + + def test_replace_field_metadata(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("my_table", data=[{"x": 0}]) diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 2a502b059..ebe03359c 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -69,7 +69,11 @@ pub enum OptimizeAction { /// **WARNING**: This should only be set to true if you can guarantee that no other process is /// currently working on this dataset. Otherwise the dataset could be put into a corrupted state. delete_unverified: Option, + /// Tagged versions are never removed, regardless of their age. + /// /// If true, an error will be returned if there are any old versions that are still tagged. + /// If false or `None` (the default), tagged versions are silently retained and all other + /// old versions are removed. error_if_tagged_old_versions: Option, }, /// Optimize the indices @@ -125,6 +129,12 @@ pub(crate) async fn optimize_indices(table: &NativeTable, options: &OptimizeOpti /// no other process is currently working on this dataset. Otherwise the /// dataset could be put into a corrupted state. /// +/// * `error_if_tagged_old_versions` - Tagged versions are always retained. If +/// this is true, an error is returned when a tagged version is older than the +/// cutoff. Defaults to false (the tagged versions are retained silently), +/// unlike Lance's own default, so that `optimize` does not fail (and skip the +/// steps after pruning) once a tagged version ages past the cutoff. +/// /// This calls into [lance::dataset::Dataset::cleanup_old_versions] and /// returns the result. pub(crate) async fn cleanup_old_versions( @@ -136,7 +146,11 @@ pub(crate) async fn cleanup_old_versions( table.dataset.ensure_mutable()?; let dataset = table.dataset.get().await?; let stats = dataset - .cleanup_old_versions(older_than, delete_unverified, error_if_tagged_old_versions) + .cleanup_old_versions( + older_than, + delete_unverified, + Some(error_if_tagged_old_versions.unwrap_or(false)), + ) .await?; // Computed-column signature sidecars live outside lance's directories; // drop the ones the surviving versions no longer reference. @@ -161,9 +175,8 @@ pub(crate) async fn cleanup_old_versions_before( if let Some(delete_unverified) = delete_unverified { policy = policy.delete_unverified(delete_unverified); } - if let Some(error_if_tagged_old_versions) = error_if_tagged_old_versions { - policy = policy.error_if_tagged_old_versions(error_if_tagged_old_versions); - } + // Tagged versions are retained rather than raising an error unless asked. + policy = policy.error_if_tagged_old_versions(error_if_tagged_old_versions.unwrap_or(false)); let stats = dataset.cleanup_with_policy(policy.build()).await?; // Computed-column signature sidecars live outside lance's directories; // drop the ones the surviving versions no longer reference. @@ -511,6 +524,90 @@ mod tests { assert_eq!(all_values, expected); } + #[tokio::test] + async fn test_optimize_prune_retains_tagged_versions() { + let tmpdir = tempfile::tempdir().unwrap(); + let conn = connect(tmpdir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)])); + let make_batch = |start: i32| { + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from_iter_values(start..start + 10))], + ) + .unwrap() + }; + + let table = conn + .create_table("test_prune_tagged", make_batch(0)) + .execute() + .await + .unwrap(); + // Tag the first version, then create more versions after it. + table.tags().await.unwrap().create("keep", 1).await.unwrap(); + for i in 1..4 { + table.add(make_batch(i * 10)).execute().await.unwrap(); + } + assert_eq!(table.list_versions().await.unwrap().len(), 4); + + // Explicitly asking for an error still errors, and leaves everything in place. + let err = table + .optimize(OptimizeAction::Prune { + older_than: Some(chrono::Duration::try_days(0).unwrap()), + delete_unverified: Some(true), + error_if_tagged_old_versions: Some(true), + }) + .await + .unwrap_err(); + assert!(err.to_string().contains("tagged version"), "{err}"); + assert_eq!(table.list_versions().await.unwrap().len(), 4); + + // By default, tagged versions are retained and the other old versions are removed. + let stats = table + .optimize(OptimizeAction::Prune { + older_than: Some(chrono::Duration::try_days(0).unwrap()), + delete_unverified: Some(true), + error_if_tagged_old_versions: None, + }) + .await + .unwrap(); + assert_eq!(stats.prune.unwrap().old_versions, 2); + let mut versions = table + .list_versions() + .await + .unwrap() + .into_iter() + .map(|v| v.version) + .collect::>(); + versions.sort(); + assert_eq!(versions, vec![1, 4]); + + // Same through the absolute-cutoff entry point used by the Node binding. + table.add(make_batch(40)).execute().await.unwrap(); + let stats = table + .optimize_prune_before(chrono::Utc::now(), Some(true), None) + .await + .unwrap(); + assert_eq!(stats.prune.unwrap().old_versions, 1); + + // The tagged version is still readable, including its data files. + assert_eq!(table.count_rows(None).await.unwrap(), 50); + table.checkout_tag("keep").await.unwrap(); + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let rows: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(rows, 10); + } + #[tokio::test] async fn test_optimize_index() { let conn = connect("memory://").execute().await.unwrap(); From 5fa30ae404fc7df335c8031ae474400b834c62b2 Mon Sep 17 00:00:00 2001 From: Yash Raj Pandey <55940078+devYRPauli@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:22:53 -0400 Subject: [PATCH 066/180] fix(python): honor explicit Cohere and VoyageAI reranker API keys (#4546) `CohereReranker` and `VoyageAIReranker` read the environment variable before the `api_key` argument. When `COHERE_API_KEY` or `VOYAGE_API_KEY` is set, the reranker ignores an explicit `api_key` and uses the account from the environment. The docs say the opposite. `docs/web/integrations/reranking/cohere.mdx` and `voyageai.mdx` use the environment variable only when `api_key` is not provided. `JinaReranker` and `WatsonxReranker` already put the explicit key first, and #4515 makes the same change for `OpenaiReranker`. ## Fix `CohereReranker._client` and `VoyageAIReranker._client` now use `self.api_key` first and the environment variable as the fallback. ## Tests `python/python/tests/test_reranker_credentials.py` replaces the SDK module with a stub whose `Client` records the API key. It covers both keys set, each key alone, and no key. With the stub, the test runs without `cohere` or `voyageai` installed. - On `main`, the 2 cases with both keys set fail and the other 6 pass. With the fix, all 8 pass. - `test_rerankers.py` with the new file: 24 passed, 13 skipped (the skipped tests need real API keys). - `ruff format --check` and `ruff check` (0.9.9) pass on the changed files. - I did not build the native extension. I ran the tests against the lancedb 0.40.0 wheel with the changed files copied over it. In that wheel, both reranker files are byte-identical to `main` before this change. Co-authored-by: Claude Opus 5.5 --- python/python/lancedb/rerankers/cohere.py | 2 +- python/python/lancedb/rerankers/voyageai.py | 2 +- .../python/tests/test_reranker_credentials.py | 74 +++++++++++++++++++ 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 python/python/tests/test_reranker_credentials.py diff --git a/python/python/lancedb/rerankers/cohere.py b/python/python/lancedb/rerankers/cohere.py index efd752c22..a1e797f15 100644 --- a/python/python/lancedb/rerankers/cohere.py +++ b/python/python/lancedb/rerankers/cohere.py @@ -62,7 +62,7 @@ class CohereReranker(Reranker): "COHERE_API_KEY not set. Either set it in your environment or \ pass it as `api_key` argument to the CohereReranker." ) - return cohere.Client(os.environ.get("COHERE_API_KEY") or self.api_key) + return cohere.Client(self.api_key or os.environ.get("COHERE_API_KEY")) def _rerank(self, result_set: pa.Table, query: str): result_set = self._handle_empty_results(result_set) diff --git a/python/python/lancedb/rerankers/voyageai.py b/python/python/lancedb/rerankers/voyageai.py index d3dbd59ac..28847564b 100644 --- a/python/python/lancedb/rerankers/voyageai.py +++ b/python/python/lancedb/rerankers/voyageai.py @@ -64,7 +64,7 @@ class VoyageAIReranker(Reranker): pass it as `api_key` argument to the VoyageAIReranker." ) return voyageai.Client( - api_key=os.environ.get("VOYAGE_API_KEY") or self.api_key, + api_key=self.api_key or os.environ.get("VOYAGE_API_KEY"), ) def _rerank(self, result_set: pa.Table, query: str): diff --git a/python/python/tests/test_reranker_credentials.py b/python/python/tests/test_reranker_credentials.py new file mode 100644 index 000000000..c8f63a9ef --- /dev/null +++ b/python/python/tests/test_reranker_credentials.py @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import sys +import types + +import pytest + +from lancedb.rerankers import CohereReranker, VoyageAIReranker + +RERANKERS = [ + pytest.param("cohere", "COHERE_API_KEY", CohereReranker, {}, id="cohere"), + pytest.param( + "voyageai", + "VOYAGE_API_KEY", + VoyageAIReranker, + {"model_name": "rerank-2.5"}, + id="voyageai", + ), +] + + +def fake_sdk(monkeypatch, module_name): + """Replace the SDK module with one whose Client records the API key.""" + keys = [] + + def client(api_key=None): + keys.append(api_key) + return object() + + module = types.ModuleType(module_name) + module.Client = client + monkeypatch.setitem(sys.modules, module_name, module) + return keys + + +@pytest.mark.parametrize("module_name, env_var, reranker_cls, kwargs", RERANKERS) +@pytest.mark.parametrize( + "explicit_key, environment_key, expected_key", + [ + ("explicit-test-key", "environment-test-key", "explicit-test-key"), + ("explicit-test-key", None, "explicit-test-key"), + (None, "environment-test-key", "environment-test-key"), + ], +) +def test_reranker_api_key_precedence( + monkeypatch, + module_name, + env_var, + reranker_cls, + kwargs, + explicit_key, + environment_key, + expected_key, +): + keys = fake_sdk(monkeypatch, module_name) + if environment_key is None: + monkeypatch.delenv(env_var, raising=False) + else: + monkeypatch.setenv(env_var, environment_key) + + reranker_cls(api_key=explicit_key, **kwargs)._client + assert keys == [expected_key] + + +@pytest.mark.parametrize("module_name, env_var, reranker_cls, kwargs", RERANKERS) +def test_reranker_requires_api_key( + monkeypatch, module_name, env_var, reranker_cls, kwargs +): + keys = fake_sdk(monkeypatch, module_name) + monkeypatch.delenv(env_var, raising=False) + with pytest.raises(ValueError, match=f"{env_var} not set"): + reranker_cls(**kwargs)._client + assert keys == [] From 353ce4d80c9e66f8f1ac9e49dbcec0ec899f1f9d Mon Sep 17 00:00:00 2001 From: Yash Raj Pandey <55940078+devYRPauli@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:23:07 -0400 Subject: [PATCH 067/180] fix(python): give each JinaEmbeddings instance its own session (#4547) `JinaEmbeddings` stores its `requests` session in a `ClassVar`. The first instance builds the session with its own API key, and every later instance reuses that session. So a second instance with a different `api_key` sends the first instance's key. ## Fix The session is now a per-instance `cached_property`, the same pattern `OpenAIEmbeddings` uses for `_openai_client`. `_init_client` and the `ClassVar` are gone. An instance with no `api_key` and no `JINA_API_KEY` now raises the missing-key error. Before, it reused the session of an earlier instance and sent that instance's key. ## Tests `test_jina_embeddings_use_their_own_api_key` creates two instances with different keys through the registry. It stubs `requests.Session.post` and records the `Authorization` header of each request. - On `main`, the test fails because both requests send `Bearer key-a`. With the fix, it passes. - `test_embeddings.py`: 18 passed, 8 skipped. - An instance still pickles after the session exists, and `safe_model_dump()` still returns only `api_key`. - On pydantic 2.7.4, the minimum version, a model with the same `cached_property` gets one session per instance and leaves it out of `model_dump()`. - `ruff format --check` and `ruff check` (0.9.9) pass on the changed files. - I did not build the native extension. I ran the tests against the lancedb 0.40.0 wheel with the changed file copied over it. In that wheel, `embeddings/jinaai.py` is byte-identical to `main` before this change. Co-authored-by: Claude Opus 5.5 --- python/python/lancedb/embeddings/jinaai.py | 26 +++++++++++----------- python/python/tests/test_embeddings.py | 25 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/python/python/lancedb/embeddings/jinaai.py b/python/python/lancedb/embeddings/jinaai.py index f6ab601b3..25b5a940b 100644 --- a/python/python/lancedb/embeddings/jinaai.py +++ b/python/python/lancedb/embeddings/jinaai.py @@ -5,9 +5,10 @@ import os import io import base64 +from functools import cached_property from urllib.parse import urlparse from pathlib import Path -from typing import TYPE_CHECKING, ClassVar, List, Union, Optional, Any, Dict +from typing import TYPE_CHECKING, List, Union, Optional, Any, Dict import numpy as np import pyarrow as pa @@ -51,7 +52,6 @@ class JinaEmbeddings(EmbeddingFunction): name: str = "jina-clip-v1" api_key: Optional[str] = None - _session: ClassVar = None def ndims(self): # TODO: fix hardcoding @@ -206,8 +206,7 @@ class JinaEmbeddings(EmbeddingFunction): texts: list[str] or np.ndarray (of str) The texts to embed """ - self._init_client() - resp = JinaEmbeddings._session.post( # type: ignore + resp = self._session.post( API_URL, json={"input": input, "model": self.name} ).json() if "data" not in resp: @@ -220,14 +219,15 @@ class JinaEmbeddings(EmbeddingFunction): return [result["embedding"] for result in sorted_embeddings] - def _init_client(self): + @cached_property + def _session(self): import requests - if JinaEmbeddings._session is None: - if self.api_key is None and os.environ.get("JINA_API_KEY") is None: - api_key_not_found_help("jina") - api_key = self.api_key or os.environ.get("JINA_API_KEY") - JinaEmbeddings._session = requests.Session() - JinaEmbeddings._session.headers.update( - {"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"} - ) + if self.api_key is None and os.environ.get("JINA_API_KEY") is None: + api_key_not_found_help("jina") + api_key = self.api_key or os.environ.get("JINA_API_KEY") + session = requests.Session() + session.headers.update( + {"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"} + ) + return session diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 129fa6742..e319d3048 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -1053,3 +1053,28 @@ def test_jina_generate_image_input_dict_local_path(tmp_path): image_dict = JinaEmbeddings._generate_image_input_dict(image) assert "image" in image_dict assert isinstance(image_dict["image"], str) and len(image_dict["image"]) > 0 + + +def test_jina_embeddings_use_their_own_api_key(monkeypatch): + """Each JinaEmbeddings instance must send its own API key.""" + pytest.importorskip("requests") + monkeypatch.delenv("JINA_API_KEY", raising=False) + registry = get_registry() + registry.set_var("jina_key_a", "key-a") + registry.set_var("jina_key_b", "key-b") + func_a = registry.get("jina").create(api_key="$var:jina_key_a") + func_b = registry.get("jina").create(api_key="$var:jina_key_b") + + sent = [] + + def fake_post(session, url, json=None, **kwargs): + sent.append(session.headers["Authorization"]) + response = MagicMock() + response.json.return_value = {"data": [{"index": 0, "embedding": [0.0]}]} + return response + + with patch("requests.Session.post", fake_post): + func_a.compute_source_embeddings(["hello"]) + func_b.compute_source_embeddings(["hello"]) + + assert sent == ["Bearer key-a", "Bearer key-b"] From 2af7d88ec7e974484e1be0d9f7bfba53732e0ef6 Mon Sep 17 00:00:00 2001 From: Yash Raj Pandey <55940078+devYRPauli@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:23:21 -0400 Subject: [PATCH 068/180] fix(python): keep OpenaiReranker scores on the rows they rate (#4549) `OpenaiReranker._rerank` asks the chat model for a relevance score per document. The model can return the documents in any order, for example sorted by score. The reranker then replaces the `text` column with the documents in that order and appends the scores in that order. The other columns keep the input order. So after a rerank, the `text` and `_relevance_score` of a row belong to a different row. The `id`, the vector and every other column still describe the original row. If the model leaves out a document, `append_column` raises `ArrowInvalid`, because the new column has fewer rows than the table. ## Fix `_rerank` keeps the `text` column unchanged, so it also keeps its position and type. It maps each score back to its row by the document content. If the model leaves out a document, `_rerank` raises a `ValueError` that gives the number of documents with no score. ## Tests `python/python/tests/test_openai_reranker.py` replaces the chat client with a stub that returns a fixed reply. The tests do not need `openai` or an API key. - One test returns the documents sorted by score. It checks that each `id` keeps its own `text` and score. On `main`, the row with id 1 gets the text `cats purr`, which belongs to id 2. - One test returns 2 of 3 documents. It checks for the `ValueError` with the count of missing documents. On `main`, the call raises `ArrowInvalid: Added column's length must match table's length`. - Both tests fail on `main` and pass with the fix. - `test_rerankers.py`: 16 passed, 13 skipped, on the lancedb 0.40.0 wheel with and without the fix. The skipped tests need real API keys. - `ruff format --check` and `ruff check` (0.9.9) pass on the changed files. - I did not build the native extension. I ran the tests against the lancedb 0.40.0 wheel with the changed file copied over it. In that wheel, `rerankers/openai.py` and `rerankers/base.py` are byte-identical to `main`. The Node SDK has no OpenAI reranker, so there is no parity change. This change does not conflict with #4515, which edits `_client` in the same file. Co-authored-by: Claude Opus 5.5 --- python/python/lancedb/rerankers/openai.py | 21 ++++--- python/python/tests/test_openai_reranker.py | 66 +++++++++++++++++++++ 2 files changed, 78 insertions(+), 9 deletions(-) create mode 100644 python/python/tests/test_openai_reranker.py diff --git a/python/python/lancedb/rerankers/openai.py b/python/python/lancedb/rerankers/openai.py index 4cbbb0822..da0394d1c 100644 --- a/python/python/lancedb/rerankers/openai.py +++ b/python/python/lancedb/rerankers/openai.py @@ -70,15 +70,18 @@ class OpenaiReranker(Reranker): ], ) results = json.loads(response.choices[0].message.content)["documents"] - docs, scores = list( - zip(*[(result["content"], result["relevance_score"]) for result in results]) - ) # tuples - # replace the self.column column with the docs - result_set = result_set.drop(self.column) - result_set = result_set.append_column( - self.column, pa.array(docs, type=pa.string()) - ) - # add the scores + # The model returns the documents in its own order, so match each score + # back to its row by content. + scores_by_content = { + result["content"]: result["relevance_score"] for result in results + } + missing = sum(doc not in scores_by_content for doc in docs) + if missing: + raise ValueError( + f"The model returned no relevance_score for {missing} of " + f"{len(docs)} documents" + ) + scores = [scores_by_content[doc] for doc in docs] result_set = result_set.append_column( "_relevance_score", pa.array(scores, type=pa.float32()) ) diff --git a/python/python/tests/test_openai_reranker.py b/python/python/tests/test_openai_reranker.py new file mode 100644 index 000000000..43475103f --- /dev/null +++ b/python/python/tests/test_openai_reranker.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from types import SimpleNamespace + +import pyarrow as pa +import pytest + +from lancedb.rerankers import OpenaiReranker + + +def reranker_replying(documents): + """Return an OpenaiReranker whose chat client replies with these documents.""" + reply = json.dumps({"documents": documents}) + + def create(**kwargs): + message = SimpleNamespace(content=reply) + return SimpleNamespace(choices=[SimpleNamespace(message=message)]) + + reranker = OpenaiReranker(api_key="test-key") + reranker.__dict__["_client"] = SimpleNamespace( + chat=SimpleNamespace(completions=SimpleNamespace(create=create)) + ) + return reranker + + +def vector_results(): + return pa.table( + { + "id": [1, 2, 3], + "text": ["dogs bark", "cats purr", "birds sing"], + "_distance": [0.1, 0.2, 0.3], + } + ) + + +def test_scores_stay_with_their_rows_when_the_model_reorders(): + reranker = reranker_replying( + [ + {"content": "cats purr", "relevance_score": 0.9}, + {"content": "birds sing", "relevance_score": 0.5}, + {"content": "dogs bark", "relevance_score": 0.1}, + ] + ) + + result = reranker.rerank_vector("which animal purrs?", vector_results()) + + assert result.select(["id", "text"]).to_pylist() == [ + {"id": 2, "text": "cats purr"}, + {"id": 3, "text": "birds sing"}, + {"id": 1, "text": "dogs bark"}, + ] + assert result["_relevance_score"].to_pylist() == pytest.approx([0.9, 0.5, 0.1]) + + +def test_a_row_the_model_leaves_out_raises(): + reranker = reranker_replying( + [ + {"content": "cats purr", "relevance_score": 0.9}, + {"content": "dogs bark", "relevance_score": 0.1}, + ] + ) + + with pytest.raises(ValueError, match="1 of 3"): + reranker.rerank_vector("which animal purrs?", vector_results()) From 0cb5bd0a5d7b96ebafa83dc0f98f98f6af70a189 Mon Sep 17 00:00:00 2001 From: Captain <42566883+po-et@users.noreply.github.com> Date: Fri, 23 Oct 2026 03:23:36 +0800 Subject: [PATCH 069/180] fix(python): accept VoyageAI text batch containers (#4558) Direct VoyageAI `compute_source_embeddings()` calls reject `list[str]` and NumPy text batches before reaching the provider, although both belong to the declared `TEXT` input type. For example, `["first", "second"]` raises `ValueError: Input type not allowed with text model.` Normalize these containers to a list before the existing string-entry validation. The regression cases exercise the public embedding API with a stub provider: input order, list/NumPy batches, Arrow controls, empty batches, and rejection of non-text entries and ordinary two-dimensional arrays. The VoyageAI integration page now documents the accepted text containers. Verified on current main `7b3ba4c` with a locally compiled native extension (0.41.0b7, Python 3.12.12): - VoyageAI suite: 7 failed / 20 passed before the fix; 27 passed afterward. - Adjacent embedding suite: 13 passed, 4 skipped, 8 slow cases deselected. - Python CI's pinned Ruff 0.9.9 lint/format checks pass; configured Pyright reports zero errors/warnings; all applicable pre-commit hooks pass. The provider is stubbed; no live Voyage API request or model-quality evaluation was performed. AI disclosure: I used Codex for investigation, implementation, tests, review, and drafting this description. --- docs/web/integrations/embedding/voyageai.mdx | 4 +- python/python/lancedb/embeddings/voyageai.py | 2 + .../python/tests/test_voyageai_embeddings.py | 57 +++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/docs/web/integrations/embedding/voyageai.mdx b/docs/web/integrations/embedding/voyageai.mdx index cfa795841..c0741b39b 100644 --- a/docs/web/integrations/embedding/voyageai.mdx +++ b/docs/web/integrations/embedding/voyageai.mdx @@ -45,6 +45,8 @@ Supported parameters (to be passed in `create` method) are: | `output_dimension` | `int` | `None` | Output embedding dimension. Only supported by `voyage-multimodal-3.5`. Valid options: 256, 512, 1024 (default), 2048. | +For text models, `compute_source_embeddings()` accepts a single string, a list of strings, a one-dimensional NumPy array, or a PyArrow `Array` or `ChunkedArray`. Batch inputs retain their order. + Usage Example: @@ -61,4 +63,4 @@ The `voyage-multimodal-3.5` model can embed text alongside images. You can use i {PyEmbeddingVoyageaiMultimodal} - \ No newline at end of file + diff --git a/python/python/lancedb/embeddings/voyageai.py b/python/python/lancedb/embeddings/voyageai.py index 4a721c998..95525e07b 100644 --- a/python/python/lancedb/embeddings/voyageai.py +++ b/python/python/lancedb/embeddings/voyageai.py @@ -145,6 +145,8 @@ def sanitize_text_input(inputs: TEXT) -> List[str]: """ if isinstance(inputs, str): inputs = [inputs] + elif isinstance(inputs, (list, np.ndarray)): + inputs = list(inputs) elif isinstance(inputs, pa.Array): inputs = inputs.to_pylist() elif isinstance(inputs, pa.ChunkedArray): diff --git a/python/python/tests/test_voyageai_embeddings.py b/python/python/tests/test_voyageai_embeddings.py index 040cade1f..d49978fb3 100644 --- a/python/python/tests/test_voyageai_embeddings.py +++ b/python/python/tests/test_voyageai_embeddings.py @@ -6,6 +6,8 @@ These tests verify model registration and configuration without requiring API calls. """ +import numpy as np +import pyarrow as pa import pytest from unittest.mock import MagicMock, patch @@ -122,3 +124,58 @@ class TestVoyageAIModelRegistration: assert "voyage-4" not in func.multimodal_embedding_models assert "voyage-4-lite" not in func.multimodal_embedding_models assert "voyage-4-large" not in func.multimodal_embedding_models + + +@pytest.mark.parametrize( + "inputs", + [ + ["first", "second"], + np.array(["first", "second"]), + pa.array(["first", "second"]), + pa.chunked_array([["first"], ["second"]]), + ], + ids=["list", "numpy", "arrow", "chunked-arrow"], +) +def test_text_source_embeddings_accept_batch_containers(inputs): + from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + client = MagicMock() + client.tokenize.return_value = [[1], [2]] + client.embed.return_value.embeddings = [[0.1, 0.2], [0.3, 0.4]] + VoyageAIEmbeddingFunction.client = client + func = get_registry().get("voyageai").create(name="voyage-3") + + assert func.compute_source_embeddings(inputs) == [[0.1, 0.2], [0.3, 0.4]] + client.embed.assert_called_once_with( + texts=["first", "second"], model="voyage-3", input_type="document" + ) + + +@pytest.mark.parametrize("inputs", [[], np.array([], dtype=str)]) +def test_text_source_embeddings_accept_empty_batch(inputs): + from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + client = MagicMock() + VoyageAIEmbeddingFunction.client = client + func = get_registry().get("voyageai").create(name="voyage-3") + + assert func.compute_source_embeddings(inputs) == [] + client.tokenize.assert_not_called() + client.embed.assert_not_called() + + +@pytest.mark.parametrize( + "inputs", + [["text", 42], np.array(["text", None]), np.array([["first", "second"]])], +) +def test_text_source_embeddings_reject_non_text_batch_entries(inputs): + from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + client = MagicMock() + VoyageAIEmbeddingFunction.client = client + func = get_registry().get("voyageai").create(name="voyage-3") + + with pytest.raises(ValueError, match="Each input should be str"): + func.compute_source_embeddings(inputs) + client.tokenize.assert_not_called() + client.embed.assert_not_called() From 118e606e8e06b6aa3ad57839184f655d996ae831 Mon Sep 17 00:00:00 2001 From: Srijan Keshri <212402043+arcusbuilds@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:53:50 +0530 Subject: [PATCH 070/180] fix(python): align vector parent indices after flattening null lists (#4572) Arrow's `flatten()` skips child values hidden under null list parents, but `list_parent_indices()` can retain their indices. This makes `has_nan_values()` raise `ArrowInvalid` because the parent indices and NaN mask have different lengths. Filter out indices belonging to null parents before applying the mask. The regression test covers `ListArray` and `LargeListArray`, float16/32/64, and chunked inputs: 12 cases. NaN and null-component policies stay the same. The crash also affects #4503. This patch fixes it separately from that PR's changes to bad-vector policies. Validation: - All 12 regression cases failed before the fix. The utility suite now passes with 87 passed and 1 skipped. - Ruff lint and formatting pass for both changed files, as does `git diff --check`. - The patch applies cleanly to main at `ca275b6d`. The patched helper from that revision also passes all 12 cases. - A separate AI reviewer checked commit `343082a6` and found no blocking issues. They reran the utility suite and compared 4,059 generated cases plus 12 explicit null-parent cases with a row-by-row reference implementation. Those checks include slices, chunked inputs, and fixed-size lists. SDK tests used base `07e626ec` with the existing compiled extension. The broader Python run stopped after 474 passed and 23 skipped at `test_local_module_outside_code_warns_at_registration` with `ModuleNotFoundError`. That test also fails with the original vector helper restored. Repository-wide Ruff reports 49 lint errors and 11 files needing formatting, all in untouched documentation examples. Full SDK integration tests against current main require a newer native build and have not been run. --- python/python/lancedb/table.py | 5 +++++ python/python/tests/test_util.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index c7de4161d..5eea55760 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -5333,6 +5333,11 @@ def has_nan_values(arr: Union[pa.ListArray, pa.ChunkedArray]) -> pa.BooleanArray else: values_has_nan = pc.is_nan(values) values_indices = pc.list_parent_indices(arr) + if arr.null_count: + # Match flatten(), which excludes child spans under null parent lists. + values_indices = pc.filter( + values_indices, pc.take(pc.is_valid(arr), values_indices) + ) has_nan_indices = pc.unique(pc.filter(values_indices, values_has_nan)) indices = pa.array(range(len(arr)), type=pa.uint32()) return pc.is_in(indices, has_nan_indices) diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index 4671109b8..4fb16bb31 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -21,6 +21,7 @@ from lancedb.table import ( _infer_target_schema, _merge_metadata, _sanitize_data, + has_nan_values, sanitize_create_table, ) import pyarrow as pa @@ -489,6 +490,20 @@ def test_handle_bad_vectors_nan(on_bad_vectors): assert output["vector"].combine_chunks() == expected +@pytest.mark.parametrize("dtype", [pa.float16(), pa.float32(), pa.float64()]) +@pytest.mark.parametrize("large", [False, True]) +@pytest.mark.parametrize("chunked", [False, True]) +def test_has_nan_values_skips_hidden_children_of_null_lists(dtype, large, chunked): + array_type = pa.LargeListArray if large else pa.ListArray + values = pa.array([float("nan"), None, float("nan"), 3.0, 4.0, 5.0], type=dtype) + arr = array_type.from_arrays( + [0, 2, 4, 6], values, mask=pa.array([True, False, False]) + ) + if chunked: + arr = pa.chunked_array([arr.slice(0, 2), arr.slice(2, 1)]) + assert has_nan_values(arr).to_pylist() == [False, True, False] + + def test_handle_bad_vectors_noop(): # ChunkedArray should be preserved as-is vector = pa.chunked_array( From f2c6aa35c236e04b012c150ce94dcc6fc09fd2f7 Mon Sep 17 00:00:00 2001 From: Captain <42566883+po-et@users.noreply.github.com> Date: Fri, 23 Oct 2026 03:24:04 +0800 Subject: [PATCH 071/180] fix(python): normalize VoyageAI image modes before JPEG encoding (#4576) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PIL images, PNG bytes and local image paths in VoyageAI source embeddings are saved directly as JPEG. RGBA, grayscale-with-alpha (LA) and palette (P) images therefore raise `OSError: cannot write mode ... as JPEG` before the provider is called. Convert to RGB at all three JPEG encoding sites. The caller’s original PIL image remains unchanged. Document that alpha is discarded and callers should composite onto a chosen background when it matters. Validation: - New image regressions + existing VoyageAI tests: **18 failed / 26 passed before → 44 passed after**. Tests cover both multimodal models, PIL/bytes/Path, RGBA/LA/P/RGB, decoded JPEG pixels and invalid images. - Independent local LanceDB table ingestion smoke: three PNG modes stored with 1024-dimensional vectors, original bytes preserved. Uses the freshly built current native extension. - Adjacent local embedding tests: 15 passed, 1 skipped (no OpenAI key), 9 deselected. The separate Flickr download test failed with `RemoteDisconnected`; it is excluded from the local result. - Pyright: 0 errors; CI-pinned Ruff 0.9.9 lint and Python formatting passed. External VoyageAI calls are stubbed; real Pillow conversion and LanceDB ingestion execute locally. No live provider or full-repository test result is claimed. AI assistance was used for implementation and validation. --- docs/web/integrations/embedding/voyageai.mdx | 7 +- python/python/lancedb/embeddings/voyageai.py | 6 +- .../tests/test_voyageai_image_inputs.py | 88 +++++++++++++++++++ 3 files changed, 97 insertions(+), 4 deletions(-) create mode 100644 python/python/tests/test_voyageai_image_inputs.py diff --git a/docs/web/integrations/embedding/voyageai.mdx b/docs/web/integrations/embedding/voyageai.mdx index c0741b39b..957ab2b4d 100644 --- a/docs/web/integrations/embedding/voyageai.mdx +++ b/docs/web/integrations/embedding/voyageai.mdx @@ -57,7 +57,12 @@ Usage Example: ### Multimodal Example {#multimodal-example} -The `voyage-multimodal-3.5` model can embed text alongside images. You can use image URLs, file paths, or PIL Image objects: +The `voyage-multimodal-3.5` model can embed text alongside images. You can use image URLs, local `pathlib.Path` objects, raw image bytes, or PIL Image objects. + +For source embeddings, PIL images and images loaded from bytes or local paths are +converted to RGB and encoded as JPEG. This supports RGBA, grayscale with alpha, +and palette images; transparency is discarded. Composite transparent images onto +your chosen background before embedding if the background color matters. diff --git a/python/python/lancedb/embeddings/voyageai.py b/python/python/lancedb/embeddings/voyageai.py index 95525e07b..bcb2fd5a3 100644 --- a/python/python/lancedb/embeddings/voyageai.py +++ b/python/python/lancedb/embeddings/voyageai.py @@ -75,7 +75,7 @@ def transform_input(input_data: Union[str, bytes, Path]): content = {"type": "text", "text": input_data} elif isinstance(input_data, PIL_Image.Image): buffered = BytesIO() - input_data.save(buffered, format="JPEG") + input_data.convert("RGB").save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") content = { "type": "image_base64", @@ -84,7 +84,7 @@ def transform_input(input_data: Union[str, bytes, Path]): elif isinstance(input_data, bytes): img = PIL_Image.open(BytesIO(input_data)) buffered = BytesIO() - img.save(buffered, format="JPEG") + img.convert("RGB").save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") content = { "type": "image_base64", @@ -103,7 +103,7 @@ def transform_input(input_data: Union[str, bytes, Path]): else: img = PIL_Image.open(input_data) buffered = BytesIO() - img.save(buffered, format="JPEG") + img.convert("RGB").save(buffered, format="JPEG") img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") content = { "type": "image_base64", diff --git a/python/python/tests/test_voyageai_image_inputs.py b/python/python/tests/test_voyageai_image_inputs.py new file mode 100644 index 000000000..885f94821 --- /dev/null +++ b/python/python/tests/test_voyageai_image_inputs.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import base64 +from io import BytesIO +from unittest.mock import MagicMock + +import pytest + +from lancedb.embeddings import get_registry +from lancedb.embeddings.voyageai import VoyageAIEmbeddingFunction + + +@pytest.mark.parametrize("model_name", ["voyage-multimodal-3", "voyage-multimodal-3.5"]) +@pytest.mark.parametrize("input_kind", ["pil", "bytes", "path"]) +@pytest.mark.parametrize( + "mode,color,expected_rgb", + [ + ("RGBA", (64, 128, 192, 128), (64, 128, 192)), + ("LA", (96, 128), (96, 96, 96)), + ("P", 0, (64, 128, 192)), + ("RGB", (64, 128, 192), (64, 128, 192)), + ], +) +def test_multimodal_source_embeddings_encode_image_modes( + model_name, input_kind, mode, color, expected_rgb, tmp_path, monkeypatch +): + Image = pytest.importorskip("PIL.Image") + image = Image.new(mode, (8, 6), color) + if mode == "P": + image.putpalette([64, 128, 192] + [0, 0, 0] * 255) + image.info["transparency"] = 0 + original_pixels = image.tobytes() + image_input = image + if input_kind != "pil": + png = BytesIO() + image.save(png, format="PNG") + if input_kind == "bytes": + image_input = png.getvalue() + else: + image_input = tmp_path / "image.png" + image_input.write_bytes(png.getvalue()) + + client = MagicMock() + client.multimodal_embed.return_value.embeddings = [[0.1, 0.2]] + monkeypatch.setattr(VoyageAIEmbeddingFunction, "client", client) + func = get_registry().get("voyageai").create(name=model_name) + + assert func.compute_source_embeddings(image_input) == [[0.1, 0.2]] + + client.multimodal_embed.assert_called_once() + request = client.multimodal_embed.call_args.kwargs + assert request["model"] == model_name + assert request["input_type"] == "document" + assert len(request["inputs"]) == 1 + (content,) = request["inputs"][0]["content"] + assert content["type"] == "image_base64" + prefix, encoded = content["image_base64"].split(",", 1) + assert prefix == "data:image/jpeg;base64" + with Image.open(BytesIO(base64.b64decode(encoded, validate=True))) as decoded: + assert decoded.format == "JPEG" + assert decoded.mode == "RGB" + assert decoded.size == (8, 6) + assert decoded.getpixel((0, 0)) == pytest.approx(expected_rgb, abs=3) + assert image.mode == mode + assert image.tobytes() == original_pixels + client.embed.assert_not_called() + + +@pytest.mark.parametrize("input_kind", ["bytes", "path"]) +def test_multimodal_source_embeddings_reject_invalid_image( + input_kind, tmp_path, monkeypatch +): + PIL = pytest.importorskip("PIL") + image_input = b"not an image" + if input_kind == "path": + image_input = tmp_path / "invalid.png" + image_input.write_bytes(b"not an image") + + client = MagicMock() + monkeypatch.setattr(VoyageAIEmbeddingFunction, "client", client) + func = get_registry().get("voyageai").create(name="voyage-multimodal-3") + + with pytest.raises(PIL.UnidentifiedImageError): + func.compute_source_embeddings(image_input) + + client.multimodal_embed.assert_not_called() + client.embed.assert_not_called() From 566517be05ff39d3fc6445c5031abccceecf11eb Mon Sep 17 00:00:00 2001 From: Raphael Fakhri Date: Thu, 22 Oct 2026 22:24:23 +0300 Subject: [PATCH 072/180] fix(python): apply pyarrow expression filters in PyarrowDatasetAdapter (#4592) `PyarrowDatasetAdapter` lets DuckDB query a LanceDB table, but DuckDB pushes `WHERE` clauses into `Dataset.scanner(filter=...)` as `pyarrow.compute.Expression` objects. The adapter forwarded them to `Table.count_rows` and `LanceQueryBuilder.where`, which accept only SQL strings, so every filtered DuckDB query failed with `TypeError: argument 'filter': 'Expression' object is not an instance of 'str'`. This change: - Applies a `pyarrow.compute.Expression` filter locally with `pyarrow.dataset.Scanner.from_batches`. The scan reads all columns and pyarrow applies the filter and projection, because DuckDB can filter on a column it does not project. - Applies `head` limits after the filter, so the limit counts matching rows. - Routes `PyarrowDatasetAdapter.count_rows(filter)` through the scanner, so it accepts both filter types. SQL string filters keep the existing path and still run inside LanceDB. Fixes #4591 ### Testing - New `test_dataset_adapter_expression_filter` in `test_pyarrow.py` covers `count_rows`, `to_table`, `head` and a projection that excludes the filtered column. - New `test_query_with_filter` in `test_duckdb.py` runs DuckDB queries with a `WHERE` clause. - Both tests fail without the fix and pass with it. `ruff check` and `ruff format --check` pass. --- python/python/lancedb/integrations/pyarrow.py | 24 ++++++++++++++++++- python/python/tests/test_duckdb.py | 16 +++++++++++++ python/python/tests/test_pyarrow.py | 17 +++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/integrations/pyarrow.py b/python/python/lancedb/integrations/pyarrow.py index 085964690..1626a6b57 100644 --- a/python/python/lancedb/integrations/pyarrow.py +++ b/python/python/lancedb/integrations/pyarrow.py @@ -52,6 +52,9 @@ class PyarrowScannerAdapter(pa.dataset.Scanner): raise NotImplementedError("memory_pool not supported") def count_rows(self): + if isinstance(self.filter, pa.compute.Expression): + # stream the batches so memory does not grow with the matching rows + return sum(batch.num_rows for batch in self.to_reader()) return self.table.count_rows(self.filter) def from_batches(self, **kwargs): @@ -83,6 +86,8 @@ class PyarrowScannerAdapter(pa.dataset.Scanner): return self.to_reader().read_all() def to_reader(self, *, limit: Optional[int] = None): + if isinstance(self.filter, pa.compute.Expression): + return self._to_reader_with_expression(limit=limit) query = self.table.search() # Disable the builtin limit if limit is None: @@ -98,13 +103,30 @@ class PyarrowScannerAdapter(pa.dataset.Scanner): query = query.where(self.filter, prefilter=True) return query.to_batches(batch_size=self.batch_size) + def _to_reader_with_expression(self, *, limit: Optional[int] = None): + # LanceDB filters are SQL strings, but engines such as DuckDB push down + # pyarrow compute expressions. Scan the table and apply the filter and + # projection with pyarrow, since the filter may reference columns that + # are not part of the projection. + if limit is not None and limit <= 0: + raise ValueError("limit must be positive") + query = self.table.search().limit(self.table.count_rows()) + scanner = pa.dataset.Scanner.from_batches( + query.to_batches(batch_size=self.batch_size), + columns=self.columns, + filter=self.filter, + ) + if limit is None: + return scanner.to_reader() + return scanner.head(limit).to_reader() + class PyarrowDatasetAdapter(pa.dataset.Dataset): def __init__(self, table: Table): self.table = table def count_rows(self, filter: Optional[Filter] = None): - return self.table.count_rows(filter) + return self.scanner(filter=filter).count_rows() def get_fragments(self, filter: Optional[Filter] = None): raise NotImplementedError diff --git a/python/python/tests/test_duckdb.py b/python/python/tests/test_duckdb.py index a307149ea..a24933210 100644 --- a/python/python/tests/test_duckdb.py +++ b/python/python/tests/test_duckdb.py @@ -22,3 +22,19 @@ def test_basic_query(tmp_path): results = duck_conn.sql("SELECT SUM(y) FROM adapter").fetchall() assert results[0][0] == 26 + + +def test_query_with_filter(tmp_path): + data = pa.table({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) + conn = lancedb.connect(tmp_path) + tbl = conn.create_table("test", data) + + adapter = PyarrowDatasetAdapter(tbl) # noqa: F841 + + duck_conn = duckdb.connect() + + results = duck_conn.sql("SELECT SUM(y) FROM adapter WHERE x > 2").fetchall() + assert results[0][0] == 15 + + results = duck_conn.sql("SELECT y FROM adapter WHERE x > 2 ORDER BY y").fetchall() + assert results == [(7,), (8,)] diff --git a/python/python/tests/test_pyarrow.py b/python/python/tests/test_pyarrow.py index 7d99d19c6..272eee2ea 100644 --- a/python/python/tests/test_pyarrow.py +++ b/python/python/tests/test_pyarrow.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import pyarrow as pa +import pyarrow.compute as pc import lancedb from lancedb.integrations.pyarrow import PyarrowDatasetAdapter @@ -48,3 +49,19 @@ def test_dataset_adapter(tmp_path): assert adapter.head(10).num_rows == 0 assert adapter.scanner().projected_schema == pa.schema({"x": pa.int64()}) + + +def test_dataset_adapter_expression_filter(tmp_path): + data = pa.table({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) + conn = lancedb.connect(tmp_path) + tbl = conn.create_table("test", data) + + adapter = PyarrowDatasetAdapter(tbl) + filt = pc.field("x") > 2 + + assert adapter.count_rows(filt) == 2 + assert adapter.to_table(filter=filt) == data.slice(2, 2) + assert adapter.head(1, filter=filt) == data.slice(2, 1) + # The filter can reference a column that is not projected + assert adapter.to_table(columns=["y"], filter=filt) == pa.table({"y": [7, 8]}) + assert adapter.scanner(filter=filt).count_rows() == 2 From a6011dcd9501a2b50a3e9d753bd0b343140d5662 Mon Sep 17 00:00:00 2001 From: Captain <42566883+po-et@users.noreply.github.com> Date: Fri, 23 Oct 2026 03:24:40 +0800 Subject: [PATCH 073/180] fix(python): accept NumPy text arrays in Ollama embeddings (#4605) `OllamaEmbeddings.compute_source_embeddings(np.array(["hello", "world"]))` raises a validation error before sending a request. The embedding interface accepts NumPy arrays, but the adapter passes the array directly to Ollama's string-or-sequence request field. Convert NumPy text arrays to lists before the batched request. This preserves input order, the single request, model options and `keep_alive`. The tests cover Unicode/object/sliced arrays, empty input, existing list/Arrow/query inputs and API error propagation. The added input-contract tests also cover two-dimensional arrays and byte strings, with equivalent list inputs as controls. The real Ollama SDK rejects 2-D inputs and invalid UTF-8 locally, before transport. Valid UTF-8 bytes are decoded normally. No extra adapter validation is needed for these cases. Validation on Python 3.12.14 / macOS arm64: - Built the Rust/PyO3 bindings using the repository's uv/maturin environment. - The initial regression run had 5 failures and 4 passing controls on the base; all 9 passed with the fix. With the 6 additional input-contract cases, the related embedding and trust suites now total 55 passed / 11 skipped. - All Python Ruff lint and formatting checks pass. Root checks still report the same 49 lint errors and 11 documentation formatting files reproduced on the untouched base. - Separate review exercised 13 public API cases. Another 7 groups passed through a real loopback HTTP transport, including local validation, UTF-8 serialization and empty-batch model-error propagation. The regression tests use the real Ollama 0.6.2 SDK with HTTPX MockTransport. The loopback check uses an HTTP surrogate, not an Ollama daemon. No live model inference was run. A live Ollama server was unavailable locally. [The current server handler](https://github.com/ollama/ollama/blob/2cd63f7a15039ccd790e97b31edc091fa1707c56/server/routes.go#L1212) explicitly returns HTTP 200 with empty embeddings for empty input after model lookup and runner setup. The adapter preserves the existing empty-list request and its model/setup errors. This is a source check, not a live-server test. Developed with OpenAI Codex, with separate agent review and executed local checks. --- docs/web/integrations/embedding/ollama.mdx | 3 + python/python/lancedb/embeddings/ollama.py | 2 + python/python/tests/test_ollama_embeddings.py | 126 ++++++++++++++++++ 3 files changed, 131 insertions(+) create mode 100644 python/python/tests/test_ollama_embeddings.py diff --git a/docs/web/integrations/embedding/ollama.mdx b/docs/web/integrations/embedding/ollama.mdx index 120cde8f2..bd161a692 100644 --- a/docs/web/integrations/embedding/ollama.mdx +++ b/docs/web/integrations/embedding/ollama.mdx @@ -10,6 +10,9 @@ Generate embeddings via the [ollama](https://github.com/ollama/ollama-python) py - [Ollama docs on embeddings](https://github.com/ollama/ollama/blob/main/docs/api.md#generate-embeddings) - [Ollama blog on embeddings](https://ollama.com/blog/embedding-models) +For direct calls, `compute_source_embeddings` accepts a list of strings or a +one-dimensional NumPy string array. Both inputs are sent to Ollama in one batch. + | Parameter | Type | Default Value | Description | |------------------------|----------------------------|--------------------------|------------------------------------------------------------------------------------------------------------------------------------------------| | `name` | `str` | `nomic-embed-text` | The name of the model. | diff --git a/python/python/lancedb/embeddings/ollama.py b/python/python/lancedb/embeddings/ollama.py index aad8742de..3151c7c72 100644 --- a/python/python/lancedb/embeddings/ollama.py +++ b/python/python/lancedb/embeddings/ollama.py @@ -70,6 +70,8 @@ class OllamaEmbeddings(TextEmbeddingFunction): The texts to embed """ # TODO retry, rate limit, token limit + if isinstance(texts, np.ndarray): + texts = texts.tolist() embeddings = self._compute_embedding(texts) return list(embeddings) diff --git a/python/python/tests/test_ollama_embeddings.py b/python/python/tests/test_ollama_embeddings.py new file mode 100644 index 000000000..9d8568ca7 --- /dev/null +++ b/python/python/tests/test_ollama_embeddings.py @@ -0,0 +1,126 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json + +import httpx +import numpy as np +import pyarrow as pa +import pytest +from pydantic import ValidationError + +from lancedb.embeddings import get_registry + + +@pytest.fixture +def ollama_embeddings(): + pytest.importorskip("ollama") + requests = [] + + def respond(request): + body = json.loads(request.content) + requests.append(body) + if body["model"] == "missing-model": + return httpx.Response(404, json={"error": "model not found"}) + return httpx.Response( + 200, + json={ + "embeddings": [ + [float(index), float(len(text))] + for index, text in enumerate(body["input"]) + ] + }, + ) + + function = ( + get_registry() + .get("ollama") + .create( + name="nomic-embed-text", + options={"num_ctx": 4096}, + keep_alive="10m", + ollama_client_kwargs={ + "transport": httpx.MockTransport(respond), + "trust_env": False, + }, + ) + ) + yield function, requests + function._ollama_client._client.close() + + +@pytest.mark.parametrize( + "texts", + [ + pytest.param(["hello", "世界"], id="list"), + pytest.param(np.array(["hello", "世界"]), id="numpy-unicode"), + pytest.param(np.array(["hello", "世界"], dtype=object), id="numpy-object"), + pytest.param( + np.array([b"hello", "世界".encode("utf-8")]), id="numpy-utf8-bytes" + ), + pytest.param([b"hello", "世界".encode("utf-8")], id="list-utf8-bytes"), + pytest.param(np.array(["hello", "unused", "世界"])[::2], id="numpy-slice"), + pytest.param(pa.array(["hello", "世界"]), id="arrow"), + pytest.param(pa.chunked_array([["hello"], ["世界"]]), id="chunked-arrow"), + ], +) +def test_ollama_source_embeddings_inputs(ollama_embeddings, texts): + function, requests = ollama_embeddings + + assert function.compute_source_embeddings(texts) == [[0.0, 5.0], [1.0, 2.0]] + assert requests == [ + { + "model": "nomic-embed-text", + "input": ["hello", "世界"], + "options": {"num_ctx": 4096}, + "keep_alive": "10m", + } + ] + + +@pytest.mark.parametrize( + "texts", + [ + pytest.param(np.array([["hello"], ["world"]]), id="numpy-two-dimensional"), + pytest.param([["hello"], ["world"]], id="list-two-dimensional"), + pytest.param(np.array([b"\xff"]), id="numpy-invalid-utf8"), + pytest.param([b"\xff"], id="list-invalid-utf8"), + ], +) +def test_ollama_source_embeddings_rejects_invalid_input_locally( + ollama_embeddings, texts +): + function, requests = ollama_embeddings + + with pytest.raises(ValidationError, match="valid string"): + function.compute_source_embeddings(texts) + + assert requests == [] + + +def test_ollama_generate_embeddings_empty_array(ollama_embeddings): + function, requests = ollama_embeddings + + assert function.generate_embeddings(np.array([], dtype=str)) == [] + assert len(requests) == 1 + assert requests[0]["input"] == [] + + +def test_ollama_query_embeddings(ollama_embeddings): + function, requests = ollama_embeddings + + assert function.compute_query_embeddings("hello") == [[0.0, 5.0]] + assert len(requests) == 1 + assert requests[0]["input"] == ["hello"] + + +def test_ollama_source_embeddings_preserves_api_error(ollama_embeddings): + ollama = pytest.importorskip("ollama") + function, requests = ollama_embeddings + function.name = "missing-model" + + with pytest.raises(ollama.ResponseError, match="model not found") as error: + function.compute_source_embeddings(np.array(["hello"])) + + assert error.value.status_code == 404 + assert len(requests) == 1 From e5873d976350d74d7d276794abb8bde1c45fcb47 Mon Sep 17 00:00:00 2001 From: Ishita Singh Date: Fri, 23 Oct 2026 00:54:56 +0530 Subject: [PATCH 074/180] fix(node): support nested blobs with blobMode 'bytes' (#4610) Closes #4609. `blobMode: "bytes"` only resolved top-level blob columns, so a blob nested in a struct came back as its descriptor. Now struct projections that contain blob columns are resolved too: the bytes are fetched per blob column and the struct is rebuilt with `LargeBinary` leaves, preserving struct validity so a null struct stays null. Sibling fields pass through untouched, aliases work for both `info.image AS image` and `info AS details`, and blobs nested in lists still keep their descriptors. Tested with `npx tsc`, `biome check`, and the full `table.test.ts` suite (580 tests, including new regressions for select-all, struct selection, aliases, null structs, null and empty blobs, sibling fields, empty results, and single-row batches). Not run against remote tables. --- .../js/interfaces/QueryExecutionOptions.md | 11 +- nodejs/__test__/table.test.ts | 125 ++++++++++++++ nodejs/lancedb/arrow.ts | 1 + nodejs/lancedb/query.ts | 154 ++++++++++++++---- 4 files changed, 258 insertions(+), 33 deletions(-) diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index 8d3749f38..c0b33dcf0 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -20,12 +20,13 @@ How to return blob v2 columns. Applies to `toArrow()` and `toArray()`. - `"descriptions"` (default): each blob is a descriptor. Read the bytes with [Table.fetchBlobs](../classes/Table.md#fetchblobs) or [Table.fetchBlobFiles](../classes/Table.md#fetchblobfiles). -- `"bytes"`: each top-level blob column holds the blob bytes as - `LargeBinary`. The query also reads `_rowid` to fetch the bytes, and - leaves it out of the result unless [QueryBase.withRowId](../classes/QueryBase.md#withrowid) was - called. All the bytes are held in memory. +- `"bytes"`: each blob column holds the blob bytes as `LargeBinary`, + including blobs nested in structs. The query also reads `_rowid` to + fetch the bytes, and leaves it out of the result unless + [QueryBase.withRowId](../classes/QueryBase.md#withrowid) was called. All the bytes are held in + memory. -Blobs nested in a struct or a list keep their descriptors. +Blobs nested in a list keep their descriptors. The rows and the bytes come from the same table version. If the table changes while the query runs, the query runs again, up to three times. diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 84340c72c..92e3df456 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3385,6 +3385,106 @@ describe("when dealing with blob columns", () => { expect(bytes[0]!.equals(payload)).toBe(true); }); + it("returns bytes for blobs nested in structs", async () => { + const { table, alpha, empty } = await openNestedBlobTable(); + const rows = await table.query().toArray({ blobMode: "bytes" }); + const byId = new Map(rows.map((row) => [Number(row.id), row])); + expect(Buffer.from(byId.get(1)!.info.image)).toEqual(alpha); + expect(byId.get(1)!.info.caption).toBe("one"); + expect(byId.get(2)!.info.image).toBeNull(); + expect(byId.get(2)!.info.caption).toBe("two"); + expect(byId.get(3)!.info).toBeNull(); + expect(Buffer.from(byId.get(4)!.info.image)).toEqual(empty); + }); + + it("lines up nested rows and bytes across single-row batches", async () => { + const { table, alpha, empty } = await openNestedBlobTable(); + const result = await table + .query() + .toArrow({ blobMode: "bytes", maxBatchLength: 1 }); + expect(result.batches.length).toBe(4); + const byId = new Map(result.toArray().map((row) => [Number(row.id), row])); + expect(Buffer.from(byId.get(1)!.info.image)).toEqual(alpha); + expect(byId.get(1)!.info.caption).toBe("one"); + expect(byId.get(2)!.info.image).toBeNull(); + expect(byId.get(2)!.info.caption).toBe("two"); + expect(byId.get(3)!.info).toBeNull(); + expect(Buffer.from(byId.get(4)!.info.image)).toEqual(empty); + }); + + it("handles struct fields named like Object prototypes", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field( + "info", + new Struct([ + new Field("constructor", new Struct([blob("image")]), true), + ]), + true, + ), + ]); + const payload = Buffer.from("proto"); + const table = await db.createTable( + "prototype_named_blobs", + [{ id: 1n, info: { constructor: { image: payload } } }], + { schema }, + ); + expect(await table.blobColumns()).toEqual(["info.constructor.image"]); + const [row] = await table.query().toArray({ blobMode: "bytes" }); + // Arrow's StructRow shadows the `constructor` property, so read the + // field through the JSON form instead of property access. + const info = JSON.parse(JSON.stringify(row.info)); + expect(Buffer.from(Object.values(info.constructor.image))).toEqual( + payload, + ); + }); + + it("returns nested blob bytes for a struct selection", async () => { + const { table, alpha } = await openNestedBlobTable(); + const [row] = await table + .query() + .where("id = 1") + .select(["info"]) + .toArray({ blobMode: "bytes" }); + expect(Object.keys(row)).toEqual(["info"]); + expect(Buffer.from(row.info.image)).toEqual(alpha); + expect(row.info.caption).toBe("one"); + }); + + it("returns nested blob bytes through aliases", async () => { + const { table, alpha } = await openNestedBlobTable(); + const [row] = await table + .query() + .where("id = 1") + .select( + new Map([ + ["picture", "info.image"], + ["details", "info"], + ]), + ) + .toArray({ blobMode: "bytes" }); + expect(Buffer.from(row.picture)).toEqual(alpha); + expect(Buffer.from(row.details.image)).toEqual(alpha); + expect(row.details.caption).toBe("one"); + }); + + it("returns a nested bytes schema for an empty result", async () => { + const { table } = await openNestedBlobTable(); + const result = await table + .query() + .where("id > 100") + .toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(0); + const field = result.schema.fields.find((f) => f.name === "info")!; + expect(arrow.DataType.isStruct(field.type)).toBe(true); + const image = (field.type as Struct).children.find( + (f) => f.name === "image", + )!; + expect(arrow.DataType.isLargeBinary(image.type)).toBe(true); + expect(isBlobField(image)).toBe(false); + }); + it("creates list blobs without advertising unfetchable elements", async () => { const db = await connect(tmpDir.name); const schema = new Schema([ @@ -3593,6 +3693,31 @@ describe("when dealing with blob columns", () => { return { table, rowIds, alpha, beta }; } + async function openNestedBlobTable() { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field( + "info", + new Struct([blob("image"), new Field("caption", new Utf8(), true)]), + true, + ), + ]); + const alpha = Buffer.from("alpha"); + const empty = Buffer.alloc(0); + const table = await db.createTable( + "nested_blobs", + [{ id: 1n, info: { image: alpha, caption: "one" } }], + { schema }, + ); + await table.add([ + { id: 2n, info: { image: null, caption: "two" } }, + { id: 3n, info: null }, + { id: 4n, info: { image: empty, caption: "four" } }, + ]); + return { table, alpha, empty }; + } + async function openExternalBlobTable() { const db = await connect(path.join(tmpDir.name, "db")); const payload = Buffer.from("external-payload"); diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 68b35e256..56c8e1897 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -61,6 +61,7 @@ import { import { inferSchema } from "./schema"; export * from "apache-arrow"; +export type { Data as ArrowData } from "apache-arrow"; export type SchemaLike = | Schema | { diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 2abe6db97..823239ef9 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -2,7 +2,9 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { + type ArrowData, Table as ArrowTable, + DataType, Field, type IntoVector, LargeBinary, @@ -70,16 +72,80 @@ function blobSources( blobColumns: string[], projection: [string, string][] | undefined, ): Map { - const columns = new Set(blobColumns); + const holds = (source: string) => + blobColumns.some( + (column) => column === source || column.startsWith(`${source}.`), + ); const pairs = projection ?? - blobColumns.map((column): [string, string] => [column, column]); - return new Map(pairs.filter(([, source]) => columns.has(source))); + Array.from(new Set(blobColumns.map((column) => column.split(".")[0]))).map( + (name): [string, string] => [name, name], + ); + return new Map(pairs.filter(([, source]) => holds(source))); +} + +// Fetched bytes for the blobs under one output column. A blob column is a +// leaf; a struct holds the blobs nested in it, keyed by field name. A Map +// keeps struct field names from reaching shared JavaScript prototypes. +type BlobBytes = (Buffer | null)[] | Map; + +function isLeaf(bytes: BlobBytes): bytes is (Buffer | null)[] { + return Array.isArray(bytes); +} + +function nestedFieldType(type: Struct, bytes: Map): Struct { + return new Struct( + type.children.map((field) => { + const inner = bytes.get(field.name); + if (inner === undefined) { + return field; + } + if (isLeaf(inner)) { + return new Field(field.name, new LargeBinary(), true); + } + return new Field( + field.name, + nestedFieldType(field.type as Struct, inner), + field.nullable, + ); + }), + ); +} + +// Rebuilds a struct with the blobs under it as bytes. The struct keeps its own +// validity, so a null struct stays null. +function nestedData( + data: ArrowData, + bytes: Map, + offset: number, +): ArrowData { + const type = data.type as Struct; + const children = data.children.map((child, index) => { + const inner = bytes.get(type.children[index].name); + if (inner === undefined) { + return child; + } + if (isLeaf(inner)) { + return vectorFromArray( + inner.slice(offset, offset + data.length), + new LargeBinary(), + ).data[0]; + } + return nestedData(child, inner, offset); + }); + return makeData({ + type: nestedFieldType(type, bytes), + length: data.length, + nullCount: data.nullCount, + nullBitmap: data.nullBitmap, + children, + }); } async function readBlobBytes( table: ArrowTable, sources: Map, + blobColumns: string[], snapshot: NativeTable, dropRowId: boolean, ): Promise { @@ -91,7 +157,11 @@ async function readBlobBytes( rowIdColumn === null ? [] : Array.from(rowIdColumn.toArray() as BigUint64Array); - const replacements = new Map(); + const fetch = async (column: string) => + (rowIds.length === 0 ? [] : await snapshot.fetchBlobs(column, rowIds)).map( + (value) => value ?? null, + ); + const replacements = new Map(); for (const [output, source] of sources) { const index = table.schema.fields.findIndex( (field) => field.name === output, @@ -99,12 +169,30 @@ async function readBlobBytes( if (index < 0) { continue; } - const values = - rowIds.length === 0 ? [] : await snapshot.fetchBlobs(source, rowIds); - replacements.set( - index, - values.map((value) => value ?? null), - ); + if (blobColumns.includes(source)) { + replacements.set(index, await fetch(source)); + continue; + } + if (!DataType.isStruct(table.schema.fields[index].type)) { + continue; + } + const nested = new Map(); + for (const column of blobColumns.filter((c) => + c.startsWith(`${source}.`), + )) { + const path = column.slice(source.length + 1).split("."); + let level = nested; + for (const name of path.slice(0, -1)) { + let next = level.get(name); + if (next === undefined) { + next = new Map(); + level.set(name, next); + } + level = next as Map; + } + level.set(path[path.length - 1], await fetch(column)); + } + replacements.set(index, nested); } const result = withBinaryColumns(table, replacements); if (!dropRowId) { @@ -121,26 +209,37 @@ async function readBlobBytes( // the bytes. function withBinaryColumns( table: ArrowTable, - replacements: Map, + replacements: Map, ): ArrowTable { if (replacements.size === 0) { return table; } - const fields = table.schema.fields.map((field, index) => - replacements.has(index) + const fields = table.schema.fields.map((field, index) => { + const bytes = replacements.get(index); + if (bytes === undefined) { + return field; + } + return isLeaf(bytes) ? new Field(field.name, new LargeBinary(), true) - : field, - ); + : new Field( + field.name, + nestedFieldType(field.type as Struct, bytes), + field.nullable, + ); + }); const schema = new Schema(fields, table.schema.metadata); let offset = 0; const batches = table.batches.map((batch) => { const children = batch.data.children.map((child, index) => { - const values = replacements.get(index); - if (values === undefined) { + const bytes = replacements.get(index); + if (bytes === undefined) { return child; } + if (!isLeaf(bytes)) { + return nestedData(child, bytes, offset); + } return vectorFromArray( - values.slice(offset, offset + batch.numRows), + bytes.slice(offset, offset + batch.numRows), new LargeBinary(), ).data[0]; }); @@ -175,12 +274,13 @@ export interface QueryExecutionOptions { * * - `"descriptions"` (default): each blob is a descriptor. Read the bytes * with {@link Table.fetchBlobs} or {@link Table.fetchBlobFiles}. - * - `"bytes"`: each top-level blob column holds the blob bytes as - * `LargeBinary`. The query also reads `_rowid` to fetch the bytes, and - * leaves it out of the result unless {@link QueryBase.withRowId} was - * called. All the bytes are held in memory. + * - `"bytes"`: each blob column holds the blob bytes as `LargeBinary`, + * including blobs nested in structs. The query also reads `_rowid` to + * fetch the bytes, and leaves it out of the result unless + * {@link QueryBase.withRowId} was called. All the bytes are held in + * memory. * - * Blobs nested in a struct or a list keep their descriptors. + * Blobs nested in a list keep their descriptors. * * The rows and the bytes come from the same table version. If the table * changes while the query runs, the query runs again, up to three times. @@ -429,17 +529,15 @@ export class QueryBase< // unchanged version afterwards proves it read the snapshot's version. const snapshot = await context.table.querySnapshot(); const version = await snapshot.version(); - const sources = blobSources( - await snapshot.blobColumns(), - context.projection, - ); + const blobColumns = await snapshot.blobColumns(); + const sources = blobSources(blobColumns, context.projection); if (sources.size === 0) { return this.collect(options, false); } const addRowId = !context.withRowId; const table = await this.collect(options, addRowId); if ((await context.table.version()) === version) { - return readBlobBytes(table, sources, snapshot, addRowId); + return readBlobBytes(table, sources, blobColumns, snapshot, addRowId); } if (attempt === BLOB_BYTES_ATTEMPTS) { throw new Error( From f5f4463b15bf1e6b08725da26f05cf8dd5188888 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 03:42:22 +0800 Subject: [PATCH 075/180] fix(node): materialize nested struct blobs in bytes mode (#4611) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `blobMode: "bytes"` left blobs inside structs as descriptors because projection matching ignored parent structs and byte replacement only rebuilt top-level fields. Expand direct struct projections and aliases to their blob leaves, then recursively replace the corresponding Arrow fields and data with `LargeBinary`. Track literal output names separately from descendant paths so scalar aliases stay intact and every overlapping blob projection is converted. Preserve null structs, null and empty blobs, sibling fields, schema metadata, and the existing row ID and snapshot behavior. Blobs inside lists retain their descriptors. Update the API docs to describe struct support. Regression coverage includes full and parent-struct projections, leaf and struct aliases, dotted output names, overlapping projections in both orders, nested structs, nulls, empty blobs and results, multiple batches, list siblings, query reuse, row IDs, and concurrent writes. Regression tests reproduce the nested-blob and projection-collision failures before the corresponding changes. Validation: - `pnpm build` - `pnpm lint` - `pnpm run docs` - `pnpm test __test__/nested_blob.test.ts __test__/blob.test.ts __test__/query.test.ts --runInBand --verbose=false` — 142 passed - `pnpm test __test__/table.test.ts --runInBand --verbose=false -t 'when dealing with blob columns'` — 60 passed Fixes #4609 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- .../js/interfaces/QueryExecutionOptions.md | 13 +- nodejs/__test__/nested_blob.test.ts | 327 ++++++++++++++++++ nodejs/__test__/table.test.ts | 125 ++++--- nodejs/lancedb/query.ts | 259 +++++++------- 4 files changed, 528 insertions(+), 196 deletions(-) create mode 100644 nodejs/__test__/nested_blob.test.ts diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index c0b33dcf0..f18ada7aa 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -20,13 +20,14 @@ How to return blob v2 columns. Applies to `toArrow()` and `toArray()`. - `"descriptions"` (default): each blob is a descriptor. Read the bytes with [Table.fetchBlobs](../classes/Table.md#fetchblobs) or [Table.fetchBlobFiles](../classes/Table.md#fetchblobfiles). -- `"bytes"`: each blob column holds the blob bytes as `LargeBinary`, - including blobs nested in structs. The query also reads `_rowid` to - fetch the bytes, and leaves it out of the result unless - [QueryBase.withRowId](../classes/QueryBase.md#withrowid) was called. All the bytes are held in - memory. +- `"bytes"`: each blob column, including blobs nested in structs, holds + the bytes as `LargeBinary`. The query also reads `_rowid` to fetch them, and + leaves it out of the result unless [QueryBase.withRowId](../classes/QueryBase.md#withrowid) was + called. All the bytes are held in memory. -Blobs nested in a list keep their descriptors. +Selecting a parent struct or directly aliasing a blob or struct also returns +bytes. Blobs inside lists keep their descriptors. Arbitrary projection +expressions are not materialized as bytes. The rows and the bytes come from the same table version. If the table changes while the query runs, the query runs again, up to three times. diff --git a/nodejs/__test__/nested_blob.test.ts b/nodejs/__test__/nested_blob.test.ts new file mode 100644 index 000000000..508b57c77 --- /dev/null +++ b/nodejs/__test__/nested_blob.test.ts @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import * as tmp from "tmp"; +import { type Table, blob, connect, isBlobField } from "../lancedb"; +import { + DataType, + Field, + Int64, + List, + Schema, + Struct, + Utf8, +} from "../lancedb/arrow"; + +describe('nested blobs with blobMode "bytes"', () => { + let tmpDir: tmp.DirResult; + let table: Table; + + const caption = new Field( + "caption", + new Utf8(), + false, + new Map([["label", "caption"]]), + ); + const info = new Field( + "info", + new Struct([ + blob("image"), + caption, + new Field("preview", new Struct([blob("image")]), true), + ]), + true, + new Map([["label", "info"]]), + ); + const schema = new Schema( + [new Field("id", new Int64(), false), info, blob("cover")], + new Map([["source", "nested-blobs"]]), + ); + + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + table = await db.createTable( + "nested_blobs", + [ + { + id: 1n, + info: { + image: Buffer.from("hello"), + caption: "first", + preview: { image: Buffer.from("preview") }, + }, + cover: Buffer.from("cover"), + }, + { id: 2n, info: null, cover: null }, + { + id: 3n, + info: { image: null, caption: "third", preview: null }, + cover: null, + }, + { + id: 4n, + info: { + image: Buffer.alloc(0), + caption: "fourth", + preview: { image: null }, + }, + cover: Buffer.alloc(0), + }, + ], + { schema }, + ); + }); + + afterEach(() => tmpDir.removeCallback()); + + it.each([false, true])( + "reads struct leaves across batches (select parent: %s)", + async (selectParent) => { + const query = table + .query() + .orderBy({ columnName: "id", ascending: true }); + if (selectParent) { + query.select(["info"]); + } + const result = await query.toArrow({ + blobMode: "bytes", + maxBatchLength: 1, + }); + expect(result.batches.length).toBeGreaterThan(1); + expect(result.schema.fields.map((field) => field.name)).toEqual( + selectParent ? ["info"] : ["id", "info", "cover"], + ); + expect(result.schema.metadata).toEqual(schema.metadata); + const infoField = result.schema.fields.find( + (field) => field.name === "info", + )!; + expect(infoField.nullable).toBe(true); + expect(infoField.metadata).toEqual(info.metadata); + const fields = (infoField.type as Struct).children; + expect(DataType.isLargeBinary(fields[0].type)).toBe(true); + expect(isBlobField(fields[0])).toBe(false); + expect(fields[0].metadata.size).toBe(0); + expect(fields[1]).toEqual(caption); + expect( + DataType.isLargeBinary((fields[2].type as Struct).children[0].type), + ).toBe(true); + + const rows = result.toArray(); + expect(Buffer.from(rows[0].info.image).toString()).toBe("hello"); + expect(rows[0].info.caption).toBe("first"); + expect(Buffer.from(rows[0].info.preview.image).toString()).toBe( + "preview", + ); + expect(rows[1].info).toBeNull(); + expect(rows[2].info.image).toBeNull(); + expect(rows[2].info.caption).toBe("third"); + expect(rows[2].info.preview).toBeNull(); + expect(Buffer.from(rows[3].info.image)).toEqual(Buffer.alloc(0)); + expect(rows[3].info.preview.image).toBeNull(); + if (!selectParent) { + expect(Buffer.from(rows[0].cover).toString()).toBe("cover"); + expect(rows[1].cover).toBeNull(); + } + }, + ); + + it("reads direct leaf and struct aliases", async () => { + const rows = await table + .query() + .orderBy({ columnName: "id", ascending: true }) + .select({ + image: "info.image", + details: "info", + preview: "info.preview", + caption: "info.caption", + }) + .toArray({ blobMode: "bytes", maxBatchLength: 1 }); + expect(Object.keys(rows[0])).toEqual([ + "image", + "details", + "preview", + "caption", + ]); + expect(Buffer.from(rows[0].image).toString()).toBe("hello"); + expect(Buffer.from(rows[0].details.image).toString()).toBe("hello"); + expect(Buffer.from(rows[0].details.preview.image).toString()).toBe( + "preview", + ); + expect(Buffer.from(rows[0].preview.image).toString()).toBe("preview"); + expect(rows[0].caption).toBe("first"); + expect(rows[1].details).toBeNull(); + expect(rows[1].image).toBeNull(); + expect(rows[2].image).toBeNull(); + expect(Buffer.from(rows[3].image)).toEqual(Buffer.alloc(0)); + }); + + it.each([false, true])( + "preserves a literal scalar alias matching a nested blob path (reverse: %s)", + async (reverse) => { + const projection: [string, string][] = [ + ["info", "info"], + ["info.image", "id"], + ]; + if (reverse) { + projection.reverse(); + } + const [row] = await table + .query() + .where("id = 1") + .select(new Map(projection)) + .toArray({ blobMode: "bytes" }); + expect(row["info.image"]).toBe(1n); + expect(Buffer.from(row.info.image).toString()).toBe("hello"); + }, + ); + + it.each([false, true])( + "materializes every overlapping blob projection (reverse: %s)", + async (reverse) => { + const columns = ["info.image", "info"]; + if (reverse) { + columns.reverse(); + } + const result = await table + .query() + .orderBy({ columnName: "id", ascending: true }) + .select(columns) + .toArrow({ blobMode: "bytes", maxBatchLength: 1 }); + expect(result.schema.fields.map((field) => field.name)).toEqual(columns); + expect(DataType.isLargeBinary(result.getChild("info.image")!.type)).toBe( + true, + ); + expect( + DataType.isLargeBinary( + result.getChild("info")!.getChild("image")!.type, + ), + ).toBe(true); + const rows = result.toArray(); + expect(Buffer.from(rows[0]["info.image"]).toString()).toBe("hello"); + expect(Buffer.from(rows[0].info.image).toString()).toBe("hello"); + expect(rows[0].info.caption).toBe("first"); + expect(rows[1]["info.image"]).toBeNull(); + expect(rows[1].info).toBeNull(); + expect(rows[2]["info.image"]).toBeNull(); + expect(rows[2].info.image).toBeNull(); + expect(Buffer.from(rows[3]["info.image"])).toEqual(Buffer.alloc(0)); + expect(Buffer.from(rows[3].info.image)).toEqual(Buffer.alloc(0)); + }, + ); + + it("materializes dotted aliases independently of nested fields", async () => { + const [row] = await table + .query() + .where("id = 1") + .select({ + details: "info", + "details.image": "info.image", + "details.preview": "info.preview", + "details.preview.image": "info.preview.image", + }) + .toArray({ blobMode: "bytes" }); + expect(Buffer.from(row.details.image).toString()).toBe("hello"); + expect(Buffer.from(row["details.image"]).toString()).toBe("hello"); + expect(Buffer.from(row.details.preview.image).toString()).toBe("preview"); + expect(Buffer.from(row["details.preview"].image).toString()).toBe( + "preview", + ); + expect(Buffer.from(row["details.preview.image"]).toString()).toBe( + "preview", + ); + }); + + it.each([false, true])( + "converts the empty result schema (alias: %s)", + async (alias) => { + const query = table.query().where("id < 0"); + if (alias) { + query.select({ image: "info.image", details: "info" }); + } + const result = await query.toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(0); + expect(result.schema.fields.map((field) => field.name)).toEqual( + alias ? ["image", "details"] : ["id", "info", "cover"], + ); + const fields = ( + result.schema.fields.find( + (field) => field.name === (alias ? "details" : "info"), + )!.type as Struct + ).children; + expect(DataType.isLargeBinary(fields[0].type)).toBe(true); + expect(isBlobField(fields[0])).toBe(false); + expect(fields[1]).toEqual(caption); + expect( + DataType.isLargeBinary((fields[2].type as Struct).children[0].type), + ).toBe(true); + if (alias) { + expect(DataType.isLargeBinary(result.schema.fields[0].type)).toBe(true); + } + }, + ); + + it("preserves requested row IDs and leaves subsequent descriptors intact", async () => { + const query = table.query().where("id = 1").select(["info"]); + const [bytes] = await query.toArray({ blobMode: "bytes" }); + expect(Object.keys(bytes)).toEqual(["info"]); + const [description] = await query.toArray(); + expect(Object.keys(description)).toEqual(["info"]); + expect(Number(description.info.image.size)).toBe(5); + const [withRowId] = await query.withRowId().toArray({ blobMode: "bytes" }); + expect(typeof withRowId._rowid).toBe("bigint"); + expect(await table.fetchBlobs("info.image", [withRowId._rowid])).toEqual([ + Buffer.from(withRowId.info.image), + ]); + }); + + it("keeps descriptors in description mode", async () => { + const [description] = await table + .query() + .where("id = 1") + .toArray({ blobMode: "descriptions" }); + expect(Number(description.info.image.size)).toBe(5); + }); + + it("keeps list elements as descriptors alongside struct blob bytes", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable( + "list_blobs", + [ + { + info: { image: Buffer.from("hello"), images: [Buffer.from("list")] }, + }, + ], + { + schema: new Schema([ + new Field( + "info", + new Struct([ + blob("image"), + new Field("images", new List(blob("item")), true), + ]), + true, + ), + ]), + }, + ); + const [bytes] = await table.query().toArray({ blobMode: "bytes" }); + expect(Buffer.from(bytes.info.image).toString()).toBe("hello"); + expect(Number(bytes.info.images.get(0).size)).toBe(4); + const [row] = await table + .query() + .select(["info.images"]) + .toArray({ blobMode: "bytes" }); + expect(Number(row["info.images"].get(0).size)).toBe(4); + expect(Object.keys(row)).toEqual(["info.images"]); + const result = await table.query().toArrow({ blobMode: "bytes" }); + const fields = (result.schema.fields[0].type as Struct).children; + const descriptions = await table.query().toArrow(); + expect(fields[1]).toEqual( + (descriptions.schema.fields[0].type as Struct).children[1], + ); + expect(DataType.isStruct((fields[1].type as List).children[0].type)).toBe( + true, + ); + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 92e3df456..d848676cd 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3314,51 +3314,64 @@ describe("when dealing with blob columns", () => { ).rejects.toThrow(/blobMode must be/); }); - it("reruns the query when the table changes before the version check", async () => { - const { table, native, update } = await openVersionedBlobTable(); - const liveVersion = native.version.bind(native); - native.version = async () => { - native.version = liveVersion; - await update(2n, "new"); - return liveVersion(); - }; - const [row] = await table.query().toArray({ blobMode: "bytes" }); - expect(row.generation).toBe(2n); - expect(Buffer.from(row.image).toString()).toBe("new"); - }); + it.each([false, true])( + "reruns the query when the table changes before the version check (nested: %s)", + async (nested) => { + const { table, native, update } = await openVersionedBlobTable(nested); + const liveVersion = native.version.bind(native); + native.version = async () => { + native.version = liveVersion; + await update(2n, "new"); + return liveVersion(); + }; + const [row] = await table.query().toArray({ blobMode: "bytes" }); + expect(row.generation).toBe(2n); + expect(Buffer.from(nested ? row.info.image : row.image).toString()).toBe( + "new", + ); + }, + ); - it("reads bytes from the query's version when a write lands before the fetch", async () => { - const { table, native, update } = await openVersionedBlobTable(); - const liveVersion = native.version.bind(native); - native.version = async () => { - native.version = liveVersion; - const version = await liveVersion(); - await update(2n, "new"); - return version; - }; - const [row] = await table.query().toArray({ blobMode: "bytes" }); - expect(row.generation).toBe(1n); - expect(Buffer.from(row.image).toString()).toBe("old"); - }); + it.each([false, true])( + "reads bytes from the query's version when a write lands before the fetch (nested: %s)", + async (nested) => { + const { table, native, update } = await openVersionedBlobTable(nested); + const liveVersion = native.version.bind(native); + native.version = async () => { + native.version = liveVersion; + const version = await liveVersion(); + await update(2n, "new"); + return version; + }; + const [row] = await table.query().toArray({ blobMode: "bytes" }); + expect(row.generation).toBe(1n); + expect(Buffer.from(nested ? row.info.image : row.image).toString()).toBe( + "old", + ); + }, + ); - it("fails when the table changes during every attempt", async () => { - const { table, native, update } = await openVersionedBlobTable(); - const liveVersion = native.version.bind(native); - let generation = 1n; - native.version = async () => { - generation += 1n; - await update(generation, `generation ${generation}`); - return liveVersion(); - }; - try { - await expect( - table.query().toArray({ blobMode: "bytes" }), - ).rejects.toThrow(/changed during each of 3 attempts/); - expect(generation).toBe(4n); - } finally { - native.version = liveVersion; - } - }); + it.each([false, true])( + "fails when the table changes during every attempt (nested: %s)", + async (nested) => { + const { table, native, update } = await openVersionedBlobTable(nested); + const liveVersion = native.version.bind(native); + let generation = 1n; + native.version = async () => { + generation += 1n; + await update(generation, `generation ${generation}`); + return liveVersion(); + }; + try { + await expect( + table.query().toArray({ blobMode: "bytes" }), + ).rejects.toThrow(/changed during each of 3 attempts/); + expect(generation).toBe(4n); + } finally { + native.version = liveVersion; + } + }, + ); it("rejects fetchBlobs on a non-blob column", async () => { const { table, rowIds } = await openBlobTable(); @@ -3642,18 +3655,28 @@ describe("when dealing with blob columns", () => { ).map((value) => (value == null ? null : Number(value.size))); } - async function openVersionedBlobTable() { + async function openVersionedBlobTable(nested = false) { const db = await connect(tmpDir.name, { storageOptions: { newTableEnableStableRowIds: "true" }, }); const schema = new Schema([ new Field("id", new Int64(), false), new Field("generation", new Int64(), true), - blob("image"), + nested + ? new Field("info", new Struct([blob("image")]), true) + : blob("image"), ]); const table = await db.createTable( "versions", - [{ id: 1n, generation: 1n, image: Buffer.from("old") }], + [ + { + id: 1n, + generation: 1n, + ...(nested + ? { info: { image: Buffer.from("old") } } + : { image: Buffer.from("old") }), + }, + ], { schema }, ); const native = ( @@ -3663,7 +3686,15 @@ describe("when dealing with blob columns", () => { await table .mergeInsert("id") .whenMatchedUpdateAll() - .execute([{ id: 1n, generation, image: Buffer.from(image) }]); + .execute([ + { + id: 1n, + generation, + ...(nested + ? { info: { image: Buffer.from(image) } } + : { image: Buffer.from(image) }), + }, + ]); }; return { table, native, update }; } diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 823239ef9..b96e4fda6 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import type { Data as ArrowData } from "apache-arrow"; import { - type ArrowData, Table as ArrowTable, DataType, Field, @@ -14,7 +14,6 @@ import { extractVectorBuffer, fromBufferToRecordBatch, fromRecordBatchToBuffer, - makeData, tableFromIPC, vectorFromArray, } from "./arrow"; @@ -68,84 +67,42 @@ export interface QueryBlobContext { const BLOB_BYTES_ATTEMPTS = 3; +interface BlobSource { + // Output names are literal: an alias containing dots is still one field. + output: string; + path: string[]; + source: string; +} + function blobSources( blobColumns: string[], projection: [string, string][] | undefined, -): Map { - const holds = (source: string) => - blobColumns.some( - (column) => column === source || column.startsWith(`${source}.`), - ); - const pairs = - projection ?? - Array.from(new Set(blobColumns.map((column) => column.split(".")[0]))).map( - (name): [string, string] => [name, name], - ); - return new Map(pairs.filter(([, source]) => holds(source))); -} - -// Fetched bytes for the blobs under one output column. A blob column is a -// leaf; a struct holds the blobs nested in it, keyed by field name. A Map -// keeps struct field names from reaching shared JavaScript prototypes. -type BlobBytes = (Buffer | null)[] | Map; - -function isLeaf(bytes: BlobBytes): bytes is (Buffer | null)[] { - return Array.isArray(bytes); -} - -function nestedFieldType(type: Struct, bytes: Map): Struct { - return new Struct( - type.children.map((field) => { - const inner = bytes.get(field.name); - if (inner === undefined) { - return field; +): BlobSource[] { + if (projection === undefined) { + return blobColumns.map((source) => { + const [output, ...path] = source.split("."); + return { output, path, source }; + }); + } + const sources: BlobSource[] = []; + for (const [output, source] of projection) { + for (const column of blobColumns) { + if (column === source || column.startsWith(`${source}.`)) { + sources.push({ + output, + path: + column === source ? [] : column.slice(source.length + 1).split("."), + source: column, + }); } - if (isLeaf(inner)) { - return new Field(field.name, new LargeBinary(), true); - } - return new Field( - field.name, - nestedFieldType(field.type as Struct, inner), - field.nullable, - ); - }), - ); -} - -// Rebuilds a struct with the blobs under it as bytes. The struct keeps its own -// validity, so a null struct stays null. -function nestedData( - data: ArrowData, - bytes: Map, - offset: number, -): ArrowData { - const type = data.type as Struct; - const children = data.children.map((child, index) => { - const inner = bytes.get(type.children[index].name); - if (inner === undefined) { - return child; } - if (isLeaf(inner)) { - return vectorFromArray( - inner.slice(offset, offset + data.length), - new LargeBinary(), - ).data[0]; - } - return nestedData(child, inner, offset); - }); - return makeData({ - type: nestedFieldType(type, bytes), - length: data.length, - nullCount: data.nullCount, - nullBitmap: data.nullBitmap, - children, - }); + } + return sources; } async function readBlobBytes( table: ArrowTable, - sources: Map, - blobColumns: string[], + sources: BlobSource[], snapshot: NativeTable, dropRowId: boolean, ): Promise { @@ -157,42 +114,27 @@ async function readBlobBytes( rowIdColumn === null ? [] : Array.from(rowIdColumn.toArray() as BigUint64Array); - const fetch = async (column: string) => - (rowIds.length === 0 ? [] : await snapshot.fetchBlobs(column, rowIds)).map( - (value) => value ?? null, + const outputFields = new Map( + table.schema.fields.map((field) => [field.name, field]), + ); + const replacements = new Map(); + for (const { output, path, source } of sources) { + let field = outputFields.get(output); + for (const name of path) { + field = + field !== undefined && DataType.isStruct(field.type) + ? field.type.children.find((child) => child.name === name) + : undefined; + } + if (field === undefined) { + continue; + } + const values = + rowIds.length === 0 ? [] : await snapshot.fetchBlobs(source, rowIds); + replacements.set( + field, + values.map((value) => value ?? null), ); - const replacements = new Map(); - for (const [output, source] of sources) { - const index = table.schema.fields.findIndex( - (field) => field.name === output, - ); - if (index < 0) { - continue; - } - if (blobColumns.includes(source)) { - replacements.set(index, await fetch(source)); - continue; - } - if (!DataType.isStruct(table.schema.fields[index].type)) { - continue; - } - const nested = new Map(); - for (const column of blobColumns.filter((c) => - c.startsWith(`${source}.`), - )) { - const path = column.slice(source.length + 1).split("."); - let level = nested; - for (const name of path.slice(0, -1)) { - let next = level.get(name); - if (next === undefined) { - next = new Map(); - level.set(name, next); - } - level = next as Map; - } - level.set(path[path.length - 1], await fetch(column)); - } - replacements.set(index, nested); } const result = withBinaryColumns(table, replacements); if (!dropRowId) { @@ -205,48 +147,76 @@ async function readBlobBytes( ); } -// A fresh field, not a clone: the descriptor field's metadata must not follow -// the bytes. function withBinaryColumns( table: ArrowTable, - replacements: Map, + replacements: Map, ): ArrowTable { if (replacements.size === 0) { return table; } - const fields = table.schema.fields.map((field, index) => { - const bytes = replacements.get(index); - if (bytes === undefined) { - return field; + const replaceField = (field: Field): Field => { + if (replacements.has(field)) { + // The descriptor's extension and encoding metadata must not follow bytes. + return new Field(field.name, new LargeBinary(), true); } - return isLeaf(bytes) - ? new Field(field.name, new LargeBinary(), true) - : new Field( - field.name, - nestedFieldType(field.type as Struct, bytes), - field.nullable, - ); - }); + if (DataType.isStruct(field.type)) { + const children = field.type.children.map(replaceField); + if (children.some((child, i) => child !== field.type.children[i])) { + return field.clone({ type: new Struct(children) }); + } + } + return field; + }; + const fields = table.schema.fields.map(replaceField); const schema = new Schema(fields, table.schema.metadata); let offset = 0; const batches = table.batches.map((batch) => { - const children = batch.data.children.map((child, index) => { - const bytes = replacements.get(index); - if (bytes === undefined) { - return child; + const replaceData = ( + data: ArrowData, + field: Field, + updated: Field, + ): ArrowData => { + if (field === updated) { + return data; } - if (!isLeaf(bytes)) { - return nestedData(child, bytes, offset); + const values = replacements.get(field); + if (values !== undefined) { + return vectorFromArray( + values.slice(offset, offset + batch.numRows), + new LargeBinary(), + ).data[0]; } - return vectorFromArray( - bytes.slice(offset, offset + batch.numRows), - new LargeBinary(), - ).data[0]; - }); + const children = data.children.map((child, index) => + replaceData( + child, + field.type.children[index], + updated.type.children[index], + ), + ); + // Keep the struct's validity bitmap and offset, including null parents. + return data.clone( + updated.type, + undefined, + undefined, + undefined, + undefined, + children, + ); + }; + const children = batch.data.children.map((child, index) => + replaceData(child, table.schema.fields[index], fields[index]), + ); offset += batch.numRows; return new RecordBatch( schema, - makeData({ type: new Struct(fields), length: batch.numRows, children }), + batch.data.clone( + new Struct(fields), + undefined, + undefined, + undefined, + undefined, + children, + ), ); }); return new ArrowTable(schema, batches); @@ -274,13 +244,14 @@ export interface QueryExecutionOptions { * * - `"descriptions"` (default): each blob is a descriptor. Read the bytes * with {@link Table.fetchBlobs} or {@link Table.fetchBlobFiles}. - * - `"bytes"`: each blob column holds the blob bytes as `LargeBinary`, - * including blobs nested in structs. The query also reads `_rowid` to - * fetch the bytes, and leaves it out of the result unless - * {@link QueryBase.withRowId} was called. All the bytes are held in - * memory. + * - `"bytes"`: each blob column, including blobs nested in structs, holds + * the bytes as `LargeBinary`. The query also reads `_rowid` to fetch them, and + * leaves it out of the result unless {@link QueryBase.withRowId} was + * called. All the bytes are held in memory. * - * Blobs nested in a list keep their descriptors. + * Selecting a parent struct or directly aliasing a blob or struct also returns + * bytes. Blobs inside lists keep their descriptors. Arbitrary projection + * expressions are not materialized as bytes. * * The rows and the bytes come from the same table version. If the table * changes while the query runs, the query runs again, up to three times. @@ -529,15 +500,17 @@ export class QueryBase< // unchanged version afterwards proves it read the snapshot's version. const snapshot = await context.table.querySnapshot(); const version = await snapshot.version(); - const blobColumns = await snapshot.blobColumns(); - const sources = blobSources(blobColumns, context.projection); - if (sources.size === 0) { + const sources = blobSources( + await snapshot.blobColumns(), + context.projection, + ); + if (sources.length === 0) { return this.collect(options, false); } const addRowId = !context.withRowId; const table = await this.collect(options, addRowId); if ((await context.table.version()) === version) { - return readBlobBytes(table, sources, blobColumns, snapshot, addRowId); + return readBlobBytes(table, sources, snapshot, addRowId); } if (attempt === BLOB_BYTES_ATTEMPTS) { throw new Error( From 88203d25156a0dd7fc7d2c51aee66410d546ae18 Mon Sep 17 00:00:00 2001 From: Christopher Krah Date: Thu, 22 Oct 2026 21:42:36 +0200 Subject: [PATCH 076/180] fix(python): keep a renamed Permutation column in its position (#4626) The `Permutation.rename_column` docstring says it "only changes the name of the column that is visible from this permutation". But `permutation.py:868-870` adds the new name at the end of the selection and then deletes the old key, so the renamed column also moves to the last position. Hugging Face `datasets`, which `Permutation` mirrors (#2725), keeps it in place. Positional formats feel it most: `with_format("numpy")` swaps the feature order of every row. Before, on `d97df0c`: ``` $ python repro.py /python/python # lancedb 0.41.0b12 extension, Python sources from the tree ['id', 'value'] ['value', 'row_id'] [{'value': 0, 'row_id': 0}] [[10 1]] ``` After: ``` $ python repro.py /python/python ['id', 'value'] ['row_id', 'value'] [{'row_id': 0, 'value': 0}] [[ 1 10]] ```
repro.py (its first output line, lancedb.__file__, is cut above) ```python import sys; sys.path.insert(0, sys.argv[1]) import tempfile import lancedb from lancedb.permutation import Permutation print(lancedb.__file__) db = lancedb.connect(tempfile.mkdtemp()) tbl = db.create_table("t", [{"id": i, "value": i * 10} for i in range(3)]) perm = Permutation.identity(tbl) print(perm.column_names) renamed = perm.rename_column("id", "row_id") print(renamed.column_names) print(renamed.__getitems__([0])) print(renamed.with_format("numpy").__getitems__([1])) ```
For comparison, `datasets` 5.1.0 gives `['new_id', 'value']` for `Dataset.from_dict({'id': [1, 2], 'value': [3, 4]}).rename_column('id', 'new_id').column_names`. No issue exists for this. The fix rebuilds the selection dict in order. The cost: code that renamed a column and then read it by position in numpy batches (say `[:, -1]`) gets a different column after this, with no error. `rename_columns` calls `rename_column` once per name, so it gets the fix too. The tests that check schema order only rename `value`, the last column, and `test_rename_rowid` checks membership but not order. The new test renames `id`. ### Verification ``` # Python 3.12.6; lancedb 0.41.0b12 wheel from pypi.fury.io, its _lancedb.abi3.so copied into the tree; pylance 14.0.0-rc.1 $ PYTHONPATH=python python -m pytest python/tests/test_permutation.py -q -p no:cacheprovider d97df0c: 72 passed in 2.53s this branch: 73 passed in 2.36s permutation.py reverted, test kept: FAILED python/tests/test_permutation.py::test_rename_column_keeps_position assert value: int64\nnew_id: int64 == new_id: int64\nvalue: int64 1 failed, 72 passed in 2.41s $ ruff format --check . && ruff check . # ruff 0.9.9, as python.yml pins it 152 files already formatted All checks passed! # not run: pyright (its include list covers neither permutation.py nor tests/), the Rust build ``` @westonpace, this is your class from #2725. Do you want the docstring to say outright that the column keeps its position? If so, I'll add that line to both rename methods in this PR. Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com> --- python/python/lancedb/permutation.py | 8 +++++--- python/python/tests/test_permutation.py | 7 +++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 355ebf798..e95db27f6 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -909,9 +909,11 @@ class Permutation: f"Cannot rename column `{old_name}` to `{new_name}` because a column " "with that name already exists" ) - new_selection = self.selection.copy() - new_selection[new_name] = new_selection[old_name] - del new_selection[old_name] + # Rebuild the mapping so the renamed column keeps its position + new_selection = { + (new_name if name == old_name else name): value + for name, value in self.selection.items() + } return self._with_selection(new_selection) def rename_columns(self, column_map: dict[str, str]) -> "Permutation": diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index ed1894340..50ca53061 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -811,6 +811,13 @@ def test_rename_column(some_permutation: Permutation): some_permutation.rename_column("non_existent", "new_value") +def test_rename_column_keeps_position(some_permutation: Permutation): + renamed = some_permutation.rename_column("id", "new_id") + assert renamed.schema == pa.schema([("new_id", pa.int64()), ("value", pa.int64())]) + batch = renamed.with_format("arrow").__getitems__([0]) + assert batch.schema.names == ["new_id", "value"] + + def test_rename_columns(some_permutation: Permutation): assert some_permutation.rename_columns({"value": "new_value"}).schema == pa.schema( [("id", pa.int64()), ("new_value", pa.int64())] From 631ea41a635890218bf7ee1ab80df6caccc7606c Mon Sep 17 00:00:00 2001 From: Colin Patrick McCabe Date: Thu, 22 Oct 2026 15:41:30 -0700 Subject: [PATCH 077/180] feat!: return lazy iterators for table and namespace listings (#4599) Make table and namespace listings consistent with other resource listings across Rust, Python, and TypeScript. Callers can iterate over individual names across all pages, with configurable page sizes and continuation tokens. In order to avoid breaking existing Python users, this change adds some compatibility methods to the returned Python iterators. Code such as: ``` for t in db.list_tables().tables: print(t) ``` will continue to work as expected because the iterator has a `tables` field and a `page_token` field, which function as expected to reveal the first page of results. In other words, it is never necessary to use the iterator __as an iterator__. It may be used as if it were an old-style response object. (As the iterator progresses, the `tables` list may switch to the second, third, etc. page of results.) Similar compatibility code allows the async python API to keep working as well. --- docs/src/js/classes/Connection.md | 80 ++------ docs/src/js/globals.md | 4 - .../js/interfaces/ListNamespacesOptions.md | 27 --- .../js/interfaces/ListNamespacesResponse.md | 23 --- docs/src/js/interfaces/ListTablesOptions.md | 35 ---- docs/src/js/interfaces/ListTablesResponse.md | 23 --- docs/src/js/interfaces/TableNamesOptions.md | 2 +- docs/src/python/python.md | 23 ++- docs/web-tests/ts/connection.test.ts | 16 +- docs/web-tests/ts/quickstart.test.ts | 7 +- nodejs/__test__/connection.test.ts | 156 ++++++++-------- nodejs/lancedb/connection.ts | 133 ++++---------- nodejs/lancedb/index.ts | 4 - nodejs/src/connection.rs | 101 ++--------- python/python/lancedb/_lancedb.pyi | 11 +- python/python/lancedb/db.py | 70 ++++--- python/python/lancedb/listing.py | 171 ++++++++++++++++++ python/python/lancedb/namespace.py | 39 ++-- python/python/lancedb/remote/db.py | 16 +- python/python/tests/test_embeddings.py | 4 + python/python/tests/test_listing.py | 137 ++++++++++++++ python/python/tests/test_ollama_embeddings.py | 2 +- python/src/connection.rs | 56 ++---- python/src/listing.rs | 30 ++- rust/lancedb/src/connection.rs | 161 +++++++++-------- rust/lancedb/src/listing.rs | 130 +++++++++---- rust/lancedb/src/remote/db.rs | 66 ++----- 27 files changed, 814 insertions(+), 713 deletions(-) delete mode 100644 docs/src/js/interfaces/ListNamespacesOptions.md delete mode 100644 docs/src/js/interfaces/ListNamespacesResponse.md delete mode 100644 docs/src/js/interfaces/ListTablesOptions.md delete mode 100644 docs/src/js/interfaces/ListTablesResponse.md diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index d5ab8c3d1..c110eb38c 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -653,94 +653,48 @@ See [Listing](Listing.md) for pagination state and error behavior. ### listNamespaces() ```ts -abstract listNamespaces(namespacePath?, options?): Promise +abstract listNamespaces(namespacePath?, options?): Listing ``` -List the immediate child namespaces under the given parent. - -Results may be paginated. To retrieve subsequent pages, pass the -`pageToken` returned by a previous call. +Lazily list immediate child namespaces, 100 per page by default. #### Parameters * **namespacePath?**: `string`[] - The parent namespace path. Defaults - to the root namespace if omitted. -* **options?**: `Partial`<[`ListNamespacesOptions`](../interfaces/ListNamespacesOptions.md)> - Pagination options - (`pageToken`, `limit`). +* **options?**: [`ListingOptions`](../interfaces/ListingOptions.md) #### Returns -`Promise`<[`ListNamespacesResponse`](../interfaces/ListNamespacesResponse.md)> - -Child namespace names and - an optional token for fetching the next page. +[`Listing`](Listing.md)<`string`> *** ### listTables() -#### listTables(options) - ```ts -abstract listTables(options?): Promise +abstract listTables(namespacePath?, options?): Listing ``` -List a page of the tables in this database. +Lazily list tables in a namespace, requesting 100 per page by default. -To retrieve the tables after the page, pass the `pageToken` the response -carries back in. A page can be shorter than `limit` without being the last -one, so walk until a response carries no page token: - -```ts -const names = []; -let pageToken = undefined; -do { - const page = await conn.listTables({ pageToken, limit: 100 }); - names.push(...page.tables); - pageToken = page.pageToken; -} while (pageToken); -``` - -##### Parameters - -* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)> - Pagination options - (`pageToken`, `limit`). - -##### Returns - -`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)> - -A page of table names and an - optional token for the tables after it. - -#### listTables(namespacePath, options) - -```ts -abstract listTables(namespacePath?, options?): Promise -``` - -List a page of the tables in this database. - -##### Parameters +#### Parameters * **namespacePath?**: `string`[] - The namespace path to list tables from - (defaults to root namespace) -* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)> - Pagination options - (`pageToken`, `limit`). +* **options?**: [`ListingOptions`](../interfaces/ListingOptions.md) -##### Returns +#### Returns -`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)> +[`Listing`](Listing.md)<`string`> -A page of table names and an - optional token for the tables after it. +#### Example + +```ts +for await (const name of conn.listTables([], { pageLimit: 20 })) { + console.log(name); +} +``` *** diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 646341190..e3830e9ad 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -108,10 +108,6 @@ - [JobEventsOptions](interfaces/JobEventsOptions.md) - [JobFailureInfo](interfaces/JobFailureInfo.md) - [JobInfo](interfaces/JobInfo.md) -- [ListNamespacesOptions](interfaces/ListNamespacesOptions.md) -- [ListNamespacesResponse](interfaces/ListNamespacesResponse.md) -- [ListTablesOptions](interfaces/ListTablesOptions.md) -- [ListTablesResponse](interfaces/ListTablesResponse.md) - [ListingOptions](interfaces/ListingOptions.md) - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) - [MemtableStats](interfaces/MemtableStats.md) diff --git a/docs/src/js/interfaces/ListNamespacesOptions.md b/docs/src/js/interfaces/ListNamespacesOptions.md deleted file mode 100644 index 79680417f..000000000 --- a/docs/src/js/interfaces/ListNamespacesOptions.md +++ /dev/null @@ -1,27 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListNamespacesOptions - -# Interface: ListNamespacesOptions - -## Properties - -### limit? - -```ts -optional limit: number; -``` - -An optional limit to the number of results to return. - -*** - -### pageToken? - -```ts -optional pageToken: string; -``` - -Token from a previous response for pagination. diff --git a/docs/src/js/interfaces/ListNamespacesResponse.md b/docs/src/js/interfaces/ListNamespacesResponse.md deleted file mode 100644 index a99ab480f..000000000 --- a/docs/src/js/interfaces/ListNamespacesResponse.md +++ /dev/null @@ -1,23 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListNamespacesResponse - -# Interface: ListNamespacesResponse - -## Properties - -### namespaces - -```ts -namespaces: string[]; -``` - -*** - -### pageToken? - -```ts -optional pageToken: string; -``` diff --git a/docs/src/js/interfaces/ListTablesOptions.md b/docs/src/js/interfaces/ListTablesOptions.md deleted file mode 100644 index b8dd8b5ef..000000000 --- a/docs/src/js/interfaces/ListTablesOptions.md +++ /dev/null @@ -1,35 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListTablesOptions - -# Interface: ListTablesOptions - -## Properties - -### limit? - -```ts -optional limit: number; -``` - -An upper bound on how many tables to return. -Defaults to 100. Zero returns an empty page without a continuation token. - -A page may hold fewer than this and still not be the last one, so keep -going while the response carries a page token rather than while pages are -full. - -*** - -### pageToken? - -```ts -optional pageToken: string; -``` - -Token from a previous response, to resume listing where it left off. - -The token is opaque: it carries whatever the database needs to resume, and -callers should not construct or interpret one. diff --git a/docs/src/js/interfaces/ListTablesResponse.md b/docs/src/js/interfaces/ListTablesResponse.md deleted file mode 100644 index 76cac2b23..000000000 --- a/docs/src/js/interfaces/ListTablesResponse.md +++ /dev/null @@ -1,23 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / ListTablesResponse - -# Interface: ListTablesResponse - -## Properties - -### pageToken? - -```ts -optional pageToken: string; -``` - -*** - -### tables - -```ts -tables: string[]; -``` diff --git a/docs/src/js/interfaces/TableNamesOptions.md b/docs/src/js/interfaces/TableNamesOptions.md index 123aa6c9f..e1fd8c382 100644 --- a/docs/src/js/interfaces/TableNamesOptions.md +++ b/docs/src/js/interfaces/TableNamesOptions.md @@ -8,7 +8,7 @@ ## Deprecated -Use [ListTablesOptions](ListTablesOptions.md) with [Connection.listTables](../classes/Connection.md#listtables) +Use [ListingOptions](ListingOptions.md) with [Connection.listTables](../classes/Connection.md#listtables) instead. ## Properties diff --git a/docs/src/python/python.md b/docs/src/python/python.md index f4c697497..c465d0ac4 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -26,14 +26,17 @@ is also an [asynchronous API client](#connections-asynchronous). ::: lancedb.db.DBConnection -Resource listings (`list_secrets`, `list_views`, `list_jobs`, `list_functions`, and -`list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to -collect synchronous results, or `[name async for name in db.list_views()]` with -an asynchronous connection. `page_limit` controls each request, and `page_token` -resumes a listing. Drain the iterator's cached results before saving its token. +Resource listings return iterators. Use `list(db.list_tables())` to collect all +table names. `db.list_tables().tables` is a list of the first page; `limit` +controls its page size and `page_token` resumes at a saved token. The same +patterns apply to `list_namespaces()`. Other resource listings use `page_limit`. ::: lancedb.listing.Listing +::: lancedb.listing.TableListing + +::: lancedb.listing.NamespaceListing + ::: lancedb.Session ## Catalogs (Synchronous) @@ -631,6 +634,16 @@ can be used to create, list, or open tables. ::: lancedb.listing.AsyncListing +`async for name in db.list_tables()` loads pages as needed. To inspect the +first page, use `page = await db.list_tables()` and then `page.tables`. Reading +the page list does not consume the iterator. `page.page_token` is the token for +the next request; drain cached results before using it to resume in a new +listing. The same behavior applies to namespaces. + +::: lancedb.listing.AsyncTableListing + +::: lancedb.listing.AsyncNamespaceListing + ## Namespaces (Asynchronous) ::: lancedb.connect_namespace_async diff --git a/docs/web-tests/ts/connection.test.ts b/docs/web-tests/ts/connection.test.ts index 891501d4c..651be7d36 100644 --- a/docs/web-tests/ts/connection.test.ts +++ b/docs/web-tests/ts/connection.test.ts @@ -4,6 +4,12 @@ import { afterEach, describe, expect, jest, test } from "@jest/globals"; import * as lancedb from "@lancedb/lancedb"; import { withTempDirectory } from "./util.ts"; +async function collectNames(items: AsyncIterable): Promise { + const names: string[] = []; + for await (const name of items) names.push(name); + return names; +} + test("connect to a local database", async () => { await withTempDirectory(async (tempDir) => { const cwd = process.cwd(); @@ -13,12 +19,12 @@ test("connect to a local database", async () => { const db = await lancedb.connect("ex_lancedb"); // --8<-- [end:connect] await db.createTable("probe", [{ id: 1 }]); - expect((await db.listTables()).tables).toEqual(["probe"]); + expect(await collectNames(db.listTables())).toEqual(["probe"]); } finally { process.chdir(cwd); } const reopened = await lancedb.connect(`${tempDir}/ex_lancedb`); - expect((await reopened.listTables()).tables).toEqual(["probe"]); + expect(await collectNames(reopened.listTables())).toEqual(["probe"]); }); }); @@ -109,8 +115,8 @@ async function namespaceTableOpsExample() { ); // Verify - console.log((await db.listNamespaces()).namespaces); // ["prod"] - console.log((await db.listNamespaces(["prod"])).namespaces); // ["recommendations", "search"] + console.log(await collectNames(db.listNamespaces())); // ["prod"] + console.log(await collectNames(db.listNamespaces(["prod"]))); // ["recommendations", "search"] console.log(await db.tableNames(["prod", "search"])); // ["user"] console.log(await db.tableNames(["prod", "recommendations"])); // ["user"] // --8<-- [end:namespace_table_ops] @@ -124,7 +130,7 @@ async function namespaceAdminOpsExample() { await db.createNamespace(["prod"]); await db.createNamespace(["prod", "search"]); - const childNamespaces = (await db.listNamespaces(["prod"])).namespaces; + const childNamespaces = await collectNames(db.listNamespaces(["prod"])); console.log(`Child namespaces under ${JSON.stringify(namespace)}:`, childNamespaces); // Child namespaces under ["prod","search"]: [ 'search' ] diff --git a/docs/web-tests/ts/quickstart.test.ts b/docs/web-tests/ts/quickstart.test.ts index e32a14f86..2c3ee8252 100644 --- a/docs/web-tests/ts/quickstart.test.ts +++ b/docs/web-tests/ts/quickstart.test.ts @@ -20,12 +20,7 @@ const connections = async function tableNames(db: lancedb.Connection) { const names: string[] = []; - let pageToken: string | undefined; - do { - const page = await db.listTables({ pageToken }); - names.push(...page.tables); - pageToken = page.pageToken; - } while (pageToken); + for await (const name of db.listTables()) names.push(name); return names; } diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index bbd0c3c52..73f99803a 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -5,15 +5,15 @@ import { mkdirSync, readdirSync } from "fs"; import { join } from "path"; import { Field, Float64, Schema } from "apache-arrow"; import * as tmp from "tmp"; -import { - Connection, - ListTablesResponse, - Table, - connect, - connectNamespace, -} from "../lancedb"; +import { Connection, Table, connect, connectNamespace } from "../lancedb"; import { LocalTable } from "../lancedb/table"; +async function collectNames(items: AsyncIterable): Promise { + const names: string[] = []; + for await (const name of items) names.push(name); + return names; +} + describe("when connecting", () => { let tmpDir: tmp.DirResult; beforeEach(() => { @@ -135,7 +135,7 @@ describe("given a connection", () => { await db.close(); expect(db.isOpen()).toBe(false); await expect(db.tableNames()).rejects.toThrow("Connection is closed"); - await expect(db.listTables()).rejects.toThrow("Connection is closed"); + expect(() => db.listTables()).toThrow("Connection is closed"); await expect(db.renameTable("a", "b")).rejects.toThrow( "Connection is closed", ); @@ -247,15 +247,15 @@ describe("given a connection", () => { await db.createTable(name, [{ id: 1 }]); } - const first = await db.listTables(namespacePath, { limit: 1 }); - expect(first.tables).toEqual(["a"]); - expect(first.pageToken).toBeDefined(); + const first = db.listTables(namespacePath, { pageLimit: 1 }); + expect(await first.next()).toEqual({ done: false, value: "a" }); + expect(first.pageToken()).toBeDefined(); - const second = await db.listTables(namespacePath, { - limit: 1, - pageToken: first.pageToken, + const second = db.listTables(namespacePath, { + pageLimit: 1, + pageToken: first.pageToken(), }); - expect(second.tables).toEqual(["b"]); + expect(await second.next()).toEqual({ done: false, value: "b" }); }); }); it("should keep the existing table when mode is exist_ok", async () => { @@ -299,19 +299,18 @@ describe("given a connection", () => { await db.createTable("a", [{ id: 1 }]); await db.createTable("c", [{ id: 1 }]); - const all = await db.listTables(); - expect(all.tables).toEqual(["a", "b", "c"]); - expect(all.pageToken).toBeUndefined(); + expect(await collectNames(db.listTables())).toEqual(["a", "b", "c"]); - const first = await db.listTables({ limit: 1 }); - expect(first.tables).toEqual(["a"]); - expect(first.pageToken).toBeDefined(); + const first = db.listTables([], { pageLimit: 1 }); + expect(first.numPageResults()).toBe(0); + expect(await first.next()).toEqual({ done: false, value: "a" }); + expect(first.pageToken()).toBeDefined(); - const second = await db.listTables({ - limit: 1, - pageToken: first.pageToken, + const second = db.listTables([], { + pageLimit: 1, + pageToken: first.pageToken(), }); - expect(second.tables).toEqual(["b"]); + expect(await second.next()).toEqual({ done: false, value: "b" }); }); it("should visit every table exactly once when walking pages", async () => { @@ -322,18 +321,9 @@ describe("given a connection", () => { await db.createTable(name, [{ id: 1 }]); } - const seen: string[] = []; - let pageToken: string | undefined = undefined; - do { - const page: ListTablesResponse = await db.listTables({ - limit: 2, - pageToken, - }); - seen.push(...page.tables); - pageToken = page.pageToken; - } while (pageToken); - - expect(seen).toEqual(created); + expect(await collectNames(db.listTables([], { pageLimit: 2 }))).toEqual( + created, + ); }); it.each([2 ** 32, 2 ** 32 + 1, Number.MAX_SAFE_INTEGER])( @@ -347,11 +337,10 @@ describe("given a connection", () => { ]) { await expect(names).resolves.toEqual(["a", "b"]); } - for (const page of [ - db.listTables({ limit }), - db.listTables([], { limit }), - ]) { - await expect(page).resolves.toEqual({ tables: ["a", "b"] }); + for (const namespacePath of [undefined, []]) { + expect(() => + db.listTables(namespacePath, { pageLimit: limit }), + ).toThrow(/limit/); } }, ); @@ -366,8 +355,11 @@ describe("given a connection", () => { ])("should reject an invalid table listing limit %s", async (limit) => { await expect(db.tableNames({ limit })).rejects.toThrow(/limit/); await expect(db.tableNames([], { limit })).rejects.toThrow(/limit/); - await expect(db.listTables({ limit })).rejects.toThrow(/limit/); - await expect(db.listTables([], { limit })).rejects.toThrow(/limit/); + for (const namespacePath of [undefined, []]) { + expect(() => db.listTables(namespacePath, { pageLimit: limit })).toThrow( + /limit/, + ); + } }); it("should preserve zero, small and unsigned-32-bit table listing limits", async () => { @@ -379,11 +371,21 @@ describe("given a connection", () => { [2 ** 32 - 1, ["a", "b"]], ] as const) { await expect(db.tableNames({ limit })).resolves.toEqual(names); - const page = await db.listTables({ limit }); - expect(page.tables).toEqual(names); } await expect(db.tableNames()).resolves.toEqual(["a", "b"]); - await expect(db.listTables()).resolves.toEqual({ tables: ["a", "b"] }); + for (const namespacePath of [undefined, []]) { + for (const pageLimit of [1, 2 ** 31 - 1]) { + expect( + await collectNames(db.listTables(namespacePath, { pageLimit })), + ).toEqual(["a", "b"]); + } + for (const pageLimit of [0, 2 ** 31, 2 ** 32 - 1]) { + expect(() => db.listTables(namespacePath, { pageLimit })).toThrow( + /limit/, + ); + } + } + expect(await collectNames(db.listTables())).toEqual(["a", "b"]); }); it("should list all names and use a default page size of 100", async () => { @@ -396,20 +398,17 @@ describe("given a connection", () => { } await expect(db.tableNames()).resolves.toEqual(names); await expect(db.tableNames({ limit: 0 })).resolves.toEqual([]); - const first = await db.listTables(); - expect(first.tables).toEqual(names.slice(0, 100)); - expect(first.pageToken).toBeDefined(); - const second = await db.listTables({ pageToken: first.pageToken }); - expect(second.tables).toEqual(names.slice(100)); - expect(second.pageToken).toBeUndefined(); - await expect(db.listTables({ limit: 200 })).resolves.toEqual({ - tables: names, - pageToken: undefined, - }); - await expect(db.listTables({ limit: 0 })).resolves.toEqual({ - tables: [], - pageToken: undefined, - }); + const first = db.listTables(); + const firstPage: string[] = []; + for (let i = 0; i < 100; i++) firstPage.push((await first.next()).value!); + expect(firstPage).toEqual(names.slice(0, 100)); + expect(first.pageToken()).toBeDefined(); + expect(first.numPageResults()).toBe(0); + expect(await collectNames(first)).toEqual(names.slice(100)); + expect(await collectNames(db.listTables([], { pageLimit: 200 }))).toEqual( + names, + ); + expect(() => db.listTables([], { pageLimit: 0 })).toThrow(/limit/); }); it("should list tables in a namespace", async () => { @@ -420,12 +419,8 @@ describe("given a connection", () => { await db.createNamespace(["child"]); await db.createTable("nested", [{ id: 1 }], ["child"]); - await expect(db.listTables(["child"])).resolves.toEqual( - expect.objectContaining({ tables: ["nested"] }), - ); - await expect(db.listTables()).resolves.toEqual( - expect.objectContaining({ tables: [] }), - ); + expect(await collectNames(db.listTables(["child"]))).toEqual(["nested"]); + expect(await collectNames(db.listTables())).toEqual([]); }); it("should create tables in v2 mode", async () => { @@ -719,22 +714,35 @@ describe("namespaces", () => { it("should list namespaces created at the root", async () => { await db.createNamespace(["alpha"]); await db.createNamespace(["beta"]); - const list = await db.listNamespaces(); - expect(list.namespaces).toEqual(expect.arrayContaining(["alpha", "beta"])); + const list = await collectNames(db.listNamespaces()); + expect(list).toEqual(expect.arrayContaining(["alpha", "beta"])); }); it("should list child namespaces under a parent", async () => { await db.createNamespace(["parent"]); await db.createNamespace(["parent", "child"]); - const list = await db.listNamespaces(["parent"]); - expect(list.namespaces).toContain("child"); + const list = await collectNames(db.listNamespaces(["parent"])); + expect(list).toContain("child"); + }); + + it("should resume a namespace listing from its page token", async () => { + await db.createNamespace(["alpha"]); + await db.createNamespace(["beta"]); + const first = db.listNamespaces([], { pageLimit: 1 }); + expect(first.numPageResults()).toBe(0); + expect((await first.next()).value).toBe("alpha"); + const second = db.listNamespaces([], { + pageLimit: 1, + pageToken: first.pageToken(), + }); + expect(await collectNames(second)).toEqual(["beta"]); }); it("should drop a namespace", async () => { await db.createNamespace(["ephemeral"]); await db.dropNamespace(["ephemeral"]); - const list = await db.listNamespaces(); - expect(list.namespaces).not.toContain("ephemeral"); + const list = await collectNames(db.listNamespaces()); + expect(list).not.toContain("ephemeral"); }); it("should raise an error on any namespace op after close", async () => { @@ -742,7 +750,7 @@ describe("namespaces", () => { await expect(db.describeNamespace(["foo"])).rejects.toThrow( "Connection is closed", ); - await expect(db.listNamespaces()).rejects.toThrow("Connection is closed"); + expect(() => db.listNamespaces()).toThrow("Connection is closed"); await expect(db.createNamespace(["foo"])).rejects.toThrow( "Connection is closed", ); diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index c93414fab..5f067eeef 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -30,16 +30,12 @@ import type { DescribeNamespaceResponse, DropNamespaceResponse, JobInfo, - ListNamespacesResponse, - ListTablesResponse, } from "./native"; import { ViewDescription, viewDescriptionFromNative } from "./view"; export type { CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, - ListNamespacesResponse, - ListTablesResponse, }; import { sanitizeTable } from "./sanitize"; import { LocalTable, Table } from "./table"; @@ -141,7 +137,7 @@ export interface OpenTableOptions { } /** - * @deprecated Use {@link ListTablesOptions} with {@link Connection.listTables} + * @deprecated Use {@link ListingOptions} with {@link Connection.listTables} * instead. */ export interface TableNamesOptions { @@ -157,32 +153,6 @@ export interface TableNamesOptions { limit?: number; } -export interface ListTablesOptions { - /** - * Token from a previous response, to resume listing where it left off. - * - * The token is opaque: it carries whatever the database needs to resume, and - * callers should not construct or interpret one. - */ - pageToken?: string; - /** - * An upper bound on how many tables to return. - * Defaults to 100. Zero returns an empty page without a continuation token. - * - * A page may hold fewer than this and still not be the last one, so keep - * going while the response carries a page token rather than while pages are - * full. - */ - limit?: number; -} - -export interface ListNamespacesOptions { - /** Token from a previous response for pagination. */ - pageToken?: string; - /** An optional limit to the number of results to return. */ - limit?: number; -} - export interface CreateNamespaceOptions { /** Creation mode. */ mode?: "create" | "exist_ok" | "overwrite"; @@ -278,45 +248,18 @@ export abstract class Connection { options?: Partial, ): Promise; - /** - * List a page of the tables in this database. - * - * To retrieve the tables after the page, pass the `pageToken` the response - * carries back in. A page can be shorter than `limit` without being the last - * one, so walk until a response carries no page token: - * + /** Lazily list tables in a namespace, requesting 100 per page by default. + * @example * ```ts - * const names = []; - * let pageToken = undefined; - * do { - * const page = await conn.listTables({ pageToken, limit: 100 }); - * names.push(...page.tables); - * pageToken = page.pageToken; - * } while (pageToken); + * for await (const name of conn.listTables([], { pageLimit: 20 })) { + * console.log(name); + * } * ``` - * - * @param {Partial} options - Pagination options - * (`pageToken`, `limit`). - * @returns {Promise} A page of table names and an - * optional token for the tables after it. - */ - abstract listTables( - options?: Partial, - ): Promise; - /** - * List a page of the tables in this database. - * - * @param {string[]} namespacePath - The namespace path to list tables from - * (defaults to root namespace) - * @param {Partial} options - Pagination options - * (`pageToken`, `limit`). - * @returns {Promise} A page of table names and an - * optional token for the tables after it. */ abstract listTables( namespacePath?: string[], - options?: Partial, - ): Promise; + options?: ListingOptions, + ): Listing; /** * Open a table in the database. @@ -542,23 +485,11 @@ export abstract class Connection { namespacePath: string[], ): Promise; - /** - * List the immediate child namespaces under the given parent. - * - * Results may be paginated. To retrieve subsequent pages, pass the - * `pageToken` returned by a previous call. - * - * @param {string[]} namespacePath - The parent namespace path. Defaults - * to the root namespace if omitted. - * @param {Partial} options - Pagination options - * (`pageToken`, `limit`). - * @returns {Promise} Child namespace names and - * an optional token for fetching the next page. - */ + /** Lazily list immediate child namespaces, 100 per page by default. */ abstract listNamespaces( namespacePath?: string[], - options?: Partial, - ): Promise; + options?: ListingOptions, + ): Listing; /** * Create a new namespace at the given path. @@ -821,22 +752,17 @@ export class LocalConnection extends Connection { ); } - async listTables( - namespacePathOrOptions?: string[] | Partial, - options?: Partial, - ): Promise { - // Detect if first argument is namespacePath array or options object - const namespacePath = Array.isArray(namespacePathOrOptions) - ? namespacePathOrOptions - : undefined; - const listTablesOptions = Array.isArray(namespacePathOrOptions) - ? options - : (namespacePathOrOptions ?? options); - - return this.inner.listTables( - namespacePath ?? [], - listTablesOptions?.pageToken, - normalizeTableListingLimit(listTablesOptions?.limit), + listTables( + namespacePath?: string[], + options: ListingOptions = {}, + ): Listing { + validateListingOptions(options); + return new Listing( + this.inner.listTables( + namespacePath ?? [], + options.pageToken, + options.pageLimit, + ), ); } @@ -1039,12 +965,15 @@ export class LocalConnection extends Connection { listNamespaces( namespacePath?: string[], - options?: Partial, - ): Promise { - return this.inner.listNamespaces( - namespacePath ?? [], - options?.pageToken, - options?.limit, + options: ListingOptions = {}, + ): Listing { + validateListingOptions(options); + return new Listing( + this.inner.listNamespaces( + namespacePath ?? [], + options.pageToken, + options.pageLimit, + ), ); } diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 4ad8b2a93..0f1b5f333 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -97,13 +97,9 @@ export { Connection, CreateTableOptions, TableNamesOptions, - ListTablesOptions, OpenTableOptions, - ListNamespacesOptions, CreateNamespaceOptions, DropNamespaceOptions, - ListNamespacesResponse, - ListTablesResponse, CreateNamespaceResponse, DropNamespaceResponse, DescribeNamespaceResponse, diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 67c4706e4..914f9e4c9 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -16,8 +16,7 @@ use crate::table::Table; use lancedb::connection::{ConnectBuilder, Connection as LanceDBConnection, connect_namespace}; use lance_namespace::models::{ - CreateNamespaceRequest, DescribeNamespaceRequest, DropNamespaceRequest, ListNamespacesRequest, - ListTablesRequest, + CreateNamespaceRequest, DescribeNamespaceRequest, DropNamespaceRequest, }; use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; @@ -31,18 +30,6 @@ pub struct DescribeNamespaceResponse { pub properties: Option>, } -#[napi(object)] -pub struct ListNamespacesResponse { - pub namespaces: Vec, - pub page_token: Option, -} - -#[napi(object)] -pub struct ListTablesResponse { - pub tables: Vec, - pub page_token: Option, -} - #[napi(object)] pub struct CreateNamespaceResponse { pub properties: Option>, @@ -239,31 +226,20 @@ impl Connection { op.execute().await.default_error() } - /// List a page of tables in the database. + /// Lazily list tables in the database. #[napi(catch_unwind)] - pub async fn list_tables( + pub fn list_tables( &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> napi::Result { - let request = ListTablesRequest { - // The root namespace is an empty path, not an absent one: a namespace-backed - // database rejects a request that names no namespace. - id: Some(namespace_path.unwrap_or_default()), - page_token, - limit: limit.map(|limit| i32::try_from(limit).unwrap_or(i32::MAX)), - ..Default::default() - }; - let response = self - .get_inner()? - .list_tables(request) - .await - .default_error()?; - Ok(ListTablesResponse { - tables: response.tables, - page_token: response.page_token, - }) + ) -> napi::Result { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_tables( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } /// Create table from a Apache Arrow IPC (file) buffer. @@ -663,28 +639,19 @@ impl Connection { } #[napi(catch_unwind)] - /// List child namespaces under the given namespace path - pub async fn list_namespaces( + /// Lazily list child namespaces under the given namespace path + pub fn list_namespaces( &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> napi::Result { - let req = ListNamespacesRequest { - id: namespace_path, - page_token, - limit: checked_limit(limit)?, - ..Default::default() - }; - let resp = self - .get_inner()? - .list_namespaces(req) - .await - .default_error()?; - Ok(ListNamespacesResponse { - namespaces: resp.namespaces, - page_token: resp.page_token, - }) + ) -> napi::Result { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_namespaces( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } #[napi(catch_unwind)] @@ -787,33 +754,3 @@ impl Connection { .default_error() } } - -fn checked_limit(limit: Option) -> napi::Result> { - limit - .map(i32::try_from) - .transpose() - .map_err(|_| napi::Error::from_reason("limit must not exceed 2147483647")) -} - -#[cfg(test)] -mod tests { - use super::checked_limit; - - #[test] - fn checked_limit_rejects_values_above_i32_max() { - // u32 values above i32::MAX wrapped negative through `as i32`, - // sending a negative page size to the server. - assert!(checked_limit(Some(3_000_000_000)).is_err()); - assert!(checked_limit(Some(u32::MAX)).is_err()); - } - - #[test] - fn checked_limit_passes_boundary_and_missing_values() { - assert_eq!( - checked_limit(Some(i32::MAX as u32)).unwrap(), - Some(i32::MAX) - ); - assert_eq!(checked_limit(Some(0)).unwrap(), Some(0)); - assert_eq!(checked_limit(None).unwrap(), None); - } -} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 96eef064c..6ef23abc7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -19,11 +19,9 @@ from .index import ( FTS, ) from lance_namespace import ( - ListNamespacesResponse, CreateNamespaceResponse, DropNamespaceResponse, DescribeNamespaceResponse, - ListTablesResponse, ) from .remote import ClientConfig from .types import BaseTokenizerType @@ -114,12 +112,12 @@ class Connection(object): uri: str async def is_open(self): ... async def close(self): ... - async def list_namespaces( + def list_namespaces( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: ... + ) -> NameListing: ... async def create_namespace( self, namespace_path: List[str], @@ -136,12 +134,12 @@ class Connection(object): self, namespace_path: List[str], ) -> DescribeNamespaceResponse: ... - async def list_tables( + def list_tables( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: ... + ) -> NameListing: ... async def table_names( self, namespace_path: Optional[List[str]], @@ -1010,6 +1008,7 @@ async def connect_catalog( class NameListing: def num_page_results(self) -> int: ... def page_token(self) -> Optional[str]: ... + async def next_page(self) -> Optional[dict[str, Any]]: ... def __aiter__(self) -> NameListing: ... async def __anext__(self) -> str: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index a74763afb..90dc1cccf 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -32,18 +32,24 @@ if sys.version_info >= (3, 12): else: from overrides import EnforceOverrides, override # type: ignore -from lancedb.listing import AsyncListing, Listing +from lancedb.listing import ( + AsyncListing, + AsyncNamespaceListing, + AsyncTableListing, + Listing, + NamespaceListing, + TableListing, + validate_page_limit, +) from lancedb.embeddings.registry import EmbeddingFunctionRegistry from lancedb.common import data_to_reader, sanitize_uri, validate_schema from lancedb.background_loop import LOOP from lance_namespace import ( LanceNamespace, - ListNamespacesResponse, CreateNamespaceResponse, DropNamespaceResponse, DescribeNamespaceResponse, - ListTablesResponse, connect as namespace_connect, ) from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError @@ -171,7 +177,7 @@ class DBConnection(EnforceOverrides): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -187,12 +193,12 @@ class DBConnection(EnforceOverrides): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return ListNamespacesResponse(namespaces=[], page_token=None) + return NamespaceListing(AsyncNamespaceListing(None, empty=True)) def create_namespace( self, @@ -317,8 +323,8 @@ class DBConnection(EnforceOverrides): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: - """List a page of tables in this database. + ) -> TableListing: + """List tables in this database, one page at a time. Parameters ---------- @@ -334,7 +340,7 @@ class DBConnection(EnforceOverrides): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ raise NotImplementedError( @@ -1436,7 +1442,7 @@ class LanceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -1452,16 +1458,14 @@ class LanceDBConnection(DBConnection): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return NamespaceListing( self._conn.list_namespaces( - namespace_path=namespace_path, - page_token=page_token, - limit=limit, + namespace_path=namespace_path, page_token=page_token, limit=limit ) ) @@ -1512,8 +1516,8 @@ class LanceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: - """List a page of tables in this database. + ) -> TableListing: + """List tables in this database, one page at a time. Parameters ---------- @@ -1529,12 +1533,12 @@ class LanceDBConnection(DBConnection): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return TableListing( self._conn.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -2286,12 +2290,12 @@ class AsyncConnection(object): else: return None - async def list_namespaces( + def list_namespaces( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> AsyncNamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -2306,15 +2310,18 @@ class AsyncConnection(object): Returns ------- - ListNamespacesResponse + AsyncNamespaceListing Response containing namespace names and optional pagination token """ if namespace_path is None: namespace_path = [] - result = await self._inner.list_namespaces( + validate_page_limit(limit) + inner = self._inner.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) - return ListNamespacesResponse(**result) + if limit == 0: + return AsyncNamespaceListing(None, empty=True) + return AsyncNamespaceListing(inner, page_token) async def create_namespace( self, @@ -2393,13 +2400,13 @@ class AsyncConnection(object): result = await self._inner.describe_namespace(namespace_path) return DescribeNamespaceResponse(**result) - async def list_tables( + def list_tables( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: - """List a page of tables in this database. + ) -> AsyncTableListing: + """List tables in this database, one page at a time. Parameters ---------- @@ -2415,15 +2422,18 @@ class AsyncConnection(object): Returns ------- - ListTablesResponse + AsyncTableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - result = await self._inner.list_tables( + validate_page_limit(limit) + inner = self._inner.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) - return ListTablesResponse(**result) + if limit == 0: + return AsyncTableListing(None, empty=True) + return AsyncTableListing(inner, page_token) async def table_names( self, diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 0620aa7d8..8abc9d85b 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar from .background_loop import LOOP @@ -83,3 +84,173 @@ class Listing(Iterator[T], Generic[T]): for initial, cached, final-page, and error behavior. """ return self._inner.page_token() + + +def validate_page_limit(limit: Optional[int]) -> None: + """Validate the legacy limit argument before passing it to the bindings.""" + if limit is not None and ( + not isinstance(limit, int) or limit < 0 or limit > 2**31 - 1 + ): + raise ValueError("limit must be between 0 and 2147483647") + + +class _AsyncPagedNameListing(AsyncIterator[str]): + """An async listing with an inspectable copy of its current backend page.""" + + def __init__( + self, inner: Any, page_token: Optional[str] = None, *, empty: bool = False + ): + self._inner = inner + self._token = page_token + self._page: Optional[list[str]] = [] if empty else None + self._position = 0 + self._done = empty + self._failure: Optional[BaseException] = None + self._lock = asyncio.Lock() + + @property + def page_token(self) -> Optional[str]: + """The continuation token for the next backend request.""" + return self._token + + def num_page_results(self) -> int: + """Count the remaining names in the current page.""" + return 0 if self._page is None else len(self._page) - self._position + + def _page_copy(self) -> list[str]: + if self._page is None: + raise RuntimeError("Await or iterate the listing before reading its page") + return self._page.copy() + + async def _fetch_page(self) -> None: + try: + page = await self._inner.next_page() + except asyncio.CancelledError: + raise + except BaseException as exc: + self._failure = exc + self._done = True + raise + if page is None: + self._page = [] + self._token = None + self._done = True + else: + self._page = page["items"] + self._token = page["page_token"] + self._done = self._token is None + self._position = 0 + + async def _load_initial(self): + async with self._lock: + if self._failure is not None: + raise self._failure + if self._page is None: + await self._fetch_page() + return self + + def __await__(self): + return self._load_initial().__await__() + + def __aiter__(self): + return self + + async def __anext__(self) -> str: + async with self._lock: + if self._failure is not None: + raise StopAsyncIteration + if self._page is None: + await self._fetch_page() + assert self._page is not None + while self._position >= len(self._page): + if self._done: + raise StopAsyncIteration + await self._fetch_page() + assert self._page is not None + item = self._page[self._position] + self._position += 1 + return item + + +class AsyncTableListing(_AsyncPagedNameListing): + """Awaitable table iterator; awaiting loads one page. + + For example:: + + page = await db.list_tables(limit=20) + print(page.tables, page.page_token) + async for name in db.list_tables(limit=20): + print(name) + """ + + @property + def tables(self) -> list[str]: + """A copy of every table name in the most recently fetched page.""" + return self._page_copy() + + +class AsyncNamespaceListing(_AsyncPagedNameListing): + """Awaitable namespace iterator; awaiting loads one page. + + For example:: + + page = await db.list_namespaces(limit=20) + print(page.namespaces, page.page_token) + """ + + @property + def namespaces(self) -> list[str]: + """A copy of every name in the most recently fetched page.""" + return self._page_copy() + + +class _PagedNameListing(Iterator[str]): + def __init__(self, inner: _AsyncPagedNameListing): + self._inner = inner + LOOP.run(inner._load_initial()) + + def __iter__(self): + return self + + def __next__(self) -> str: + try: + return LOOP.run(self._inner.__anext__()) + except StopAsyncIteration: + raise StopIteration from None + + @property + def page_token(self) -> Optional[str]: + return self._inner.page_token + + def num_page_results(self) -> int: + return self._inner.num_page_results() + + +class TableListing(_PagedNameListing): + """Table iterator retaining the current page as a list. + + For example:: + + page = db.list_tables(limit=20) + print(page.tables, page.page_token) + for name in db.list_tables(limit=20): + print(name) + """ + + @property + def tables(self) -> list[str]: + return self._inner.tables + + +class NamespaceListing(_PagedNameListing): + """Namespace iterator retaining the current page as a list. + + For example:: + + page = db.list_namespaces(limit=20) + print(page.namespaces, page.page_token) + """ + + @property + def namespaces(self) -> list[str]: + return self._inner.namespaces diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index a5d88eb1f..55baa39a3 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -52,7 +52,14 @@ from lancedb.background_loop import LOOP from lancedb.arrow import AsyncRecordBatchReader from lancedb.db import AsyncConnection, DBConnection from lancedb.job import AsyncJob, Job -from lancedb.listing import AsyncListing, Listing +from lancedb.listing import ( + AsyncListing, + AsyncNamespaceListing, + AsyncTableListing, + Listing, + NamespaceListing, + TableListing, +) from lancedb.sql import AsyncQuery as AsyncSqlQuery from lancedb.sql import QueryDescription, QueryParameters from lance_namespace import ( @@ -61,8 +68,6 @@ from lance_namespace import ( CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, - ListNamespacesResponse, - ListTablesResponse, NamespaceExistsRequest, TableExistsRequest, ) @@ -854,7 +859,7 @@ class LanceNamespaceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """ List child namespaces under the given namespace. @@ -871,12 +876,12 @@ class LanceNamespaceDBConnection(DBConnection): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return NamespaceListing( self._inner.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -1023,7 +1028,7 @@ class LanceNamespaceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: + ) -> TableListing: """ List all tables in this database with pagination support. @@ -1040,12 +1045,12 @@ class LanceNamespaceDBConnection(DBConnection): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return TableListing( self._inner.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -1459,12 +1464,12 @@ class AsyncLanceNamespaceDBConnection: namespace_path = [] await self._inner.drop_all_tables(namespace_path=namespace_path) - async def list_namespaces( + def list_namespaces( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> AsyncNamespaceListing: """ List child namespaces under the given namespace. @@ -1481,12 +1486,12 @@ class AsyncLanceNamespaceDBConnection: Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return await self._inner.list_namespaces( + return self._inner.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -1616,12 +1621,12 @@ class AsyncLanceNamespaceDBConnection: except TableNotFoundError: return False - async def list_tables( + def list_tables( self, namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: + ) -> AsyncTableListing: """ List all tables in this database with pagination support. @@ -1638,12 +1643,12 @@ class AsyncLanceNamespaceDBConnection: Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return await self._inner.list_tables( + return self._inner.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 89c7f8a78..08125cc42 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -36,7 +36,7 @@ from lancedb.remote import ClientConfig, RetryConfig, TimeoutConfig, TlsConfig import pyarrow as pa from ..common import DATA -from lancedb.listing import Listing +from lancedb.listing import Listing, NamespaceListing, TableListing from ..db import DBConnection, LOOP from ..functions import FunctionVersion, UdfDefinition from ..job import AsyncJob, Job @@ -54,8 +54,6 @@ from lance_namespace import ( CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, - ListNamespacesResponse, - ListTablesResponse, ) from ..pydantic import LanceModel from ..table import Table @@ -268,7 +266,7 @@ class RemoteDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListNamespacesResponse: + ) -> NamespaceListing: """List immediate child namespace names in the given namespace. Parameters @@ -284,12 +282,12 @@ class RemoteDBConnection(DBConnection): Returns ------- - ListNamespacesResponse + NamespaceListing Response containing namespace names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return NamespaceListing( self._conn.list_namespaces( namespace_path=namespace_path, page_token=page_token, limit=limit ) @@ -379,7 +377,7 @@ class RemoteDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, page_token: Optional[str] = None, limit: Optional[int] = None, - ) -> ListTablesResponse: + ) -> TableListing: """List a page of tables in this database. Parameters @@ -396,12 +394,12 @@ class RemoteDBConnection(DBConnection): Returns ------- - ListTablesResponse + TableListing Response containing table names and optional page_token for pagination. """ if namespace_path is None: namespace_path = [] - return LOOP.run( + return TableListing( self._conn.list_tables( namespace_path=namespace_path, page_token=page_token, limit=limit ) diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index e319d3048..207a3d253 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -896,6 +896,8 @@ def test_transient_embedding_error_is_retried_in_table_add(tmp_path): assert len(calls) == 3 assert mock_sleep.call_count == 2 assert all(call.args[0] <= 60 for call in mock_sleep.call_args_list) + + @patch("time.sleep") @pytest.mark.parametrize( "error", @@ -941,6 +943,8 @@ def test_retry_on_wrapped_provider_error(mock_sleep): assert wrapped_func() == [0.1] assert mock_func.call_count == 2 assert mock_sleep.call_count == 1 + + def test_openai_bad_request_partial_batch_recovery(): # Regression test for issue #1677 diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index 4a2745eb8..b0b973bbf 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -88,6 +88,143 @@ async def advance(items, asynchronous): KINDS = ["secrets", "views", "jobs", "functions", "materialized_views"] +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_compatible_name_listing_pages(listing_server, kind, asynchronous): + endpoint, requests, responses = listing_server + responses.extend( + [ + (200, response_page(kind, ["a", "b"], "next")), + (200, response_page(kind, ["c"], None)), + ] + ) + db = await connection(endpoint, asynchronous) + listing = getattr(db, "list_" + kind)( + namespace_path=["team"], page_token="start", limit=2 + ) + field = kind + assert len(requests) == (0 if asynchronous else 1) + if asynchronous: + with pytest.raises(RuntimeError, match="Await or iterate"): + getattr(listing, field) + assert listing.page_token == "start" + assert await listing is listing + assert len(requests) == 1 + page_names = getattr(listing, field) + assert type(page_names) is list + assert page_names == ["a", "b"] + page_names.append("changed") + assert getattr(listing, field) == ["a", "b"] + assert listing.page_token == "next" + assert listing.num_page_results() == 2 + assert await advance(listing, asynchronous) == "a" + assert getattr(listing, field) == ["a", "b"] + assert await advance(listing, asynchronous) == "b" + assert len(requests) == 1 + assert await advance(listing, asynchronous) == "c" + assert getattr(listing, field) == ["c"] + assert listing.page_token is None + assert len(requests) == 2 + assert ([item async for item in listing] if asynchronous else list(listing)) == [] + if asynchronous: + assert await listing is listing + assert len(requests) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_skips_empty_page_only_during_iteration( + listing_server, kind +): + endpoint, requests, responses = listing_server + responses.extend( + [ + (200, response_page(kind, [], "next")), + (200, response_page(kind, ["a"], None)), + ] + ) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)() + await listing + assert getattr(listing, kind) == [] + assert listing.page_token == "next" + assert len(requests) == 1 + assert [name async for name in listing] == ["a"] + assert len(requests) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_name_listing_zero_limit_uses_no_request( + listing_server, kind, asynchronous +): + endpoint, requests, _ = listing_server + db = await connection(endpoint, asynchronous) + listing = getattr(db, "list_" + kind)(limit=0) + if asynchronous: + assert await listing is listing + assert [name async for name in listing] == [] + else: + assert list(listing) == [] + assert getattr(listing, kind) == [] + assert listing.page_token is None + assert requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_failure_retains_token(listing_server, kind): + endpoint, requests, responses = listing_server + responses.append((401, {})) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)(page_token="retry") + with pytest.raises(HttpError): + await listing + assert listing.page_token == "retry" + with pytest.raises(HttpError): + await listing + assert [name async for name in listing] == [] + assert len(requests) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_direct_async_iteration(listing_server, kind): + endpoint, requests, responses = listing_server + responses.extend( + [ + (200, response_page(kind, ["a"], "next")), + (200, response_page(kind, ["b"], None)), + ] + ) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)(limit=1) + assert requests == [] + assert [name async for name in listing] == ["a", "b"] + assert getattr(listing, kind) == ["b"] + assert len(requests) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["tables", "namespaces"]) +async def test_name_listing_serializes_concurrent_advances(listing_server, kind): + endpoint, requests, responses = listing_server + responses.append((200, response_page(kind, ["a", "b"], None))) + db = await connection(endpoint, True) + listing = getattr(db, "list_" + kind)() + results = await asyncio.gather( + listing.__anext__(), + listing.__anext__(), + listing.__anext__(), + return_exceptions=True, + ) + assert results[:2] == ["a", "b"] + assert isinstance(results[2], StopAsyncIteration) + assert len(requests) == 1 + + @pytest.mark.asyncio @pytest.mark.parametrize("kind", KINDS) @pytest.mark.parametrize("asynchronous", [False, True]) diff --git a/python/python/tests/test_ollama_embeddings.py b/python/python/tests/test_ollama_embeddings.py index 9d8568ca7..de36dc24b 100644 --- a/python/python/tests/test_ollama_embeddings.py +++ b/python/python/tests/test_ollama_embeddings.py @@ -3,7 +3,6 @@ import json -import httpx import numpy as np import pyarrow as pa import pytest @@ -14,6 +13,7 @@ from lancedb.embeddings import get_registry @pytest.fixture def ollama_embeddings(): + httpx = pytest.importorskip("httpx") pytest.importorskip("ollama") requests = [] diff --git a/python/src/connection.rs b/python/src/connection.rs index baeb29780..2cdf71f4a 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -590,29 +590,17 @@ impl Connection { #[pyo3(signature = (namespace_path=None, page_token=None, limit=None))] pub fn list_namespaces( - self_: PyRef<'_, Self>, + &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> PyResult> { - let inner = self_.get_inner()?.clone(); - let py = self_.py(); - future_into_py(py, async move { - use lance_namespace::models::ListNamespacesRequest; - let request = ListNamespacesRequest { - id: namespace_path, - page_token, - limit: limit.map(|l| l as i32), - ..Default::default() - }; - let response = inner.list_namespaces(request).await.infer_error()?; - Python::attach(|py| -> PyResult> { - let dict = PyDict::new(py); - dict.set_item("namespaces", response.namespaces)?; - dict.set_item("page_token", response.page_token)?; - Ok(dict.unbind()) - }) - }) + ) -> PyResult { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_namespaces( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } #[pyo3(signature = (namespace_path, mode=None, properties=None))] @@ -725,29 +713,17 @@ impl Connection { #[pyo3(signature = (namespace_path=None, page_token=None, limit=None))] pub fn list_tables( - self_: PyRef<'_, Self>, + &self, namespace_path: Option>, page_token: Option, limit: Option, - ) -> PyResult> { - let inner = self_.get_inner()?.clone(); - let py = self_.py(); - future_into_py(py, async move { - use lance_namespace::models::ListTablesRequest; - let request = ListTablesRequest { - id: namespace_path, - page_token, - limit: limit.map(|l| l as i32), - ..Default::default() - }; - let response = inner.list_tables(request).await.infer_error()?; - Python::attach(|py| -> PyResult> { - let dict = PyDict::new(py); - dict.set_item("tables", response.tables)?; - dict.set_item("page_token", response.page_token)?; - Ok(dict.unbind()) - }) - }) + ) -> PyResult { + Ok(crate::listing::NameListing::new( + self.get_inner()?.list_tables( + &namespace_path.unwrap_or_default(), + crate::listing::options(page_token, limit), + ), + )) } /// Get the configuration for constructing an equivalent namespace client. diff --git a/python/src/listing.rs b/python/src/listing.rs index 2d1a3916e..79a7effdd 100644 --- a/python/src/listing.rs +++ b/python/src/listing.rs @@ -3,10 +3,11 @@ use crate::error::PythonErrorExt; use crate::runtime::future_into_py; -use futures::{StreamExt, future::poll_fn}; +use futures::{Future, StreamExt, future::poll_fn}; use lancedb::listing::{Listing, ListingOptions}; use pyo3::exceptions::PyStopAsyncIteration; -use pyo3::{Bound, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; +use pyo3::types::{PyDict, PyDictMethods}; +use pyo3::{Bound, Py, PyAny, PyRef, PyResult, Python, pyclass, pymethods}; use std::sync::{Arc, Mutex}; pub fn options(page_token: Option, page_limit: Option) -> ListingOptions { @@ -52,6 +53,31 @@ impl NameListing { Ok(value) }) } + + fn next_page(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + let next_lock = self_.next_lock.clone(); + future_into_py(self_.py(), async move { + let _guard = next_lock.lock().await; + let page = futures::future::poll_fn(|cx| { + let mut inner = inner.lock().unwrap(); + let future = inner.next_page(); + futures::pin_mut!(future); + future.poll(cx) + }) + .await + .infer_error()?; + Python::attach(|py| -> PyResult>> { + page.map(|page| { + let dict = PyDict::new(py); + dict.set_item("items", page.items)?; + dict.set_item("page_token", page.page_token)?; + Ok(dict.unbind()) + }) + .transpose() + }) + }) + } } #[pyclass] diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 8a0e489c2..124f6a54a 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -13,7 +13,7 @@ use lance::dataset::refs::MAIN_BRANCH; use lance_namespace::models::{ CreateNamespaceRequest, CreateNamespaceResponse, DescribeNamespaceRequest, DescribeNamespaceResponse, DropNamespaceRequest, DropNamespaceResponse, ListNamespacesRequest, - ListNamespacesResponse, ListTablesRequest, ListTablesResponse, + ListTablesRequest, }; #[cfg(feature = "aws")] use object_store::aws::AwsCredential; @@ -28,7 +28,7 @@ use crate::database::{ }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; -use crate::listing::{Listing, ListingOptions}; +use crate::listing::{Listing, ListingOptions, ListingPage}; #[cfg(feature = "remote")] use crate::remote::{ client::ClientConfig, @@ -1126,12 +1126,43 @@ impl Connection { self.internal.drop_all_tables(namespace_path).await } - /// List immediate child namespace names in the given namespace - pub async fn list_namespaces( + /// Lazily list immediate child namespace names. Each request asks for at + /// most 100 names unless `options.page_limit` is set. + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// let names: Vec = connection.list_namespaces(&[], Default::default()) + /// .try_collect().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn list_namespaces( &self, - request: ListNamespacesRequest, - ) -> Result { - self.internal.list_namespaces(request).await + namespace_path: &[String], + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + let namespace_path = namespace_path.to_vec(); + Listing::new(options, move |options| { + let database = database.clone(); + let namespace_path = namespace_path.clone(); + async move { + validate_namespace(&namespace_path)?; + let response = database + .list_namespaces(ListNamespacesRequest { + id: Some(namespace_path), + page_token: options.page_token, + limit: Some(options.page_limit.unwrap_or(100) as i32), + ..Default::default() + }) + .await?; + Ok(ListingPage { + items: response.namespaces, + page_token: response.page_token, + }) + } + }) } /// Create a new namespace @@ -1182,23 +1213,43 @@ impl Connection { self.internal.namespace_client_config().await } - /// List tables with pagination support + /// Lazily list tables. Each request asks for at most 100 names unless + /// `options.page_limit` is set. /// - /// The default limit is 100 tables per page for both local and remote connections, - /// including namespaces. Zero returns an empty page without a continuation token. - /// Follow the response's opaque `page_token` until it is absent to retrieve every table; - /// a page can contain fewer than the limit even when more tables remain. - pub async fn list_tables(&self, mut request: ListTablesRequest) -> Result { - // Apply the SDK's page size here so every backend receives the same request. - let limit = request.limit.get_or_insert(100); - if *limit <= 0 { - return Ok(ListTablesResponse { - context: None, - tables: Vec::new(), - page_token: None, - }); - } - self.internal.list_tables(request).await + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// let names: Vec = connection.list_tables(&[], Default::default()) + /// .try_collect().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn list_tables( + &self, + namespace_path: &[String], + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + let namespace_path = namespace_path.to_vec(); + Listing::new(options, move |options| { + let database = database.clone(); + let namespace_path = namespace_path.clone(); + async move { + validate_namespace(&namespace_path)?; + let response = database + .list_tables(ListTablesRequest { + id: Some(namespace_path), + page_token: options.page_token, + limit: Some(options.page_limit.unwrap_or(100) as i32), + ..Default::default() + }) + .await?; + Ok(ListingPage { + items: response.tables, + page_token: response.page_token, + }) + } + }) } /// Get the in-memory embedding registry. @@ -2260,26 +2311,11 @@ mod tests { } names.sort(); - // Walking in pages has to reach every table exactly once, with nothing lost at a - // page boundary. - let mut seen = Vec::with_capacity(names.len()); - let mut page_token = None; - loop { - let page = db - .list_tables(ListTablesRequest { - id: Some(Vec::new()), - limit: Some(2), - page_token, - ..Default::default() - }) - .await - .unwrap(); - seen.extend(page.tables); - page_token = page.page_token.filter(|token| !token.is_empty()); - if page_token.is_none() { - break; - } - } + let seen = futures::TryStreamExt::try_collect::>( + db.list_tables(&[], ListingOptions::default().page_limit(2)), + ) + .await + .unwrap(); assert_eq!(seen, names); } @@ -2305,37 +2341,20 @@ mod tests { .is_empty() ); - let first = db.list_tables(ListTablesRequest::default()).await.unwrap(); - assert_eq!(first.tables, names[..100]); + let mut listing = db.list_tables(&[], ListingOptions::default()); + assert_eq!(listing.num_page_results(), 0); + let first = listing.next_page().await.unwrap().unwrap(); + assert_eq!(first.items, names[..100]); assert!(first.page_token.is_some()); - let second = db - .list_tables(ListTablesRequest { - page_token: first.page_token, - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(second.tables, names[100..]); + let second = listing.next_page().await.unwrap().unwrap(); + assert_eq!(second.items, names[100..]); assert!(second.page_token.is_none()); + assert!(listing.next_page().await.unwrap().is_none()); - let all = db - .list_tables(ListTablesRequest { - limit: Some(200), - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(all.tables, names); - assert!(all.page_token.is_none()); - let empty = db - .list_tables(ListTablesRequest { - limit: Some(0), - ..Default::default() - }) - .await - .unwrap(); - assert!(empty.tables.is_empty()); - assert!(empty.page_token.is_none()); + let mut all = db.list_tables(&[], ListingOptions::default().page_limit(200)); + assert_eq!(all.next_page().await.unwrap().unwrap().items, names); + let mut invalid = db.list_tables(&[], ListingOptions::default().page_limit(0)); + assert!(invalid.next_page().await.is_err()); } #[tokio::test] diff --git a/rust/lancedb/src/listing.rs b/rust/lancedb/src/listing.rs index 710202d9d..a0f6e5d5e 100644 --- a/rust/lancedb/src/listing.rs +++ b/rust/lancedb/src/listing.rs @@ -51,8 +51,9 @@ type FetchPage = /// A lazy stream of resources with inspectable pagination state. /// -/// No requests are made until the stream is polled. Empty pages with continuation -/// tokens are skipped. Errors terminate the stream and retain the failed request's +/// No requests are made until the stream is polled or [`Self::next_page`] is called. +/// Item iteration skips empty pages with continuation tokens; `next_page` returns +/// them. Errors terminate the listing and retain the failed request's /// token, allowing a new stream to retry it. Repeated tokens are rejected. /// /// A token advances when its page is fetched. Drain [`Self::num_page_results`] @@ -100,6 +101,64 @@ impl Listing { pub fn page_token(&self) -> Option<&str> { self.options.page_token.as_deref() } + + /// Return exactly one page without consuming a following page. + /// + /// If item iteration has started, this returns the remaining items in its + /// cached page. An empty page with a continuation token is returned as is. + pub async fn next_page(&mut self) -> Result>> { + if self.items.len() == 0 { + if self.done { + return Ok(None); + } + futures::future::poll_fn(|cx| self.poll_fetch_page(cx)).await?; + } + let items = std::mem::replace(&mut self.items, Vec::new().into_iter()).collect(); + Ok(Some(ListingPage { + items, + page_token: self.options.page_token.clone(), + })) + } + + fn poll_fetch_page(&mut self, cx: &mut Context<'_>) -> Poll> { + if self + .options + .page_limit + .is_some_and(|limit| limit == 0 || limit > i32::MAX as u32) + { + self.done = true; + return Poll::Ready(Err(Error::InvalidInput { + message: "Listing page limit must be between 1 and 2147483647".into(), + })); + } + let pending = self + .pending + .get_or_insert_with(|| (self.fetch)(self.options.clone())); + let response = futures::ready!(pending.as_mut().poll(cx)); + self.pending = None; + match response { + Ok(response) => { + let token = response.page_token.filter(|token| !token.is_empty()); + if token + .as_ref() + .is_some_and(|token| !self.seen_tokens.insert(token.clone())) + { + self.done = true; + return Poll::Ready(Err(Error::Runtime { + message: "Listing response repeated a page_token".into(), + })); + } + self.done = token.is_none(); + self.options.page_token = token; + self.items = response.items.into_iter(); + Poll::Ready(Ok(())) + } + Err(error) => { + self.done = true; + Poll::Ready(Err(error)) + } + } + } } impl Stream for Listing { @@ -114,41 +173,8 @@ impl Stream for Listing { if this.done { return Poll::Ready(None); } - if this - .options - .page_limit - .is_some_and(|limit| limit == 0 || limit > i32::MAX as u32) - { - this.done = true; - return Poll::Ready(Some(Err(Error::InvalidInput { - message: "Listing page limit must be between 1 and 2147483647".into(), - }))); - } - let pending = this - .pending - .get_or_insert_with(|| (this.fetch)(this.options.clone())); - let response = futures::ready!(pending.as_mut().poll(cx)); - this.pending = None; - match response { - Ok(response) => { - let token = response.page_token.filter(|token| !token.is_empty()); - if token - .as_ref() - .is_some_and(|token| !this.seen_tokens.insert(token.clone())) - { - this.done = true; - return Poll::Ready(Some(Err(Error::Runtime { - message: "Listing response repeated a page_token".into(), - }))); - } - this.done = token.is_none(); - this.options.page_token = token; - this.items = response.items.into_iter(); - } - Err(error) => { - this.done = true; - return Poll::Ready(Some(Err(error))); - } + if let Err(error) = futures::ready!(this.poll_fetch_page(cx)) { + return Poll::Ready(Some(Err(error))); } } } @@ -224,6 +250,36 @@ mod tests { assert!(listing.next().await.is_none()); } + #[tokio::test] + async fn next_page_preserves_empty_pages_and_remaining_items() { + let requests = Arc::new(Mutex::new(0)); + let count = requests.clone(); + let mut listing = Listing::new(ListingOptions::default(), move |options| { + *count.lock().unwrap() += 1; + async move { + let (items, page_token) = match options.page_token.as_deref() { + None => (vec![], Some("second".to_string())), + Some("second") => (vec!["a", "b"], Some("last".to_string())), + Some("last") => (vec!["c"], None), + _ => unreachable!(), + }; + Ok(ListingPage { items, page_token }) + } + }); + assert_eq!(*requests.lock().unwrap(), 0); + assert!(listing.next_page().await.unwrap().unwrap().items.is_empty()); + assert_eq!(*requests.lock().unwrap(), 1); + assert_eq!(listing.try_next().await.unwrap(), Some("a")); + assert_eq!(*requests.lock().unwrap(), 2); + let remaining = listing.next_page().await.unwrap().unwrap(); + assert_eq!(remaining.items, vec!["b"]); + assert_eq!(remaining.page_token.as_deref(), Some("last")); + assert_eq!(*requests.lock().unwrap(), 2); + assert_eq!(listing.next_page().await.unwrap().unwrap().items, vec!["c"]); + assert!(listing.next_page().await.unwrap().is_none()); + assert_eq!(*requests.lock().unwrap(), 3); + } + #[tokio::test] async fn invalid_limits_do_not_fetch() { for limit in [0, u32::MAX] { diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 4a8cbf32e..8a456ab3b 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -2349,16 +2349,8 @@ mod tests { .unwrap() .is_empty() ); - let page = conn - .list_tables(lance_namespace::models::ListTablesRequest { - id: Some(namespace), - limit: Some(0), - ..Default::default() - }) - .await - .unwrap(); - assert!(page.tables.is_empty()); - assert!(page.page_token.is_none()); + let mut listing = conn.list_tables(&namespace, ListingOptions::default().page_limit(0)); + assert!(listing.next_page().await.is_err()); } #[rstest::rstest] @@ -2393,25 +2385,17 @@ mod tests { ) .unwrap() }); - let first = conn - .list_tables(lance_namespace::models::ListTablesRequest { - id: Some(namespace.clone()), - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(first.tables.len(), 100); + let mut first_listing = conn.list_tables(&namespace, ListingOptions::default()); + let first = first_listing.next_page().await.unwrap().unwrap(); + assert_eq!(first.items.len(), 100); assert_eq!(first.page_token.as_deref(), Some("opaque-token")); - let second = conn - .list_tables(lance_namespace::models::ListTablesRequest { - id: Some(namespace), - page_token: first.page_token, - ..Default::default() - }) - .await - .unwrap(); + let mut second_listing = conn.list_tables( + &namespace, + ListingOptions::default().page_token(first.page_token.unwrap()), + ); + let second = second_listing.next_page().await.unwrap().unwrap(); let expected: Vec<_> = (100..130).map(|i| format!("t{i:03}")).collect(); - assert_eq!(second.tables, expected); + assert_eq!(second.items, expected); assert!(second.page_token.is_none()); } @@ -3680,14 +3664,9 @@ mod tests { assert!(table.is_ok(), "Failed to create table: {:?}", table.err()); // List tables in the child namespace - let list_response = conn - .list_tables(ListTablesRequest { - id: Some(namespace.clone()), - ..Default::default() - }) - .await - .expect("Failed to list tables"); - assert_eq!(list_response.tables, vec!["test_table"]); + let list_response = conn.list_tables(&namespace, ListingOptions::default()); + let names = list_response.try_collect::>().await.unwrap(); + assert_eq!(names, vec!["test_table"]); // Get namespace client and verify it can also list tables let namespace_client = conn.namespace_client().await.unwrap(); @@ -3754,17 +3733,12 @@ mod tests { } // List tables in the child namespace - let list_response = conn - .list_tables(ListTablesRequest { - id: Some(namespace.clone()), - ..Default::default() - }) - .await - .unwrap(); - assert_eq!(list_response.tables.len(), 3); - assert!(list_response.tables.contains(&"table1".to_string())); - assert!(list_response.tables.contains(&"table2".to_string())); - assert!(list_response.tables.contains(&"table3".to_string())); + let list_response = conn.list_tables(&namespace, ListingOptions::default()); + let names = list_response.try_collect::>().await.unwrap(); + assert_eq!(names.len(), 3); + assert!(names.contains(&"table1".to_string())); + assert!(names.contains(&"table2".to_string())); + assert!(names.contains(&"table3".to_string())); } } From 444f7f3bde8d18aa6ef39cba714dbe1bb448fb1d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 23 Oct 2026 12:45:25 +0800 Subject: [PATCH 078/180] ci: refresh apt lists before installing protobuf in docs build (#4636) The docs deploy workflow installs protobuf-compiler without refreshing apt lists first. Ubuntu noble-updates replaced `protobuf 3.21.12-8.2ubuntu0.3` with `.0.4`, so stale package lists in older runner images make `apt install` fail with 404 and exit code 100. Run `apt update` before installing, matching the other workflows. --- .github/workflows/docs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index d0ec583bf..fb3fb1d6a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -38,6 +38,7 @@ jobs: uses: actions/checkout@v6 - name: Install dependencies needed for ubuntu run: | + sudo apt update sudo apt install -y protobuf-compiler libssl-dev rustup update && rustup default - name: Set up Python From 45c4b159cab990a749d592b42e21e030f7479192 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Thu, 22 Oct 2026 22:51:40 -0700 Subject: [PATCH 079/180] fix: cap the remote job poll interval at one second (#4629) job.wait() polled on a backoff that doubled up to 5 s, so a job's completion was seen 2.5 s late on average, as long as a small refresh itself takes. Cap the interval at 1 s; the first polls still back off from 200 ms, so a quick job is seen quickly and a long one costs one request a second. Linear: OSS-2704 https://linear.app/lancedb/issue/OSS-2704 --- rust/lancedb/src/remote/job.rs | 36 ++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 41d8971ac..7d2e70ac9 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -18,7 +18,9 @@ use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; /// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`]. const INITIAL_POLL_INTERVAL: Duration = Duration::from_millis(200); -const MAX_POLL_INTERVAL: Duration = Duration::from_secs(5); +/// A job's completion is seen at most this long after it happens. A 5 s cap +/// added 2.5 s on average to every short refresh, as much as the job itself. +const MAX_POLL_INTERVAL: Duration = Duration::from_secs(1); #[derive(Debug, Clone, PartialEq, Eq)] enum JobState { @@ -268,13 +270,18 @@ impl JobHandle for RemoteJob { #[cfg(test)] mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + use async_trait::async_trait; use crate::Result; use crate::function::{FunctionVersion, RefreshColumnResult}; use crate::job::{Job, JobHandle, TerminalResult}; + use crate::remote::client::test_utils::client_with_handler; - use super::DescribeJobResponse; + use super::{DescribeJobResponse, RemoteJob}; const FUNCTION_JOB: &str = include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_job.json"); @@ -333,6 +340,31 @@ mod tests { ); } + /// Five in-progress polls then done: 0.2 + 0.4 + 0.8 + 1 + 1 s of waiting. + /// Under the old 5 s cap the same job would have waited 10 s. + #[tokio::test(start_paused = true)] + async fn wait_polls_at_most_every_second() { + let describes = Arc::new(AtomicUsize::new(0)); + let seen = describes.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let n = seen.fetch_add(1, Ordering::SeqCst); + let body = if n < 5 { + r#"{"job_state":"IN_PROGRESS"}"#.to_string() + } else { + UNIT_JOB.to_string() + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let started = tokio::time::Instant::now(); + RemoteJob::new(client, "job-1".to_string()) + .wait() + .await + .expect("unit job completes"); + assert_eq!(describes.load(Ordering::SeqCst), 6); + assert_eq!(started.elapsed(), Duration::from_millis(3400)); + } + #[test] fn remote_wire_unknown_fields_are_forward_decodable() { let response: DescribeJobResponse = From a9535684cc1d9901c54c852f103dd0d492d61c3f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 23 Oct 2026 20:17:38 +0800 Subject: [PATCH 080/180] chore(deps): bump ctutils to 0.4.4 for RUSTSEC-2026-0385 (#4638) Fixes RUSTSEC-2026-0385: `ctutils` < 0.4.4 generates masks with branches on secret values (`u128` mask generation / comparisons are not constant-time on some targets). - Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0385 - Affected: `ctutils 0.4.2` pinned in `Cargo.lock`, reached transitively via `digest 0.11` (RustCrypto) - Change: `cargo update -p ctutils --precise 0.4.4`; single lockfile-only change (patch bump, no API impact) The `deny` CI job started failing for every PR head after the advisory was published at 06:45Z today; `main`'s last `deny` run (05:51Z) predates it and does not yet cover this advisory. --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 34ee05cb1..8bad6ca92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2230,9 +2230,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" dependencies = [ "cmov", ] From b762ec221ba5d99ab368f2959f50381c589c762b Mon Sep 17 00:00:00 2001 From: LuQQiu Date: Fri, 23 Oct 2026 10:06:20 -0700 Subject: [PATCH 081/180] docs: add Enterprise distributed search reference page (#4625) Adds the Enterprise reference page at `docs/web/enterprise/distributed-search.mdx`, following the same arrangement as Enterprise architecture. The page describes distributed search and the embedded execution model, with links to shared search guides. Enterprise architecture links to it, and the official sidebar lists it immediately after Architecture in the existing Deployment group. Adds stable anchors for the RaBitQ and `approx_mode` sections linked by the Enterprise guide. Companion: https://github.com/lancedb/sophon/pull/8986 supplies the detailed Enterprise overlay at the same path. Merge this reference-page PR first so the overlay has an existing route to replace. Validation: - Combined-site assembly with both PR branches passed (309 files). - Mintlify build validation and link, anchor, and redirect checks passed. --- docs/web/docs.json | 1 + docs/web/enterprise/architecture.mdx | 3 ++ docs/web/enterprise/distributed-search.mdx | 33 ++++++++++++++++++++++ docs/web/indexing/vector-index.mdx | 2 +- docs/web/search/vector-search.mdx | 2 +- 5 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 docs/web/enterprise/distributed-search.mdx diff --git a/docs/web/docs.json b/docs/web/docs.json index 9c9468a3b..54203f1a0 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -350,6 +350,7 @@ "pages": [ "enterprise/index", "enterprise/architecture", + "enterprise/distributed-search", "enterprise/deployment/index", "deployment/storage", "deployment/monitoring", diff --git a/docs/web/enterprise/architecture.mdx b/docs/web/enterprise/architecture.mdx index c47dcbd2e..8f887c142 100644 --- a/docs/web/enterprise/architecture.mdx +++ b/docs/web/enterprise/architecture.mdx @@ -18,3 +18,6 @@ run on machines that can be replaced without any of them owning the data. [Architecture](/architecture) covers this alongside the embedded form, which is the comparison most readers want first. + +See [Distributed search](/enterprise/distributed-search) for how Enterprise +distributes index execution and table-data reads. diff --git a/docs/web/enterprise/distributed-search.mdx b/docs/web/enterprise/distributed-search.mdx new file mode 100644 index 000000000..ebac960ba --- /dev/null +++ b/docs/web/enterprise/distributed-search.mdx @@ -0,0 +1,33 @@ +--- +title: "Distributed search" +sidebarTitle: "Distributed search" +description: "How LanceDB Enterprise distributes index execution and table-data reads." +icon: "network-wired" +availability: + oss: unavailable + enterprise: available + summary: >- + LanceDB Enterprise distributes index execution and table-data reads across + plan executors. Embedded LanceDB executes searches in the application process. +--- + +Distributed search spreads index execution, table-data reads, and caching across +multiple serving machines in LanceDB Enterprise. Query nodes plan queries and +combine results. Plan executors cache index structures and table data and execute +the remote work. See [Enterprise architecture](/enterprise/architecture). + +## Embedded search {#embedded-search} + +LanceDB OSS runs inside your application process. It searches indexes and reads +table data using that process's resources, including its index cache. Reading a +table from object storage does not by itself distribute query execution across +machines. + +## Search interfaces {#search-interfaces} + +The shared search guides describe the query APIs and index settings: + +- [Vector search](/search/vector-search) and [vector indexes](/indexing/vector-index). +- [Full-text search](/search/full-text-search) and [FTS indexes](/indexing/fts-index). +- [Filtering](/search/filtering) and [scalar indexes](/indexing/scalar-index). +- [Query plans](/search/explain) for inspecting execution and runtime measurements. diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 2742a992f..b26e0c295 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -384,7 +384,7 @@ The inner workings of RaBitQ quantization are rather mathematically dense. It ge applying a uniformly random, approximately distance-preserving orthogonal transformation of the vertices of the $d$-dimensional hypercube, where $d$ is the dimensionality of the dataset. We defer the details, and an elegant theoretical error bound, to [the original paper.](https://arxiv.org/pdf/2405.12497) -##### Using RaBitQ +##### Using RaBitQ {#using-rabitq} Use RaBitQ quantization by selecting quantized index types ending in the suffix `RQ`. For example, call `create_index` with `index_type="IVF_RQ"`. Note that when using `IVF_RQ`, the dimension of the dataset must be a multiple of `8`. diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index 3519df553..cc6ae5421 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -235,7 +235,7 @@ The table below summarizes the behavior of `_distance` in search results based o See [vector indexes](/indexing/vector-index) for index configuration. The following sections cover query-time settings. -### Tuning `approx_mode` +### Tuning `approx_mode` {#tuning-approx-mode} Use `approx_mode` when you want to adjust the speed/recall trade-off for approximate vector search at query time. This setting currently applies only to RQ-quantized indexes, such as `IVF_RQ`; other index types ignore it. From 5a79c7d22da9f9729d27adc7e9d0b166767bbd4e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 24 Oct 2026 01:52:45 +0800 Subject: [PATCH 082/180] ci: run aarch64 Windows tests on main only (#4637) Run the aarch64 Windows build/test cycle only on pushes to main so PRs wait for a single Windows platform (x86_64). Main keeps the same native aarch64 coverage as before. GitHub evaluates job-level `if` before the matrix strategy is applied, so the aarch64 target is split into its own `windows-arm` job instead of being filtered inside the existing matrix. The job keeps the historical check name. --- .github/workflows/rust.yml | 43 ++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index cbfefc83d..930ae67e2 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -245,12 +245,6 @@ jobs: include: - target: x86_64-pc-windows-msvc runner: windows-2022 - # windows-11-arm is a standard runner, so it is free on public repos. - # Running natively lets the aarch64 tests actually execute -- this - # job used to cross-compile them and then skip the test step, paying - # full codegen and link cost for a compile check. - - target: aarch64-pc-windows-msvc - runner: windows-11-arm runs-on: ${{ matrix.runner }} defaults: run: @@ -279,6 +273,43 @@ jobs: # dependency graph a second time. cargo test --profile ci --features aws,remote --locked --target ${{ matrix.target }} + # Run the aarch64 Windows tests only on main so PRs wait for a single + # Windows platform. windows-11-arm is a standard runner, so it is free on + # public repos. Running natively lets the aarch64 tests actually execute -- + # this job used to cross-compile them and then skip the test step, paying + # full codegen and link cost for a compile check. + windows-arm: + # Keep the historical name so the check shows up as before on main. + name: windows (aarch64-pc-windows-msvc, windows-11-arm) + if: github.ref == 'refs/heads/main' + runs-on: windows-11-arm + defaults: + run: + working-directory: rust/lancedb + steps: + - uses: actions/checkout@v6 + - name: Set target + run: rustup target add aarch64-pc-windows-msvc + - uses: Swatinem/rust-cache@v2 + with: + # Restore everywhere, but only save from main. Per-PR saves are + # unreadable outside their own branch anyway, since GitHub scopes + # caches to the creating ref. + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Install Protoc v21.12 + run: choco install --no-progress protoc + - name: Build + run: | + $env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT + cargo build --profile ci --features aws,remote --tests --locked --target aarch64-pc-windows-msvc + - name: Run tests + run: | + $env:VCPKG_ROOT = $env:VCPKG_INSTALLATION_ROOT + # `--target` has to match the build step above. Without it cargo uses + # target/ci/ rather than target//ci/ and rebuilds the entire + # dependency graph a second time. + cargo test --profile ci --features aws,remote --locked --target aarch64-pc-windows-msvc + msrv: # Check the minimum supported Rust version name: MSRV Check - Rust v${{ matrix.msrv }} From 702389654e11d1af5cd120d64866f028f41d6b90 Mon Sep 17 00:00:00 2001 From: KarthikS Date: Fri, 23 Oct 2026 15:27:32 -0400 Subject: [PATCH 083/180] fix(python): align pylance extra and preview install indexes (#4556) Fixes #4248. The preview index still contains pylance 1.0.0b6. uv's default first-index resolution can select it, or backtrack to an old LanceDB release when installing the extra. Meanwhile, the extra still permits pylance 5 even though current main bundles Lance 14. Raise the optional dependency to `pylance>=14.0.0b12`, the version already pinned in the test extra, and keep the lockfile metadata consistent. Document both Fury indexes and uv's `unsafe-best-match` strategy in the Python README and the source-owned quickstart (`docs/web/quickstart.mdx`). Explain the index trust requirement and recommend installing the extra to enforce the version floor. Add CI checks that reject older Lance majors and ensure the pylance and tests extras remain compatible. Run these checks when either dependency manifest changes, so a future Lance major bump cannot silently leave the Python minimum behind. ### Validation - Recreated the reported install on Ubuntu 26.04 / CPython 3.12.15 with uv 0.12.23: `lancedb==0.40.0b5` plus the old index selects `pylance==1.0.0b6`. Reproduced both the missing `blob_array` import and the unexpected `blob_handling` scanner argument using a real blob table. - Resolved the modified `python/pyproject.toml` with the pylance extra against both indexes: selects `pylance==14.0.0b18`, matching the current Rust pin. - Ran both documented pip and uv installations in isolated environments: `lancedb==0.41.0b7`, `pylance==14.0.0b18`; blob-array construction and a blob-bytes round trip through `to_pandas(blob_mode="bytes")` pass. Both package dependency checks pass. - New regression fails on the original dependency bound (27 rejected-version cases incorrectly accepted), then passes with the fix. Full CI-script suite: 3 tests pass. - `uv lock --check` with both indexes passes; focused Ruff checks pass; `git diff --check` passes. - Repository-wide Ruff reports 49 existing errors in untouched `docs/web-tests` files. Unrelated formatting changes were discarded. Runtime smoke checks used released native wheels; source dependency resolution was tested directly from the modified pyproject. No Rust or Python runtime code changes. --------- Co-authored-by: Xuanwo --- .../lancedb-update-lance-dependency/SKILL.md | 27 +++++++++++ .github/workflows/ci-scripts.yml | 6 +++ ci/tests/test_python_dependencies.py | 47 +++++++++++++++++++ docs/web/quickstart.mdx | 27 +++++++++++ python/README.md | 27 +++++++++++ python/pyproject.toml | 5 +- python/uv.lock | 18 +++---- 7 files changed, 146 insertions(+), 11 deletions(-) create mode 100644 ci/tests/test_python_dependencies.py diff --git a/.agents/skills/lancedb-update-lance-dependency/SKILL.md b/.agents/skills/lancedb-update-lance-dependency/SKILL.md index e97fae7ac..3cba2ae75 100644 --- a/.agents/skills/lancedb-update-lance-dependency/SKILL.md +++ b/.agents/skills/lancedb-update-lance-dependency/SKILL.md @@ -48,6 +48,23 @@ Inputs can be a version (`7.2.0-beta.1`), a tag (`v7.2.0-beta.1`), a tag ref (`r This updates the Rust workspace Lance dependencies through `ci/set_lance_version.py`, updates `java/pom.xml`, refreshes Cargo metadata, and prints JSON metadata containing `branch_name`, `commit_message`, and `pr_title`. + Also synchronize the Python requirements in `python/pyproject.toml`: set the + `tests` extra's exact `pylance` pin to the matching published Python release, + and update the `pylance` extra's minimum when needed to exclude older bundled + Lance majors. The minimum must still accept the test pin. Python prerelease + spelling differs from Rust (for example, `15.0.0-beta.1` becomes `15.0.0b1`). + Confirm the matching Python release is published before changing the pin. + + Refresh and check `python/uv.lock` from the repository root: + + ```bash + uv lock --project python --index https://pypi.fury.io/lancedb/ --index https://pypi.fury.io/lance-format/ --index-strategy unsafe-best-match + uv lock --project python --check --index https://pypi.fury.io/lancedb/ --index https://pypi.fury.io/lance-format/ --index-strategy unsafe-best-match + ``` + + This strategy considers versions across indexes; use it only with trusted + indexes. Commit the Python requirements and lockfile together with the bump. + 5. Run validation: ```bash @@ -57,6 +74,16 @@ Inputs can be a version (`7.2.0-beta.1`), a tag (`v7.2.0-beta.1`), a tag ref (`r Fix real diagnostics and rerun clippy until it succeeds. Do not skip warnings. + Run the Python dependency guards with Python 3.11+ and `packaging` installed: + + ```bash + python3 -m unittest discover -s ci/tests -p test_python_dependencies.py -v + ``` + + These checks reject older Lance majors and ensure the `pylance` and `tests` + extras remain compatible. The full CI-script suite uses + `python3 -m unittest discover -s ci/tests -v`. + 6. Inspect `git status --short` and `git diff` to ensure only the Lance dependency update and required compatibility fixes are present. 7. If the task only asks to prepare local changes, stop here and report the changed files and validation result. diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml index f7f0dbb07..d45289c2d 100644 --- a/.github/workflows/ci-scripts.yml +++ b/.github/workflows/ci-scripts.yml @@ -5,6 +5,8 @@ on: branches: - main paths: + - Cargo.toml + - python/pyproject.toml - ci/check_cargo_lock.py - ci/check_sdist.py - ci/set_lance_version.py @@ -12,6 +14,8 @@ on: - .github/workflows/ci-scripts.yml pull_request: paths: + - Cargo.toml + - python/pyproject.toml - ci/check_cargo_lock.py - ci/check_sdist.py - ci/set_lance_version.py @@ -30,5 +34,7 @@ jobs: - uses: actions/setup-python@v6 with: python-version: "3.13" + - name: Install test dependencies + run: python -m pip install packaging - name: Run tests run: python -m unittest discover -s ci/tests -v diff --git a/ci/tests/test_python_dependencies.py b/ci/tests/test_python_dependencies.py new file mode 100644 index 000000000..97fb672c6 --- /dev/null +++ b/ci/tests/test_python_dependencies.py @@ -0,0 +1,47 @@ +import tomllib +import unittest +from pathlib import Path + +from packaging.requirements import Requirement +from packaging.version import Version + + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +class PythonDependenciesTest(unittest.TestCase): + def setUp(self): + with (REPO_ROOT / "python/pyproject.toml").open("rb") as f: + self.project = tomllib.load(f)["project"] + self.pylance = Requirement(self.project["optional-dependencies"]["pylance"][0]) + + def test_pylance_extra_excludes_older_lance_majors(self): + with (REPO_ROOT / "Cargo.toml").open("rb") as f: + lance = tomllib.load(f)["workspace"]["dependencies"]["lance"] + if "version" not in lance: + self.skipTest("Local Lance checkout has no version requirement") + major = Version(lance["version"].lstrip("=")).major + for older_major in range(major): + for suffix in (".0.0", ".0.0b6", ".999.999"): + version = f"{older_major}{suffix}" + with self.subTest(version=version): + self.assertFalse( + self.pylance.specifier.contains(version, prereleases=True), + f"The pylance extra must exclude Lance {version}; " + f"the bundled Lance is major {major}", + ) + + def test_pylance_extra_accepts_tested_version(self): + requirements = [ + Requirement(dep) for dep in self.project["optional-dependencies"]["tests"] + ] + tested = next(dep for dep in requirements if dep.name == "pylance") + pin = next(spec for spec in tested.specifier if spec.operator == "==") + self.assertTrue( + self.pylance.specifier.contains(pin.version, prereleases=True), + f"The tests and pylance extras must be installable together: {tested}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 788dd6585..3f466041d 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -58,6 +58,33 @@ uv add --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb ```
+If you also need the optional `lance` Python API, install the `pylance` extra and +include the Lance preview index: + + +```bash Python (pip) icon="terminal" +pip install --pre \ + --extra-index-url https://pypi.fury.io/lancedb/ \ + --extra-index-url https://pypi.fury.io/lance-format/ \ + "lancedb[pylance]" +``` + +```bash Python (uv) icon="terminal" +uv pip install --prerelease allow \ + --index https://pypi.fury.io/lancedb/ \ + --index https://pypi.fury.io/lance-format/ \ + --index-strategy unsafe-best-match \ + "lancedb[pylance]" +``` + + +The LanceDB preview index contains old `pylance` releases; current Lance previews +are published to the `lance-format` index. By default, uv only considers versions +from the first index containing a package, which can select an old `pylance` or +backtrack to an older LanceDB release. `unsafe-best-match` searches all configured +indexes, like pip; use it only with indexes you trust. Install the extra rather +than an unconstrained `pylance` so LanceDB's minimum supported version is enforced. + Pre-release builds receive the same level of testing as stable releases, but their availability is not guaranteed for more than 6 months after release. For real-world workloads, we recommend you use the latest stable release diff --git a/python/README.md b/python/README.md index f941c9e20..907f7c099 100644 --- a/python/README.md +++ b/python/README.md @@ -40,6 +40,33 @@ Stable releases are created about every 2 weeks. For the latest features and bug pip install --pre --extra-index-url https://pypi.fury.io/lancedb/ lancedb ``` +If you also need the optional `lance` Python API, install the `pylance` extra +and include the Lance preview index: + +```bash +pip install --pre \ + --extra-index-url https://pypi.fury.io/lancedb/ \ + --extra-index-url https://pypi.fury.io/lance-format/ \ + "lancedb[pylance]" +``` + +With uv, also select the best matching version across the indexes: + +```bash +uv pip install --prerelease allow \ + --index https://pypi.fury.io/lancedb/ \ + --index https://pypi.fury.io/lance-format/ \ + --index-strategy unsafe-best-match \ + "lancedb[pylance]" +``` + +The LanceDB preview index contains old `pylance` releases; current Lance previews +are published to the `lance-format` index. By default, uv only considers versions +from the first index containing a package, which can select an old `pylance` or +backtrack to an older LanceDB release. `unsafe-best-match` searches all configured +indexes, like pip; use it only with indexes you trust. Install the extra rather +than an unconstrained `pylance` so LanceDB's minimum supported version is enforced. + ### Threading in CPU-limited containers LanceDB uses separate pools for compute work and storage I/O. On a container with diff --git a/python/pyproject.toml b/python/pyproject.toml index ed54ae536..a0de6509c 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -45,7 +45,8 @@ repository = "https://github.com/lancedb/lancedb" [project.optional-dependencies] pylance = [ - "pylance>=5.0.0b5", + # Keep the minimum in the bundled Lance major and compatible with tests below. + "pylance>=15.0.0b1", ] # A library only needs the OpenTelemetry API; the application supplies and # configures the SDK (the actual exporter/reader). See @@ -63,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow<25", "pyarrow-stubs>=16.0", - "pylance==14.0.0b12", + "pylance==15.0.0b1", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index e808f5f9e..99bcb439c 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2006,8 +2006,8 @@ requires-dist = [ { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, - { name = "pylance", marker = "extra == 'pylance'", specifier = ">=5.0.0b5" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==14.0.0b12" }, + { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b1" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b1" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -3938,7 +3938,7 @@ crypto = [ [[package]] name = "pylance" -version = "14.0.0b12" +version = "15.0.0b1" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -3948,12 +3948,12 @@ dependencies = [ { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1Ixasc/pylance-14.0.0b12-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:84350a3c5c1eea3398f4c4fad7cfe85b831d831a5e43b5ca2a783dbdb0e11969" }, - { url = "https://pypi.fury.io/lance-format/-/ver_sCEkG/pylance-14.0.0b12-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:76b386c182a6a8e7b86fbef28f84d1dd39e4626ac8681a0cf36f40a45dd7cb87" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1vdT1C/pylance-14.0.0b12-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6aa548c7937fcdfa8f1943a2d59041a42f8b500199880dbb509c7195fa253381" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2fXu1V/pylance-14.0.0b12-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:79f82d6a6c50f37aab338470e3733436e6a27fbb5972d29fcf453ece56d3b3c6" }, - { url = "https://pypi.fury.io/lance-format/-/ver_24UavN/pylance-14.0.0b12-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:de0305999257002785f60169e6926896584d66f1da050bb5afd1d48c6e3d9bb9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_XNynX/pylance-14.0.0b12-cp310-abi3-win_amd64.whl", hash = "sha256:4d0cdb689e898ce71e8e434d00a3b97639cea8fb97da21f1c921543be363268f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_23L1Nd/pylance-15.0.0b1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:19605d3daca1224cc0db079054be5d4eec403dcf286bf4617430bfc259ab0a52" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1Ho3RK/pylance-15.0.0b1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be22b0b6f1e1d250ffaa82b449e982c817db33103c483d1005020285310623cf" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1QmyF0/pylance-15.0.0b1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5b2761d60b1b9db112058213f1f7b2de82b08cbe65888fab08b0a56e702482e" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1in2Ph/pylance-15.0.0b1-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:294a0fedae312ed32d1b66cddbf7e69770ec9b4c82a873af60c619ed88450718" }, + { url = "https://pypi.fury.io/lance-format/-/ver_21xpLH/pylance-15.0.0b1-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ff20a16703d4d3f3bc675b25ce1871ba1d54137929dc46305bffdd07f7b35a6b" }, + { url = "https://pypi.fury.io/lance-format/-/ver_AAGzF/pylance-15.0.0b1-cp310-abi3-win_amd64.whl", hash = "sha256:3b134e24a5becfc940ca134cf78aa3bae8b80ec40f8927a1b856273ab76213f2" }, ] [[package]] From e74a7c15b5f322f8ac15b96bdfc391616518d711 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 24 Oct 2026 03:47:16 +0800 Subject: [PATCH 084/180] fix: bump tokio to address RUSTSEC-2026-0386 (#4642) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upgrade the locked Tokio version from 1.53.1 to 1.53.3 to fix [RUSTSEC-2026-0386](https://rustsec.org/advisories/RUSTSEC-2026-0386) and restore the Rust workflow's `deny` job. The diff changes only Tokio's version and checksum. Validation: - `cargo deny check advisories` — passed. - `cargo deny check advisories bans licenses sources` — passed with the repository's `deny.toml`. - `cargo check --quiet -p lancedb` — passed (dead-code warnings). - PR `deny` job — [passed](https://github.com/lancedb/lancedb/actions/runs/40000920646/job/120576455117). --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8bad6ca92..fac89c4da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10446,9 +10446,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.53.1" +version = "1.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" dependencies = [ "bytes", "libc", From 3321860e9fc7248d9c97c7513bc0ac0d258738a0 Mon Sep 17 00:00:00 2001 From: LeonSGP <154585401+LeonSGP43@users.noreply.github.com> Date: Sat, 24 Oct 2026 04:22:30 +0800 Subject: [PATCH 085/180] fix(python): preserve Arrow map scalars in updates (#4448) Arrow map scalars returned by a table query cannot currently be passed back to `update`: the generic Arrow scalar conversion turns them into a list of tuples, which the SQL literal encoder cannot handle. Empty map scalars become an untyped SQL list and also fail to update a map column. Add a dedicated `MapScalar` conversion that renders its keys and values as a SQL map while preserving the existing null conversion. The regression tests exercise real synchronous and asynchronous table updates, quoted keys, nullable values, empty typed maps, and nested maps. Validation: the complete documented unit-test scope passed locally (1,515 passed, 37 skipped; unchanged baseline: 1,507 passed, 37 skipped). Full doctests passed (71 passed, 6 skipped), and repository-wide Python formatting/lint, Rust formatting/clippy, and Python 3.13 type checking passed. The locally built native wheel also passed all eight regression cases in a separate Python 3.13 environment. Full Linux/S3 integration and all platform matrices remain for CI. The SQL map constructor's existing backend constraints still apply: duplicate keys are rejected, and a nested map containing both nonempty and empty inner maps can fail SQL type unification. This change does not claim arbitrary Arrow map roundtrip support. AI assistance: implementation and local verification used Codex with gpt-6.1-sol agents; the diff and evidence were reviewed before submission. --------- Co-authored-by: Xuanwo --- python/python/lancedb/util.py | 9 ++++++ python/python/tests/test_table.py | 51 +++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index a043f0c8d..36536f499 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -452,6 +452,15 @@ def _(value: pa.Scalar): return value_to_sql(value.as_py()) +@value_to_sql.register(pa.MapScalar) +def _(value: pa.MapScalar): + if not value.is_valid: + return value_to_sql(None) + keys = value_to_sql(list(value.values.field(0))) + values = value_to_sql(list(value.values.field(1))) + return f"map({keys}, {values})" + + @value_to_sql.register(np.ndarray) def _(value: np.ndarray): return value_to_sql(value.tolist()) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index b55abfa7e..18d3c16db 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2724,6 +2724,57 @@ def test_update_with_arrow_scalar(mem_db: DBConnection): assert table.to_arrow()["vector"].to_pylist() == [[1.0, 2.0, 3.0, 4.0]] +@pytest.mark.asyncio +@pytest.mark.parametrize("async_api", [False, True]) +@pytest.mark.parametrize("entries", [[("o'brien", 4), ("nil", None)], [], None]) +async def test_update_map_arrow_scalar(tmp_path, async_api, entries): + map_type = pa.map_(pa.string(), pa.int64()) + data = pa.table( + { + "id": [1, 2], + "attrs": pa.array([[("original", 1)], entries], type=map_type), + } + ) + if async_api: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("maps", data) + source = await table.query().where("id = 2").to_arrow() + result = await table.update({"attrs": source["attrs"][0]}, where="id = 1") + actual = await table.query().to_arrow() + else: + db = lancedb.connect(tmp_path) + table = db.create_table("maps", data) + source = table.search().where("id = 2").to_arrow() + result = table.update(values={"attrs": source["attrs"][0]}, where="id = 1") + actual = table.to_arrow() + assert result.rows_updated == 1 + assert actual.schema.field("attrs").type == map_type + assert actual.sort_by("id")["attrs"].to_pylist() == [entries, entries] + + +@pytest.mark.parametrize( + "map_type, entries", + [ + (pa.map_(pa.int64(), pa.string()), []), + ( + pa.map_(pa.string(), pa.map_(pa.string(), pa.int64())), + [("outer", [("inner", 3)]), ("null", None)], + ), + ], +) +def test_update_typed_map_arrow_scalar(mem_db: DBConnection, map_type, entries): + table = mem_db.create_table( + "maps", + pa.table({"id": [1, 2], "attrs": pa.array([None, entries], type=map_type)}), + ) + scalar = table.search().where("id = 2").to_arrow()["attrs"][0] + result = table.update(values={"attrs": scalar}, where="id = 1") + actual = table.to_arrow().sort_by("id")["attrs"] + assert result.rows_updated == 1 + assert actual.type == map_type + assert actual.to_pylist() == [entries, entries] + + @pytest.mark.parametrize("use_arrow_scalar", [False, True]) @pytest.mark.parametrize( "decimal_type, value", From 9da4658d57cbdcd037827f12effd9a4dc869a095 Mon Sep 17 00:00:00 2001 From: Joaquin Hui Gomez <132194176+joaquinhuigomez@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:10:07 +0100 Subject: [PATCH 086/180] fix(python): accept with_row_id in take_offsets/take_row_ids on every Table implementation (#4374) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Table.take_offsets` and `Table.take_row_ids` declare a keyword-only `with_row_id: bool = False`, but none of the three implementations accept it — `LanceTable`, `AsyncTable` and `RemoteTable` all raise `TypeError: ... got an unexpected keyword argument 'with_row_id'` on the documented call. The builders they return already support it (`LanceTakeQueryBuilder.with_row_id()` / `AsyncTakeQuery.with_row_id()`), so this is a signature that never reached the implementations. The base docstrings also don't mention the parameter and still say `take_offsets` returns a `pa.RecordBatch` (it returns a `LanceTakeQueryBuilder`), so those are corrected too. Each implementation now accepts the kwarg and applies `.with_row_id()` to the builder it returns. Tests: sync and async assert `_rowid` appears in the result columns; the remote test uses the suite's request-capturing fixture and asserts `with_row_id: true` reaches the wire (and is absent by default). All three fail on `main` with the `TypeError`. ruff format/check clean. A related mismatch I left alone: the deprecated `LanceTable.create_scalar_index`/`create_fts_index` also drop a `wait_timeout` the base declares — deprecated since 0.25, so not worth touching here. Co-authored-by: Xuanwo --- python/python/lancedb/remote/table.py | 18 +++++++-- python/python/lancedb/table.py | 58 ++++++++++++++++++++------- python/python/tests/test_query.py | 27 +++++++++++++ python/python/tests/test_remote_db.py | 17 ++++++++ 4 files changed, 102 insertions(+), 18 deletions(-) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 86e8fb8a0..0744410b3 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1154,11 +1154,21 @@ class RemoteTable(Table): """ return LOOP.run(self._table.uri()) - def take_offsets(self, offsets: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + def take_offsets( + self, offsets: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + if with_row_id: + builder.with_row_id() + return builder - def take_row_ids(self, row_ids: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + def take_row_ids( + self, row_ids: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + if with_row_id: + builder.with_row_id() + return builder def uses_v2_manifest_paths(self) -> bool: return LOOP.run(self._table.uses_v2_manifest_paths()) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5eea55760..b9557f219 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2103,11 +2103,14 @@ class Table(ABC): ---------- offsets: list[int] The offsets to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- - pa.RecordBatch - A record batch containing the rows at the given offsets. + LanceTakeQueryBuilder + A query builder that can be executed to get the rows at the given + offsets. """ def __getitems__(self, offsets: list[int]) -> pa.RecordBatch: @@ -2188,11 +2191,13 @@ class Table(ABC): ---------- row_ids: list[int] The row ids to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- - AsyncTakeQuery - A query object that can be executed to get the rows. + LanceTakeQueryBuilder + A query builder that can be executed to get the rows. """ @abstractmethod @@ -3182,11 +3187,21 @@ class LanceTable(Table): """Get the current version of the table""" return LOOP.run(self._table.version()) - def take_offsets(self, offsets: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + def take_offsets( + self, offsets: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + if with_row_id: + builder.with_row_id() + return builder - def take_row_ids(self, row_ids: list[int]) -> LanceTakeQueryBuilder: - return LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + def take_row_ids( + self, row_ids: list[int], *, with_row_id: bool = False + ) -> LanceTakeQueryBuilder: + builder = LanceTakeQueryBuilder(self._table.take_row_ids(row_ids)) + if with_row_id: + builder.with_row_id() + return builder def blob_columns(self) -> list[str]: return LOOP.run(self._table.blob_columns()) @@ -7325,7 +7340,9 @@ class AsyncTable: """ await self._inner.restore(version) - def take_offsets(self, offsets: list[int]) -> AsyncTakeQuery: + def take_offsets( + self, offsets: list[int], *, with_row_id: bool = False + ) -> AsyncTakeQuery: """ Take a list of offsets from the table. @@ -7343,15 +7360,23 @@ class AsyncTable: ---------- offsets: list[int] The offsets to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- - pa.RecordBatch - A record batch containing the rows at the given offsets. + AsyncTakeQuery + A query object that can be executed to get the rows at the given + offsets. """ - return AsyncTakeQuery(self._inner.take_offsets(offsets), self) + query = AsyncTakeQuery(self._inner.take_offsets(offsets), self) + if with_row_id: + query.with_row_id() + return query - def take_row_ids(self, row_ids: list[int]) -> AsyncTakeQuery: + def take_row_ids( + self, row_ids: list[int], *, with_row_id: bool = False + ) -> AsyncTakeQuery: """ Take a list of row ids from the table. @@ -7372,13 +7397,18 @@ class AsyncTable: ---------- row_ids: list[int] The row ids to take. + with_row_id: bool, default False + If True, include the "_rowid" column in the results. Returns ------- AsyncTakeQuery A query object that can be executed to get the rows. """ - return AsyncTakeQuery(self._inner.take_row_ids(row_ids), self) + query = AsyncTakeQuery(self._inner.take_row_ids(row_ids), self) + if with_row_id: + query.with_row_id() + return query async def blob_columns(self) -> list[str]: return await self._inner.blob_columns() diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 58ea7deb5..cef985aa6 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -2324,6 +2324,33 @@ def test_take_queries(tmp_path): ] +def test_take_queries_with_row_id(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", pa.table({"idx": range(100)})) + + by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow() + assert "_rowid" in by_row_id.column_names + by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() + assert "_rowid" in by_offset.column_names + + # The column is opt-in and must stay out of the default projection. + assert "_rowid" not in table.take_row_ids([5, 2, 17]).to_arrow().column_names + + +@pytest.mark.asyncio +async def test_take_queries_with_row_id_async(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", pa.table({"idx": range(100)})) + + by_row_id = await table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow() + assert "_rowid" in by_row_id.column_names + by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() + assert "_rowid" in by_offset.column_names + + default = await table.take_row_ids([5, 2, 17]).to_arrow() + assert "_rowid" not in default.column_names + + def test_take_queries_to_batches(tmp_path): # Regression test for the sync take-query path: `to_batches` previously # raised ``AttributeError: 'AsyncTakeQuery' object has no attribute diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a45e1aaef..9655f5807 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2225,6 +2225,23 @@ def test_head(): assert data == pa.table({"id": [1, 2, 3]}) +def test_remote_take_row_ids_with_row_id(): + bodies = [] + + def handler(body): + bodies.append(body) + return pa.table({"id": [1, 2], "_rowid": pa.array([0, 1], pa.uint64())}) + + with query_test_table(handler) as table: + result = table.take_row_ids([0, 1], with_row_id=True).to_arrow() + assert "_rowid" in result.column_names + assert bodies[-1]["with_row_id"] is True + + with query_test_table(handler) as table: + table.take_row_ids([0, 1]).to_arrow() + assert "with_row_id" not in bodies[-1] + + def test_query_sync_minimal(): def handler(body): assert body == { From 27b65064d0166feabe1c307eba07f66ca2601857 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:37:07 -0700 Subject: [PATCH 087/180] fix(python): support custom blob thresholds without pylance (#4634) --- python/python/lancedb/schema.py | 62 ++++++++++------ python/python/tests/test_blob.py | 37 ++++++++++ python/python/tests/test_table.py | 118 ++++++++++++++++++++++++++++++ 3 files changed, 193 insertions(+), 24 deletions(-) diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py index 5edda5610..8bec17058 100644 --- a/python/python/lancedb/schema.py +++ b/python/python/lancedb/schema.py @@ -4,6 +4,7 @@ """Schema helpers for Lance blob columns.""" +import ctypes import importlib from typing import TYPE_CHECKING, Optional @@ -16,6 +17,7 @@ if TYPE_CHECKING: _BLOB_EXTENSION_NAME = "lance.blob.v2" _BLOB_V1_KEY = "lance-encoding:blob" _ARROW_EXT_NAME_KEY = "ARROW:extension:name" +_MAX_RUST_USIZE = ctypes.c_size_t(-1).value _BLOB_V2_STORAGE_TYPE = pa.struct( [ pa.field("data", pa.large_binary(), nullable=True), @@ -209,32 +211,44 @@ def blob( Maximum size in bytes of a single packed blob sidecar file before a new one is started. Must be positive. - The thresholds are forwarded to ``lance.blob_field``, which validates - them and stores them as field metadata, so pylance is required whenever - any threshold is set. When all thresholds are omitted the behavior is - unchanged. + Thresholds are validated and stored as Arrow field metadata, with the + same format as ``lance.blob_field``. They do not require pylance. """ - if ( - inline_size_threshold is None - and dedicated_size_threshold is None - and pack_file_size_threshold is None + metadata = {} + for threshold, value, allow_zero, key in ( + ( + "inline_size_threshold", + inline_size_threshold, + True, + "lance-encoding:blob-inline-size-threshold", + ), + ( + "dedicated_size_threshold", + dedicated_size_threshold, + False, + "lance-encoding:blob-dedicated-size-threshold", + ), + ( + "pack_file_size_threshold", + pack_file_size_threshold, + False, + "lance-encoding:blob-pack-file-size-threshold", + ), ): - blob_type = _resolve_blob_type() - return pa.field(name, blob_type(), nullable=nullable) - try: - lance = importlib.import_module("lance") - except ModuleNotFoundError as err: - raise ValueError( - "Setting blob tier thresholds requires pylance to be installed" - ) from err - _resolve_blob_type() - return lance.blob_field( - name, - nullable=nullable, - inline_size_threshold=inline_size_threshold, - dedicated_size_threshold=dedicated_size_threshold, - pack_file_size_threshold=pack_file_size_threshold, - ) + if value is None: + continue + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"{threshold} must be an int, got {type(value).__name__}") + if value < 0 or (value == 0 and not allow_zero): + bound = "non-negative" if allow_zero else "positive" + raise ValueError(f"{threshold} must be {bound}") + if value > _MAX_RUST_USIZE: + raise OverflowError(f"{threshold} must fit in a Rust usize") + metadata[key] = str(value) + + blob_type = _resolve_blob_type() + field = pa.field(name, blob_type(), nullable=nullable) + return field.with_metadata(metadata) if metadata else field def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType: diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index ec1b8b27e..c2dc2a265 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import ctypes import io import subprocess import sys @@ -14,6 +15,7 @@ import pytest from lance.blob import Blob, BlobType as LanceBlobType import lancedb +from lancedb import schema as schema_module from lancedb._blob import ( _set_blob_column, blob_v2_projection_sources, @@ -139,6 +141,41 @@ def test_blob_without_thresholds_has_no_threshold_metadata(): assert not any(b"threshold" in key for key in metadata) +@pytest.mark.parametrize("nullable", [False, True]) +@pytest.mark.parametrize( + "thresholds", + [ + {}, + {"inline_size_threshold": 0}, + {"inline_size_threshold": 8192}, + {"dedicated_size_threshold": 1 << 20}, + {"pack_file_size_threshold": 1 << 26}, + { + "inline_size_threshold": 8192, + "dedicated_size_threshold": 1 << 20, + "pack_file_size_threshold": 1 << 26, + }, + { + "inline_size_threshold": ctypes.c_size_t(-1).value, + "dedicated_size_threshold": ctypes.c_size_t(-1).value, + "pack_file_size_threshold": ctypes.c_size_t(-1).value, + }, + ], +) +def test_blob_thresholds_match_pylance(monkeypatch, nullable, thresholds): + expected = lance.blob_field("payload", nullable=nullable, **thresholds) + actual = lancedb.blob("payload", nullable=nullable, **thresholds) + assert type(actual.type) is LanceBlobType + assert actual.equals(expected, check_metadata=True) + + # Both extension classes must encode the same Arrow field on the wire. + monkeypatch.setattr( + schema_module, "_resolve_blob_type", lambda: schema_module._FallbackBlobType + ) + fallback = lancedb.blob("payload", nullable=nullable, **thresholds) + assert pa.schema([fallback]).serialize() == pa.schema([expected]).serialize() + + def test_blob_thresholds_are_validated(): with pytest.raises(ValueError, match="inline_size_threshold must be non-negative"): lancedb.blob("payload", inline_size_threshold=-1) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 18d3c16db..6ccba606f 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -59,6 +59,124 @@ def _blob_v2_table(db: DBConnection, name: str): return table +@pytest.mark.parametrize( + "threshold", + [ + "inline_size_threshold", + "dedicated_size_threshold", + "pack_file_size_threshold", + ], +) +@pytest.mark.parametrize( + "value,error", + [ + (-1, ValueError), + (True, TypeError), + (False, TypeError), + (1.5, TypeError), + ("8192", TypeError), + (ctypes.c_size_t(-1).value + 1, OverflowError), + ], +) +def test_blob_thresholds_reject_invalid_values(threshold, value, error): + # Also runs in CI with pylance actually uninstalled. + with pytest.raises(error, match=f"{threshold} must"): + lancedb.blob("blob", **{threshold: value}) + + +@pytest.mark.parametrize( + "threshold", ["dedicated_size_threshold", "pack_file_size_threshold"] +) +def test_blob_thresholds_reject_zero_for_positive_thresholds(threshold): + with pytest.raises(ValueError, match=f"{threshold} must be positive"): + lancedb.blob("blob", **{threshold: 0}) + + +def test_blob_thresholds_accept_integer_boundaries(): + maximum = ctypes.c_size_t(-1).value + field = lancedb.blob( + "blob", + nullable=False, + inline_size_threshold=0, + dedicated_size_threshold=maximum, + pack_file_size_threshold=maximum, + ) + assert not field.nullable + assert field.metadata == { + b"lance-encoding:blob-inline-size-threshold": b"0", + b"lance-encoding:blob-dedicated-size-threshold": str(maximum).encode(), + b"lance-encoding:blob-pack-file-size-threshold": str(maximum).encode(), + } + + +def test_blob_thresholds_control_writes_after_reopen(tmp_path): + # Keep this in test_table.py: CI runs it without pylance or pandas installed. + field = lancedb.blob( + "blob", + inline_size_threshold=4, + dedicated_size_threshold=12, + pack_file_size_threshold=8, + ) + metadata = { + b"lance-encoding:blob-inline-size-threshold": b"4", + b"lance-encoding:blob-dedicated-size-threshold": b"12", + b"lance-encoding:blob-pack-file-size-threshold": b"8", + } + assert field.metadata == metadata + schema = pa.schema([pa.field("id", pa.int64()), field]) + db = lancedb.connect(tmp_path) + table = db.create_table("blobs", schema=schema) + # Every payload fits in the default inline tier; custom thresholds must + # instead send the larger values to packed and dedicated storage. + rows = [ + {"id": 0, "blob": b"a" * 2}, + {"id": 1, "blob": b"b" * 8}, + {"id": 2, "blob": b"c" * 16}, + {"id": 3, "blob": b"d" * 8}, + ] + + def check_writes(table, expected): + assert table.schema.field("blob").metadata.items() >= metadata.items() + hits = table.search().with_row_id(True).limit(10).to_arrow() + actual = {row["id"]: row for row in hits.to_pylist()} + assert actual.keys() == {row["id"] for row in expected} + for row in expected: + size = len(row["blob"]) + descriptor = actual[row["id"]]["blob"] + assert descriptor["size"] == size + assert descriptor["kind"] == (2 if size > 12 else 1 if size > 4 else 0) + row_ids = [actual[row["id"]]["_rowid"] for row in expected] + assert table.fetch_blobs("blob", row_ids).to_pylist() == [ + row["blob"] for row in expected + ] + # Two packed values reach the configured sidecar limit independently. + packed = [ + actual[row["id"]]["blob"] for row in expected if len(row["blob"]) == 8 + ] + assert len({desc["blob_id"] for desc in packed}) == len(packed) + + table.add(rows) + check_writes(table, rows) + table = lancedb.connect(tmp_path).open_table("blobs") + check_writes(table, rows) + updates = [ + {"id": 0, "blob": b"e" * 16}, + {"id": 1, "blob": b"f" * 2}, + {"id": 2, "blob": b"g" * 8}, + {"id": 3, "blob": b"h" * 8}, + {"id": 4, "blob": b"i" * 16}, + ] + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(updates) + ) + assert result.num_updated_rows == 4 + assert result.num_inserted_rows == 1 + check_writes(lancedb.connect(tmp_path).open_table("blobs"), updates) + + async def _blob_v2_table_async(db: AsyncConnection, name: str): schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("blob")]) table = await db.create_table(name, schema=schema) From 8cf115b081d6a4b48db13a11c8fcbde8deadb750 Mon Sep 17 00:00:00 2001 From: alexcastgonz <82875882+pcbeingused333@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:25:44 -0400 Subject: [PATCH 088/180] fix(python): replace the retired gpt-4-turbo-preview default in OpenaiReranker (#4613) OpenAI shuts down `gpt-4-turbo` and its snapshots on 2026-10-23 (https://developers.openai.com/api/docs/deprecations), so `OpenaiReranker` fails for every user who relies on the default `gpt-4-turbo-preview` after that date. This changes the default to `gpt-5.6-sol`, the replacement OpenAI names for `gpt-4-turbo` on that page, in the class, its docstring and the integration docs page. `_rerank` also stops sending `temperature=0`: the GPT-5 models only accept the default temperature, so keeping it would fail the new default on its first call. The reranker still asks for `json_object` output and the rest of the request is unchanged. The new test calls `_rerank` with a mocked client and checks that no `temperature` is sent. It fails on main and passes with the change. No request was made to OpenAI. This change was made with Claude Code. Co-authored-by: Xuanwo --- docs/web/integrations/reranking/openai.mdx | 2 +- python/python/lancedb/rerankers/openai.py | 5 ++--- python/python/tests/test_rerankers.py | 19 +++++++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/web/integrations/reranking/openai.mdx b/docs/web/integrations/reranking/openai.mdx index 6ceb8a030..71fe63117 100644 --- a/docs/web/integrations/reranking/openai.mdx +++ b/docs/web/integrations/reranking/openai.mdx @@ -26,7 +26,7 @@ credentials from environment variables or a secrets manager. ## Accepted Arguments {#accepted-arguments} | Argument | Type | Default | Description | | --- | --- | --- | --- | -| `model_name` | `str` | `"gpt-4-turbo-preview"` | The name of the reranker model to use.| +| `model_name` | `str` | `"gpt-5.6-sol"` | The name of the reranker model to use.| | `column` | `str` | `"text"` | The name of the column to use as input to the cross encoder model. | | `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". The type of score to return. If "relevance", will return only the `_relevance_score. If "all" is supported, will return relevance score along with the vector and/or fts scores depending on query type. | | `api_key` | `str` | `None` | The API key to use. If None, will use the OPENAI_API_KEY environment variable. diff --git a/python/python/lancedb/rerankers/openai.py b/python/python/lancedb/rerankers/openai.py index da0394d1c..49b067f79 100644 --- a/python/python/lancedb/rerankers/openai.py +++ b/python/python/lancedb/rerankers/openai.py @@ -21,7 +21,7 @@ class OpenaiReranker(Reranker): Parameters ---------- - model_name : str, default "gpt-4-turbo-preview" + model_name : str, default "gpt-5.6-sol" The name of the cross encoder model to use. column : str, default "text" The name of the column to use as input to the cross encoder model. @@ -33,7 +33,7 @@ class OpenaiReranker(Reranker): def __init__( self, - model_name: str = "gpt-4-turbo-preview", + model_name: str = "gpt-5.6-sol", column: str = "text", return_score="relevance", api_key: Optional[str] = None, @@ -54,7 +54,6 @@ class OpenaiReranker(Reranker): response = self._client.chat.completions.create( model=self.model_name, response_format={"type": "json_object"}, - temperature=0, messages=[ { "role": "system", diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index 743669367..dd6cb4ab5 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import os +from unittest.mock import MagicMock import random import lancedb @@ -547,6 +548,24 @@ def test_openai_reranker(tmp_path): _run_test_reranker(reranker, table, "single player experience", None, schema) +def test_openai_reranker_does_not_send_temperature(): + reranker = OpenaiReranker(api_key="test-key") + create = MagicMock() + create.return_value.choices = [ + MagicMock( + message=MagicMock( + content='{"documents": [{"content": "a", "relevance_score": 0.5}]}' + ) + ) + ] + reranker.__dict__["_client"] = MagicMock() + reranker.__dict__["_client"].chat.completions.create = create + + reranker._rerank(pa.table({"text": ["a"]}), "query") + + assert "temperature" not in create.call_args.kwargs + + @pytest.mark.skipif( os.environ.get("JINA_API_KEY") is None, reason="JINA_API_KEY not set" ) From 0dd78656b966233569d2f44a2d8833dffa9003e1 Mon Sep 17 00:00:00 2001 From: Kerman Lau <107780822+WitBlue6@users.noreply.github.com> Date: Sat, 24 Oct 2026 07:13:09 +0800 Subject: [PATCH 089/180] fix(python): honor explicit OpenAI reranker API keys (#4515) Fixes #4514 ## Summary Honor an explicitly supplied `OpenaiReranker(api_key=...)` before falling back to `OPENAI_API_KEY`, matching the constructor documentation. Previously the environment key always won when both were set, so an instance configured for a different account still used the process-wide account. ## Tests Added four cases using real OpenAI client construction without sending requests: explicit/environment conflict, explicit key alone, environment fallback, and missing credentials. The conflict case fails before the change; all four pass afterward. Clients are closed after each assertion. - Targeted source-module tests: 4 passed. - Ruff check and format check: passed for both changed files. - Full native source build was attempted but failed because the environment has no Rust toolchain; bootstrap then attempted a cache path outside the writable workspace. The targeted tests load the current Python reranker module against installed dependencies and the released LanceDB package; no database/native behavior is exercised. Full native/integration suite not run. This change and its tests were prepared with an AI coding agent. The diff was reviewed and the failure/pass behavior verified locally. Co-authored-by: Xuanwo --- python/python/lancedb/rerankers/openai.py | 2 +- .../tests/test_openai_reranker_credentials.py | 38 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 python/python/tests/test_openai_reranker_credentials.py diff --git a/python/python/lancedb/rerankers/openai.py b/python/python/lancedb/rerankers/openai.py index 49b067f79..75efbbfc7 100644 --- a/python/python/lancedb/rerankers/openai.py +++ b/python/python/lancedb/rerankers/openai.py @@ -131,4 +131,4 @@ class OpenaiReranker(Reranker): "OPENAI_API_KEY not set. Either set it in your environment or \ pass it as `api_key` argument to the CohereReranker." ) - return openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY") or self.api_key) + return openai.OpenAI(api_key=self.api_key or os.environ.get("OPENAI_API_KEY")) diff --git a/python/python/tests/test_openai_reranker_credentials.py b/python/python/tests/test_openai_reranker_credentials.py new file mode 100644 index 000000000..aa11239b2 --- /dev/null +++ b/python/python/tests/test_openai_reranker_credentials.py @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +from lancedb.rerankers import OpenaiReranker + + +@pytest.mark.parametrize( + "explicit_key, environment_key, expected_key", + [ + ("explicit-test-key", "environment-test-key", "explicit-test-key"), + ("explicit-test-key", None, "explicit-test-key"), + (None, "environment-test-key", "environment-test-key"), + ], +) +def test_openai_reranker_api_key_precedence( + monkeypatch, explicit_key, environment_key, expected_key +): + pytest.importorskip("openai") + if environment_key is None: + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + else: + monkeypatch.setenv("OPENAI_API_KEY", environment_key) + + reranker = OpenaiReranker(api_key=explicit_key) + client = reranker._client + try: + assert client.api_key == expected_key + finally: + client.close() + + +def test_openai_reranker_requires_api_key(monkeypatch): + pytest.importorskip("openai") + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="OPENAI_API_KEY not set"): + OpenaiReranker()._client From dd4795028b390302f8edad3b1cdef9b2ed3d9b9f Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Sat, 24 Oct 2026 08:25:16 +0800 Subject: [PATCH 090/180] fix(python): align sync remote methods with async behavior (#4411) Sync remote table and connection methods inherited bare base-class stubs, so unsupported conversion and bulk-drop operations raised `NotImplementedError` with an empty message and differed from the async API. Delegate `to_lance()`, `drop_all_tables()`, and `drop_database()` to the async implementation. Sync and async remote Lance conversion share #4306's native-table guard and reject before requesting a URI or opening client storage. Conversion documentation directs remote reads through server queries. Add an explicit Polars error, suggest query conversions in Arrow/Pandas/Polars errors, and give the remaining base-class errors an operation name. Preserve upstream `blob_mode` validation for remote Arrow and Pandas conversion. The shared remote bulk-drop error suggests dropping tables individually. Regression tests cover sync/async rejection parity, accessible and missing advertised locations, pinned versions, and bulk-drop rejection without requests. Sync blob query tests verify that descriptions come from the server and unsupported modes cannot open client storage. Keep the remote closed-blob-handle assertion consistent with the upstream `ValueError` contract. Validation: - All 30 focused regression cases passed. - 222 Python tests passed with rebuilt bindings in the locked uv environment: the full remote and error suites, plus selected local conversion, blob, and deletion tests. - Python lint and formatting, Rust formatting, `cargo check --quiet --features remote --tests --examples`, and `cargo clippy --quiet --features remote --tests --examples` passed. - Root Ruff checking reports 49 existing errors in upstream `docs/web-tests`; those files are unchanged relative to `main`. Fixes #4392 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/db.py | 31 +++-- python/python/lancedb/remote/db.py | 14 +++ python/python/lancedb/remote/table.py | 29 ++++- python/python/lancedb/table.py | 56 +++++---- python/python/tests/test_errors.py | 21 ++++ python/python/tests/test_remote_db.py | 157 ++++++++++++++++++++++++-- rust/lancedb/src/remote/db.rs | 4 +- 7 files changed, 271 insertions(+), 41 deletions(-) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 90dc1cccf..74acc28ba 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -548,7 +548,9 @@ class DBConnection(EnforceOverrides): LanceTable(name='table4', ...) """ - raise NotImplementedError + raise NotImplementedError( + "create_table is not supported for this connection type" + ) def __getitem__(self, name: str) -> LanceTable: return self.open_table(name) @@ -603,7 +605,9 @@ class DBConnection(EnforceOverrides): ------- A LanceTable object representing the table. """ - raise NotImplementedError + raise NotImplementedError( + "open_table is not supported for this connection type" + ) def create_materialized_view( self, @@ -743,13 +747,17 @@ class DBConnection(EnforceOverrides): """ if namespace_path is None: namespace_path = [] - raise NotImplementedError + raise NotImplementedError( + "drop_table is not supported for this connection type" + ) def drop_table_async( self, name: str, namespace_path: Optional[List[str]] = None ) -> Job: """Start dropping a table and return its cleanup job.""" - raise NotImplementedError + raise NotImplementedError( + "drop_table_async is not supported for this connection type" + ) def rename_table( self, @@ -777,19 +785,26 @@ class DBConnection(EnforceOverrides): cur_namespace_path = [] if new_namespace_path is None: new_namespace_path = [] - raise NotImplementedError + raise NotImplementedError( + "rename_table is not supported for this connection type" + ) def drop_database(self): """ Drop database This is the same thing as dropping all the tables """ - raise NotImplementedError + raise NotImplementedError( + "drop_database is not supported for this connection type" + ) def drop_all_tables(self, namespace_path: Optional[List[str]] = None): """ Drop all tables from the database + Remote connections do not currently support this operation. Use + ``list_tables()`` and ``drop_table()`` to drop tables individually. + Parameters ---------- namespace_path: List[str], optional @@ -798,7 +813,9 @@ class DBConnection(EnforceOverrides): """ if namespace_path is None: namespace_path = [] - raise NotImplementedError + raise NotImplementedError( + "drop_all_tables is not supported for this connection type" + ) @property def uri(self) -> str: diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 08125cc42..5e9288471 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -841,6 +841,20 @@ class RemoteDBConnection(DBConnection): job = LOOP.run(self._conn.drop_table_async(name, namespace_path=namespace_path)) return Job(job if isinstance(job, AsyncJob) else AsyncJob(job)) + @override + def drop_all_tables(self, namespace_path: Optional[List[str]] = None): + """Drop all tables from the database. + + The remote API does not currently support this operation. Use + ``list_tables()`` and ``drop_table()`` to drop tables individually. + """ + LOOP.run(self._conn.drop_all_tables(namespace_path=namespace_path)) + + @override + def drop_database(self): + """Deprecated alias for ``drop_all_tables()``.""" + LOOP.run(self._conn.drop_database()) + @override def rename_table( self, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 0744410b3..53591182e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -7,6 +7,7 @@ import logging from functools import cached_property import os from typing import ( + TYPE_CHECKING, Any, Callable, Dict, @@ -82,6 +83,10 @@ from ..table import ( from ..types import BaseTokenizerType from ..util import infer_vector_column_name +if TYPE_CHECKING: + import lance + import polars as pl + class RemoteTable(Table): def __init__( @@ -243,12 +248,32 @@ class RemoteTable(Table): def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table: """to_arrow() is not supported for remote tables.""" validate_blob_mode(blob_mode) - raise NotImplementedError("to_arrow() is not supported for remote tables.") + raise NotImplementedError( + "to_arrow() is not supported for remote tables. " + "Use table.search().to_arrow() instead." + ) def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs): """to_pandas() is not supported for remote tables.""" validate_blob_mode(blob_mode) - raise NotImplementedError("to_pandas() is not supported for remote tables.") + raise NotImplementedError( + "to_pandas() is not supported for remote tables. " + "Use table.search().to_pandas() instead." + ) + + def to_lance(self, **kwargs) -> "lance.LanceDataset": + """Direct Lance dataset access is not supported for remote tables. + + Use ``table.search().to_arrow()`` to read query results through the server. + """ + return LOOP.run(self._table.to_lance(**kwargs)) + + def to_polars(self, **kwargs) -> "pl.LazyFrame": + """Use ``table.search().to_polars()`` to read remote query results.""" + raise NotImplementedError( + "to_polars() is not supported for remote tables. " + "Use table.search().to_polars() instead." + ) def checkout(self, version: Union[int, str]): result = LOOP.run(self._table.checkout(version)) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index b9557f219..c08c6390e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1356,13 +1356,13 @@ class Table(ABC): @abstractmethod def name(self) -> str: """The name of this Table""" - raise NotImplementedError + raise NotImplementedError("name is not supported for this table type") @property @abstractmethod def version(self) -> int: """The version of this Table""" - raise NotImplementedError + raise NotImplementedError("version is not supported for this table type") @property @abstractmethod @@ -1371,7 +1371,7 @@ class Table(ABC): of this Table """ - raise NotImplementedError + raise NotImplementedError("schema is not supported for this table type") @property @abstractmethod @@ -1400,7 +1400,7 @@ class Table(ABC): tags = table.tags.list() """ - raise NotImplementedError + raise NotImplementedError("tags is not supported for this table type") @property def branches(self) -> "Branches": @@ -1409,11 +1409,11 @@ class Table(ABC): Branches are isolated, writable lines of history forked from another branch (or version). Writes on a branch do not affect ``main``. """ - raise NotImplementedError + raise NotImplementedError("branches is not supported for this table type") def current_branch(self) -> Optional[str]: """The branch this table handle is scoped to, or ``None`` for ``main``.""" - raise NotImplementedError + raise NotImplementedError("current_branch is not supported for this table type") def __len__(self) -> int: """The number of rows in this Table""" @@ -1436,7 +1436,7 @@ class Table(ABC): filter: str, optional A SQL where clause to filter the rows to count. """ - raise NotImplementedError + raise NotImplementedError("count_rows is not supported for this table type") def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs) -> "pandas.DataFrame": """Return the table as a pandas DataFrame. @@ -1471,20 +1471,26 @@ class Table(ABC): ------- pa.Table """ - raise NotImplementedError + raise NotImplementedError("to_arrow is not supported for this table type") def to_lance(self, **kwargs) -> lance.LanceDataset: - """Return the table as a lance.LanceDataset. + """Return a local table as a lance.LanceDataset. + + Remote tables cannot be opened as Lance datasets by the client. Use + ``table.search().to_arrow()`` to read them through the server. Returns ------- lance.LanceDataset """ - raise NotImplementedError + raise NotImplementedError("to_lance is not supported for this table type") def to_polars(self, **kwargs) -> "pl.LazyFrame": """Return the table as a Polars LazyFrame. + For remote tables, use ``table.search().to_polars()`` to convert query + results to a Polars DataFrame. + Note ---- The Polars streaming engine is not supported because it does not currently @@ -1495,7 +1501,7 @@ class Table(ABC): ------- polars.LazyFrame """ - raise NotImplementedError + raise NotImplementedError("to_polars is not supported for this table type") # New unified API overload @overload @@ -1600,7 +1606,7 @@ class Table(ABC): ... "l2", vector_column_name="vector" ... ) """ - raise NotImplementedError + raise NotImplementedError("create_index is not supported for this table type") def create_index_async( self, @@ -1618,7 +1624,9 @@ class Table(ABC): be complete when returned; callers must not assume the index exists until :meth:`Job.wait` returns. """ - raise NotImplementedError + raise NotImplementedError( + "create_index_async is not supported for this table type" + ) def drop_index(self, name: str) -> None: """ @@ -1638,7 +1646,7 @@ class Table(ABC): Use [list_indices][lancedb.table.Table.list_indices] to find the names of the indices. """ - raise NotImplementedError + raise NotImplementedError("drop_index is not supported for this table type") def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) @@ -1655,14 +1663,14 @@ class Table(ABC): timeout: timedelta Timeout to wait for asynchronous indexing. The default is 5 minutes. """ - raise NotImplementedError + raise NotImplementedError("wait_for_index is not supported for this table type") @abstractmethod def stats(self) -> TableStatistics: """ Retrieve table and fragment statistics. """ - raise NotImplementedError + raise NotImplementedError("stats is not supported for this table type") @abstractmethod def create_scalar_index( @@ -1727,7 +1735,9 @@ class Table(ABC): ``my_col = 0 OR not_indexed = 1`` will not be able to use any scalar index on ``my_col``. """ - raise NotImplementedError + raise NotImplementedError( + "create_scalar_index is not supported for this table type" + ) def create_fts_index( self, @@ -1853,7 +1863,9 @@ class Table(ABC): ``LANCE_LANGUAGE_MODEL_HOME`` to override the default platform data directory under ``lance/language_models``. """ - raise NotImplementedError + raise NotImplementedError( + "create_fts_index is not supported for this table type" + ) @abstractmethod def add( @@ -1927,7 +1939,7 @@ class Table(ABC): AddResult An object containing the new version number of the table after adding data. """ - raise NotImplementedError + raise NotImplementedError("add is not supported for this table type") def merge_insert(self, on: Union[str, Iterable[str]]) -> LanceMergeInsertBuilder: """ @@ -2079,7 +2091,7 @@ class Table(ABC): - and also the "_distance" column which is the distance between the query vector and the returned vector. """ - raise NotImplementedError + raise NotImplementedError("search is not supported for this table type") @abstractmethod def take_offsets( @@ -2365,7 +2377,7 @@ class Table(ABC): x vector 0 3 [5.0, 6.0] """ - raise NotImplementedError + raise NotImplementedError("delete is not supported for this table type") @abstractmethod def update( @@ -2432,7 +2444,7 @@ class Table(ABC): 1 4 [5.0, 6.0] 2 3 [10.0, 10.0] """ - raise NotImplementedError + raise NotImplementedError("update is not supported for this table type") @abstractmethod def cleanup_old_versions( diff --git a/python/python/tests/test_errors.py b/python/python/tests/test_errors.py index 338b6a0d7..0e362e5d8 100644 --- a/python/python/tests/test_errors.py +++ b/python/python/tests/test_errors.py @@ -3,7 +3,28 @@ import pickle +import pytest + +from lancedb.db import DBConnection from lancedb.remote.errors import HttpError, LanceDBClientError, RetryError +from lancedb.table import Table + + +@pytest.mark.parametrize( + "base, method", + [ + (Table, "to_lance"), + (Table, "to_polars"), + (DBConnection, "drop_all_tables"), + (DBConnection, "drop_database"), + ], +) +def test_base_unsupported_methods_have_messages(base, method): + with pytest.raises(NotImplementedError) as exc_info: + getattr(base, method)(None) + message = str(exc_info.value) + assert method in message + assert "not supported" in message def test_pickle_lancedb_client_error(): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 9655f5807..c1db92948 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -857,10 +857,116 @@ def test_table_unimplemented_functions(): with mock_lancedb_connection(handler) as db: table = db.create_table("test", [{"id": 1}]) - with pytest.raises(NotImplementedError): - table.to_arrow() - with pytest.raises(NotImplementedError): - table.to_pandas() + for method in ["to_arrow", "to_pandas", "to_polars"]: + with pytest.raises(NotImplementedError) as exc_info: + getattr(table, method)() + message = str(exc_info.value) + assert method in message + assert "not" in message and "supported" in message + assert "remote tables" in message + assert "cloud" not in message.lower() + assert f"search().{method}()" in message + + +@pytest.mark.parametrize("method", ["to_arrow", "to_pandas"]) +@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes", "invalid"]) +def test_remote_conversion_blob_mode_errors(method, blob_mode): + with blob_remote_table() as table: + if blob_mode == "invalid": + with pytest.raises(ValueError, match="blob_mode must be one of"): + getattr(table, method)(blob_mode=blob_mode) + else: + with pytest.raises(NotImplementedError) as error: + getattr(table, method)(blob_mode=blob_mode) + assert f"search().{method}()" in str(error.value) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("version", [None, 1]) +@pytest.mark.parametrize("expose_location", [False, True]) +async def test_remote_to_lance_rejection( + tmp_path, version, expose_location, monkeypatch +): + import lance + + location = tmp_path / "test.lance" + lance.write_dataset(pa.table({"id": [1]}), location) + lance.write_dataset(pa.table({"id": [2]}), location, mode="append") + requests = [] + + def fail_dataset(*args, **kwargs): + raise AssertionError("remote storage must not be opened") + + monkeypatch.setattr(lance, "dataset", fail_dataset) + + def handler(request): + requests.append(request.path) + assert request.path == "/v1/table/test/describe/" + content_len = int(request.headers.get("Content-Length", 0)) + body = json.loads(request.rfile.read(content_len)) if content_len else {} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + response = { + "version": body.get("version") or 2, + "schema": {"fields": []}, + } + if expose_location: + response["location"] = str(location) + request.wfile.write(json.dumps(response).encode()) + + options = {"default_scan_options": {"with_row_id": True}} + with mock_lancedb_connection(handler) as db: + table = db.open_table("test", version=version) + opened_requests = list(requests) + with pytest.raises(NotImplementedError) as sync_error: + table.to_lance(**options) + assert requests == opened_requests + + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test", version=version) + opened_requests = list(requests) + with pytest.raises(NotImplementedError) as async_error: + await table.to_lance(**options) + assert requests == opened_requests + + assert "to_lance() is not supported for remote tables" in str(sync_error.value) + assert "query the server" in str(sync_error.value) + assert str(sync_error.value) == str(async_error.value) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "method, kwargs", + [ + ("drop_all_tables", {}), + ("drop_all_tables", {"namespace_path": []}), + ("drop_all_tables", {"namespace_path": ["team"]}), + ("drop_database", {}), + ], +) +async def test_remote_drop_all_tables_not_supported(method, kwargs): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(500) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + with pytest.raises(NotImplementedError) as sync_error: + getattr(db, method)(**kwargs) + + async with mock_lancedb_connection_async(handler) as db: + with pytest.raises(NotImplementedError) as async_error: + await getattr(db, method)(**kwargs) + + assert "Dropping all tables is not currently supported in the remote API" in str( + sync_error.value + ) + assert "drop_table" in str(sync_error.value) + assert str(sync_error.value) == str(async_error.value) + assert requests == [] def test_table_to_pandas_not_supported(): @@ -1681,10 +1787,13 @@ def test_remote_python_only_messages(caplog): table = db.open_table("test", storage_options={}, index_cache_size=1) assert "storage_options is ignored for remote tables" in caplog.text assert "index_cache_size is ignored for remote tables" in caplog.text - for method in ["to_arrow", "to_pandas"]: + for method in ["to_arrow", "to_pandas", "to_polars"]: with pytest.raises(NotImplementedError) as error: getattr(table, method)() - assert str(error.value) == f"{method}() is not supported for remote tables." + assert str(error.value) == ( + f"{method}() is not supported for remote tables. " + f"Use table.search().{method}() instead." + ) for method in ["compact_files", "cleanup_old_versions"]: with pytest.warns(UserWarning) as warning: getattr(table, method)() @@ -3490,14 +3599,17 @@ def blob_descriptor_take_table(): @contextlib.contextmanager -def blob_remote_table(*, server_version=Version("0.5.0")): +def blob_remote_table(*, server_version=Version("0.5.0"), location=None): def handler(request): if request.path == "/v1/table/test/describe/": request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) request.end_headers() - request.wfile.write(json.dumps(BLOB_DESCRIBE_RESPONSE).encode()) + response = dict(BLOB_DESCRIBE_RESPONSE) + if location is not None: + response["location"] = str(location) + request.wfile.write(json.dumps(response).encode()) elif request.path.startswith("/v1/table/test/blob/image/"): path = request.path.partition("?")[0] row_id = int(path.split("/")[-2]) @@ -3532,7 +3644,6 @@ def blob_remote_table(*, server_version=Version("0.5.0")): if columns == ["id"]: response_table = blob_query_response_table().select(["id"]) else: - assert body["with_row_id"] is True if columns == ["image"]: # Blob handles are sized from a descriptor take. assert body["filter"].startswith("_rowid IN") @@ -3545,6 +3656,8 @@ def blob_remote_table(*, server_version=Version("0.5.0")): ) else: response_table = blob_query_response_table() + if not body.get("with_row_id", False): + response_table = response_table.drop(["_rowid"]) request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.file") request.send_header("x-lancedb-version", "1") @@ -3579,6 +3692,32 @@ def test_remote_blob_columns_and_fetch(): assert blobs.to_pylist() == [b"alpha", None, b"gamma"] +@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes", "lazy"]) +def test_sync_remote_blob_pandas_avoids_storage_access( + tmp_path, monkeypatch, blob_mode +): + import lance + + location = tmp_path / "remote.lance" + lance.write_dataset(pa.table({"id": [7], "image": [b"server-owned"]}), location) + + def fail_dataset(*args, **kwargs): + raise AssertionError("remote storage must not be opened") + + monkeypatch.setattr(lance, "dataset", fail_dataset) + with blob_remote_table(location=location) as table: + monkeypatch.setattr(table, "to_lance", fail_dataset) + query = table.search().select(["id", "image"]) + if blob_mode == "descriptions": + df = query.to_pandas(blob_mode=blob_mode) + assert df["id"].tolist() == [1, 2, 3] + assert "_rowid" not in df.columns + assert df["image"][0]["size"] == 5 + else: + with pytest.raises(NotImplementedError, match="stable table snapshot"): + query.to_pandas(blob_mode=blob_mode) + + @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) async def test_remote_fetch_blob_ranges(use_async): diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 8a456ab3b..cad60ab7d 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1707,7 +1707,9 @@ impl Database for RemoteDatabase { // TODO: Implement namespace-aware drop_all_tables let _namespace_path = namespace_path; // Suppress unused warning for now Err(crate::Error::NotSupported { - message: "Dropping all tables is not currently supported in the remote API".to_string(), + message: "Dropping all tables is not currently supported in the remote API. \ + List tables and call drop_table for each table instead." + .to_string(), }) } From 6777a40dc280be8fd8f55e67750cbc6ecf7a2a60 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:51:10 +0800 Subject: [PATCH 091/180] fix: support remote tables in storage root (#3881) ## Summary - allow `db://` to select the remote storage root when a host override supplies the endpoint - preserve the empty `x-lancedb-database` header used by the legacy clients for root storage - reject root-storage connections without a host override before constructing an invalid Cloud URL - document the supported URI and cover both accepted and rejected configurations ## Root cause The shared Rust remote URL parser required every `db://` URI to contain a host. That validation was introduced when the Node and Python clients moved to the Rust implementation, but the legacy Node client intentionally treated the empty host in `db://` as the storage-root selector. ## Validation - `cargo fmt --all` - `cargo test --quiet --features remote -p lancedb test_connect_remote_storage_root` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` - `cargo test --quiet --features remote --tests` Fixes #1944 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- rust/lancedb/src/connection.rs | 34 +++++++++++++++++++++++++++++++ rust/lancedb/src/lib.rs | 1 + rust/lancedb/src/remote/client.rs | 31 +++++++++++++++++----------- rust/lancedb/src/remote/db.rs | 7 +++++++ 4 files changed, 61 insertions(+), 12 deletions(-) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 124f6a54a..482acf89a 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -1270,6 +1270,7 @@ pub struct ConnectRequest { /// - `/path/to/database` - local database on file system. /// - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store /// - `db://dbname` - LanceDB Cloud + /// - `db://` with a host override - remote tables in the storage root pub uri: String, #[cfg(feature = "remote")] @@ -1382,6 +1383,8 @@ impl ConnectBuilder { /// /// This option is only used when connecting to LanceDB Cloud (db:// URIs) /// and will be ignored for other URIs. + /// Use the URI `db://` together with a host override to connect to remote + /// tables stored directly in the storage root. /// /// # Arguments /// @@ -2007,6 +2010,37 @@ mod tests { } } + #[cfg(feature = "remote")] + #[tokio::test] + async fn test_connect_remote_storage_root() { + let conn = ConnectBuilder::new("db://") + .region("us-east-1") + .api_key("my-api-key") + .host_override("https://example.com") + .execute() + .await + .unwrap(); + + let (impl_name, properties) = conn.namespace_client_config().await.unwrap(); + assert_eq!(impl_name, "rest"); + assert_eq!(properties["uri"], "https://example.com"); + assert!( + !properties.contains_key("header.x-lancedb-database"), + "storage-root connections must not send the x-lancedb-database header" + ); + + let result = ConnectBuilder::new("db://") + .region("us-east-1") + .api_key("my-api-key") + .execute() + .await; + assert!(matches!( + result, + Err(Error::InvalidInput { message }) + if message.contains("A host override is required") + )); + } + #[cfg(feature = "remote")] #[tokio::test] async fn test_connect_rejects_header_provider_with_oauth_config() { diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index e15017e7f..68521ff2c 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -54,6 +54,7 @@ //! - `/path/to/database` - local database on file system. //! - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store //! - `db://dbname` - Lance Cloud +//! - `db://` with a host override - remote tables in the storage root //! //! You can also use [`ConnectBuilder`] to configure the connection to the database. //! diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index 783d2ef84..fe4a2072e 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -378,23 +378,30 @@ pub struct ParsedDbUrl { /// Parse a database URL and extract the database name and optional prefix. /// -/// Expected format: `db://db_name` or `db://db_name/prefix` +/// Expected format: `db://db_name`, `db://db_name/prefix`, or `db://` when +/// connecting to the storage root through a host override. pub fn parse_db_url(db_url: &str) -> Result { let parsed_url = url::Url::parse(db_url).map_err(|err| Error::InvalidInput { message: format!("db_url is not a valid URL. '{db_url}'. Error: {err}"), })?; debug_assert_eq!(parsed_url.scheme(), "db"); - if !parsed_url.has_host() { - return Err(Error::InvalidInput { - message: format!("Invalid database URL (missing host) '{}'", db_url), - }); - } - let db_name = urlencoding::decode(parsed_url.host_str().unwrap()) - .map_err(|err| Error::InvalidInput { - message: format!("Invalid encoded database name: {err}"), - })? - .into_owned(); - validate_database_name(&db_name)?; + let db_name = match parsed_url.host_str() { + Some(db_name) => { + let db_name = urlencoding::decode(db_name) + .map_err(|err| Error::InvalidInput { + message: format!("Invalid encoded database name: {err}"), + })? + .into_owned(); + validate_database_name(&db_name)?; + db_name + } + None if matches!(parsed_url.path(), "" | "/") => String::new(), + None => { + return Err(Error::InvalidInput { + message: format!("Invalid database URL (missing host) '{}'", db_url), + }); + } + }; let db_prefix = { let prefix = parsed_url.path().trim_start_matches('/'); if prefix.is_empty() { diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index cad60ab7d..f07d20fc3 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -318,6 +318,13 @@ impl RemoteDatabase { read_consistency_interval: Option, ) -> Result { let parsed = super::client::parse_db_url(uri)?; + if parsed.db_name.is_empty() && host_overrides.rest.is_none() { + return Err(Error::InvalidInput { + message: + "A host override is required when connecting to the storage root with 'db://'" + .to_string(), + }); + } Self::try_new_with_identity( uri, api_key, From a8305e072246d21a97e8857c480e3bbdb9a4178f Mon Sep 17 00:00:00 2001 From: Romin Parekh <3831468+rominparekh@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:08:40 -0700 Subject: [PATCH 092/180] fix(rust): accept usize::MAX as a local query limit (#4567) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #2211. Local queries converted `limit`/`offset` with `as i64`, so `limit(usize::MAX)` wrapped to `-1` and Lance failed with `Limit must be non-negative`. The remote client already worked around this (#2354); this fixes the local path. - Saturate scanner offsets to `i64::MAX` and cap limits at `i64::MAX - offset`, keeping both conversion and full-text pagination addition safe. - Use `saturating_add` for vector `top_k = limit + offset`, then cap candidates at the dataset row count to avoid indexed-search capacity and refinement overflows. Keep a positive candidate bound for empty tables because Lance rejects `k = 0`. - Leave public APIs and remote query handling unchanged. ### Testing - Regression coverage includes plain scans, indexed IVF search, refinement, index bypass, empty vector tables, and indexed full-text pagination with finite and extreme limits/offsets. - Reproduced the indexed-search and FTS overflows before applying the follow-up fix. - `cargo test --quiet --features remote -p lancedb --lib query::` — 81 passed. - `cargo clippy --quiet --features remote -p lancedb --tests --examples` — clean. - `cargo fmt --all` and `git diff --check` — clean. Vector planning now reads the dataset row count (metadata fast path) to bound candidate allocation; this was not performance-benchmarked. --------- Co-authored-by: Romin Parekh Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/query.py | 29 +++--- rust/lancedb/src/query.rs | 153 ++++++++++++++++++++++++++++++++ rust/lancedb/src/table/query.rs | 21 ++++- 3 files changed, 188 insertions(+), 15 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 9d7610f72..52f38d077 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1561,9 +1561,10 @@ class LanceQueryBuilder(ABC): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters ---------- @@ -1619,8 +1620,8 @@ class LanceQueryBuilder(ABC): GlobalLimitExec: elapsed=..., skip=0, fetch=10, metrics=[output_rows=..., elapsed_compute=..., output_bytes=...] FilterExec: elapsed=..., _distance@2 IS NOT NULL, metrics=[...] - SortExec: elapsed=..., TopK(fetch=10), expr=[...], - preserve_partitioning=[...], + SortExec: elapsed=..., TopK(fetch=1), expr=[...], + preserve_partitioning=[...], filter=[...], metrics=[output_rows=..., elapsed_compute=..., output_bytes=..., row_replacements=...] KNNVectorDistance: elapsed=..., metric=l2, @@ -1633,6 +1634,7 @@ class LanceQueryBuilder(ABC): metrics=[output_rows=..., elapsed_compute=..., output_bytes=..., fragments_scanned=..., ranges_scanned=1, rows_scanned=1, bytes_read=..., iops=..., requests=..., task_wait_time=...] + Parameters ---------- @@ -2959,9 +2961,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters ---------- @@ -3601,9 +3604,10 @@ class AsyncQueryBase(object): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters @@ -4521,9 +4525,9 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): LanceRead: uri=..., projection=[text], source=stream(_rowid) GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... ProjectionExec: expr=[vector@2 as vector, text@3 as text, _score@1 as _score, _rowid@0 as _rowid] LanceRead: uri=..., projection=[vector, text], source=stream(_rowid) GlobalLimitExec: skip=0, fetch=10 @@ -4877,9 +4881,10 @@ class BaseQueryBuilder(object): ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance] GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL - SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] + SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 - LanceRead: uri=..., projection=[vector], ... + LanceRead: uri=..., projection=[vector], num_fragments=..., ... + Parameters diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 00a2b88f3..9bac51209 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -2714,6 +2714,159 @@ mod tests { } } + #[tokio::test] + async fn test_limit_usize_max() { + let conn = connect("memory://foo").execute().await.unwrap(); + let table = conn + .create_table("my_table", make_non_empty_batches()) + .execute() + .await + .unwrap(); + let expected = table.count_rows(None).await.unwrap(); + + let batches: Vec = table + .query() + .limit(usize::MAX) + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(num_rows, expected); + + let batches: Vec = table + .query() + .limit(usize::MAX) + .offset(1) + .nearest_to(&[0.1; 4]) + .unwrap() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(num_rows, expected - 1); + } + + #[tokio::test] + async fn test_indexed_vector_limit_usize_max() { + use crate::index::vector::IvfFlatIndexBuilder; + + let conn = connect("memory://indexed_limit").execute().await.unwrap(); + let table = conn + .create_table("vectors", make_non_empty_batches()) + .execute() + .await + .unwrap(); + table + .create_index( + &["vector"], + Index::IvfFlat(IvfFlatIndexBuilder::default().num_partitions(1)), + ) + .execute() + .await + .unwrap(); + let expected = table.count_rows(None).await.unwrap(); + + for limit in [expected, i64::MAX as usize, usize::MAX] { + for offset in [0, 1, usize::MAX] { + for (bypass, refine_factor) in [(false, None), (false, Some(2)), (true, None)] { + let query = table + .query() + .limit(limit) + .offset(offset) + .nearest_to(&[0.1; 4]) + .unwrap(); + let query = if bypass { + query.bypass_vector_index() + } else { + query + }; + let query = if let Some(factor) = refine_factor { + query.refine_factor(factor) + } else { + query + }; + let batches: Vec = + query.execute().await.unwrap().try_collect().await.unwrap(); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + expected.saturating_sub(offset), + "limit={limit}, offset={offset}, bypass={bypass}, refine={refine_factor:?}" + ); + } + } + } + } + + #[tokio::test] + async fn test_empty_vector_limit_usize_max() { + let conn = connect("memory://empty_limit").execute().await.unwrap(); + let table = conn + .create_table("vectors", make_test_batches()) + .execute() + .await + .unwrap(); + let batches: Vec = table + .query() + .limit(usize::MAX) + .nearest_to(&[0.1; 128]) + .unwrap() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + } + + #[tokio::test] + async fn test_fts_limit_usize_max_with_offset() { + let conn = connect("memory://fts_limit").execute().await.unwrap(); + let data = RecordBatch::try_from_iter([( + "text", + Arc::new(StringArray::from_iter_values((0..32).map(|_| "hello"))) + as arrow_array::ArrayRef, + )]) + .unwrap(); + let table = conn + .create_table("documents", data) + .execute() + .await + .unwrap(); + table + .create_index(&["text"], Index::FTS(Default::default())) + .execute() + .await + .unwrap(); + + for limit in [32, i64::MAX as usize, usize::MAX] { + for offset in [0, 1, i64::MAX as usize, usize::MAX] { + let batches: Vec = table + .query() + .full_text_search(FullTextSearchQuery::new("hello".into())) + .limit(limit) + .offset(offset) + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + 32usize.saturating_sub(offset), + "limit={limit}, offset={offset}" + ); + } + } + } + #[tokio::test] async fn test_repeated_only_if_combines_with_and() { use crate::expr::{col, lit}; diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index f625a4aff..4ad840350 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -280,7 +280,13 @@ pub async fn create_plan( let (_, element_type) = lance::index::vector::utils::get_vector_type(schema, &column)?; let is_binary = matches!(element_type, DataType::UInt8); - let top_k = query.base.limit.unwrap_or(DEFAULT_TOP_K) + query.base.offset.unwrap_or(0); + let top_k = query + .base + .limit + .unwrap_or(DEFAULT_TOP_K) + .saturating_add(query.base.offset.unwrap_or(0)) + // Lance allocates candidates from k; no search can return more rows than the table. + .min(ds_ref.count_rows(None).await?.max(1)); if is_binary { let query_vector = arrow::compute::cast(&query_vector, &DataType::UInt8)?; @@ -317,9 +323,18 @@ pub async fn create_plan( // For a batch query, `nearest` already applies k to each query vector. // Adding Scanner's global limit would truncate the combined result to k rows. if !is_batch_query { + let offset = query + .base + .offset + .map(|offset| i64::try_from(offset).unwrap_or(i64::MAX)); scanner.limit( - query.base.limit.map(|limit| limit as i64), - query.base.offset.map(|offset| offset as i64), + // Lance's FTS planner adds limit + offset as i64. + query.base.limit.map(|limit| { + i64::try_from(limit) + .unwrap_or(i64::MAX) + .min(i64::MAX - offset.unwrap_or(0)) + }), + offset, )?; } From cf5c9b5453e5abb30341d33ca1b67a7812b58ecb Mon Sep 17 00:00:00 2001 From: J Ganesh Kumar Reddy Date: Sat, 24 Oct 2026 10:01:49 +0530 Subject: [PATCH 093/180] fix: validate cached remote tables on open (#4557) ## Summary Fixes #4401. - Validate cached remote table entries with the existing `describe` endpoint before returning a handle. - Preserve cached server-version behavior after a successful validation. - Add a regression test for a table dropped by another connection after its entry has been cached. A cached entry can otherwise outlive an external drop, allowing `open_table()` to return a handle that fails only on its first later operation. ## Verification [Linux validation](https://github.com/Ganesh1729-ui/lancedb/actions/runs/39420560974) passed against the exact runtime and test sources at PR head `d39092b01f6b49921b5d66ccedf29709a7ddc23d`, using the repository's Rust toolchain and `ci` profile: - `cargo fmt --all -- --check` - `cargo test --profile ci --locked -p lancedb --features remote --lib remote::db::tests::test_open_table -- --nocapture`: **8 passed**, including cached-table deletion, independent handle checkout, branch/version handling, schema seeding and describe-response handling. - Removing only the cached-hit existence guard makes `test_open_table_checks_that_a_cached_table_still_exists` fail at its `TableNotFound` assertion; restoring the fix makes the same test pass again. - `git diff --check` The validation workflow is on a separate fork branch and is excluded from this PR. These are focused, mock-backed remote unit tests; the full upstream matrix and live Cloud integration tests still need upstream CI approval. Local Windows compilation was unavailable because the MSVC environment has no `link.exe`; the linked Linux run completed successfully. --------- Co-authored-by: Ganesh172919 Co-authored-by: Xuanwo --- deny.toml | 10 +++++++++ rust/lancedb/src/remote/db.rs | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/deny.toml b/deny.toml index 7d60ae63f..77412709f 100644 --- a/deny.toml +++ b/deny.toml @@ -110,8 +110,18 @@ ignore = [ # compact_str/smol_str, so clearing this requires polars to migrate. # https://rustsec.org/advisories/RUSTSEC-2026-0249 { id = "RUSTSEC-2026-0249", reason = "smartstring unmaintained via polars; no fixed upstream release" }, + # crypto-bigint < 0.7.6: timing side-channels in constant-time ops, + # incl. subtraction, zero counting, division and Montgomery multiplication. + # Reached only through aws-sdk-s3 sigv4a -> aws-sigv4 (p256/ecdsa); signed + # requests carry the SigV4a credential-derived key. The patched 0.7.6 was + # published 2026-10-23, but no published aws-sigv4 release uses it yet + # (latest 1.6.3 pins crypto-bigint ^0.5), so clearing requires smithy-rs to + # ship an updated aws-sigv4. + # https://rustsec.org/advisories/RUSTSEC-2026-0387 + { id = "RUSTSEC-2026-0387", reason = "crypto-bigint via aws-sigv4 (sigv4a); no fixed upstream aws-sigv4 release yet" }, ] + # --------------------------------------------------------------------------- # Licenses: only allow licenses we've reviewed as compatible with Apache-2.0. # --------------------------------------------------------------------------- diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index f07d20fc3..768de79d2 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1614,6 +1614,17 @@ impl Database for RemoteDatabase { // Every open gets its own checkout, schema cache, and freshness state. if let Some(version) = self.table_cache.get(&cache_key).await { + // A cached version can outlive a drop from another connection. Verify that + // the table still exists before returning a handle for it. + let req = self + .client + .post(&format!("/v1/table/{}/describe/", identifier)) + .json(&serde_json::json!({})); + let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; + let rsp = + RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; + self.client.check_response(&request_id, rsp).await?; + Ok(Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), request.name, @@ -2557,6 +2568,37 @@ mod tests { assert_eq!(table.name(), "table1"); } + #[tokio::test] + async fn test_open_table_checks_that_a_cached_table_still_exists() { + let describe_calls = Arc::new(AtomicUsize::new(0)); + let calls = describe_calls.clone(); + let mut db = super::RemoteDatabase::new_mock(move |request| { + assert_eq!(request.url().path(), "/v1/table/table1/describe/"); + match calls.fetch_add(1, Ordering::SeqCst) { + 0 => http::Response::builder() + .status(200) + .body(r#"{"version": 1}"#.to_string()) + .unwrap(), + 1 => http::Response::builder() + .status(404) + .body("table not found".to_string()) + .unwrap(), + call => panic!("unexpected describe call: {call}"), + } + }); + db.table_cache = moka::future::Cache::new(10); + let conn = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + + conn.open_table("table1").execute().await.unwrap(); + let result = conn.open_table("table1").execute().await; + + assert!(matches!(result, Err(Error::TableNotFound { .. }))); + assert_eq!(describe_calls.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn test_open_table_checkout_is_independent_per_handle() { let latest = Arc::new(AtomicUsize::new(2)); From 2c9f2e75a068a960863f3c45c36334d965bf2c1c Mon Sep 17 00:00:00 2001 From: Yeluru Nitish <141549775+Nitish-1303@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:21:48 -0500 Subject: [PATCH 094/180] fix: keep FTS indexes in list_indices when their files are missing (#4251) Fixes #4250 `list_indices()` loads each FTS index's segment params from the index files to fill in `index_details`. That call used `?`, so a single FTS index with missing files made the whole listing fail. A BTree or Bitmap index with missing files still lists fine, because it never takes that path. Now, if the params can't be loaded, it logs a warning and keeps the entry with the details from the manifest. Callers can still see the damaged index and rebuild or drop it. Added a Python test based on the repro in the issue. It fails on 0.39.0 with the same RuntimeError. --------- Co-authored-by: Xuanwo --- python/python/tests/test_fts.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index d7fa2e0ec..1dc2fd9a1 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -391,6 +391,20 @@ def test_custom_stop_words_list(table): ) +def test_list_indices_with_missing_fts_files(table): + # Regression test for https://github.com/lancedb/lancedb/issues/4250 + table.create_fts_index("text") + table.create_scalar_index("id") + + fts = next(i for i in table.list_indices() if i.index_type == "FTS") + shutil.rmtree(Path(table.uri) / "_indices" / fts.index_uuid) + + indices = {i.name: i for i in table.list_indices()} + assert set(indices) == {"text_idx", "id_idx"} + assert indices["text_idx"].index_type == "FTS" + assert indices["text_idx"].columns == ["text"] + + def test_search_fts(table): table.create_fts_index("text") results = table.search("puppy").select(["id", "text"]).limit(5).to_list() From 0ea932dafdac1ba3f86135cded890012d9733fdc Mon Sep 17 00:00:00 2001 From: Shiduo Li Date: Fri, 23 Oct 2026 23:47:41 -0700 Subject: [PATCH 095/180] fix(rust): compile jobs without remote feature (#4103) ## What Move typed job decode error construction behind a feature-aware helper so builds without the `remote` feature do not reference `Error::Http`. Local decode failures continue to surface as `Error::Runtime`, while remote builds retain HTTP errors with request IDs. Add a regression test for local typed-result decode failures. Closes #4096. ## Testing - `cargo fmt --all -- --check` - `cargo check -p lancedb --no-default-features` - `cargo test -p lancedb --no-default-features job::tests::local_typed_result_decode_errors_are_runtime_errors` Co-authored-by: Xuanwo --- rust/lancedb/src/job.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 6865e59ee..d671365f9 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -636,6 +636,14 @@ mod tests { use super::*; + #[test] + fn local_typed_result_decode_errors_are_runtime_errors() { + assert!(matches!( + TerminalResult::local(Value::Null).decode::(), + Err(Error::Runtime { .. }) + )); + } + #[tokio::test] async fn mapped_spawned_job_reuses_outcome() { let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); From 6b6778e68495466e78cc786ebc912601c57c8b5d Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 24 Oct 2026 18:50:27 -0700 Subject: [PATCH 096/180] feat: infer lazy blob reader Function inputs (#4663) Infer Blob V2 input access from the Python Function signature. `video: BlobReader` requests a lazy, seekable reader; `video: bytes` requests the complete payload. Users do not need a separate `blob_inputs` registration option. ## Python experience For a video table joined to a table of frame timestamps, the Function can pass its reader directly to a media decoder: ```python import io import av from lancedb import BlobReader, udf @udf(pip=["av", "Pillow"]) def extract_frame(video: BlobReader, timestamp_s: float) -> bytes: with av.open(video) as container: stream = container.streams.video[0] container.seek(int(timestamp_s / stream.time_base), stream=stream) for frame in container.decode(stream): if frame.time is not None and frame.time >= timestamp_s: output = io.BytesIO() frame.to_image().save(output, format="JPEG") return output.getvalue() raise ValueError("No frame at or after the requested timestamp") ``` After registering `extract_frame`, the query keeps the usual Function call: ```sql SELECT f.video_id, f.timestamp_s, extract_frame(v.video, f.timestamp_s) AS image FROM videos AS v JOIN frames AS f ON v.id = f.video_id ``` The returned JPEG can feed a subsequent image-model step. The reader provides `read`, `readinto`, `seek`, `tell`, `size()`, and `read_range(offset, length)`; range reads leave the sequential cursor unchanged. Each row invocation owns its reader, which closes after the call. Decoder seeks can request the parts of the MP4 needed to locate and decode the requested frame; the amount read depends on the file layout and codec. Functions that need the whole value can keep a bytes signature: ```python @udf def video_length(video: bytes) -> int: return len(video) ``` ## Execution contract - Signature inference maps `BlobReader` to a Blob V2 field and records `blob_access="reader"`. `bytes` keeps its binary Arrow type and records `blob_access="bytes"`; it can also bind to a Blob V2 source. Explicit schemas support the same choice, including a Blob V2 field annotated as `bytes`. - Reader execution carries a compact blob reference into the Function worker. Payload reads happen when Python calls the reader, with requests split into at most 1 MiB ranges. The full video does not need to enter the Arrow input batch just to invoke the Function. - Bytes execution materializes the full source before the Function runs and remains subject to eager-input memory admission. Calling `reader.read()` without a size also materializes the remaining contents in Python; lazy access depends on how the Function consumes it. - Input access metadata survives Python/Rust Function serialization and registration. Packaged Functions import the worker-provided reader implementation. This PR defines the SDK contract; execution requires corresponding server support. - This changes blob inputs. The example still returns ordinary image bytes; it does not add streamed outputs or run an image model. Adds coverage for signature inference, explicit schemas, nullable readers, signature round trips, seeking, bounded range reads, buffering, and invalid responses. --- docs/src/python/python.md | 8 ++ docs/web/management/function.mdx | 34 +++++ python/python/lancedb/__init__.py | 1 + python/python/lancedb/_blob_reader.py | 120 ++++++++++++++++++ python/python/lancedb/functions.py | 80 +++++++++--- python/python/tests/test_blob_reader.py | 59 +++++++++ .../tests/test_first_class_function_slice2.py | 55 ++++++++ rust/lancedb/src/function.rs | 23 ++++ 8 files changed, 359 insertions(+), 21 deletions(-) create mode 100644 python/python/lancedb/_blob_reader.py create mode 100644 python/python/tests/test_blob_reader.py diff --git a/docs/src/python/python.md b/docs/src/python/python.md index c465d0ac4..5d1393924 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -304,6 +304,14 @@ listing a storage directory. ## Functions and Jobs +Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or +with `bytes` to materialize its contents before the Function runs. Reader +inputs infer the Blob V2 type without an explicit input schema. Readers are +scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, +`size`, and cursor-independent `read_range`. + +::: lancedb.BlobReader + ::: lancedb.functions.FunctionArtifact ::: lancedb.functions.FunctionParameter diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 8e5b53e4a..6df99b5fd 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -205,6 +205,40 @@ Function output blobs follow the same compaction and cleanup lifecycle as ingested Managed blobs. Retained versions continue to own their payloads; cleanup reclaims an object only after its retained references are gone. +### Draft: incremental blob inputs (upcoming) + +This feature requires an SDK that exports `BlobReader` and a compatible +Enterprise runtime with reader input support enabled. Coordinate the runtime +upgrade before registering or executing reader Functions. + +Annotate a row Function parameter with `BlobReader` to read a Blob v2 input +incrementally. The signature selects the access mode without another +registration option. For example, read the first MP4 box type without loading +the whole video: + +```python +from lancedb import BlobReader, udf + + +@udf +def first_box_type(video: BlobReader) -> bytes: + video.seek(4) + return video.read(4) +``` + +The worker passes a seekable reader backed by the stored blob. `read(size)` +reads from the current cursor; `read_range(offset, length)` reads a byte range +without moving it. `size()` returns the payload size without reading it. +Each row call receives its own reader, which closes when the call returns or +raises. Do not retain it for another invocation. + +Use `video: bytes` when the Function needs the complete payload. Bytes inputs +materialize before invocation and remain subject to eager input limits. +Reader inputs keep the unread payload out of the input batch, but calling +`video.read()` without a size loads all remaining bytes in Python. Reader +inputs are supported in row mode. Return values remain ordinary values such +as `bytes`; this feature does not add streamed outputs. + ## Declare the environment {#environment} The function runs remotely, so its dependencies are part of its definition: diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 6b902c466..a3aa55209 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -24,6 +24,7 @@ from .remote import ClientConfig from .remote.db import RemoteDBConnection from .expr import Expr, col, lit, func from .schema import blob, vector +from ._blob_reader import BlobReader as BlobReader from .job import AsyncJob, Job from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery diff --git a/python/python/lancedb/_blob_reader.py b/python/python/lancedb/_blob_reader.py new file mode 100644 index 000000000..2fd0f00ca --- /dev/null +++ b/python/python/lancedb/_blob_reader.py @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Seekable binary input for Functions that consume Blob V2 values lazily.""" + +import io +import operator +import urllib.request +from collections.abc import Callable +from http import HTTPStatus + +_READ_CHUNK_BYTES = 1024 * 1024 +_READ_TIMEOUT_SECONDS = 300 + + +class BlobReader(io.RawIOBase): + """Read a blob incrementally inside a Function. + + Annotating a Function input with ``BlobReader`` requests a lazy, seekable + reader. Annotating it with ``bytes`` requests materialized bytes instead. + ``read_range`` does not change the sequential cursor. Readers are scoped + to the invocation and must not be retained for a later call. + + For local calls, construct a reader from a range-reading callable and the + blob's size. The callable accepts an offset and length and returns bytes. + """ + + def __init__(self, read_range: Callable[[int, int], bytes], size: int): + super().__init__() + self._read_range = read_range + self._size = operator.index(size) + if self._size < 0: + raise ValueError("blob size must be nonnegative") + self._position = 0 + + @classmethod + def _from_uri(cls, uri: str, size: int): + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + def read_range(offset, length): + request = urllib.request.Request( + uri, headers={"Range": f"bytes={offset}-{offset + length - 1}"} + ) + with opener.open(request, timeout=_READ_TIMEOUT_SECONDS) as response: + if response.status != HTTPStatus.PARTIAL_CONTENT: + raise OSError( + "blob range service did not return a partial response" + ) + data = response.read(length + 1) + if len(data) != length: + raise OSError( + "blob range service returned an invalid payload length" + ) + return data + + return cls(read_range, size) + + def readable(self) -> bool: + return not self.closed + + def seekable(self) -> bool: + return not self.closed + + def size(self) -> int: + """Return the blob size without reading its payload.""" + self._checkClosed() + return self._size + + def tell(self) -> int: + self._checkClosed() + return self._position + + def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: + self._checkClosed() + offset = operator.index(offset) + if whence == io.SEEK_SET: + position = offset + elif whence == io.SEEK_CUR: + position = self._position + offset + elif whence == io.SEEK_END: + position = self._size + offset + else: + raise ValueError(f"invalid whence: {whence}") + if position < 0: + raise ValueError("negative seek position") + self._position = position + return position + + def read_range(self, offset: int, length: int) -> bytes: + """Read a byte range without changing the cursor; truncate at EOF.""" + self._checkClosed() + offset, length = operator.index(offset), operator.index(length) + if offset < 0 or length < 0: + raise ValueError("offset and length must be nonnegative") + remaining = min(length, max(0, self._size - offset)) + chunks = [] + while remaining: + count = min(remaining, _READ_CHUNK_BYTES) + chunk = self._read_range(offset, count) + if len(chunk) != count: + raise OSError("blob range reader returned an invalid payload length") + chunks.append(chunk) + offset += count + remaining -= count + return b"".join(chunks) + + def read(self, size: int = -1) -> bytes: + self._checkClosed() + size = -1 if size is None else operator.index(size) + if size < 0: + size = max(0, self._size - self._position) + data = self.read_range(self._position, size) + self._position += len(data) + return data + + def readinto(self, buffer) -> int: + view = memoryview(buffer).cast("B") + data = self.read(len(view)) + view[: len(data)] = data + return len(data) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 7f5776b32..42c4b27e1 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -33,6 +33,7 @@ from typing import ( Annotated, Any, Callable, + Literal, Optional, Union, get_args, @@ -52,7 +53,9 @@ from pydantic import ( model_validator, ) +from .schema import blob as _blob_field from .schema import is_blob_v2_field as _is_blob_v2_field +from ._blob_reader import BlobReader from .secrets import EnvVarSecret _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) @@ -213,6 +216,7 @@ class FunctionParameter(_RemoteValue): name: str arrow_type: str nullable: bool + blob_access: Optional[Literal["bytes", "reader"]] = None class FunctionResultField(_OpenRemoteValue): @@ -1096,6 +1100,43 @@ def _infer_signature( if (input_schema is None) != (output_schema is None): raise ValueError("input_schema and output_schema must be provided together") + try: + annotations = get_type_hints(function, include_extras=True) + except Exception as error: + raise TypeError(f"failed to resolve Function annotations: {error}") from error + + def input_parameter(field): + annotation = annotations.get(field.name) + if get_origin(annotation) in (Union, types.UnionType): + choices = [ + value for value in get_args(annotation) if value is not type(None) + ] + if len(choices) == 1: + annotation = choices[0] + arrow_type = _canonical_arrow_field(field) + if annotation is BlobReader: + if arrow_type != _FUNCTION_BLOB_V2_TYPE: + raise TypeError( + f"BlobReader input '{field.name}' requires a Blob V2 field" + ) + access = "reader" + elif annotation is bytes: + if arrow_type != _FUNCTION_BLOB_V2_TYPE and not ( + pa.types.is_binary(field.type) or pa.types.is_large_binary(field.type) + ): + raise TypeError( + f"bytes input '{field.name}' requires binary or Blob V2" + ) + access = "bytes" + else: + access = "bytes" if arrow_type == _FUNCTION_BLOB_V2_TYPE else None + return FunctionParameter( + name=field.name, + arrow_type=arrow_type, + nullable=field.nullable, + blob_access=access, + ) + if input_schema is not None: if not isinstance(input_schema, pa.Schema): raise TypeError("input_schema must be a PyArrow Schema") @@ -1110,20 +1151,9 @@ def _infer_signature( "input_schema fields must exactly match callable parameters in order: " f"expected {expected!r}, got {actual!r}" ) - inputs = tuple( - FunctionParameter( - name=field.name, - arrow_type=_canonical_arrow_field(field), - nullable=field.nullable, - ) - for field in input_schema - ) + inputs = tuple(input_parameter(field) for field in input_schema) return FunctionSignature(inputs=inputs, output=_function_output(output_schema)) - try: - annotations = get_type_hints(function, include_extras=True) - except Exception as error: - raise TypeError(f"failed to resolve Function annotations: {error}") from error missing = [ parameter.name for parameter in parameters if parameter.name not in annotations ] @@ -1132,15 +1162,21 @@ def _infer_signature( raise TypeError(f"missing Function annotations: {names!r}") inputs = [] for parameter in parameters: - data_type, nullable = _annotation_type(annotations[parameter.name]) - inputs.append( - FunctionParameter( - name=parameter.name, - arrow_type=_canonical_arrow_field( - pa.field(parameter.name, data_type, nullable=nullable) - ), - nullable=nullable, + annotation = annotations[parameter.name] + base = annotation + nullable = False + if get_origin(base) in (Union, types.UnionType): + choices = [value for value in get_args(base) if value is not type(None)] + if len(choices) == 1: + base, nullable = choices[0], True + if base is BlobReader: + inputs.append( + input_parameter(_blob_field(parameter.name, nullable=nullable)) ) + continue + data_type, nullable = _annotation_type(annotation) + inputs.append( + input_parameter(pa.field(parameter.name, data_type, nullable=nullable)) ) output_type, output_nullable = _annotation_type(annotations["return"]) if output_nullable: @@ -1239,7 +1275,7 @@ _PYTHON_CALLABLE_ARTIFACT = "python_callable" _PYTHON_BUNDLE_ARTIFACT = "python_bundle" # Modules the Function image places beside user code. _RESERVED_SOURCE_MODULES = frozenset( - {"user_function", "lance_source", "lance_callable"} + {"user_function", "lance_source", "lance_callable", "lance_blob"} ) # The service accepts bundle paths made of these components only. _SOURCE_PATH_COMPONENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") @@ -1499,6 +1535,8 @@ class _SourcePackager: """One module-level line that rebinds `name` to `value` in the artifact: an import for modules and importable classes/functions, a literal otherwise.""" + if value is BlobReader: + return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): if value.__name__.split(".")[0] in _NAMESPACE_MODULES: raise ValueError( diff --git a/python/python/tests/test_blob_reader.py b/python/python/tests/test_blob_reader.py new file mode 100644 index 000000000..dd12409af --- /dev/null +++ b/python/python/tests/test_blob_reader.py @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import io + +import pytest + +from lancedb import BlobReader + + +def test_reader_is_lazy_and_seekable(): + requests = [] + size = 64 * 1024 * 1024 + + def read_range(offset, length): + requests.append((offset, length)) + return bytes((index % 251 for index in range(offset, offset + length))) + + with BlobReader(read_range, size) as reader: + assert requests == [] + assert reader.size() == size + reader.seek(-4, io.SEEK_END) + assert reader.read(10) == bytes(index % 251 for index in range(size - 4, size)) + assert reader.read(1) == b"" + assert requests == [(size - 4, 4)] + assert reader.read_range(1, 3) == b"\x01\x02\x03" + assert reader.tell() == size + reader.seek(2) + target = bytearray(3) + assert reader.readinto(target) == 3 + assert target == b"\x02\x03\x04" + reader.seek(-1, io.SEEK_CUR) + assert reader.tell() == 4 + with pytest.raises(ValueError, match="closed"): + reader.read(1) + + +def test_reader_supports_buffered_io_and_bounds_range_requests(): + requests = [] + payload = b"x" * (3 * 1024 * 1024 + 7) + + def read_range(offset, length): + requests.append((offset, length)) + return payload[offset : offset + length] + + with io.BufferedReader(BlobReader(read_range, len(payload))) as reader: + assert reader.read() == payload + assert requests + assert all(length <= 1024 * 1024 for _, length in requests) + + +def test_reader_rejects_invalid_ranges_and_short_reads(): + reader = BlobReader(lambda offset, length: b"", 10) + with pytest.raises(ValueError): + reader.seek(-1) + with pytest.raises(ValueError): + reader.read_range(-1, 1) + with pytest.raises(OSError, match="payload length"): + reader.read(1) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 9ee3e388a..874034564 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -23,6 +23,7 @@ import pyarrow as pa import pytest import lancedb +from lancedb import BlobReader from lancedb.functions import ( PythonRuntimeSpec, SecretBinding, @@ -966,6 +967,60 @@ def test_blob_fields_use_the_scalar_function_semantic_type(): assert signature.output.arrow_type == "blob_v2" +def test_blob_input_access_is_inferred_from_annotations(): + @udf + def read_blob(video: BlobReader, timestamp_s: float) -> bytes: + video.seek(int(timestamp_s)) + return video.read(4) + + @udf + def read_bytes(video: bytes) -> int: + return len(video) + + reader = read_blob.registration_request.signature + assert reader.inputs[0].arrow_type == "blob_v2" + assert reader.inputs[0].blob_access == "reader" + assert reader.inputs[1].blob_access is None + assert reader.output.arrow_type == "binary" + eager = read_bytes.registration_request.signature.inputs[0] + assert eager.arrow_type == "binary" + assert eager.blob_access == "bytes" + encoded = json.loads(read_blob.registration_request.to_canonical_json()) + assert encoded["signature"]["inputs"][0]["blob_access"] == "reader" + + +def test_nullable_blob_reader_and_explicit_blob_bytes(): + @udf + def nullable(video: Optional[BlobReader]) -> int: + return 0 if video is None else video.size() + + @udf( + input_schema=pa.schema([lancedb.blob("video", nullable=False)]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def eager(video: bytes) -> int: + return len(video) + + parameter = nullable.registration_request.signature.inputs[0] + assert parameter.nullable is True + assert parameter.blob_access == "reader" + parameter = eager.registration_request.signature.inputs[0] + assert parameter.arrow_type == "blob_v2" + assert parameter.blob_access == "bytes" + + +def test_blob_reader_rejects_an_incompatible_explicit_schema(): + def read(video: BlobReader) -> int: + return video.size() + + with pytest.raises(TypeError, match="requires a Blob V2 field"): + udf( + read, + input_schema=pa.schema([pa.field("video", pa.int64(), nullable=False)]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + + def test_whole_named_struct_function_can_include_a_blob_result_field(): @udf( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 98d915118..36e6c30c8 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -156,11 +156,20 @@ pub struct FunctionArtifact { } /// One ordered Arrow input parameter. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BlobAccess { + Bytes, + Reader, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionParameter { pub name: String, pub arrow_type: String, pub nullable: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blob_access: Option, } /// One field of an ordered named-struct result. @@ -956,6 +965,20 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn blob_reader_access_survives_signature_round_trip() { + let parameter: FunctionParameter = serde_json::from_value(serde_json::json!({ + "name": "video", "arrow_type": "blob_v2", "nullable": false, + "blob_access": "reader" + })) + .unwrap(); + assert_eq!(parameter.blob_access, Some(BlobAccess::Reader)); + assert_eq!( + serde_json::to_value(parameter).unwrap()["blob_access"], + "reader" + ); + } + /// Canonical form is what the FunctionVersion hash is taken over, so key /// order must come from the keys and not from however serde happened to /// emit them. Nesting is included because the sort is recursive. From 24c2669a50d31ad14fb763bbdd1e236a5087b0b7 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 25 Oct 2026 00:47:29 -0700 Subject: [PATCH 097/180] feat(sql): follow adaptive streaming and polling responses (#4664) SQL execution now starts with one Flight call. The server can stream rows immediately or return a polling continuation, which the SDK follows through the existing query handle and reader APIs. The same behavior applies with and without parameters. Both initial transports share direct-stream lifecycle handling. Handoffs are explicitly negotiated; existing servers can continue returning ordinary streams. Add coverage for streaming, deferred results, cancellation, malformed decisions, and legacy responses. ```mermaid flowchart TD A[execute_query or execute_query_async] --> B{Parameters supplied?} B -->|No| C[DoGet: SQL command ticket] B -->|Yes| D[DoExchange: SQL and Arrow parameter row] C --> E[Server chooses execution path] D --> E E -->|Stream| F[Initial response: streaming decision and Arrow batches] E -->|Defer| G[Initial response: PollInfo continuation] G --> H[SDK follows PollFlightInfo] H -->|Still running| H H -->|Result endpoints available| I[SDK fetches tickets with DoGet] F --> J[Query reader yields Arrow batches] I --> J ``` `execute_query` opens the reader; `execute_query_async` returns its query handle. The caller does not select the transport or execution path. --- docs/src/python/python.md | 13 +- docs/web/basics/sql.mdx | 2 + python/python/lancedb/db.py | 13 +- rust/lancedb/src/connection.rs | 10 +- rust/lancedb/src/remote/sql.rs | 86 ++++--- .../src/remote/sql/{exchange.rs => stream.rs} | 191 +++++++++++----- rust/lancedb/src/remote/sql_test.rs | 212 +++++++++++++++++- rust/lancedb/src/sql.rs | 20 +- 8 files changed, 414 insertions(+), 133 deletions(-) rename rust/lancedb/src/remote/sql/{exchange.rs => stream.rs} (69%) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5d1393924..41d3e16d7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -221,10 +221,19 @@ The connected database and `default_namespace_path=["public"]` are used for unqualified tables. Fully qualified references can still query other databases and namespaces available to the same deployment. `execute_query` returns a reader as soon as its initial result stream is available. `execute_query_async` -returns a query handle immediately; use it to inspect progress, open a reader, +returns a query handle once submission is accepted; use it to inspect progress, open a reader, or cancel the query. The SQL client is initialized by the first query and retained for the lifetime of the remote connection. Query ids are random, -connection-scoped references rather than encoded SQL or durable resume tokens: +connection-scoped references rather than encoded SQL or durable resume tokens. + +Both APIs start with one Flight call. The server can stream results on that +call or return a polling continuation that the SDK follows automatically. +This behavior is the same with and without parameters. Open the reader directly; +a directly streamed query needs its reader to make progress. Dropping an unread +handle or its reader stops direct streaming. Deferred execution continues until +explicitly cancelled. + +For example: ```python import lancedb diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 1c4ad46cd..c89bd7a20 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -82,6 +82,8 @@ In application code, load credentials from environment variables or a secrets manager. The [connection guide](/basics/connect#enterprise) shows that setup. `execute_query()` returns a blocking Arrow reader when results start arriving. +The server can stream rows on the first call or return result tickets that the +SDK follows automatically, with the same behavior for parameterized queries. The example uses `read_all()` to collect the small result in memory. For larger results, consume the reader in batches. To submit a query and check its status separately, use `execute_query_async()`. See [Queries](/basics/query) for query diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 74acc28ba..8e53eac04 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1253,12 +1253,13 @@ class DBConnection(EnforceOverrides): parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10], ) - Parameters are supported in queries, not in DDL or DML. A - parameterized query runs on the call that returns its rows: - cancelling it, or dropping its handle before reading, stops it on the - server. Its status follows that stream as well: ``describe()`` - reports ``running`` until the reader has received every row, so open - ``reader()`` directly rather than waiting for ``finished``. + Parameters are supported in queries, not in DDL or DML. With or + without parameters, the server chooses whether to stream rows on the + initial call or return a polling continuation. The reader follows + either path transparently. Dropping an unread handle or its reader + stops a directly streamed query; deferred execution requires explicit + cancellation. Open ``reader()`` directly: a streamed query needs its + reader to make progress and reports ``running`` until the stream ends. Local connections do not support SQL. """ diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 482acf89a..26afef5e8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -372,12 +372,10 @@ impl ExecuteQueryAsyncBuilder { /// Do not follow a named placeholder directly with `$`: `$a$` starts a /// dollar-quoted string. /// - /// A parameterized statement runs on the call that returns its rows rather - /// than detached from it: cancelling the query, or dropping its handle - /// before reading it, stops the statement on the server. Its status follows - /// that stream too -- it reports `Running` until the reader has received - /// every row -- so open the reader directly rather than waiting for - /// `Finished`. + /// With or without parameters, the server may stream rows on the initial + /// call or return a polling continuation. The reader follows either path + /// transparently. Open it directly instead of waiting for `Finished`: + /// directly streamed queries need their reader to make progress. /// /// # Example /// diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index a58a9afad..d8f04119f 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -34,9 +34,9 @@ use crate::remote::client::{ClientConfig, TlsConfig}; use crate::remote::retry::ResolvedRetryConfig; use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; -mod exchange; +mod stream; -use exchange::{ExchangeQuery, ExchangeQueryHandle}; +use stream::{StreamingQuery, StreamingQueryHandle, Submission}; const DEFAULT_SQL_PORT: u16 = 10025; const DEFAULT_SQL_TLS_PORT: u16 = 10026; @@ -191,20 +191,39 @@ impl SqlClient { } pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { - match request.parameters { - Some(parameters) => { - self.submit_with_parameters( - &request.query, - parameters, - &request.default_namespace_path, - ) - .await + let timeout = self.inner.overall_timeout()?; + with_overall_timeout(timeout, "SQL query submission", async { + validate_namespace_path(&request.default_namespace_path)?; + let query_id = Uuid::now_v7(); + let submission = StreamingQuery::open( + self.inner.clone(), + &request.query, + request.parameters, + &request.default_namespace_path, + ) + .await?; + match submission { + Submission::Stream(response) => { + let query = + Arc::new(StreamingQuery::new(query_id, self.inner.clone(), response)); + self.queries + .insert(query_id, RegisteredQuery::Streamed(query.clone())); + Ok(Query::new(Arc::new(StreamingQueryHandle::new(query)))) + } + Submission::Deferred(poll_info) => { + let query = Arc::new(RemoteQuery::new( + query_id, + self.inner.clone(), + request.default_namespace_path, + poll_info, + )?); + self.queries + .insert(query_id, RegisteredQuery::Polled(query.clone())); + Ok(Query::new(Arc::new(RemoteQueryHandle::new(query)))) + } } - None => { - self.submit(&request.query, &request.default_namespace_path) - .await - } - } + }) + .await } pub(super) async fn submit( @@ -271,35 +290,6 @@ impl SqlClient { }) } - /// Values cannot ride on a poll, so a statement that has them is sent on - /// its own exchange instead. - pub(super) async fn submit_with_parameters( - &self, - query: &str, - parameters: RecordBatch, - default_namespace_path: &[String], - ) -> Result { - let timeout = self.inner.overall_timeout()?; - with_overall_timeout(timeout, "SQL query submission", async { - validate_namespace_path(default_namespace_path)?; - let query_id = Uuid::now_v7(); - let query = Arc::new( - ExchangeQuery::open( - query_id, - self.inner.clone(), - query, - parameters, - default_namespace_path, - ) - .await?, - ); - self.queries - .insert(query_id, RegisteredQuery::Exchanged(query.clone())); - Ok(Query::new(Arc::new(ExchangeQueryHandle::new(query)))) - }) - .await - } - pub(super) async fn describe(&self, query_id: Uuid) -> Result { let query = self .queries @@ -586,14 +576,14 @@ impl SqlClientInner { #[derive(Clone)] enum RegisteredQuery { Polled(Arc), - Exchanged(Arc), + Streamed(Arc), } impl RegisteredQuery { fn touch(&self) { match self { Self::Polled(query) => query.touch(), - Self::Exchanged(query) => query.touch(), + Self::Streamed(query) => query.touch(), } } @@ -602,14 +592,14 @@ impl RegisteredQuery { fn registry_expired(&self) -> bool { match self { Self::Polled(query) => query.registry_expired(Arc::strong_count(query) == 1), - Self::Exchanged(query) => query.registry_expired(Arc::strong_count(query) == 1), + Self::Streamed(query) => query.registry_expired(Arc::strong_count(query) == 1), } } async fn describe(&self) -> Result { match self { Self::Polled(query) => query.describe().await, - Self::Exchanged(query) => query.describe(), + Self::Streamed(query) => query.describe(), } } } diff --git a/rust/lancedb/src/remote/sql/exchange.rs b/rust/lancedb/src/remote/sql/stream.rs similarity index 69% rename from rust/lancedb/src/remote/sql/exchange.rs rename to rust/lancedb/src/remote/sql/stream.rs index 523aaf5d7..ed85c6c92 100644 --- a/rust/lancedb/src/remote/sql/exchange.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -1,26 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! SQL statements sent with parameters. -//! -//! A statement without parameters is polled: `PollFlightInfo` starts it -//! detached from the connection and `DoGet` reads its endpoints. Neither call -//! carries Arrow data, so a statement's values would have to be spelled into -//! its text. A statement with parameters is sent on one `DoExchange` instead: -//! the command and the parameter schema, then one row, and the result rows -//! come back on the same call. The call is the statement's lifetime, so -//! cancelling it -- or dropping the handle before reading -- stops the -//! statement on the server. +//! SQL submitted on one call, with either streamed rows or a polling handoff. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex as StdMutex, OnceLock}; use std::time::Instant; use arrow_array::RecordBatch; -use arrow_flight::FlightDescriptor; +use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::encode::FlightDataEncoderBuilder; -use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; +use arrow_flight::sql::{Any, CommandStatementQuery, ProstMessageExt}; +use arrow_flight::{FlightDescriptor, PollInfo, Ticket}; use arrow_schema::SchemaRef; +use futures::TryStreamExt; use prost::Message; use tokio::sync::{Notify, mpsc}; use uuid::Uuid; @@ -51,8 +44,8 @@ fn failure(error: &Error) -> Lifecycle { }) } -/// A statement running on its own `DoExchange` call. -pub(super) struct ExchangeQuery { +/// A statement streaming on its initial `DoGet` or `DoExchange` call. +pub(super) struct StreamingQuery { id: Uuid, client: Arc, /// The call's rows, until a reader takes them or a cancellation drops them. @@ -63,7 +56,7 @@ pub(super) struct ExchangeQuery { last_accessed: StdMutex, } -struct PreparedExchange { +struct PreparedStream { schema: SchemaRef, first: Option, rest: Option, @@ -76,7 +69,7 @@ struct PreparedExchange { /// this one did. A query cancelled meanwhile has its rows dropped instead, /// which ends the call. struct Borrowed<'a> { - query: &'a ExchangeQuery, + query: &'a StreamingQuery, rows: Option, } @@ -104,18 +97,37 @@ impl Drop for Borrowed<'_> { } } -impl ExchangeQuery { - /// Send the statement and its parameters, returning once the server has - /// planned it: a statement it refuses is refused here, as a polled one is - /// on its first poll. +pub(super) const PROTOCOL_HEADER: &str = "lancedb-sql-protocol"; +pub(super) const PROTOCOL_VERSION: &str = "adaptive-v1"; +const RESPONSE_TYPE_URL: &str = "type.googleapis.com/lancedb.sql.QueryResponse"; + +#[derive(Clone, PartialEq, Message)] +pub(super) struct QueryResponse { + #[prost(message, optional, tag = "1")] + pub poll_info: Option, +} + +#[derive(Clone, PartialEq, Message)] +struct CommandTicket { + #[prost(bytes = "vec", tag = "2")] + command: Vec, +} + +pub(super) enum Submission { + Stream(ResultEndpointStream), + Deferred(PollInfo), +} + +impl StreamingQuery { pub(super) async fn open( - id: Uuid, client: Arc, query: &str, - parameters: RecordBatch, + parameters: Option, default_namespace_path: &[String], - ) -> Result { - if parameters.num_rows() != 1 { + ) -> Result { + if let Some(parameters) = ¶meters + && parameters.num_rows() != 1 + { return Err(Error::InvalidInput { message: format!( "SQL query parameters must be exactly one row, got {}", @@ -130,39 +142,102 @@ impl ExchangeQuery { Some(DEFAULT_READ_TIMEOUT), )? .unwrap(); - let descriptor = FlightDescriptor::new_cmd( - CommandStatementQuery { - query: query.to_string(), - transaction_id: None, + let command = CommandStatementQuery { + query: query.to_string(), + transaction_id: None, + } + .as_any() + .encode_to_vec(); + let connection = client.connection(&request_id).await?; + let headers = client.headers(default_namespace_path, &request_id).await?; + let mut metadata = super::client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + metadata.insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap()); + let mut flight = connection.client.clone(); + let response = if let Some(parameters) = parameters { + let messages = FlightDataEncoderBuilder::new() + .with_flight_descriptor(Some(FlightDescriptor::new_cmd(command))) + .with_schema(parameters.schema()) + .build(futures::stream::iter([Ok(parameters)])) + .try_collect::>() + .await + .map_err(|error| sql_error(&request_id, error))?; + let mut request = tonic::Request::new(futures::stream::iter(messages)); + *request.metadata_mut() = metadata; + tokio::time::timeout(read_timeout, flight.do_exchange(request)).await + } else { + let mut request = + tonic::Request::new(Ticket::new(CommandTicket { command }.encode_to_vec())); + *request.metadata_mut() = metadata; + tokio::time::timeout(read_timeout, flight.do_get(request)).await + } + .map_err(|_| sql_error(&request_id, "SQL query submission timed out"))? + .map_err(|error| sql_error(&request_id, error))?; + let negotiated = response + .metadata() + .get(PROTOCOL_HEADER) + .is_some_and(|value| value == PROTOCOL_VERSION); + let mut response_stream = response.into_inner(); + if negotiated { + let first = tokio::time::timeout(read_timeout, response_stream.message()) + .await + .map_err(|_| sql_error(&request_id, "SQL query handoff timed out"))? + .map_err(|error| sql_error(&request_id, error))? + .ok_or_else(|| { + sql_error(&request_id, "SQL response omitted its execution decision") + })?; + if !first.data_header.is_empty() || !first.data_body.is_empty() { + return Err(sql_error( + &request_id, + "SQL response sent rows before its execution decision", + )); } - .as_any() - .encode_to_vec(), + let envelope = + Any::decode(first.app_metadata).map_err(|error| sql_error(&request_id, error))?; + if envelope.type_url != RESPONSE_TYPE_URL { + return Err(sql_error( + &request_id, + "SQL response returned an unknown execution decision", + )); + } + let decision = QueryResponse::decode(envelope.value) + .map_err(|error| sql_error(&request_id, error))?; + if let Some(info) = decision.poll_info { + if info.info.is_none() && info.flight_descriptor.is_none() { + return Err(sql_error( + &request_id, + "SQL handoff omitted result and continuation information", + )); + } + return Ok(Submission::Deferred(info)); + } + } + let stream = FlightRecordBatchStream::new_from_flight_data( + response_stream + .map_err(|status| arrow_flight::error::FlightError::Tonic(Box::new(status))), ); - // The descriptor rides on the schema message, and the row follows it. - let request = FlightDataEncoderBuilder::new() - .with_flight_descriptor(Some(descriptor)) - .with_schema(parameters.schema()) - .build(futures::stream::iter([Ok(parameters)])); - let mut flight = client - .client_with_headers(default_namespace_path, &request_id) - .await?; - let stream = tokio::time::timeout(read_timeout, flight.do_exchange(request)) - .await - .map_err(|_| sql_error(&request_id, "SQL query submission timed out"))? - .map_err(|err| sql_error(&request_id, err))?; - Ok(Self { + Ok(Submission::Stream(ResultEndpointStream { + stream, + request_id, + read_timeout, + })) + } + + pub(super) fn new( + id: Uuid, + client: Arc, + response: ResultEndpointStream, + ) -> Self { + Self { id, client, - response: StdMutex::new(Some(ResultEndpointStream { - stream, - request_id, - read_timeout, - })), + response: StdMutex::new(Some(response)), lifecycle: StdMutex::new(Lifecycle::Running), cancelled: Notify::new(), terminal_at: OnceLock::new(), last_accessed: StdMutex::new(Instant::now()), - }) + } } pub(super) fn touch(&self) { @@ -242,7 +317,7 @@ impl ExchangeQuery { } /// Take the rows and wait for the first batch, which carries the schema. - async fn prepare(&self) -> Result { + async fn prepare(&self) -> Result { let Some(rows) = self.response.lock().unwrap().take() else { // Taken by an earlier attempt that failed, or dropped by a cancel. return Err(match &*self.lifecycle.lock().unwrap() { @@ -275,7 +350,7 @@ impl ExchangeQuery { if first.is_none() { self.settle(Lifecycle::Finished); } - Ok(PreparedExchange { + Ok(PreparedStream { schema, rest: first.is_some().then_some(rows), first, @@ -284,7 +359,7 @@ impl ExchangeQuery { async fn run( self: Arc, - mut prepared: PreparedExchange, + mut prepared: PreparedStream, sender: mpsc::Sender>, ) -> Result<()> { if let Some(batch) = prepared.first.take() @@ -343,13 +418,13 @@ impl ExchangeQuery { } } -pub(super) struct ExchangeQueryHandle { - query: Arc, +pub(super) struct StreamingQueryHandle { + query: Arc, result_started: AtomicBool, } -impl ExchangeQueryHandle { - pub(super) fn new(query: Arc) -> Self { +impl StreamingQueryHandle { + pub(super) fn new(query: Arc) -> Self { Self { query, result_started: AtomicBool::new(false), @@ -357,7 +432,7 @@ impl ExchangeQueryHandle { } } -impl Drop for ExchangeQueryHandle { +impl Drop for StreamingQueryHandle { // Rows nobody took are rows nobody will read. Keeping the call open would // hold the statement running on the server, stalled on flow control, // until the registry forgot it. @@ -369,7 +444,7 @@ impl Drop for ExchangeQueryHandle { } #[async_trait::async_trait] -impl QueryHandle for ExchangeQueryHandle { +impl QueryHandle for StreamingQueryHandle { fn id(&self) -> Uuid { self.query.touch(); self.query.id diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 79ca339db..4837baab7 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -19,6 +19,7 @@ use futures::{StreamExt, TryStreamExt}; use tonic::metadata::MetadataMap; use tonic::{Request, Response, Status, Streaming}; +use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::database::Database; use crate::remote::RemoteCatalogOptions; @@ -70,6 +71,9 @@ type ReceivedExchanges = Arc)> #[derive(Clone)] struct TestSqlService { + adaptive: bool, + defer: bool, + invalid_decision: bool, query_count: Arc, do_get_count: Arc, cancel_count: Arc, @@ -120,6 +124,51 @@ impl TestSqlService { .unwrap_or_default(), }); } + fn adaptive_response( + &self, + query: &str, + rows: BoxStream<'static, std::result::Result>, + ) -> Response>> { + if !self.adaptive { + return Response::new(rows); + } + let poll_info = + self.defer.then(|| PollInfo { + info: Some(FlightInfo::new().with_endpoint( + FlightEndpoint::new().with_ticket(Ticket::new(query.to_string())), + )), + flight_descriptor: Some(FlightDescriptor::new_cmd(format!("poll:1:{query}"))), + progress: Some(0.25), + expiration_time: None, + }); + let first = FlightData { + app_metadata: if self.invalid_decision { + b"invalid protobuf".to_vec().into() + } else { + Any { + type_url: "type.googleapis.com/lancedb.sql.QueryResponse".to_string(), + value: QueryResponse { poll_info }.encode_to_vec().into(), + } + .encode_to_vec() + .into() + }, + ..Default::default() + }; + let rest = if self.defer { + futures::stream::empty().boxed() + } else { + rows + }; + let mut response = Response::new( + futures::stream::once(async { Ok(first) }) + .chain(rest) + .boxed(), + ); + response + .metadata_mut() + .insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap()); + response + } } impl Default for TestSqlService { @@ -154,6 +203,9 @@ impl Default for TestSqlService { let dictionary_result = RecordBatch::try_new(dictionary_schema, vec![Arc::new(dictionary)]).unwrap(); Self { + adaptive: false, + defer: false, + invalid_decision: false, query_count: Arc::new(AtomicUsize::new(0)), do_get_count: Arc::new(AtomicUsize::new(0)), cancel_count: Arc::new(AtomicUsize::new(0)), @@ -308,7 +360,22 @@ impl FlightService for TestSqlService { request: Request, ) -> std::result::Result::DoGetStream>, Status> { self.do_get_count.fetch_add(1, Ordering::SeqCst); - let ticket = request.get_ref().ticket.as_ref(); + let initial = Any::decode(request.get_ref().ticket.clone()) + .ok() + .and_then(|envelope| Any::decode(envelope.value).ok()) + .and_then(|command| command.unpack::().ok().flatten()); + if initial.is_some() { + self.capture_headers(request.metadata()); + assert_eq!( + request.metadata().get(PROTOCOL_HEADER).unwrap(), + PROTOCOL_VERSION + ); + } + let query = initial + .as_ref() + .map(|command| command.query.as_bytes()) + .unwrap_or(request.get_ref().ticket.as_ref()); + let ticket = query; let gate_refresh = ticket == b"REFRESH MATERIALIZED VIEW \"cancel_view\""; let empty = ticket == b"SELECT empty"; let slow = ticket == b"SELECT slow get"; @@ -337,7 +404,11 @@ impl FlightService for TestSqlService { encoder = encoder.with_max_flight_data_size(8 * 1024 * 1024); } let stream = encoder.build(input).map_err(Status::from); - Ok(Response::new(Box::pin(stream))) + if let Some(initial) = initial { + Ok(self.adaptive_response(&initial.query, stream.boxed())) + } else { + Ok(Response::new(stream.boxed())) + } } async fn do_put( @@ -486,7 +557,7 @@ impl FlightService for TestSqlService { let _dropped = &dropped; message }); - Ok(Response::new(Box::pin(stream))) + Ok(self.adaptive_response(&query, stream.boxed())) } } @@ -1609,3 +1680,138 @@ fn validates_metadata_with_header_map() { assert!(insert_header(&mut headers, "bad header", "value").is_err()); assert!(insert_header(&mut headers, "valid-header", "bad\nvalue").is_err()); } + +#[tokio::test] +async fn adaptive_streams_start_on_one_rpc_for_both_inputs() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let polls = service.query_count.clone(); + let gets = service.do_get_count.clone(); + let exchanges = service.exchanges.clone(); + let expected = parameters.clone().unwrap_or_else(|| service.result.clone()); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let with_parameters = parameters.is_some(); + let query = client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT echo") + }) + .await + .unwrap(); + assert_eq!(query.describe().await.unwrap().status, QueryStatus::Running); + assert_eq!(collect_result(&query).await.unwrap(), vec![expected]); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + assert!(query.reader().await.is_err()); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert_eq!(gets.load(Ordering::SeqCst), usize::from(!with_parameters)); + assert_eq!( + exchanges.lock().unwrap().len(), + usize::from(with_parameters) + ); + } +} + +#[tokio::test] +async fn adaptive_handoffs_share_polling_and_survive_handle_drop() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let polls = service.query_count.clone(); + let gets = service.do_get_count.clone(); + let exchanges = service.exchanges.clone(); + let expected = service.result.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let with_parameters = parameters.is_some(); + let query = client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT adaptive") + }) + .await + .unwrap(); + let id = query.id(); + assert_eq!(collect_result(&query).await.unwrap(), vec![expected]); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Finished + ); + assert!(query.reader().await.is_err()); + drop(query); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "the original SQL must not be resubmitted through polling" + ); + assert_eq!( + gets.load(Ordering::SeqCst), + 1 + usize::from(!with_parameters) + ); + assert_eq!( + exchanges.lock().unwrap().len(), + usize::from(with_parameters) + ); + } +} + +#[tokio::test] +async fn adaptive_handoffs_use_server_cancellation_for_both_inputs() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let cancels = service.cancel_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let query = client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT cancel") + }) + .await + .unwrap(); + query.cancel().await.unwrap(); + assert_eq!(cancels.load(Ordering::SeqCst), 1); + assert_eq!( + query.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + assert!(query.reader().await.is_err()); + } +} + +#[tokio::test] +async fn malformed_adaptive_decision_never_resubmits_the_statement() { + for parameters in [None, Some(parameter_row())] { + let service = TestSqlService { + adaptive: true, + invalid_decision: true, + ..Default::default() + }; + let polls = service.query_count.clone(); + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + assert!( + client + .execute(ExecuteQueryRequest { + parameters, + ..ExecuteQueryRequest::new("SELECT invalid") + }) + .await + .is_err() + ); + assert_eq!(polls.load(Ordering::SeqCst), 0); + } +} diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index c2ef13ba5..fee2d5d79 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -18,9 +18,9 @@ pub enum QueryStatus { Running, /// The server has made the complete result available. /// - /// A query submitted with parameters streams its rows on the call that - /// runs it, so it reports `Finished` only once its reader has received - /// the last batch. Read it rather than waiting for this status. + /// Directly streamed queries report `Finished` when their stream reaches + /// its end. Deferred queries report the server's execution state. Open the + /// reader directly instead of waiting for this status before reading. Finished, /// The server accepted cancellation but has not confirmed it yet. Cancelling, @@ -64,9 +64,10 @@ pub(crate) trait QueryHandle: Send + Sync { /// A handle to a submitted SQL query. /// /// The handle can be inspected, opened as an Arrow reader, or cancelled. -/// Dropping it does not cancel the server-side query, unless the query was -/// submitted with parameters: those run on the call that returns their rows, -/// so dropping the handle before reading, or dropping the reader, stops them. +/// The server may stream results on the initial call or defer execution and +/// return result tickets. Dropping an unread handle or its reader stops a +/// directly streamed query; deferred execution continues until explicitly +/// cancelled. This applies equally with and without parameters. /// Identifier lookup is scoped to the connection that submitted the query and /// is not a durable resume mechanism. pub struct Query { @@ -95,10 +96,9 @@ impl Query { /// Get a point-in-time description of the query. /// - /// For a query submitted with parameters the status follows its result - /// stream: it stays [`QueryStatus::Running`] until the reader has received - /// every row, so open [`Self::reader`] directly instead of polling for - /// [`QueryStatus::Finished`] first. + /// Directly streamed queries stay [`QueryStatus::Running`] until the result + /// stream ends. Deferred queries expose the server's execution state. Open + /// [`Self::reader`] directly instead of waiting for [`QueryStatus::Finished`]. pub async fn describe(&self) -> Result { self.handle.describe().await } From 9af77570532c57029a47c7d47481b5cc12a9e2fe Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 25 Oct 2026 01:20:13 -0700 Subject: [PATCH 098/180] fix: execute remote materialized view creation through SQL (#4665) Remote materialized-view creation currently expects a REST response containing a registry job ID, while refresh already submits SQL. Route both through the SQL query backend and preserve Python's synchronous and asynchronous return types. ### Query to Job mapping `SqlClient::submit_as_job()` submits an `ExecuteQueryRequest` through the same backend as `execute_query_async()`. Once submission succeeds, it retains the returned `Query` and starts one client-side task that consumes its result reader to completion. `Job::from_query_task()` wraps that task, its cached outcome, a single ID and a cancellation callback. Python exposes this as `Job[T]` or `AsyncJob[T]`. The existing `job_type` property maps SQL-backed handles to the new `"query"` kind. The shared `id` contains that query's UUID string, so Python callers can inspect it with `db.describe_query(job.id)` on the submitting connection. No separate `query_id`, backend enum or `type()` API is added. | Handle | `job_type` | `id` | Available lookup | | --- | --- | --- | --- | | SQL-backed | `"query"`, known at submission | Connection-scoped query UUID string | `describe_query(job.id)` | | Registry-backed | Existing server-reported kind, after `status()` or `refresh()` | Registry job ID string | Registry job APIs, descriptions and events | | Local | `None` | `None` | The current in-process handle | | Job concept | SQL-backed behavior | | --- | --- | | Submission | Await initial SQL submission before returning the handle. Submission errors propagate immediately. | | `status()` | Tracks the adapter task: running during result consumption/finalization, finished after both succeed, failed if either fails, or cancelled after cancellation. | | `wait()` | Returns the operation's typed terminal result. One task consumes the query reader once; repeated waits reuse its cached outcome without resubmitting SQL or reopening the reader. | | `cancel()` | Delegates to `Query.cancel()`. Rejected or unsupported cancellation leaves the task running; an accepted request stops the task. Cancelling a finished operation is a no-op. | | Registry details | Query-backed handles expose no registry description, event history, pause/resume or reattachment after a client restart. `refresh()` updates cached lifecycle state. | The Job tracks command completion rather than exposing SQL batches. A wait timeout does not cancel the query. Query IDs remain scoped to the submitting connection and cannot be used with registry APIs or as durable resume tokens. Python `describe_query()` accepts both UUID objects and the string `id` exposed by query-backed jobs. Rust, Python and TypeScript expose the same classification through their existing job-type accessors. ### Materialized-view operations - **CREATE:** Render `CREATE MATERIALIZED VIEW` with the view namespace and optional auto-refresh settings. After command completion, resolve the job to `None`. Synchronous creation waits on the job, then opens and returns the materialized view. - **REFRESH:** Submit `REFRESH MATERIALIZED VIEW` through the same adapter. After command completion, read the refreshed table's version and row count to construct the existing typed refresh result. Synchronous refresh waits on the same path. Remote creation requires the SQL service. Execution placement remains a server decision. REST endpoints are unchanged. The job guide documents the ID/job-type contract and query-backed limitations. Regression coverage exercises SQL submission, namespaces, refresh options, job-type/ID preservation through typed result mapping, repeated waits, failures and cancellation rejection. No local builds or tests were run. --- docs/src/js/classes/Job.md | 13 +- docs/web/basics/jobs.mdx | 37 ++++- nodejs/__test__/materialized_view.test.ts | 1 + nodejs/lancedb/job.ts | 13 +- nodejs/src/job.rs | 12 +- python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 25 ++- python/python/lancedb/job.py | 30 ++-- python/python/lancedb/namespace.py | 2 +- python/python/lancedb/remote/db.py | 2 +- .../tests/test_first_class_function_slice2.py | 4 + .../python/tests/test_materialized_views.py | 87 +++++++--- python/python/tests/test_sql.py | 20 ++- python/src/job.rs | 5 + rust/lancedb/src/job.rs | 76 +++++++-- rust/lancedb/src/materialized_view.rs | 3 +- rust/lancedb/src/remote/db.rs | 144 ++++++----------- rust/lancedb/src/remote/sql.rs | 45 +++--- rust/lancedb/src/remote/sql_test.rs | 152 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 8 +- 20 files changed, 465 insertions(+), 216 deletions(-) diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index cfbe454ec..74e1c00e2 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -17,7 +17,8 @@ extra round trip on every call: - [Job.refresh](Job.md#refresh) and [Job.status](Job.md#status) fetch the whole record. - [Job.wait](Job.md#wait) records the terminal state it establishes, but not the rest of the record. -- Everything is null until one of those runs. +- Registry details are null until one of those runs. Query handles report + jobType "query" immediately. ## Accessors @@ -57,8 +58,10 @@ get id(): null | string Identifies the operation on the server that is running it. -Operations that run in this process have no server id. The value is -opaque: parsing it or storing it to resume the job later is not supported. +Registry handles expose a registry job ID; query handles expose a +connection-scoped SQL query UUID string. Local handles have no ID. +Query handles report jobType "query". Their IDs are not registry IDs or +durable resume tokens. #### Returns @@ -72,8 +75,8 @@ opaque: parsing it or storing it to resume the job later is not supported. get jobType(): null | string ``` -The job's type, as the server names it. Null for an in-process job, which -has no server-side record. +"query" immediately for SQL-backed handles; otherwise the cached +server-reported job type. Null for in-process handles. #### Returns diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 0577cd120..a87663a51 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -20,19 +20,20 @@ failures. Methods such as Python's `create_index_async` and TypeScript's `createIndexAsync` return job handles. In OSS, the work runs in your application -process; in Enterprise, it runs on server workers. A returned handle can -represent an operation that has already finished, so check its status before +process; in Enterprise, it runs on server workers or through the SQL query +backend. A returned handle can represent an operation that has already finished, +so check its status before waiting or requesting cancellation. See the operation's API reference for when the method returns. ## Submit and wait for a job {#waiting} 1. **Submit the operation.** Keep the returned job handle. For an Enterprise - job, also keep its ID if another process needs to look it up later. + registry job, also keep its ID if another process needs to look it up later. 2. **Check progress.** Read the current status while the operation runs. 3. **Wait for completion.** Check that the job succeeded before using its - result. If it failed or was cancelled, inspect the failure details and any - results it committed before stopping. + result. If it failed or was cancelled, inspect the failure details and any + results it committed before stopping. In Python, `job.status()` reports the current state and `job.wait()` waits for completion, raising if the job fails or is cancelled. If `job.wait()` times out, the client stops waiting. @@ -59,13 +60,37 @@ history. ## OSS and Enterprise execution {#in-process} -| | OSS | Enterprise | +The following table describes local operations and Enterprise registry jobs. +SQL-backed job handles follow the query lifecycle described below. + +| | OSS | Enterprise registry job | | --- | --- | --- | | Execution | In your application process | On server workers | | Job identity | No server ID | A server ID for looking up the job | | Event history | No server event history | Available through the jobs API | | Reattaching after a client restart | No server job to reopen | Reopen by ID while the record is retained | +### SQL-backed job handles + +Remote materialized-view CREATE and REFRESH use the SQL query backend. Python's +`create_materialized_view_async()` and `mv.refresh_async()` still return job +handles with `status()`, `wait()` and `cancel()`. Synchronous creation and refresh +wait on the same SQL execution before returning. + +The existing `job.job_type` identifies query-backed handles as `"query"` from +submission, and `job.id` contains the connection-scoped SQL query UUID string. +Use `describe_query(job.id)` on the submitting connection to inspect the query. +Registry handles retain their server-reported job types (available after +`status()` or `refresh()`) and registry IDs. Local handles have no ID or job type. + +SQL-backed handles do not expose registry records or event history and cannot +be reopened through `open_job()` or reattached after a client restart. Their IDs +are not durable resume tokens. Cancellation follows the SQL server's +capabilities and can be unsupported. + +The server decides whether SQL executes on its serving fleet or starts SQL job +workers. That placement does not change the handle's query-backed identity. + ## Learn more {#next} - [Build and repair indexes](/indexing/reindexing): submit index work. diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index 3e47a00e9..3852af717 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -129,6 +129,7 @@ describe("materialized views", () => { const job = await db.dropMaterializedViewAsync("adults"); expect(job.id).toBeNull(); + expect(job.jobType).toBeNull(); await job.wait(); expect(await collect(db.listMaterializedViews())).toEqual([]); }); diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index 0baa0f571..1c8d74ad2 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -24,7 +24,8 @@ export interface JobEventsOptions { * - {@link Job.refresh} and {@link Job.status} fetch the whole record. * - {@link Job.wait} records the terminal state it establishes, but not the * rest of the record. - * - Everything is null until one of those runs. + * - Registry details are null until one of those runs. Query handles report + * jobType "query" immediately. * * @hideconstructor */ @@ -38,8 +39,10 @@ export class Job { /** * Identifies the operation on the server that is running it. * - * Operations that run in this process have no server id. The value is - * opaque: parsing it or storing it to resume the job later is not supported. + * Registry handles expose a registry job ID; query handles expose a + * connection-scoped SQL query UUID string. Local handles have no ID. + * Query handles report jobType "query". Their IDs are not registry IDs or + * durable resume tokens. */ get id(): string | null { return this.inner.id ?? null; @@ -51,8 +54,8 @@ export class Job { } /** - * The job's type, as the server names it. Null for an in-process job, which - * has no server-side record. + * "query" immediately for SQL-backed handles; otherwise the cached + * server-reported job type. Null for in-process handles. */ get jobType(): string | null { return this.inner.jobType ?? null; diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 214e687b4..320812128 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -29,8 +29,8 @@ impl Job { #[napi] impl Job { - /// Identifies the operation on the server that is running it. Operations - /// that run in this process have no server id. The value is opaque. + /// The operation's opaque ID. Interpret registry and query IDs using job_type(). + /// Local handles have no ID. #[napi(getter)] pub fn id(&self) -> Option { self.inner.id().map(str::to_string) @@ -62,8 +62,8 @@ impl Job { /// Ask the backend for this job's current state, and for a server-side job /// its full record, then cache it for the getters below. /// - /// They are all null until this runs, because submitting an operation - /// returns only a job id. {@link Job.status} fetches the whole record too; + /// Registry details are null until this runs; query handles already expose + /// job_type "query". {@link Job.status} fetches the whole registry record too; /// {@link Job.wait} records only the terminal state it establishes. #[napi(catch_unwind)] pub async fn refresh(&self) -> napi::Result<()> { @@ -76,8 +76,8 @@ impl Job { self.inner.state() } - /// The job's type, as the server names it. Null for an in-process job, - /// which has no server-side record. + /// "query" immediately for SQL-backed handles; otherwise the cached + /// server-reported job type. Null for in-process handles. #[napi(getter)] pub fn job_type(&self) -> Option { self.inner.job_type() diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 6ef23abc7..9e602cce8 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -320,6 +320,8 @@ class Job: @property def id(self) -> Optional[str]: ... @property + def job_type(self) -> Optional[str]: ... + @property def _state(self) -> Optional[str]: ... @property def _description(self) -> Optional[JobDescription]: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 8e53eac04..1558dd52a 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -674,10 +674,11 @@ class DBConnection(EnforceOverrides): ) -> Job[None]: """Submit materialized-view creation and return its job. - The job may already be complete for a local database. On LanceDB - Cloud and Enterprise, its ``id`` is the server job identifier from - the ``202 Accepted`` create response. Wait for the job before opening - or querying the view. + The job may already be complete for a local database. Remote creation + submits CREATE MATERIALIZED VIEW through the SQL server. Its job has + ``job_type == "query"`` and ``id`` identifies the connection-scoped + query. Registry event history is unavailable. + Wait for the job before opening or querying the view. """ raise NotImplementedError( "materialized views are not supported on this connection type" @@ -1265,7 +1266,7 @@ class DBConnection(EnforceOverrides): """ raise NotImplementedError("SQL is not supported for this connection type") - def describe_query(self, query_id: UUID) -> QueryDescription: + def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: """Describe a submitted SQL query by its connection-scoped id.""" raise NotImplementedError("SQL is not supported for this connection type") @@ -2869,7 +2870,9 @@ class AsyncConnection(object): ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. - Wait for the returned job before opening or querying the view. + Wait for the returned job before opening or querying the view. Remote + creation uses SQL; ``job_type`` is ``"query"`` and ``id`` + identifies that query on this connection. """ source, native_options = await self._materialized_view_source( source, select, where, limit @@ -3409,8 +3412,14 @@ class AsyncConnection(object): ) ) - async def describe_query(self, query_id: UUID) -> QueryDescription: - """Describe a submitted SQL query by its connection-scoped id.""" + async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: + """Describe a submitted SQL query by its UUID or string ID. + + For a handle with ``job_type == "query"``, pass its ``id`` on the + connection that submitted it. Registry job IDs are not query IDs. + """ + if isinstance(query_id, str): + query_id = UUID(query_id) return await self._inner.describe_query(query_id) async def namespace_client(self) -> LanceNamespace: diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index e57fde0ea..e61a188f2 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Handles to operations a server may run asynchronously.""" +"""Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio import json @@ -44,12 +44,12 @@ class AsyncJob(Generic[T]): @property def id(self) -> Optional[str]: - """Identifies the operation on the server that is running it. + """The operation's opaque ID, interpreted according to :attr:`job_type`. - Returned for correlating with server logs or the jobs API. Operations - that run in this process have no server id and return `None`. The value - is opaque: parsing it or storing it to resume the job later is not - supported. + Registry jobs expose a registry job ID; SQL-backed jobs expose a + connection-scoped query ID as a string. Local operations return ``None``. + Query IDs cannot be used with registry job APIs or to resume after a + client restart. """ return self._inner.id if self._inner is not None else None @@ -94,9 +94,11 @@ class AsyncJob(Generic[T]): """Ask the backend for this job's current state, and for a server-side job its full record, then cache it for the properties below. - The properties are all `None` until this runs, because submitting an - operation returns only a job id. `status` fetches the whole record too; - `wait` records only the terminal state it establishes. + Registry details are `None` until this runs, because submitting an + operation does not fetch its full registry record. Query-backed jobs + expose only lifecycle state through this method. For registry jobs, + `status` fetches the whole record too; `wait` records only the terminal + state it establishes. """ if self._inner is None: return @@ -114,11 +116,13 @@ class AsyncJob(Generic[T]): @property def job_type(self) -> Optional[str]: - """The job's type, as the server names it. + """The job's kind of work, without contacting the backend. - `None` for an in-process job, which has no server-side record. + SQL-backed handles report ``"query"`` immediately. Registry handles + report the server's job type after :meth:`refresh` or :meth:`status`. + In-process handles return ``None``. """ - return self._field("job_type") + return self._inner.job_type if self._inner is not None else None @property def creation_ms(self) -> Optional[int]: @@ -294,7 +298,7 @@ class Job(Generic[T]): @property def job_type(self) -> Optional[str]: """The job's type. See :attr:`AsyncJob.job_type`.""" - return self._field("job_type") + return self._inner.job_type if self._inner is not None else None @property def creation_ms(self) -> Optional[int]: diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 55baa39a3..992926769 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -1683,7 +1683,7 @@ class AsyncLanceNamespaceDBConnection: parameters=parameters, ) - async def describe_query(self, query_id: UUID) -> QueryDescription: + async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: """Describe a submitted SQL query when supported.""" return await self._inner.describe_query(query_id) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 5e9288471..62d00f284 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1134,7 +1134,7 @@ class RemoteDBConnection(DBConnection): ) @override - def describe_query(self, query_id: UUID) -> QueryDescription: + def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription: """Describe a submitted SQL query by its connection-scoped id.""" return LOOP.run( self._conn.describe_query( diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 874034564..61e511345 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1729,7 +1729,11 @@ def test_remote_registration_job_and_exact_version_reopen_round_trip(): ) registration = db.create_function_async(normalize_score) assert registration.id == "job-register" + assert registration.job_type is None + assert registration.status() == "finished" + assert registration.job_type == "create_function" created = registration.wait() + assert registration.job_type == "create_function" reopened = db.get_function("normalize_score", version=created.version) assert created == reopened diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 46972a15c..e2be9c0d4 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -8,6 +8,7 @@ import threading import lancedb import pytest +from lancedb.db import AsyncConnection from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection @@ -56,7 +57,7 @@ def mock_remote_materialized_views(): @contextlib.contextmanager -def mock_remote_materialized_view_create(): +def mock_remote_materialized_view_drop(): requests = [] class Handler(http.server.BaseHTTPRequestHandler): @@ -67,7 +68,8 @@ def mock_remote_materialized_view_create(): length = int(self.headers.get("Content-Length", 0)) body = json.loads(self.rfile.read(length) or b"{}") requests.append((self.path, body)) - job_id = "mv-drop-123" if self.path.endswith("/drop") else "mv-create-123" + assert self.path.endswith("/drop") + job_id = "mv-drop-123" encoded = json.dumps({"job_id": job_id}).encode() self.send_response(202) self.send_header("Content-Type", "application/json") @@ -98,7 +100,7 @@ def test_remote_list_uses_namespace_route(): def test_remote_drop_async_returns_server_job(): - with mock_remote_materialized_view_create() as (host, requests): + with mock_remote_materialized_view_drop() as (host, requests): db = lancedb.connect( "db://dev", api_key="fake", @@ -192,11 +194,13 @@ def test_create_and_refresh_jobs(tmp_path): "adults", "people", where="age >= 18", with_no_data=True ) assert create_job.id is None + assert create_job.job_type is None assert create_job.wait() is None view = db.open_materialized_view("adults") refresh_job = view.refresh_async() assert refresh_job.id is None + assert refresh_job.job_type is None result = refresh_job.wait() assert result.mode == "rebuild" assert result.rows_written == 2 @@ -337,11 +341,13 @@ async def test_async_create_and_refresh_jobs(tmp_path): "adults", "people", with_no_data=True ) assert create_job.id is None + assert create_job.job_type is None assert await create_job.wait() is None view = await db.open_materialized_view("adults") refresh_job = await view.refresh_async() assert refresh_job.id is None + assert refresh_job.job_type is None result = await refresh_job.wait() assert result.mode == "rebuild" assert result.rows_written == 1 @@ -567,6 +573,27 @@ def test_local_materialized_view_listing_pages_and_resume(tmp_path): assert list(resumed) == [] +class QueryBackedCreateJob: + id = "0198f1b2-c3d4-7e5f-8123-456789abcdef" + + job_type = "query" + + async def wait(self): + return None + + async def status(self): + return "finished" + + +class CapturingCreateConnection: + def __init__(self): + self.calls = [] + + async def create_materialized_view_async(self, name, source, **options): + self.calls.append((name, source, options)) + return QueryBackedCreateJob() + + @pytest.mark.parametrize( "options", [ @@ -576,16 +603,28 @@ def test_local_materialized_view_listing_pages_and_resume(tmp_path): ], ) def test_remote_create_forwards_refresh_options_without_interval_default(options): - with mock_remote_materialized_view_create() as (host, requests): - db = lancedb.connect("db://dev", api_key="fake", host_override=host) - job = db.create_materialized_view_async("adults", "people", **options) - assert job.id == "mv-create-123" - assert requests == [ + native = CapturingCreateConnection() + db = RemoteDBConnection.__new__(RemoteDBConnection) + db._conn = AsyncConnection(native) + job = db.create_materialized_view_async("adults", "people", **options) + assert job.id == QueryBackedCreateJob.id + assert job.job_type == "query" + assert not hasattr(job, "query_id") + assert job.wait() is None + assert job.status() == "finished" + assert native.calls == [ ( - "/v1/materialized_view/adults/create", + "adults", + "people", { - "query": 'SELECT * FROM "people"', - **options, + "projections": None, + "filter": None, + "limit": None, + "with_no_data": False, + "auto_refresh_enabled": options.get("auto_refresh_enabled"), + "auto_refresh_interval_seconds": options.get( + "auto_refresh_interval_seconds" + ), }, ) ] @@ -593,18 +632,18 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options @pytest.mark.asyncio async def test_async_remote_create_keeps_interval_unspecified(): - with mock_remote_materialized_view_create() as (host, requests): - db = await lancedb.connect_async("db://dev", api_key="fake", host_override=host) - job = await db.create_materialized_view_async( - "adults", - "people", - auto_refresh_enabled=True, - ) - assert job.id == "mv-create-123" - assert requests[0][1] == { - "query": 'SELECT * FROM "people"', - "auto_refresh_enabled": True, - } + native = CapturingCreateConnection() + db = AsyncConnection(native) + job = await db.create_materialized_view_async( + "adults", "people", auto_refresh_enabled=True + ) + assert job.id == QueryBackedCreateJob.id + assert job.job_type == "query" + assert not hasattr(job, "query_id") + assert await job.wait() is None + assert await job.status() == "finished" + assert native.calls[0][2]["auto_refresh_enabled"] is True + assert native.calls[0][2]["auto_refresh_interval_seconds"] is None @pytest.mark.parametrize( @@ -625,7 +664,7 @@ def test_embedded_create_refuses_automatic_refresh_before_creating_view( @pytest.mark.parametrize("seconds", [0, -1, float("nan"), float("inf")]) def test_remote_create_rejects_invalid_interval_without_request(seconds): - with mock_remote_materialized_view_create() as (host, requests): + with mock_remote_materialized_view_drop() as (host, requests): db = lancedb.connect("db://dev", api_key="fake", host_override=host) with pytest.raises(ValueError, match="positive, finite"): db.create_materialized_view_async( diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index e6f5fd3c7..539b88647 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -137,9 +137,23 @@ async def test_async_namespace_connection_rejects_sql(tmp_path): await connection.describe_query(NIL_QUERY_ID) -def test_describe_query_requires_uuid(): - with pytest.raises(TypeError, match="UUID"): - remote_connection().describe_query(str(NIL_QUERY_ID)) +@pytest.mark.asyncio +@pytest.mark.parametrize("identity", [NIL_QUERY_ID, str(NIL_QUERY_ID)]) +async def test_describe_query_accepts_uuid_and_job_id_string(identity): + calls = [] + + class NativeConnection: + async def describe_query(self, query_id): + calls.append(query_id) + + connection = AsyncConnection(NativeConnection()) + await connection.describe_query(identity) + assert calls == [NIL_QUERY_ID] + + +def test_describe_query_rejects_registry_job_id(): + with pytest.raises(ValueError, match="UUID"): + remote_connection().describe_query("registry-job-id") @pytest.mark.parametrize( diff --git a/python/src/job.rs b/python/src/job.rs index e22b2f897..1740b3e00 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -81,6 +81,11 @@ impl Job { self.inner.id().map(str::to_string) } + #[getter] + pub fn job_type(&self) -> Option { + self.inner.job_type() + } + pub fn status(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py( diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index d671365f9..5c27587dc 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -13,6 +13,7 @@ use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; use tokio::sync::watch; use tokio::task::{AbortHandle, JoinHandle}; +use uuid::Uuid; use crate::database::JobDescription; use crate::error::{Error, JobFailure, Result}; @@ -55,10 +56,13 @@ fn job_detail_not_supported(what: &str) -> Result { /// Backend-specific tracking for an asynchronous operation. #[async_trait] pub(crate) trait JobHandle: Send + Sync { - /// Server-assigned id, when the backend has one. + /// Backend-specific id, when the operation has one. fn id(&self) -> Option<&str> { None } + fn job_type(&self) -> Option<&str> { + None + } async fn status(&self) -> Result; async fn wait(&self) -> Result; async fn cancel(&self) -> Result<()>; @@ -167,14 +171,15 @@ struct JobCache { /// the endpoint's successful terminal result; unit-result operations use the /// default `Job<()>`. /// -/// The detail accessors ([`Job::state`], [`Job::job_type`], ...) read what the +/// Registry detail accessors ([`Job::state`], [`Job::job_type`], ...) read what the /// handle last observed. Submitting an operation returns only a job id, so /// populating them eagerly would cost an extra round trip on every call: /// /// - [`Job::refresh`] and [`Job::status`] fetch the whole record. /// - [`Job::wait`] records the terminal state it establishes, but not the rest /// of the record; call [`Job::refresh`] for that. -/// - Everything is `None` until one of those runs. +/// - Registry details are `None` until one of those runs. Query-backed handles +/// report [`Job::job_type`] as `"query"` immediately. pub struct Job where T: Clone + Send + Sync + 'static, @@ -273,13 +278,18 @@ where Self::new_typed(Box::new(SpawnedJob::new(task))) } - pub(crate) fn spawned_with_cancellation(task: JoinHandle>, cancel: F) -> Self + pub(crate) fn from_query_task( + query_id: Uuid, + task: JoinHandle>, + cancel: F, + ) -> Self where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future> + Send + 'static, { let cancellation: Cancellation = Arc::new(move || Box::pin(cancel())); Self::new_typed(Box::new(SpawnedJob::new_with_cancellation( + query_id, task, cancellation, ))) @@ -290,12 +300,10 @@ impl Job where T: Clone + Send + Sync + 'static, { - /// Identifies the operation on the server that is running it. - /// - /// Returned for correlating with server logs or the jobs API. Operations - /// that run in this process have no server id and return `None`. The - /// value is opaque: parsing it or storing it to resume the job later is - /// not supported. + /// The operation's opaque identity, interpreted according to [`Job::job_type`]. + /// Registry handles expose a registry job ID; query handles expose the + /// connection-scoped SQL query UUID as a string. Local handles return None. + /// A query ID cannot be used with registry APIs or to resume after restart. pub fn id(&self) -> Option<&str> { match &self.inner { JobInner::Handle { handle, .. } => handle.id(), @@ -369,8 +377,14 @@ where self.cache_read().description.clone() } - /// The job's type, as the server names it. `None` for an in-process job. + /// The job's type: `"query"` for SQL-backed handles, otherwise the cached + /// server-reported kind of work. `None` for an in-process job. pub fn job_type(&self) -> Option { + if let JobInner::Handle { handle, .. } = &self.inner + && let Some(job_type) = handle.job_type() + { + return Some(job_type.to_string()); + } self.with_description(|description| description.job_type.clone()) } @@ -536,6 +550,7 @@ struct SpawnedJob { outcome: watch::Receiver>, abort: AbortHandle, cancellation: Option, + id: Option, } type CancellationFuture = Pin> + Send>>; @@ -549,11 +564,17 @@ impl SpawnedJob { Self::new_inner(task, None) } - fn new_with_cancellation(task: JoinHandle>, cancellation: Cancellation) -> Self + fn new_with_cancellation( + query_id: Uuid, + task: JoinHandle>, + cancellation: Cancellation, + ) -> Self where T: Serialize + Send + 'static, { - Self::new_inner(task, Some(cancellation)) + let mut handle = Self::new_inner(task, Some(cancellation)); + handle.id = Some(query_id.to_string()); + handle } fn new_inner(task: JoinHandle>, cancellation: Option) -> Self @@ -582,12 +603,21 @@ impl SpawnedJob { outcome, abort, cancellation, + id: None, } } } #[async_trait] impl JobHandle for SpawnedJob { + fn id(&self) -> Option<&str> { + self.id.as_deref() + } + + fn job_type(&self) -> Option<&str> { + self.id.as_ref().map(|_| "query") + } + async fn status(&self) -> Result { let label = match &*self.outcome.borrow() { None => "running", @@ -648,11 +678,31 @@ mod tests { async fn mapped_spawned_job_reuses_outcome() { let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); + assert_eq!(job.job_type(), None); + assert_eq!(job.id(), None); assert_eq!(job.wait().await.unwrap(), 42); assert_eq!(job.wait().await.unwrap(), 42); assert_eq!(job.status().await.unwrap(), "finished"); } + #[tokio::test] + async fn mapped_query_job_preserves_identity_and_type() { + let query_id = Uuid::new_v4(); + let job = Job::from_query_task(query_id, tokio::spawn(async { Ok(41_u64) }), || async { + Ok(()) + }) + .map(|value| value + 1); + assert_eq!(job.job_type().as_deref(), Some("query")); + assert_eq!(job.id(), Some(query_id.to_string().as_str())); + assert_eq!(job.wait().await.unwrap(), 42); + assert_eq!(job.wait().await.unwrap(), 42); + assert_eq!(job.job_type().as_deref(), Some("query")); + assert_eq!(job.id(), Some(query_id.to_string().as_str())); + let completed = Job::new_done(); + assert_eq!(completed.job_type(), None); + assert_eq!(completed.id(), None); + } + #[tokio::test] async fn mapped_spawned_job_preserves_cancellation() { let job = Job::spawned(tokio::spawn(async { pending::>().await })) diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index ecdd1783b..7ee76a160 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1716,7 +1716,8 @@ impl CreateMaterializedViewBuilder { } /// Submit creation and initial population, returning a [`Job`] that - /// settles when the view is ready. + /// settles when the view is ready. Remote creation submits SQL; the handle's + /// [`Job::job_type`] is `"query"` and its ID identifies that query. pub async fn execute_async(self) -> Result { if self.connection.uri().starts_with("db://") { return self diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 768de79d2..d33565653 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -63,15 +63,6 @@ struct RemoteCloneTableRequest { is_shallow: Option, } -#[derive(serde::Serialize)] -struct RemoteCreateMaterializedViewRequest { - query: String, - #[serde(skip_serializing_if = "Option::is_none")] - auto_refresh_enabled: Option, - #[serde(skip_serializing_if = "Option::is_none")] - auto_refresh_interval_seconds: Option, -} - // the versions of the server that we support // for any new feature that we need to change the SDK behavior, we should bump the server version, // and add a feature flag as method of `ServerVersion` here. @@ -594,6 +585,11 @@ mod test_utils { } } + pub(in crate::remote) fn with_sql_client(mut self, client: SqlClient) -> Self { + self.sql_client = Some(client); + self + } + pub fn new_mock_with_config(handler: F, config: ClientConfig) -> Self where F: Fn(reqwest::Request) -> http::Response + Send + Sync + 'static, @@ -885,8 +881,7 @@ impl Database for RemoteDatabase { ) -> Result { if request.with_no_data { return Err(Error::NotSupported { - message: "remote materialized views are always populated by their SQL job" - .to_string(), + message: "remote materialized views must be populated during creation".to_string(), }); } if let Some(seconds) = request.auto_refresh_interval_seconds @@ -896,36 +891,37 @@ impl Database for RemoteDatabase { message: "auto_refresh_interval_seconds must be positive, finite seconds".into(), }); } - let identifier = build_table_identifier(&request.name, &request.namespace_path)?; - let body = RemoteCreateMaterializedViewRequest { - query: request.query, - auto_refresh_enabled: request.auto_refresh_enabled, - auto_refresh_interval_seconds: request.auto_refresh_interval_seconds, - }; - let request = self - .client - .post(&format!("/v1/materialized_view/{identifier}/create")) - .json(&body); - let (request_id, response) = self.client.send(request).await?; - let response = self.client.check_response(&request_id, response).await?; - let status = response.status(); - let body = response.text().await.err_to_http(request_id.clone())?; - if status != StatusCode::ACCEPTED { - return Err(Error::Http { - source: "materialized-view creation must return 202 Accepted".into(), - request_id, - status_code: Some(status), - }); + validate_table_name(&request.name)?; + validate_namespace(&request.namespace_path)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })?; + let mut options = Vec::new(); + if let Some(enabled) = request.auto_refresh_enabled { + options.push(format!("auto_refresh_enabled = {enabled}")); } - let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { - source: "materialized-view create response did not contain a valid job_id".into(), - request_id, - status_code: Some(status), - })?; - Ok(Job::new(Box::new(RemoteJob::new( - self.client.clone(), - job_id, - )))) + if let Some(seconds) = request.auto_refresh_interval_seconds { + options.push(format!("auto_refresh_interval_seconds = {seconds}")); + } + let name = request.name.replace('"', "\"\""); + let options = if options.is_empty() { + String::new() + } else { + format!(" WITH ({})", options.join(", ")) + }; + client + .submit_as_job( + format!( + "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", + request.query + ), + request.namespace_path, + || async { Ok(()) }, + ) + .await } async fn drop_materialized_view_async( @@ -2016,72 +2012,22 @@ mod tests { } #[tokio::test] - async fn test_create_materialized_view_uses_rest_and_preserves_optional_settings() { - for (enabled, interval) in [(None, None), (Some(true), None), (Some(false), Some(0.5))] { - let db = super::RemoteDatabase::new_mock(move |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/materialized_view/analytics$adults/create" - ); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!(body["query"], "SELECT * FROM people"); - assert_eq!( - body.get("auto_refresh_enabled"), - enabled.map(serde_json::Value::from).as_ref() - ); - assert_eq!( - body.get("auto_refresh_interval_seconds"), - interval.map(serde_json::Value::from).as_ref() - ); - http::Response::builder() - .status(202) - .body(serde_json::json!({"job_id": "j1-mv-create"}).to_string()) - .unwrap() - }); - let job = db - .create_materialized_view_async(CreateMaterializedViewRequest { - name: "adults".into(), - namespace_path: vec!["analytics".into()], - query: "SELECT * FROM people".into(), - with_no_data: false, - auto_refresh_enabled: enabled, - auto_refresh_interval_seconds: interval, - }) - .await - .unwrap(); - assert_eq!(job.id(), Some("j1-mv-create")); - } - } - - #[tokio::test] - async fn test_create_materialized_view_rejects_invalid_acceptance() { - for (status, body) in [ - (200, r#"{"job_id":"j1"}"#), - (202, "{}"), - (202, r#"{"job_id":""}"#), - ] { - let db = super::RemoteDatabase::new_mock(move |_| { - http::Response::builder().status(status).body(body).unwrap() - }); - let error = db + async fn test_create_materialized_view_validates_before_submission() { + let db = super::RemoteDatabase::new_mock(|_| -> http::Response { + panic!("materialized-view creation must not send REST requests") + }); + for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { + let result = db .create_materialized_view_async(CreateMaterializedViewRequest { name: "adults".into(), namespace_path: vec![], query: "SELECT * FROM people".into(), with_no_data: false, auto_refresh_enabled: None, - auto_refresh_interval_seconds: None, + auto_refresh_interval_seconds: Some(seconds), }) - .await - .err() - .unwrap(); - assert!(error.to_string().contains(if status == 200 { - "202 Accepted" - } else { - "job_id" - })); + .await; + assert!(matches!(result, Err(Error::InvalidInput { .. }))); } } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index d8f04119f..846e852f5 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::fs; -use std::future::{Future, pending}; +use std::future::Future; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex as StdMutex, OnceLock}; use std::time::{Duration, Instant}; @@ -12,6 +12,7 @@ use arrow_array::RecordBatch; use arrow_flight::decode::FlightRecordBatchStream; use arrow_flight::error::FlightError; use arrow_flight::flight_service_client::FlightServiceClient; +#[cfg(test)] use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; use arrow_flight::{ Action, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, FlightClient, @@ -22,7 +23,7 @@ use futures::TryStreamExt; use http::header::{HeaderMap, HeaderName, HeaderValue}; use prost::Message; use serde::{Serialize, de::DeserializeOwned}; -use tokio::sync::{Mutex, Notify, OnceCell, mpsc, watch}; +use tokio::sync::{Mutex, Notify, OnceCell, mpsc}; use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}; use uuid::Uuid; @@ -226,6 +227,7 @@ impl SqlClient { .await } + #[cfg(test)] pub(super) async fn submit( &self, query: &str, @@ -254,40 +256,36 @@ impl SqlClient { .await } - pub(super) fn submit_as_job( + pub(super) async fn submit_as_job( &self, statement: String, namespace: Vec, finish: F, - ) -> Job + ) -> Result> where T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, F: FnOnce() -> Fut + Send + 'static, Fut: Future> + Send + 'static, { - let client = self.clone(); - let (query_tx, query_rx) = watch::channel(None::>); + let query = Arc::new( + self.execute(ExecuteQueryRequest { + query: statement, + default_namespace_path: namespace, + parameters: None, + }) + .await?, + ); + let query_id = query.id(); + let execution = query.clone(); let task = tokio::spawn(async move { - let query = Arc::new(client.submit(&statement, &namespace).await?); - query_tx.send_replace(Some(query.clone())); - let mut reader = query.reader().await?; + let mut reader = execution.reader().await?; while reader.try_next().await?.is_some() {} finish().await }); - Job::spawned_with_cancellation(task, move || { - let mut query_rx = query_rx.clone(); - async move { - loop { - let query = query_rx.borrow().clone(); - if let Some(query) = query { - return query.cancel().await; - } - if query_rx.changed().await.is_err() { - pending::<()>().await; - } - } - } - }) + Ok(Job::from_query_task(query_id, task, move || { + let query = query.clone(); + async move { query.cancel().await } + })) } pub(super) async fn describe(&self, query_id: Uuid) -> Result { @@ -315,6 +313,7 @@ impl SqlClientInner { ) } + #[cfg(test)] async fn poll( &self, descriptor: FlightDescriptor, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 4837baab7..1368dd753 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -22,6 +22,7 @@ use tonic::{Request, Response, Status, Streaming}; use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::database::Database; +use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; use crate::remote::client::HeaderProvider; use crate::remote::client::test_utils::client_with_handler; @@ -75,6 +76,7 @@ struct TestSqlService { defer: bool, invalid_decision: bool, query_count: Arc, + statements: Arc>>, do_get_count: Arc, cancel_count: Arc, cancel_denied_count: Arc, @@ -207,6 +209,7 @@ impl Default for TestSqlService { defer: false, invalid_decision: false, query_count: Arc::new(AtomicUsize::new(0)), + statements: Arc::new(std::sync::Mutex::new(Vec::new())), do_get_count: Arc::new(AtomicUsize::new(0)), cancel_count: Arc::new(AtomicUsize::new(0)), cancel_denied_count: Arc::new(AtomicUsize::new(0)), @@ -269,6 +272,7 @@ impl FlightService for TestSqlService { .and_then(|any| any.unpack::().ok().flatten()); let (query, stage) = if let Some(command) = command { self.query_count.fetch_add(1, Ordering::SeqCst); + self.statements.lock().unwrap().push(command.query.clone()); (command.query, 0_u8) } else { let continuation = std::str::from_utf8(request.get_ref().cmd.as_ref()) @@ -289,6 +293,9 @@ impl FlightService for TestSqlService { .ok_or_else(|| Status::invalid_argument("invalid continuation"))?; (query.to_string(), stage) }; + if query == "SELECT rejected" { + return Err(Status::invalid_argument("invalid statement")); + } if (query == "SELECT slow" || query == "SELECT cancelling") && stage > 0 { tokio::time::sleep(Duration::from_millis(250)).await; } @@ -364,7 +371,11 @@ impl FlightService for TestSqlService { .ok() .and_then(|envelope| Any::decode(envelope.value).ok()) .and_then(|command| command.unpack::().ok().flatten()); - if initial.is_some() { + if let Some(command) = &initial { + self.statements.lock().unwrap().push(command.query.clone()); + if command.query == "SELECT rejected" { + return Err(Status::invalid_argument("invalid statement")); + } self.capture_headers(request.metadata()); assert_eq!( request.metadata().get(PROTOCOL_HEADER).unwrap(), @@ -376,7 +387,8 @@ impl FlightService for TestSqlService { .map(|command| command.query.as_bytes()) .unwrap_or(request.get_ref().ticket.as_ref()); let ticket = query; - let gate_refresh = ticket == b"REFRESH MATERIALIZED VIEW \"cancel_view\""; + let gate_refresh = ticket == b"REFRESH MATERIALIZED VIEW \"cancel_view\"" + || ticket == b"SELECT job cancel denied"; let empty = ticket == b"SELECT empty"; let slow = ticket == b"SELECT slow get"; let large = ticket == b"SELECT large message"; @@ -458,7 +470,9 @@ impl FlightService for TestSqlService { { return Err(Status::not_found("query cancellation completed")); } - let status = if query == "SELECT cancel unspecified" { + let status = if query == "SELECT job cancel denied" { + CancelStatus::NotCancellable + } else if query == "SELECT cancel unspecified" { CancelStatus::Unspecified } else if query == "SELECT cancelling" { if self @@ -880,6 +894,132 @@ async fn catalog_connections_use_explicit_sql_endpoint_and_database_scope() { server.await.unwrap().unwrap(); } +#[tokio::test] +async fn remote_create_uses_sql_and_preserves_options_and_namespace() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let count = service.query_count.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("CREATE must use SQL, not REST: {}", request.url().path()); + }) + .with_sql_client(sql_client.clone()); + for (enabled, interval, expected) in [ + (None, None, ""), + (Some(true), None, " WITH (auto_refresh_enabled = true)"), + ( + Some(false), + Some(0.5), + " WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 0.5)", + ), + ] { + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "adults".into(), + namespace_path: vec!["team".into(), "reports".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: enabled, + auto_refresh_interval_seconds: interval, + }) + .await + .unwrap(); + assert_eq!(job.job_type().as_deref(), Some("query")); + let query_id = + Uuid::parse_str(job.id().expect("SQL-backed job must expose its ID")).unwrap(); + job.wait().await.unwrap(); + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert!(job.events(Default::default()).await.is_err()); + assert_eq!(job.job_type().as_deref(), Some("query")); + assert_eq!( + sql_client.describe(query_id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!( + statements.lock().unwrap().last().unwrap(), + &format!("CREATE MATERIALIZED VIEW \"adults\"{expected} AS SELECT * FROM people") + ); + } + assert_eq!(count.load(Ordering::SeqCst), 0); + assert_eq!(statements.lock().unwrap().len(), 3); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn query_backed_jobs_propagate_submission_and_execution_failures() { + let (client, shutdown) = start_sql_service( + TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }, + ClientConfig::default(), + ) + .await; + let rejected = client + .submit_as_job("SELECT rejected".into(), vec![], || async { Ok(()) }) + .await; + assert!(rejected.is_err()); + let finished = Arc::new(AtomicBool::new(false)); + let callback_finished = finished.clone(); + let job = client + .submit_as_job("SELECT fail".into(), vec![], move || async move { + callback_finished.store(true, Ordering::SeqCst); + Ok(()) + }) + .await + .unwrap(); + assert!(matches!(job.wait().await, Err(Error::JobFailed { .. }))); + assert!(matches!(job.wait().await, Err(Error::JobFailed { .. }))); + assert_eq!(job.status().await.unwrap(), "failed"); + assert!(!finished.load(Ordering::SeqCst)); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn rejected_job_cancellation_does_not_abort_sql_completion() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let do_get_count = service.do_get_count.clone(); + let release = service.gate_refresh_release.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let job = client + .submit_as_job("SELECT job cancel denied".into(), vec![], || async { + Ok(()) + }) + .await + .unwrap(); + wait_for(&do_get_count, 1, "job did not begin reading its SQL result").await; + assert!(matches!( + job.cancel().await, + Err(Error::NotSupported { .. }) + )); + assert_eq!(job.status().await.unwrap(), "running"); + release.notify_one(); + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + job.cancel().await.unwrap(); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn remote_refresh_twice_keeps_latest_selector() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -969,7 +1109,11 @@ async fn cancelling_remote_refresh_cancels_sql_query() { let (socket, _) = listener.accept().await?; Ok::<_, std::io::Error>(Some((socket, listener))) }); - let service = TestSqlService::default(); + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; let cancel_count = service.cancel_count.clone(); let do_get_count = service.do_get_count.clone(); let gate_refresh_release = service.gate_refresh_release.clone(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index b722dc4a1..4cbba04df 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2247,8 +2247,8 @@ impl BaseTable for RemoteTable { let freshness = self.freshness.clone(); let freshness_request = self.snapshot_freshness_headers(); let job_sql_client = sql_client.clone(); - Ok( - sql_client.submit_as_job(statement, namespace.clone(), move || async move { + sql_client + .submit_as_job(statement, namespace.clone(), move || async move { let table = Self::new_with_sql_client( client, name, @@ -2270,8 +2270,8 @@ impl BaseTable for RemoteTable { source_version: 0, version, }) - }), - ) + }) + .await } async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; From dcfef7c5ab259d2ce36003b6d6bf10c6de22cd9e Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 25 Oct 2026 02:31:21 -0700 Subject: [PATCH 099/180] feat(python): open lazy blob files from SQL descriptors (#4668) SQL blob descriptors need pinned source identity to reopen a value after the query finishes. Adds `open_blob_file(descriptor)` and `open_blob_files(descriptors)` so Python can read the original blob incrementally without materializing it in the SQL result. ### Python experience ```python rows = db.execute_query(""" SELECT f.timestamp, blob_descriptor(v.video) AS video FROM videos v JOIN frames f ON v.id = f.video_id """).read_all() videos = db.open_table("videos") for row in rows.to_pylist(): if row["video"] is not None: with videos.open_blob_file(row["video"]) as video: frame = extract_frame(video, row["timestamp"]) ``` The singular API accepts the descriptor dictionary or an Arrow struct scalar directly and returns a seekable `BlobFile`. `videos.open_blob_files(rows["video"])` accepts an Arrow array/chunked array or another iterable, opens handles as iteration advances, and preserves order, duplicates, and nulls as `None`. Async tables provide `await videos.open_blob_file(...)` and `async for video in videos.open_blob_files(...)`. The iterable API can be used directly with the Arrow result column. Zip it with the rows to keep each frame timestamp: ```python for row, video in zip(rows.to_pylist(), videos.open_blob_files(rows["video"])): if video is not None: with video: frame = extract_frame(video, row["timestamp"]) ``` Each iteration opens one handle. Null descriptors yield `None`; handles preserve input order and duplicates, and the `with` block closes each non-null file. For an async table: ```python async for video in async_videos.open_blob_files(rows["video"]): if video is not None: with video: payload = await video.aread() ``` ### Execution The descriptor retains the canonical `kind`, `position`, `size`, `blob_id`, and `blob_uri` fields and carries a `source` struct with its dataset URI, version, commit timestamp, branch, column, row reference, and whether that reference is a physical address. Native opening resolves that exact snapshot without changing the table handle's checkout and rejects a descriptor belonging to another table. Remote handles send authenticated byte-range requests with the captured version/branch, commit timestamp, and source URI, so an old physical address is never interpreted against the latest table. Known-size remote descriptors open without a payload request. External blobs with an unspecified size use a metadata-only HEAD request. Payload bytes load only when the file is read; full reads still allocate the full value. Existing row-ID-based `fetch_blob_files` remains available when a descriptor is not already present. Coverage includes native snapshot preservation after overwrite, both row IDs and addresses, dictionary/Arrow inputs, null/empty values, reordered and duplicate descriptors, lazy iterable behavior, async iteration, and remote range pinning for all six storage kinds. Descriptor reads isolate their pinned snapshot from the live table handle's freshness state. Both native and remote reads verify the source commit timestamp to reject a replaced snapshot after table recreation. --- docs/src/python/python.md | 54 +++++++- python/README.md | 49 +++++++ python/python/lancedb/_blob.py | 14 +- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/remote/table.py | 5 + python/python/lancedb/table.py | 76 ++++++++++ python/python/tests/test_blob.py | 132 ++++++++++++++++++ python/src/table.rs | 19 ++- rust/lancedb/src/blob.rs | 111 ++++++++++++++- rust/lancedb/src/remote/client.rs | 5 + rust/lancedb/src/remote/table.rs | 4 + rust/lancedb/src/remote/table/blobs.rs | 183 ++++++++++++++++++++++++- rust/lancedb/src/table.rs | 33 ++++- 13 files changed, 674 insertions(+), 12 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 41d3e16d7..02ccced2c 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -538,12 +538,64 @@ instead of being materialized with the rest of the row. `lancedb.BlobType` is `lance.blob.BlobType` when pylance is installed. Without pylance, LanceDB uses a matching `lance.blob.v2` extension type so blob columns -still work. Queries return descriptors. Call +still work. Native table queries return descriptors. Call [`fetch_blob_files`][lancedb.table.Table.fetch_blob_files] for lazy reads or [`fetch_blobs`][lancedb.table.Table.fetch_blobs] for eager bytes. One missing or deleted row ID rejects the entire blob-read batch; the APIs do not return partial results. +Remote SQL returns blob bytes by default. Select `blob_descriptor(video)` to +return an openable reference instead, then use +[`open_blob_file`][lancedb.table.Table.open_blob_file] or the lazy iterable +[`open_blob_files`][lancedb.table.Table.open_blob_files]: + +```python +rows = db.execute_query(""" + SELECT f.timestamp, blob_descriptor(v.video) AS video + FROM videos v JOIN frames f ON v.id = f.video_id +""").read_all() +videos = db.open_table("videos") +for row in rows.to_pylist(): + if row["video"] is not None: + with videos.open_blob_file(row["video"]) as video: + frame = extract_frame(video, row["timestamp"]) +``` + +This example uses a remote SQL connection that produces source-bearing +descriptors. The descriptor contains `kind`, `position`, `size`, `blob_id`, +`blob_uri`, and a `source` struct with `uri`, `version`, `committed_at_micros`, +`branch`, `column`, `row_reference`, and `row_is_address`. The opener verifies +the source table and commit and reads the captured version without changing +the table handle's checkout. Raw native storage descriptors omit `source`; +use `fetch_blob_files(column, row_ids)` for those query results. + +The singular API accepts a dictionary or Arrow struct scalar. The iterable +accepts Arrow arrays/chunked arrays or another iterable, opens handles as +iteration advances, and preserves order, duplicates, and nulls as `None`. +Close each non-null handle after use. Async tables provide +`await table.open_blob_file(...)` and +`async for file in table.open_blob_files(...)`. + +```python +for row, video in zip(rows.to_pylist(), videos.open_blob_files(rows["video"])): + if video is not None: + with video: + frame = extract_frame(video, row["timestamp"]) +``` + +For an async table, the iterable is consumed with `async for`: + +```python +async for video in async_videos.open_blob_files(rows["video"]): + if video is not None: + with video: + payload = await video.aread() +``` + +Payload bytes load on reads. Opening an external blob with unspecified size +can issue a metadata-only HEAD request. Remote reads use authenticated range +requests that validate the captured URI and commit timestamp. + Blobs inside lists can be written and queried as descriptors. They are omitted from `blob_columns()` because row ids do not identify individual list elements, so the fetch APIs cannot read their bytes yet. diff --git a/python/README.md b/python/README.md index 907f7c099..0b640d27c 100644 --- a/python/README.md +++ b/python/README.md @@ -101,3 +101,52 @@ print(results) ### Development See [CONTRIBUTING.md](./CONTRIBUTING.md) for information on how to contribute to LanceDB. + +### Opening SQL blob descriptors + +A SQL `blob_descriptor(video)` result keeps the Blob V2 storage metadata and a +`source` struct containing its table URI, version, commit timestamp, branch, +column and row identity. This example uses a remote SQL connection whose SQL +service produces those source-bearing descriptors. Open the reference on the +source table to read incrementally: + +```python +rows = db.execute_query(""" + SELECT f.timestamp, blob_descriptor(v.video) AS video + FROM videos v JOIN frames f ON v.id = f.video_id +""").read_all() + +videos = db.open_table("videos") +for row in rows.to_pylist(): + if row["video"] is not None: + with videos.open_blob_file(row["video"]) as video: + frame = extract_frame(video, row["timestamp"]) +``` + +`open_blob_file` accepts the dictionary or an Arrow struct scalar directly. It +keeps the query's version and branch without changing the table handle's checkout. +Payload bytes load on reads. An external blob with an unspecified size may need a +metadata-only HEAD request to open. + +`videos.open_blob_files(rows["video"])` returns an iterator over the same handles, +preserving order, duplicates and nulls (`None`). It accepts Arrow arrays/chunked +arrays or another iterable and opens each handle as iteration advances. Close each +non-null handle after use. Async tables offer `await videos.open_blob_file(...)` +and `async for video in videos.open_blob_files(...)`. + +```python +for video in videos.open_blob_files(rows["video"]): + if video is not None: + with video: + header = video.read(4096) +``` + +To extract a frame while retaining each row's timestamp, iterate over the +handles and rows together: + +```python +for row, video in zip(rows.to_pylist(), videos.open_blob_files(rows["video"])): + if video is not None: + with video: + frame = extract_frame(video, row["timestamp"]) +``` diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 1e9110dd0..46462553c 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -7,7 +7,7 @@ from __future__ import annotations import io import operator -from collections.abc import Awaitable, Callable, Iterable +from collections.abc import Awaitable, Callable, Iterable, Mapping from typing import TYPE_CHECKING, Optional, Union import pyarrow as pa @@ -31,6 +31,18 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray] FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]] +def _normalize_blob_descriptor(value): + if isinstance(value, pa.Scalar): + value = value.as_py() + if value is None: + return None + if not isinstance(value, Mapping): + raise TypeError( + "blob descriptor must be a mapping, an Arrow struct scalar, or None" + ) + return dict(value) + + class BlobFile(io.RawIOBase): """Seekable lazy handle from :meth:`~lancedb.table.Table.fetch_blob_files`. diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 9e602cce8..0b4fc82f1 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -580,6 +580,7 @@ class Table: async def fetch_blob_files( self, column: str, row_ids: list[int] ) -> list[Optional[BlobFile]]: ... + async def open_blob_file(self, descriptor: str) -> BlobFile: ... def vector_search(self) -> VectorQuery: ... class Tags: diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 53591182e..dd22dea48 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1221,6 +1221,11 @@ class RemoteTable(Table): ) -> "list[Optional[BlobFile]]": return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + return LOOP.run(self._table.open_blob_file(descriptor)) + def head(self, n=5) -> pa.Table: """ Return the first `n` rows of the table. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index c08c6390e..665520479 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -15,9 +15,11 @@ from functools import cached_property from typing import ( TYPE_CHECKING, Any, + AsyncIterator, Callable, Dict, Iterable, + Iterator, List, Literal, Optional, @@ -33,6 +35,7 @@ from lancedb.scannable import _hf_batches, _register_optional_converters, to_sca from . import __version__ from ._blob import ( BlobFile, + _normalize_blob_descriptor, _normalize_blob_row_ids, _wrap_blob_files, strip_auto_row_ids, @@ -2289,6 +2292,44 @@ class Table(ABC): handles are returned. """ + @abstractmethod + def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + """Open a seekable file from a SQL ``blob_descriptor`` result. + + Accepts the descriptor dictionary or an Arrow struct scalar. Its source + pins the table version, branch, column and row identity, so opening does + not change this table's checkout. Null descriptors return ``None``. + Payload bytes load only when the returned handle is read. An external + blob with an unspecified size may require a metadata request on opening. + + ```python + rows = db.execute_query( + "SELECT blob_descriptor(video) AS video FROM videos" + ).read_all() + with videos.open_blob_file(rows["video"][0]) as video: + header = video.read(4096) + ``` + """ + + def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]: + """Iterate over lazy files from descriptor dictionaries or Arrow scalars. + + Accepts an Arrow array/chunked array or any iterable. Opens each handle + as iteration advances, preserving input order and nulls as ``None``. + Close each non-null handle after use, normally with a ``with`` block. + + ```python + for video in videos.open_blob_files(rows["video"]): + if video is not None: + with video: + header = video.read(4096) + ``` + """ + for descriptor in descriptors: + yield self.open_blob_file(descriptor) + @abstractmethod def _execute_query( self, @@ -3239,6 +3280,11 @@ class LanceTable(Table): ) -> "list[Optional[BlobFile]]": return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + return LOOP.run(self._table.open_blob_file(descriptor)) + @property def tags(self) -> Tags: """Tag management for the table. @@ -7451,6 +7497,36 @@ class AsyncTable: ) return _wrap_blob_files(handles) + async def open_blob_file( + self, descriptor: Union[dict, pa.StructScalar, None] + ) -> Optional[BlobFile]: + """Open a snapshot-bound descriptor as a seekable file. + + See [Table.open_blob_file][lancedb.table.Table.open_blob_file]. + """ + descriptor = _normalize_blob_descriptor(descriptor) + if descriptor is None: + return None + return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor))) + + async def open_blob_files( + self, descriptors: Iterable + ) -> AsyncIterator[Optional[BlobFile]]: + """Asynchronously iterate over files in descriptor order, preserving nulls. + + Use ``async for file in table.open_blob_files(descriptors)``. Each + non-null file must be closed after use. + + ```python + async for video in videos.open_blob_files(rows["video"]): + if video is not None: + with video: + payload = await video.aread() + ``` + """ + for descriptor in descriptors: + yield await self.open_blob_file(descriptor) + @property def tags(self) -> AsyncTags: """Tag management for the dataset. diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index c2dc2a265..da362f053 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -2696,3 +2696,135 @@ def test_create_table_with_python_blob_dict_and_object(): b"from-dict", b"from-blob", ] + + +def _openable_descriptors(table, *, by_address): + hits = ( + table.search() + .select(["id", "image", "_rowaddr"]) + .with_row_id(True) + .limit(100) + .to_arrow(blob_mode="descriptions") + ) + version = table.version + committed_at = next( + item["timestamp"] + for item in table.list_versions() + if item["version"] == version + ) + descriptors = {} + for row in hits.to_pylist(): + descriptor = row["image"] + if descriptor is not None and descriptor.get("kind") is not None: + descriptor = dict(descriptor) + descriptor["source"] = { + "uri": table.to_lance().uri, + "version": version, + "committed_at_micros": round(committed_at.timestamp() * 1_000_000), + "branch": None, + "column": "image", + "row_reference": row["_rowaddr" if by_address else "_rowid"], + "row_is_address": by_address, + } + else: + descriptor = None + descriptors[row["id"]] = descriptor + return descriptors + + +@pytest.mark.parametrize("by_address", [False, True]) +def test_open_blob_files_preserve_snapshot_order_nulls_and_empty_values( + tmp_path, by_address +): + db = lancedb.connect(str(tmp_path)) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("videos", schema=schema) + table.add( + [ + {"id": 1, "image": b"alpha"}, + {"id": 2, "image": None}, + {"id": 3, "image": b"beta"}, + {"id": 4, "image": b""}, + ] + ) + descriptors = _openable_descriptors(table, by_address=by_address) + table.add([{"id": 1, "image": b"replacement"}], mode="overwrite") + latest_version = table.version + values = pa.array( + [descriptors[3], descriptors[2], descriptors[1], descriptors[3], descriptors[4]] + ) + files = table.open_blob_files( + pa.chunked_array([values.slice(0, 2), values.slice(2)]) + ) + assert iter(files) is files + actual = [] + for file in files: + if file is None: + actual.append(None) + else: + with file: + actual.append(file.read()) + assert file.closed + assert actual == [b"beta", None, b"alpha", b"beta", b""] + with table.open_blob_file(descriptors[1]) as file: + file.seek(2) + assert file.read_range(0, 2) == b"al" + assert file.tell() == 2 + assert file.read(2) == b"ph" + assert table.version == latest_version + assert table.open_blob_file(pa.scalar(None, type=values.type)) is None + other = db.create_table("other", schema=schema) + with pytest.raises(ValueError, match="different table"): + other.open_blob_file(descriptors[1]) + stale = dict(descriptors[1], source=dict(descriptors[1]["source"])) + stale["source"]["committed_at_micros"] += 1 + with pytest.raises(ValueError, match="snapshot has been replaced"): + table.open_blob_file(stale) + raw = {key: value for key, value in descriptors[1].items() if key != "source"} + with pytest.raises(ValueError, match="source"): + table.open_blob_file(raw) + with pytest.raises(TypeError, match="descriptor"): + table.open_blob_file("not a descriptor") + + +def test_open_blob_files_does_not_open_ahead(monkeypatch): + table = _blob_table("lazy_descriptor_iteration", [{"id": 1, "image": b"x"}]) + opened = [] + + def open_file(descriptor): + opened.append(descriptor) + return descriptor + + monkeypatch.setattr(table, "open_blob_file", open_file) + files = table.open_blob_files(iter([1, None, 2])) + assert opened == [] + assert next(files) == 1 + assert opened == [1] + assert list(files) == [None, 2] + assert opened == [1, None, 2] + + +@pytest.mark.asyncio +async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path): + db = lancedb.connect(str(tmp_path)) + table = db.create_table( + "videos", + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), + ) + table.add([{"id": 1, "image": b"alpha"}, {"id": 2, "image": None}]) + descriptors = _openable_descriptors(table, by_address=True) + async_db = await lancedb.connect_async(str(tmp_path)) + videos = await async_db.open_table("videos") + file = await videos.open_blob_file(pa.scalar(descriptors[1])) + with file: + assert file.read(2) == b"al" + actual = [] + async for file in videos.open_blob_files( + [descriptors[2], descriptors[1], descriptors[1]] + ): + if file is None: + actual.append(None) + else: + with file: + actual.append(await file.aread()) + assert actual == [None, b"alpha", b"alpha"] diff --git a/python/src/table.rs b/python/src/table.rs index e77c58578..e58b8a139 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -24,7 +24,7 @@ use arrow::{ ffi_stream::ArrowArrayStreamReader, pyarrow::{FromPyArrow, PyArrowType, ToPyArrow}, }; -use lancedb::blob::{BlobFile, BlobRangeRequest}; +use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest}; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ AddDataMode, ColumnAlteration, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken, @@ -1551,6 +1551,23 @@ impl Table { }) } + #[pyo3(signature = (descriptor))] + pub fn open_blob_file<'py>( + self_: PyRef<'py, Self>, + descriptor: &str, + ) -> PyResult> { + let descriptor: BlobDescriptor = serde_json::from_str(descriptor) + .map_err(|error| PyValueError::new_err(format!("invalid blob descriptor: {error}")))?; + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let file = inner.open_blob_file(&descriptor).await.infer_error()?; + Ok(PyBlobFile { + inner: Arc::new(file), + closed: AtomicBool::new(false), + }) + }) + } + /// Optimize the on-disk data by compacting and pruning old data, for better performance. #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None))] pub fn optimize( diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 05650d7c2..142b2264e 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -20,11 +20,120 @@ use arrow_schema::{DataType, Field, Schema}; use lance::dataset::{BlobRangeRequest as LanceBlobRangeRequest, Dataset, WriteParams}; use lance_arrow::FieldExt; use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; -use lance_io::object_store::ObjectStore; +use lance_io::object_store::{ObjectStore, uri_to_url}; use object_store::path::Path; +use serde::{Deserialize, Serialize}; use crate::error::{Error, Result}; +/// A stored Blob V2 descriptor with the source needed to reopen its snapshot. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BlobDescriptor { + /// Canonical Blob V2 storage kind (0 through 5). + pub kind: u8, + /// Stored offset within the backing object. + pub position: u64, + /// Stored length; zero on an external blob can mean unspecified. + pub size: u64, + /// Stored sidecar or base identifier. + pub blob_id: u32, + /// Stored external URI or managed path. + pub blob_uri: String, + /// Source identity captured by the query. + pub source: BlobDescriptorSource, +} + +/// The pinned source of a descriptor returned by SQL. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BlobDescriptorSource { + /// URI of the dataset on the source branch. + pub uri: String, + /// Exact table version read by the query. + pub version: u64, + /// Commit timestamp in microseconds, distinguishing recreated tables. + pub committed_at_micros: u64, + /// Source branch; `None` identifies main. + pub branch: Option, + /// Blob column path in the source table. + pub column: String, + /// Row ID or row address, as specified by `row_is_address`. + pub row_reference: u64, + /// Whether the row reference is a physical address. + pub row_is_address: bool, +} + +impl BlobDescriptor { + pub(crate) fn validate(&self) -> Result<()> { + if self.kind > 5 + || self.source.version == 0 + || self.source.uri.is_empty() + || self.source.column.is_empty() + { + return Err(Error::InvalidInput { + message: "invalid stored blob descriptor or missing pinned source".into(), + }); + } + Ok(()) + } +} + +pub(crate) async fn open_native_blob_file( + dataset: &Dataset, + descriptor: &BlobDescriptor, +) -> Result { + descriptor.validate()?; + let source = &descriptor.source; + let expected_uri = dataset + .branch_location() + .find_branch(source.branch.as_deref())? + .uri; + if uri_to_url(&expected_uri)? != uri_to_url(&source.uri)? { + return Err(Error::InvalidInput { + message: "blob descriptor belongs to a different table".into(), + }); + } + let dataset = Arc::new( + dataset + .checkout_version(lance::dataset::refs::Ref::Version( + source.branch.clone(), + Some(source.version), + )) + .await?, + ); + if uri_to_url(dataset.uri())? != uri_to_url(&source.uri)? { + return Err(Error::InvalidInput { + message: "blob descriptor belongs to a different table".into(), + }); + } + if dataset.manifest().timestamp_nanos / 1_000 != u128::from(source.committed_at_micros) { + return Err(Error::InvalidInput { + message: "blob descriptor source snapshot has been replaced".into(), + }); + } + ensure_blob_v2_column(dataset.schema(), &source.column)?; + let mut files = if source.row_is_address { + dataset + .take_blobs_by_addresses(&[source.row_reference], &source.column) + .await? + } else { + dataset + .take_blobs(&[source.row_reference], &source.column) + .await? + }; + if files.len() != 1 { + return Err(Error::InvalidInput { + message: "blob descriptor does not resolve to one stored value".into(), + }); + } + files + .pop() + .flatten() + .map(Into::into) + .ok_or_else(|| Error::InvalidInput { + message: "non-null blob descriptor resolved to a null value".into(), + }) +} + /// Seekable handle for one blob value, backed by local storage or a remote /// HTTP byte-range endpoint. #[derive(Debug)] diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index fe4a2072e..f54e2fe3e 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -809,6 +809,11 @@ impl RestfulLanceDbClient { self.client.get(full_uri) } + pub fn head(&self, uri: &str) -> RequestBuilder { + let full_uri = format!("{}{}", self.host, uri); + self.client.head(full_uri) + } + pub fn post(&self, uri: &str) -> RequestBuilder { let full_uri = format!("{}{}", self.host, uri); self.client.post(full_uri) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 4cbba04df..181ce61f9 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2927,6 +2927,10 @@ impl BaseTable for RemoteTable { self.fetch_blob_files_impl(column, row_ids).await } + async fn open_blob_file(&self, descriptor: &crate::blob::BlobDescriptor) -> Result { + self.open_blob_file_impl(descriptor).await + } + async fn explain_plan(&self, query: &AnyQuery, verbose: bool) -> Result { if let AnyQuery::Query(request) = query && let Some(offsets) = &request.take_offsets diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index bcaf47765..e3cdfc6a6 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -21,7 +21,7 @@ use reqwest::{Response, StatusCode, header}; use tokio::sync::{Mutex, OwnedSemaphorePermit}; use crate::Error; -use crate::blob::{BlobFile, BlobRangeRequest}; +use crate::blob::{BlobDescriptor, BlobDescriptorSource, BlobFile, BlobRangeRequest}; use crate::error::Result; use crate::query::{QueryFilter, QueryRequest, Select}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; @@ -49,6 +49,7 @@ fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { enum RangeRequestMode { SizeProbe, DataRead, + MetadataRead, } #[async_trait::async_trait] @@ -86,6 +87,9 @@ struct TableBlobRangeRequester { path: String, version: Option, branch: Option, + source_uri: Option, + source_commit_micros: Option, + row_is_address: bool, freshness: Arc>, parent_freshness: Arc>, parent_freshness_request: FreshnessHeaders, @@ -109,15 +113,27 @@ impl BlobRangeRequester for TableBlobRangeRequester { .expect("blob request semaphore is never closed"); let freshness_request = freshness_headers_snapshot(&self.freshness, self.read_consistency_interval); - let mut request = freshness_request - .apply(self.client.get(&self.path)) - .header(header::RANGE, range_header); + let mut request = if matches!(mode, RangeRequestMode::MetadataRead) { + freshness_request.apply(self.client.head(&self.path)) + } else { + freshness_request + .apply(self.client.get(&self.path)) + .header(header::RANGE, range_header) + }; if let Some(version) = version.or(self.version) { request = request.query(&[("version", version)]); } if let Some(branch) = &self.branch { request = request.query(&[("branch", branch)]); } + if let Some(source_uri) = &self.source_uri { + request = request + .query(&[("source_uri", source_uri)]) + .query(&[("row_is_address", self.row_is_address)]); + } + if let Some(timestamp) = self.source_commit_micros { + request = request.query(&[("source_commit_micros", timestamp)]); + } let (request_id, response) = self.client.send_with_retry(request, None, true).await?; // Preserve 416 size-probe responses so the caller can detect empty blobs. if response.status() == StatusCode::RANGE_NOT_SATISFIABLE @@ -131,8 +147,10 @@ impl BlobRangeRequester for TableBlobRangeRequester { } let response = self.client.check_response(&request_id, response).await?; freshness_request.observe_headers(&self.freshness, response.headers()); - self.parent_freshness_request - .observe_headers(&self.parent_freshness, response.headers()); + if self.source_uri.is_none() { + self.parent_freshness_request + .observe_headers(&self.parent_freshness, response.headers()); + } Ok(BlobRangeResponse { request_id, response, @@ -630,6 +648,51 @@ impl RemoteTable { Ok(files) } + pub(super) async fn open_blob_file_impl( + &self, + descriptor: &BlobDescriptor, + ) -> Result { + descriptor.validate()?; + self.ensure_blob_files_supported()?; + let source = &descriptor.source; + let snapshot = ReadSnapshot { + version: Some(source.version), + freshness_state: FreshnessState { + pinned: true, + ..Default::default() + }, + ..Default::default() + }; + let requester = self.blob_range_requester_with_source( + &source.column, + source.row_reference, + &snapshot, + Some(source), + ); + let size = if descriptor.kind == 3 && descriptor.size == 0 { + let metadata = requester + .request_range("", RangeRequestMode::MetadataRead, Some(source.version)) + .await?; + if metadata.response.status() != StatusCode::OK { + return Err(Error::InvalidInput { + message: "non-null blob descriptor did not resolve to a stored value".into(), + }); + } + metadata + .response + .headers() + .get(header::CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .ok_or_else(|| Error::InvalidInput { + message: "blob metadata response has no valid Content-Length".into(), + })? + } else { + descriptor.size + }; + Ok(RemoteBlobFile::new(requester, size, Some(source.version)).into()) + } + /// Probe each row once for its size. /// /// Serves callers that must not issue a query, such as a single blob that @@ -793,6 +856,16 @@ impl RemoteTable { column: &str, row_id: u64, read_snapshot: &ReadSnapshot, + ) -> Arc { + self.blob_range_requester_with_source(column, row_id, read_snapshot, None) + } + + fn blob_range_requester_with_source( + &self, + column: &str, + row_id: u64, + read_snapshot: &ReadSnapshot, + source: Option<&BlobDescriptorSource>, ) -> Arc { let path = format!( "/v1/table/{}/blob/{}/{row_id}/bytes", @@ -803,7 +876,10 @@ impl RemoteTable { client: self.client.clone(), path, version: read_snapshot.version, - branch: self.branch.clone(), + branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), + source_uri: source.map(|source| source.uri.clone()), + source_commit_micros: source.map(|source| source.committed_at_micros), + row_is_address: source.is_some_and(|source| source.row_is_address), freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), parent_freshness: self.freshness.clone(), parent_freshness_request: read_snapshot.freshness, @@ -1024,6 +1100,99 @@ mod tests { .unwrap() } + #[tokio::test] + async fn open_descriptor_files_are_lazy_and_pin_ranges_for_every_storage_kind() { + for kind in 0..=5 { + let requests = Arc::new(StdMutex::new(Vec::new())); + let captured = requests.clone(); + let table = RemoteTable::new_mock( + "videos".to_string(), + move |request| { + for name in [ + "x-lancedb-min-version", + "x-lancedb-min-read-version", + "x-lancedb-min-timestamp", + ] { + assert!(request.headers().get(name).is_none()); + } + assert_eq!( + request.url().path(), + "/v1/table/videos/blob/video/12884901889/bytes" + ); + let parameters = request + .url() + .query_pairs() + .into_owned() + .collect::>(); + assert_eq!(parameters["version"], "7"); + assert_eq!(parameters["source_commit_micros"], "1234"); + assert_eq!(parameters["branch"], "dev"); + assert_eq!(parameters["row_is_address"], "true"); + assert_eq!( + parameters["source_uri"], + "s3://bucket/videos.lance/tree/dev" + ); + captured.lock().unwrap().push(request.method().clone()); + if request.method() == reqwest::Method::HEAD { + assert!(request.headers().get(header::RANGE).is_none()); + http::Response::builder() + .status(200) + .header(header::CONTENT_LENGTH, PAYLOAD.len().to_string()) + .body(Vec::new()) + .unwrap() + } else { + range_response(&request, PAYLOAD) + } + }, + Some(Version::new(0, 5, 0)), + ); + { + let mut freshness = table.freshness.lock().unwrap(); + freshness.min_version = Some(99); + freshness.min_read_version = Some(2); + } + let descriptor = BlobDescriptor { + kind, + position: 0, + size: if kind == 3 { 0 } else { PAYLOAD.len() as u64 }, + blob_id: 0, + blob_uri: String::new(), + source: BlobDescriptorSource { + uri: "s3://bucket/videos.lance/tree/dev".into(), + version: 7, + committed_at_micros: 1234, + branch: Some("dev".into()), + column: "video".into(), + row_reference: 12884901889, + row_is_address: true, + }, + }; + let file = table.open_blob_file(&descriptor).await.unwrap(); + let expected = if kind == 3 { + vec![reqwest::Method::HEAD] + } else { + vec![] + }; + assert_eq!(*requests.lock().unwrap(), expected); + assert_eq!(file.size(), PAYLOAD.len() as u64); + file.seek(4).await.unwrap(); + assert_eq!(file.read_up_to(5).await.unwrap().as_ref(), &PAYLOAD[4..9]); + assert_eq!(file.tell().await.unwrap(), 9); + assert_eq!(table.freshness.lock().unwrap().min_read_version, Some(2)); + assert_eq!(file.read_range(0..3).await.unwrap().as_ref(), &PAYLOAD[..3]); + assert_eq!(file.tell().await.unwrap(), 9); + assert_eq!( + requests + .lock() + .unwrap() + .iter() + .filter(|method| **method == reqwest::Method::GET) + .count(), + 2 + ); + } + } + fn mock_remote_blob_table( requests: Arc>>, ) -> RemoteTable { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 3123eb776..3fcf4bdb7 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -3,7 +3,7 @@ //! LanceDB Table APIs -use crate::blob::BlobFile; +use crate::blob::{BlobDescriptor, BlobFile}; use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader}; use arrow_schema::{Schema, SchemaRef}; use async_trait::async_trait; @@ -796,6 +796,12 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "fetch_blob_files is not supported on this table type".into(), }) } + /// Open a descriptor at its pinned source version. See [`Table::open_blob_file`]. + async fn open_blob_file(&self, _descriptor: &BlobDescriptor) -> Result { + Err(Error::NotSupported { + message: "open_blob_file is not supported on this table type".into(), + }) + } /// Gets the table tag manager. async fn tags(&self) -> Result>; /// Optimize the dataset. @@ -1377,6 +1383,26 @@ impl Table { self.inner.fetch_blob_files(column.as_ref(), row_ids).await } + /// Open a seekable file from a SQL `blob_descriptor` result. + /// + /// The descriptor carries its table version, branch, column and row identity. + /// Opening does not materialize the payload or change this table's checkout. + /// Remote reads use the table's authenticated HTTP byte-range endpoint. + /// + /// ``` + /// use lancedb::{Table, blob::BlobDescriptor}; + /// + /// # async fn read_header(videos: &Table, descriptor: &BlobDescriptor) -> lancedb::Result<()> { + /// let video = videos.open_blob_file(descriptor).await?; + /// let header = video.read_range(0..video.size().min(4096)).await?; + /// video.close().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn open_blob_file(&self, descriptor: &BlobDescriptor) -> Result { + self.inner.open_blob_file(descriptor).await + } + /// Insert new records into this Table /// /// # Arguments @@ -3764,6 +3790,11 @@ impl BaseTable for NativeTable { crate::blob::take_blob_files_aligned(&dataset, column, row_ids).await } + async fn open_blob_file(&self, descriptor: &BlobDescriptor) -> Result { + let dataset = self.dataset.get().await?; + crate::blob::open_native_blob_file(&dataset, descriptor).await + } + /// Delete rows from the table async fn delete(&self, predicate: Predicate<'_>) -> Result { let result = delete::execute_delete(self, predicate).await?; From de0c5edc7d05cea0a79adb180a5ae374514c69e4 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 25 Oct 2026 11:22:16 +0000 Subject: [PATCH 100/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.13=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.14?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 0909579cb..7dcefa69c 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.13" +current_version = "0.41.0-beta.14" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index fac89c4da..03f4b0864 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5700,7 +5700,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.13" +version = "0.41.0-beta.14" dependencies = [ "ahash", "anyhow", @@ -5798,7 +5798,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.13" +version = "0.41.0-beta.14" dependencies = [ "arrow-array", "arrow-buffer", @@ -5823,7 +5823,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.13" +version = "0.41.0-beta.14" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 0c887f66f..9dbccbc81 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.13 + 0.41.0-beta.14 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 87c5d4cb8..7c34a801a 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.13 + 0.41.0-beta.14 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 1f3e0efb0..2dc959887 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.13 + 0.41.0-beta.14 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 1b9d47e46..e343d68ca 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.13" +version = "0.41.0-beta.14" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index bd4b95463..343483a8e 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 6e4e57684..4c3b93c81 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index f77c50ee2..7679a422d 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index b671b7ebf..6a62f8e8a 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index b75738ff1..d68341382 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 7158748f9..42a517310 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 83d0fb6f2..b116f2819 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 21f903235..f746f6daf 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.13", + "version": "0.41.0-beta.14", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 076299a7d..82fb7efae 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.13" +version = "0.41.0-beta.14" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 486eb1e8e..006886647 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.13" +version = "0.41.0-beta.14" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 197403e8913fc1976d72ede8a73b7e0c69b6ff10 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 25 Oct 2026 07:19:55 -0700 Subject: [PATCH 101/180] fix: honor downstream Lance dependency overrides (#4671) Consumers that provide a local Lance checkout cannot resolve the dependency graph because the SDK directly selects a vendored `lance-arrow`, producing two path packages with the same name and version. The Rust core now declares its upstream Git dependency separately so the consuming workspace can override that source consistently. Python continues inheriting the vendored workspace dependency, keeping the sliced-struct validity fix in Maturin source distributions. Standalone SDK builds still select that same fix through the existing root patch. Adds a downstream consumer CI regression that resolves a local Lance override and checks that exactly one canonical `lance-arrow` package is selected. The Lance version updater also updates the core declaration in stable, preview and local modes. Public APIs and query behavior are unchanged. The workspace declaration lint excludes path dependencies because the Python binding intentionally uses the bundled source. Duplicate and unused external declarations remain errors; advisory, license, banned-package and source checks continue covering the full dependency graph. --------- Co-authored-by: Lance Release --- .github/workflows/pypi-publish.yml | 3 ++ .github/workflows/rust.yml | 57 ++++++++++++++++++++++++++++++ ci/set_lance_version.py | 14 ++++++++ ci/tests/test_set_lance_version.py | 28 +++++++++++++++ deny.toml | 4 ++- python/Cargo.toml | 1 - rust/lancedb/Cargo.toml | 2 +- 7 files changed, 106 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index e71564473..1784c4c8a 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -15,6 +15,9 @@ on: - ci/check_cargo_lock.py - ci/check_sdist.py - python/pyproject.toml + - python/Cargo.toml + - python/vendor/** + - rust/lancedb/Cargo.toml - Cargo.toml # Change in dependency frequently breaks builds - Cargo.lock diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 930ae67e2..17fe3a7b4 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -29,6 +29,63 @@ env: RUST_BACKTRACE: "1" jobs: + dependency-overrides: + name: Downstream Lance override + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + - uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Read the pinned Lance tag + id: lance + run: | + python3 - <<'PYTHON' + import os + import tomllib + from pathlib import Path + + manifest = tomllib.loads(Path("Cargo.toml").read_text()) + tag = manifest["workspace"]["dependencies"]["lance"]["tag"] + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + output.write(f"tag={tag}\n") + PYTHON + - uses: actions/checkout@v6 + with: + repository: lance-format/lance + ref: ${{ steps.lance.outputs.tag }} + path: local-lance + - name: Resolve a downstream workspace with a local Lance override + run: | + mkdir -p downstream/src + touch downstream/src/lib.rs + cat > downstream/Cargo.toml <<'TOML' + [package] + name = "lancedb-local-lance-consumer" + version = "0.1.0" + edition = "2024" + + [workspace] + + [dependencies] + lancedb = { path = "../rust/lancedb", default-features = false } + lance-arrow = { path = "../local-lance/rust/lance-arrow" } + + [patch."https://github.com/lance-format/lance.git"] + lance-arrow = { path = "../local-lance/rust/lance-arrow" } + TOML + cargo metadata --manifest-path downstream/Cargo.toml --format-version 1 > downstream/graph.json + python3 - <<'PYTHON' + import json + from pathlib import Path + + graph = json.loads(Path("downstream/graph.json").read_text()) + packages = [p for p in graph["packages"] if p["name"] == "lance-arrow"] + assert len(packages) == 1, [p["id"] for p in packages] + assert Path(packages[0]["manifest_path"]).resolve() == Path( + "local-lance/rust/lance-arrow/Cargo.toml" + ).resolve() + PYTHON + lint: timeout-minutes: 30 runs-on: ubuntu-24.04 diff --git a/ci/set_lance_version.py b/ci/set_lance_version.py index c7bf41f55..bef97f8ad 100644 --- a/ci/set_lance_version.py +++ b/ci/set_lance_version.py @@ -2,6 +2,8 @@ import argparse import re import sys import json +import tomllib +from pathlib import Path LANCE_GIT_URL = "https://github.com/lance-format/lance.git" @@ -148,6 +150,18 @@ def update_cargo_toml(line_updater): with open("Cargo.toml", "w") as f: f.writelines(new_lines) + core_manifest = Path("rust/lancedb/Cargo.toml") + if core_manifest.exists(): + lines = core_manifest.read_text().splitlines(keepends=True) + for index, line in enumerate(lines): + if line.startswith("lance-arrow ="): + updated = tomllib.loads(line_updater(line))["lance-arrow"] + config = {"version": updated} if isinstance(updated, str) else updated + if "path" in config: + config["path"] = "../../" + config["path"] + lines[index] = dict_to_toml_line("lance-arrow", config) + core_manifest.write_text("".join(lines)) + def set_stable_version(version: str): """ diff --git a/ci/tests/test_set_lance_version.py b/ci/tests/test_set_lance_version.py index 1493fc59d..1173eab84 100644 --- a/ci/tests/test_set_lance_version.py +++ b/ci/tests/test_set_lance_version.py @@ -4,6 +4,7 @@ import subprocess import sys import tempfile import textwrap +import tomllib import unittest from pathlib import Path @@ -83,6 +84,13 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], " with self.subTest(version=version), tempfile.TemporaryDirectory() as tmp: workdir = Path(tmp) (workdir / "Cargo.toml").write_text(CARGO_TOML) + core_manifest = workdir / "rust/lancedb/Cargo.toml" + core_manifest.parent.mkdir(parents=True) + core_manifest.write_text( + "[dependencies]\nlance-arrow = { " + 'version = "=1.0.0", git = "https://github.com/lance-format/lance.git", ' + 'tag = "v1.0.0" }\narrow.workspace = true\n' + ) command_log = workdir / "commands.log" fake_bin = workdir / "bin" fake_bin.mkdir() @@ -111,6 +119,26 @@ lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], " + updated_dependencies + UNTOUCHED_DEPENDENCIES, ) + core = tomllib.loads(core_manifest.read_text())["dependencies"] + dependency = core["lance-arrow"] + if isinstance(dependency, str): + dependency = {"version": dependency} + if version == "local": + self.assertEqual( + dependency["path"], "../../../lance/rust/lance-arrow" + ) + else: + expected_version = { + "stable": "9.9.9", + "preview": "10.0.0-beta.3", + }.get(version, version.removeprefix("v")) + self.assertEqual(dependency["version"], f"={expected_version}") + if "beta" in expected_version: + self.assertEqual(dependency["git"], LANCE_GIT_URL) + self.assertEqual(dependency["tag"], f"v{expected_version}") + else: + self.assertNotIn("git", dependency) + self.assertEqual(core["arrow"], {"workspace": True}) commands = command_log.read_text().splitlines() for command in expected_commands: self.assertTrue( diff --git a/deny.toml b/deny.toml index 77412709f..e4982c149 100644 --- a/deny.toml +++ b/deny.toml @@ -177,7 +177,9 @@ wildcards = "deny" # `[workspace.dependencies]` table: any crate used by more than one member must # go through `workspace = true`, and entries nothing uses are an error. This # keeps versions from drifting between the core crate and the bindings. -workspace-dependencies = { duplicates = "deny", unused = "deny" } +# Python bundles a patched path crate while the Rust SDK uses the overridable +# upstream source. Check shared external declarations, not these path bindings. +workspace-dependencies = { duplicates = "deny", unused = "deny", include-path-dependencies = false } # Internal workspace crates reference each other via `path = "..."`, which # cargo-deny sees as a wildcard version. That's fine for private workspace # members (not published to crates.io), so allow it specifically for paths. diff --git a/python/Cargo.toml b/python/Cargo.toml index 82fb7efae..265e4d270 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -22,7 +22,6 @@ bytes.workspace = true lancedb.workspace = true datafusion-common.workspace = true lance-core.workspace = true -# The workspace path dependency includes the patched crate in Maturin sources. lance-arrow.workspace = true lance-namespace.workspace = true lance-namespace-impls.workspace = true diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 006886647..c18db11fe 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -46,7 +46,7 @@ lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lind lance-table = { workspace = true } lance-linalg = { workspace = true } lance-encoding = { workspace = true } -lance-arrow = { workspace = true } +lance-arrow = { version = "=15.0.0-beta.1", tag = "v15.0.0-beta.1", git = "https://github.com/lance-format/lance.git" } lance-namespace = { workspace = true } lance-namespace-impls = { workspace = true } metrics = { workspace = true, optional = true } From e6789a4118e037824e7f3891691891841ee2773b Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:55:37 +0800 Subject: [PATCH 102/180] fix: support system columns in DataFusion table adapters (#4667) DataFusion plans SQL against the adapter's declared schema, which omitted `_rowid` and `_rowaddr` even though Lance can project both. SQL therefore rejected these columns before reaching the scan. Add `BaseTableAdapter::with_system_columns` to opt into either column using Lance's nullable `UInt64` fields. Scans without a projection now select the full declared column list so their output matches the provider schema. Default adapters retain data-only `SELECT *` and remain compatible with `INSERT INTO ... SELECT *`; opted-in adapters include the requested system columns in `SELECT *`. Regression tests compare SQL results with native queries and cover projection order, system-only projections, row-ID predicates, scans without a projection, duplicate/unsupported names, and default SQL inserts. Validation: - DataFusion unit suite: 436 tests passed with `cargo test --locked --quiet --profile ci -p lancedb --features remote --lib table::datafusion`. - `cargo clippy --locked --quiet --profile ci -p lancedb --features remote --tests --examples -- -D warnings` passed. - The new builder's documentation example passed its doctest. - `cargo fmt --all -- --check` and `git diff --check` passed. Fixes #4666 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/table/datafusion.rs | 222 ++++++++++++++++++++++++++- 1 file changed, 221 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 39f3cd4c6..e6a76c3f5 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -25,10 +25,11 @@ use datafusion_physical_plan::{ }; use futures::{TryFutureExt, TryStreamExt}; use lance::dataset::{WriteMode, WriteParams}; +use lance_core::{ROW_ADDR, ROW_ADDR_FIELD, ROW_ID, ROW_ID_FIELD}; use super::{AnyQuery, BaseTable}; use crate::{ - Result, + Error, Result, query::{QueryExecutionOptions, QueryFilter, QueryRequest, Select}, }; use arrow_schema::{DataType, Field}; @@ -186,6 +187,46 @@ impl BaseTableAdapter { }) } + /// Expose the requested Lance system columns to DataFusion. + /// + /// Supports [`ROW_ID`] (`_rowid`) and [`ROW_ADDR`] (`_rowaddr`), both nullable + /// `UInt64` fields. Columns are appended in the requested order, skipping any + /// already exposed by this adapter. Other names return [`Error::InvalidInput`]. + /// + /// System columns are hidden by default so existing `SELECT *` queries keep + /// their data-only schema. After opting in, `SELECT *` includes these columns. + /// + /// ``` + /// use lance_core::{ROW_ADDR, ROW_ID}; + /// use lancedb::table::datafusion::BaseTableAdapter; + /// + /// # async fn adapter(table: &lancedb::Table) -> lancedb::Result { + /// BaseTableAdapter::try_new(table.base_table().clone()) + /// .await? + /// .with_system_columns(&[ROW_ID, ROW_ADDR]) + /// # } + /// ``` + pub fn with_system_columns(mut self, columns: &[impl AsRef]) -> Result { + let mut fields = self.schema.fields().to_vec(); + for column in columns { + let column = column.as_ref(); + let field = match column { + ROW_ID => &*ROW_ID_FIELD, + ROW_ADDR => &*ROW_ADDR_FIELD, + _ => { + return Err(Error::InvalidInput { + message: format!("Unsupported system column: {column}"), + }); + } + }; + if !fields.iter().any(|field| field.name() == column) { + fields.push(Arc::new(field.clone())); + } + } + self.schema = Arc::new(ArrowSchema::new(fields)); + Ok(self) + } + /// Set the RTE read routing of every scan; see [`QueryRequest::use_rte`]. pub fn with_use_rte(mut self, use_rte: Option) -> Self { self.use_rte = use_rte; @@ -242,6 +283,15 @@ impl TableProvider for BaseTableAdapter { .map(|i| self.schema.field(*i).name().clone()) .collect(); query.select = Select::Columns(field_names); + } else { + // Select::All excludes system columns, which may be part of our schema. + query.select = Select::Columns( + self.schema + .fields() + .iter() + .map(|field| field.name().clone()) + .collect(), + ); } if !filters.is_empty() { let first = filters.first().unwrap().clone(); @@ -319,6 +369,7 @@ pub mod tests { BinaryArray, Float64Array, Int32Array, Int64Array, RecordBatch, StringArray, UInt32Array, }; use arrow_schema::{DataType, Field, Schema}; + use arrow_select::concat::concat_batches; use datafusion::{ datasource::provider_as_source, prelude::{SessionConfig, SessionContext}, @@ -328,11 +379,13 @@ pub mod tests { use datafusion_execution::SendableRecordBatchStream; use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, col, lit}; use futures::{StreamExt, TryStreamExt}; + use lance_core::{ROW_ADDR, ROW_ADDR_FIELD, ROW_ID, ROW_ID_FIELD}; use tempfile::tempdir; use crate::{ connect, index::{Index, scalar::BTreeIndexBuilder}, + query::{ExecutableQuery, Query, QueryBase, Select}, table::datafusion::BaseTableAdapter, }; @@ -509,6 +562,173 @@ pub mod tests { } } + #[tokio::test] + async fn test_system_columns_opt_in() { + let fixture = TestFixture::new().await; + let ctx = SessionContext::new(); + ctx.register_table("foo", fixture.adapter.clone()).unwrap(); + + let batches = ctx + .sql("SELECT * FROM foo") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(batches[0].num_columns(), 2); + assert_eq!(batches[0].schema(), fixture.adapter.schema()); + for column in [ROW_ID, ROW_ADDR] { + assert!(ctx.sql(&format!("SELECT {column} FROM foo")).await.is_err()); + } + + let adapter = BaseTableAdapter::try_new(fixture.adapter.table.clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ADDR, ROW_ADDR]) + .unwrap(); + assert_eq!(adapter.schema().fields().len(), 3); + assert_eq!(adapter.schema().field(2), &*ROW_ADDR_FIELD); + assert!(adapter.schema().index_of(ROW_ID).is_err()); + + let adapter = adapter + .with_system_columns(&[ROW_ID.to_string(), ROW_ADDR.to_string()]) + .unwrap(); + assert_eq!(adapter.schema().fields().len(), 4); + assert_eq!(adapter.schema().field(3), &*ROW_ID_FIELD); + assert!(adapter.schema().metadata().is_empty()); + + let err = adapter.with_system_columns(&["_unknown"]).unwrap_err(); + assert!(matches!(err, crate::Error::InvalidInput { .. })); + + // Default adapters must remain compatible with INSERT ... SELECT *. + ctx.sql("INSERT INTO foo SELECT * FROM foo") + .await + .unwrap() + .collect() + .await + .unwrap(); + let batches = ctx + .sql("SELECT COUNT(*) FROM foo") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 20 + ); + } + + #[tokio::test] + async fn test_system_columns_sql() { + let fixture = TestFixture::new().await; + let adapter = BaseTableAdapter::try_new(fixture.adapter.table.clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap(); + let ctx = SessionContext::new(); + ctx.register_table("foo", Arc::new(adapter)).unwrap(); + + // Compare SQL results with the native query's row IDs and row addresses. + let native = Query::new(fixture.adapter.table.clone()) + .select(Select::columns(&["i", "indexed", ROW_ADDR])) + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let schema = Arc::new( + native[0] + .schema() + .as_ref() + .clone() + .with_metadata(HashMap::new()), + ); + let expected = concat_batches(&schema, &native).unwrap(); + + for columns in [ + vec!["i", ROW_ID], + vec![ROW_ID, "i"], + vec!["i", ROW_ADDR], + vec![ROW_ADDR, "i"], + vec![ROW_ADDR, ROW_ID], + vec![ROW_ID], + vec![ROW_ADDR], + vec!["i", "indexed", ROW_ID, ROW_ADDR], + ] { + let sql = format!("SELECT {} FROM foo ORDER BY i", columns.join(", ")); + let batches = ctx.sql(&sql).await.unwrap().collect().await.unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + let indices = columns + .iter() + .map(|name| schema.index_of(name).unwrap()) + .collect::>(); + assert_eq!(actual, expected.project(&indices).unwrap(), "{sql}"); + } + + let batches = ctx + .sql("SELECT * FROM foo ORDER BY i") + .await + .unwrap() + .collect() + .await + .unwrap(); + let indices = ["i", "indexed", ROW_ID, ROW_ADDR].map(|name| schema.index_of(name).unwrap()); + assert_eq!(batches[0], expected.project(&indices).unwrap()); + + // Filtering on the ID must work even when the ID is not in the output. + let row_id = expected + .column_by_name(ROW_ID) + .unwrap() + .as_primitive::() + .value(3); + let batches = ctx + .sql(&format!("SELECT i FROM foo WHERE _rowid = {row_id}")) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(batches[0], expected.project(&[0]).unwrap().slice(3, 1)); + } + + #[tokio::test] + async fn test_system_columns_scan_without_projection() { + let fixture = TestFixture::new().await; + let adapter = BaseTableAdapter::try_new(fixture.adapter.table.clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ADDR, ROW_ID]) + .unwrap(); + let ctx = SessionContext::new(); + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 10); + for batch in batches { + assert_eq!(batch.schema(), adapter.schema()); + assert_eq!( + batch + .column(2) + .as_primitive::() + .values(), + batch + .column(3) + .as_primitive::() + .values() + ); + } + } + #[tokio::test] async fn test_batch_size() { let fixture = TestFixture::new().await; From 256db55a5195bba35b9e240932d17d580589009b Mon Sep 17 00:00:00 2001 From: Joaquin Hui Gomez <132194176+joaquinhuigomez@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:02:36 +0000 Subject: [PATCH 103/180] fix(python)!: align RemoteDBConnection.create_table parameter order (#4608) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `RemoteDBConnection.create_table` orders its parameters `(name, data, schema, on_bad_vectors, fill_value, mode, exist_ok, ...)`, while `DBConnection`, `LanceDBConnection` and `LanceNamespaceDBConnection` all use `(name, data, schema, mode, exist_ok, on_bad_vectors, fill_value, ...)`. Since `RemoteDBConnection` subclasses `DBConnection`, identical positional calls bind to different parameters: switching a working script from `lancedb.connect(path)` to `lancedb.connect("db://...")` silently turns `mode="overwrite"` into `on_bad_vectors="overwrite"` and `exist_ok=True` into `fill_value=True`, and nothing client-side validates either. `inspect.signature(...).bind(None, "t", data, None, "overwrite", True)` shows it deterministically, no cloud needed. This reorders the remote signature to match the other three; every parameter keeps its own existing default (including the remote's `mode=None`, which its body relies on), and the body already forwards by keyword so nothing else changes. The new test asserts positional parity with `DBConnection` through `embedding_functions` and fails on `main`. Blast radius, stated plainly: only remote callers passing four or more positional arguments are affected — positions 4–7 move; positions 1–3 and 8 are unchanged and keyword callers are unaffected. No in-repo caller passes more than two positionals. Anyone relying on the current order was relying on behaviour that contradicts the documented base contract and diverges from local connections. Not added here: the `storage_options`/`data_storage_version`/`enable_v2_manifest_paths` parameters the remote signature still lacks. --------- Co-authored-by: Xuanwo --- python/python/lancedb/remote/db.py | 4 ++-- python/python/tests/test_remote_db.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 62d00f284..c11e01ff4 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -569,10 +569,10 @@ class RemoteDBConnection(DBConnection): name: str, data: DATA = None, schema: Optional[Union[pa.Schema, LanceModel]] = None, - on_bad_vectors: str = "error", - fill_value: float = 0.0, mode: Optional[str] = None, exist_ok: bool = False, + on_bad_vectors: str = "error", + fill_value: float = 0.0, embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None, *, namespace_path: Optional[List[str]] = None, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index c1db92948..95da3eba2 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5,6 +5,7 @@ import contextlib from datetime import timedelta import http.server import io +import inspect import json import multiprocessing as mp import pickle @@ -765,6 +766,15 @@ def test_create_table_embedding_functions(with_schema): ] +def test_create_table_positional_parameters_match_base_contract(): + from lancedb.db import DBConnection + from lancedb.remote.db import RemoteDBConnection + + expected = list(inspect.signature(DBConnection.create_table).parameters)[:9] + actual = list(inspect.signature(RemoteDBConnection.create_table).parameters)[:9] + assert actual == expected + + def test_create_table_exist_ok(): def handler(request): if request.path == "/v1/table/test/create/?mode=exist_ok": From 7ed03e1c4006f662e5da4b8e69c7b72f7904bd60 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:46:35 +0800 Subject: [PATCH 104/180] fix(python): honor bad-vector policies for pandas NaNs (#4503) Pandas converts NaN vector components to Arrow nulls. Both Python's NaN mask and Rust's default append validator ignored null children, so `add()` silently stored incomplete vectors despite `on_bad_vectors="error"`. Reject null components in the existing Rust ingestion validator, and include null components in Python's bad-vector detection and filling. `drop` removes affected rows, `fill` repairs missing components while preserving valid ones, and `null` replaces affected vectors. Explicit null components in Arrow and list inputs follow the same policies. Rust allows whole null vectors and retains the explicit `NaNVectorBehavior::Keep` opt-out. The ingestion guide and synchronous/asynchronous `create_table()` option docs describe null components, all four policies, and filling that preserves valid components. Validation: - Reproduced the default pandas append failure with the regression test before changing the Rust validator. - Rebuilt the native Python extension from the merged sources. The Python table and utility suites passed: 481 passed, 1 skipped. Coverage includes create/append/overwrite, pandas/rows/Arrow inputs, every bad-vector policy, float16/32/64, sliced and chunked arrays, all-null components, and hidden children of null lists. - All 43 focused Rust tests passed: 7 validator tests and 36 ingestion tests. - Rust Clippy with `remote`, tests, and examples passed. Ruff lint passes for the Python package, formatting checks pass for modified Python files, and `cargo fmt --all` is clean. - Documentation follow-up: all 56 focused vector-policy tests passed; Python package lint and creation-docstring formatting checks passed. Repository-wide Ruff reports 49 existing errors in untouched documentation examples. Create/overwrite retain their existing `RuntimeError` wrapping for errors raised while consuming lazy Arrow readers. Fixes #4435 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/web/ingestion/create-table.mdx | 8 ++- python/python/lancedb/db.py | 14 ++-- python/python/lancedb/table.py | 48 +++++-------- python/python/tests/test_table.py | 65 +++++++++++++++++ python/python/tests/test_util.py | 54 ++++++++++++-- rust/lancedb/src/table/add_data.rs | 31 +++++--- .../src/table/datafusion/reject_nan.rs | 71 +++++++++++++------ 7 files changed, 214 insertions(+), 77 deletions(-) diff --git a/docs/web/ingestion/create-table.mdx b/docs/web/ingestion/create-table.mdx index 7d4363be7..0921de22e 100644 --- a/docs/web/ingestion/create-table.mdx +++ b/docs/web/ingestion/create-table.mdx @@ -148,9 +148,11 @@ non-nullable column, or provide actual nulls for it, ingestion fails; nullable c omitted or written with null values. Without an explicit schema, Python infers list-like vector values as fixed-size `float32` vector fields from the observed dimension. -For Python ingest, malformed vector values fail by default. If you expect occasional wrong-length, -null, or NaN vectors, choose an `on_bad_vectors` policy: `"drop"` removes those rows, `"fill"` writes -`fill_value`, and `"null"` writes nulls. +For Python ingestion, malformed vectors fail by default (`on_bad_vectors="error"`). This includes +vectors with incorrect sizes, NaNs, or null components, including pandas NaNs converted to Arrow +nulls. Use `"drop"` to remove affected rows, or `"null"` to replace affected vectors with nulls. +Use `"fill"` to replace NaN or null components with `fill_value` while preserving valid components. +This also pads short vectors with `fill_value` and truncates long vectors to the expected dimension. ### From an Arrow Table {#from-an-arrow-table} You can also create LanceDB tables directly from Arrow tables. diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 1558dd52a..9ed772e1c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -428,10 +428,13 @@ class DBConnection(EnforceOverrides): it will not add the provided data but will validate against any schema that's specified. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. - One of "error", "drop", "fill". + How to handle vectors with incorrect sizes, NaNs, or null elements. + One of "error", "drop", "fill", "null". fill_value: float The value to use when filling vectors. Only used if on_bad_vectors="fill". + NaN or null elements and missing trailing elements are replaced with this + value. Valid elements are preserved, and vectors longer than the expected + dimension are truncated. storage_options: dict, optional Additional options for the storage backend. Options already set on the connection will be inherited by the table, but can be overridden here. @@ -2550,10 +2553,13 @@ class AsyncConnection(object): it will not add the provided data but will validate against any schema that's specified. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. - One of "error", "drop", "fill". + How to handle vectors with incorrect sizes, NaNs, or null elements. + One of "error", "drop", "fill", "null". fill_value: float The value to use when filling vectors. Only used if on_bad_vectors="fill". + NaN or null elements and missing trailing elements are replaced with this + value. Valid elements are preserved, and vectors longer than the expected + dimension are truncated. storage_options: dict, optional Additional options for the storage backend. Options already set on the connection will be inherited by the table, but can be overridden here. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 665520479..2ad7f821d 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -547,10 +547,11 @@ def _sanitize_data( metadata : Optional[dict], default None The embedding metadata to add to the schema. on_bad_vectors : Literal["error", "drop", "fill", "null"], default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. fill_value : float, default 0.0 The value to use when filling vectors. Only used if on_bad_vectors="fill". - All entries in the vector will be set to this value. + NaN or null elements and missing trailing elements are replaced with this + value. Valid elements are preserved. """ # At this point, the table might not match the schema we are targeting: # 1. There might be embedding columns missing that will be added @@ -1898,8 +1899,8 @@ class Table(ABC): "append" and "overwrite". Overwrite adopts explicitly declared blob layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. - One of "error", "drop", "fill". + How to handle vectors with incorrect sizes, NaNs, or null elements. + One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". progress: bool, callable, or tqdm-like, optional @@ -4254,7 +4255,7 @@ class LanceTable(Table): "append" and "overwrite". Overwrite adopts explicitly declared blob layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". @@ -4571,7 +4572,7 @@ class LanceTable(Table): otherwise just open the table, it will not add the provided data but will validate against any schema that's specified. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". @@ -5260,7 +5261,7 @@ def _handle_bad_vector_column( vector_column_name: str The name of the vector column. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0.0 The value to use when filling vectors. Only used if on_bad_vectors="fill". @@ -5279,7 +5280,8 @@ def _handle_bad_vector_column( data = data.set_column(position, vector_column_name, vec_arr) if expected_value_type is not None and ( - pa.types.is_integer(vec_arr.type.value_type) + pa.types.is_null(vec_arr.type.value_type) + or pa.types.is_integer(vec_arr.type.value_type) or pa.types.is_unsigned_integer(vec_arr.type.value_type) ): vec_arr = pa.array(vec_arr.to_pylist(), type=pa.list_(expected_value_type)) @@ -5323,7 +5325,7 @@ def _handle_bad_vector_column( ) else: raise ValueError( - f"Vector column '{vector_column_name}' has NaNs. " + f"Vector column '{vector_column_name}' has NaNs or null values. " "Set on_bad_vectors='drop' to remove them, " "set on_bad_vectors='fill' and fill_value= to replace them, " "or set on_bad_vectors='null' to replace them with null." @@ -5359,29 +5361,11 @@ def _fill_bad_vector_values( arr = arr.combine_chunks() # A fixed-size slice truncates long vectors and pads short vectors with nulls. - # Slice an array marking the original child nulls in parallel so padding nulls - # can be distinguished from null values that were already present. + # Both padding and existing null elements need to be filled. sliced = pc.list_slice(arr, 0, dim, return_fixed_size_list=True) - child_nulls = pc.is_null(arr.values) - parent_nulls = pc.is_null(arr) - if pa.types.is_list(arr.type): - original_child_nulls = pa.ListArray.from_arrays( - arr.offsets, child_nulls, mask=parent_nulls - ) - elif pa.types.is_large_list(arr.type): - original_child_nulls = pa.LargeListArray.from_arrays( - arr.offsets, child_nulls, mask=parent_nulls - ) - else: - original_child_nulls = pa.FixedSizeListArray.from_arrays( - child_nulls, arr.type.list_size, mask=parent_nulls - ) - sliced_child_nulls = pc.list_slice( - original_child_nulls, 0, dim, return_fixed_size_list=True - ) - needs_fill = pc.is_null(sliced_child_nulls.values) values = sliced.values + needs_fill = pc.is_null(values) if pa.types.is_floating(values.type): values_for_nan_check = ( values.cast(pa.float32()) if pa.types.is_float16(values.type) else values @@ -5395,6 +5379,7 @@ def _fill_bad_vector_values( def has_nan_values(arr: Union[pa.ListArray, pa.ChunkedArray]) -> pa.BooleanArray: + """Find vectors with NaN or null components, including pandas-converted NaNs.""" if isinstance(arr, pa.ChunkedArray): values = pa.chunked_array([chunk.flatten() for chunk in arr.chunks]) else: @@ -5405,6 +5390,9 @@ def has_nan_values(arr: Union[pa.ListArray, pa.ChunkedArray]) -> pa.BooleanArray values_has_nan = pc.is_nan(values.cast(pa.float32())) else: values_has_nan = pc.is_nan(values) + # Pandas represents NaN components as Arrow nulls. is_nan returns null + # for these values, so count them as invalid before filtering parent indices. + values_has_nan = pc.fill_null(values_has_nan, True) values_indices = pc.list_parent_indices(arr) if arr.null_count: # Match flatten(), which excludes child spans under null parent lists. @@ -6318,7 +6306,7 @@ class AsyncTable: "append" and "overwrite". Overwrite adopts explicitly declared blob layouts, while inferred bytes retain the existing blob v2 fields. on_bad_vectors: str, default "error" - What to do if any of the vectors are not the same size or contains NaNs. + How to handle vectors with incorrect sizes, NaNs, or null elements. One of "error", "drop", "fill", "null". fill_value: float, default 0. The value to use when filling vectors. Only used if on_bad_vectors="fill". diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 6ccba606f..7d92b0e6d 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2170,6 +2170,71 @@ def test_add_with_nans(mem_db: DBConnection): assert np.allclose(filled_vectors[22.0], np.array([5.0, 0.0])) +@pytest.mark.parametrize("operation", ["create", "append", "overwrite"]) +@pytest.mark.parametrize("input_type", ["pandas", "rows", "arrow"]) +@pytest.mark.parametrize("on_bad_vectors", [None, "error", "drop", "fill", "null"]) +def test_write_vectors_with_null_elements( + mem_db: DBConnection, operation, input_type, on_bad_vectors +): + schema = pa.schema({"vector": pa.list_(pa.float32(), 2), "id": pa.int64()}) + vectors = [[3.0, 4.0], [np.nan, 1.0], [np.nan, np.nan]] + if input_type == "pandas": + pd = pytest.importorskip("pandas") + + data = pd.DataFrame( + { + "vector": [np.array(v, dtype=np.float32) for v in vectors], + "id": [0, 1, 2], + } + ) + else: + # Pandas turns the NaNs above into null child elements. Explicit nulls + # in other input formats must follow the same bad-vector policy. + data = [ + {"vector": [3.0, 4.0], "id": 0}, + {"vector": [None, 1.0], "id": 1}, + {"vector": [None, None], "id": 2}, + ] + if input_type == "arrow": + data = pa.Table.from_pylist(data, schema=schema) + + options = {} if on_bad_vectors is None else {"on_bad_vectors": on_bad_vectors} + if on_bad_vectors == "fill": + options["fill_value"] = 42.0 + + table = None + if operation != "create": + table = mem_db.create_table("test", schema=schema) + + def write(): + if operation == "create": + return mem_db.create_table("test", data=data, schema=schema, **options) + table.add(data, mode=operation, **options) + return table + + if on_bad_vectors in (None, "error"): + # Create/overwrite can wrap errors from lazy Arrow readers in RuntimeError. + expected_error = ( + ValueError if operation == "append" else (ValueError, RuntimeError) + ) + with pytest.raises(expected_error, match="NaN|null"): + write() + if table is not None: + assert table.count_rows() == 0 + return + + table = write() + if on_bad_vectors == "drop": + expected = [{"vector": [3.0, 4.0], "id": 0}] + else: + expected = [ + {"vector": [3.0, 4.0], "id": 0}, + {"vector": [42.0, 1.0] if on_bad_vectors == "fill" else None, "id": 1}, + {"vector": [42.0, 42.0] if on_bad_vectors == "fill" else None, "id": 2}, + ] + assert table.to_arrow().to_pylist() == expected + + def test_add_with_empty_fixed_size_list_drops_bad_rows(mem_db: DBConnection): class Schema(LanceModel): text: str diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index 4fb16bb31..e85afb5bc 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -406,7 +406,7 @@ def test_handle_bad_vectors_jagged(on_bad_vectors): ).read_all() if on_bad_vectors == "drop": - expected = pa.array([[1.0, 2.0], [4.0, 5.0], [None, 9.0]]) + expected = pa.array([[1.0, 2.0], [4.0, 5.0]]) elif on_bad_vectors == "fill": expected = pa.array( [ @@ -414,12 +414,12 @@ def test_handle_bad_vectors_jagged(on_bad_vectors): [3.0, 42.0], [4.0, 5.0], [6.0, 7.0], - [None, 9.0], + [42.0, 9.0], [42.0, 42.0], ] ) elif on_bad_vectors == "null": - expected = pa.array([[1.0, 2.0], None, [4.0, 5.0], None, [None, 9.0], None]) + expected = pa.array([[1.0, 2.0], None, [4.0, 5.0], None, None, None]) assert output["vector"].combine_chunks() == expected @@ -430,17 +430,17 @@ def test_handle_bad_vectors_jagged(on_bad_vectors): ( pa.list_(pa.float64()), [[1.0, float("nan")], [2.0], None, [None, 3.0], [4.0, 5.0, 6.0]], - [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [None, 3.0], [4.0, 5.0]], + [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [42.0, 3.0], [4.0, 5.0]], ), ( pa.large_list(pa.float64()), [[1.0, float("nan")], [2.0], None, [None, 3.0], [4.0, 5.0, 6.0]], - [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [None, 3.0], [4.0, 5.0]], + [[1.0, 42.0], [2.0, 42.0], [42.0, 42.0], [42.0, 3.0], [4.0, 5.0]], ), ( pa.list_(pa.float64(), 2), [[1.0, float("nan")], None, [None, 3.0]], - [[1.0, 42.0], [42.0, 42.0], [None, 3.0]], + [[1.0, 42.0], [42.0, 42.0], [42.0, 3.0]], ), ], ) @@ -467,7 +467,7 @@ def test_handle_bad_vectors_nan(on_bad_vectors): ).read_all() output = exception_output(e) assert output == ( - "ValueError: Vector column 'vector' has NaNs. Set " + "ValueError: Vector column 'vector' has NaNs or null values. Set " "on_bad_vectors='drop' to remove them, set on_bad_vectors='fill' " "and fill_value= to replace them, or set on_bad_vectors='null' " "to replace them with null." @@ -490,6 +490,46 @@ def test_handle_bad_vectors_nan(on_bad_vectors): assert output["vector"].combine_chunks() == expected +@pytest.mark.parametrize("value_type", [pa.float16(), pa.float32(), pa.float64()]) +@pytest.mark.parametrize( + "list_type", [pa.list_, pa.large_list, lambda t: pa.list_(t, 2)] +) +@pytest.mark.parametrize("chunked", [False, True]) +def test_has_nan_values_with_null_elements(value_type, list_type, chunked): + arr = pa.array( + [[None, None], [1.0, 2.0], [None, 3.0], None, [4.0, float("nan")], [5.0, 6.0]], + type=list_type(value_type), + ).slice(1, 5) + if chunked: + arr = pa.chunked_array([arr.slice(0, 2), arr.slice(2)]) + # Whole null vectors have no components to inspect. Their handling is + # separate from missing or NaN components in a valid vector. + assert has_nan_values(arr).to_pylist() == [False, True, False, True, False] + + +@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"]) +def test_sanitize_vectors_with_only_null_elements(on_bad_vectors): + data = pa.table({"vector": [[None, None]]}) + schema = pa.schema({"vector": pa.list_(pa.float32(), 2)}) + + def sanitize(): + return _sanitize_data( + data, schema, on_bad_vectors=on_bad_vectors, fill_value=42.0 + ).read_all() + + if on_bad_vectors == "error": + with pytest.raises(ValueError, match="null"): + sanitize() + return + + expected = { + "drop": [], + "fill": [{"vector": [42.0, 42.0]}], + "null": [{"vector": None}], + } + assert sanitize().to_pylist() == expected[on_bad_vectors] + + @pytest.mark.parametrize("dtype", [pa.float16(), pa.float32(), pa.float64()]) @pytest.mark.parametrize("large", [False, True]) @pytest.mark.parametrize("chunked", [False, True]) diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 12404ec73..445f29a18 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -45,10 +45,12 @@ pub struct AddResult { #[derive(Debug, Default, Clone, Copy)] pub enum NaNVectorBehavior { - /// Reject any vectors containing NaN values (the default) + /// Reject any vectors containing NaN values or null elements (the default). + /// Whole null vectors are allowed. #[default] Error, - /// Allow NaN values to be added, but they will not be indexed for search + /// Allow NaN values and null elements to be added, but they will not be indexed + /// for search. Keep, } @@ -104,11 +106,12 @@ impl AddDataBuilder { self } - /// Configure how to handle NaN values in vector columns. + /// Configure how to handle NaN values and null elements in vector columns. /// - /// By default, any vectors containing NaN values will be rejected with an - /// error, since NaNs cannot be indexed for search. Setting this to `Keep` - /// will allow NaN values to be added to the table, but they will not be + /// By default, any vectors containing NaN values or null elements will be + /// rejected with an error, since these vectors cannot be indexed for search. + /// Whole null vectors are allowed. Setting this to `Keep` will allow NaN values + /// and null elements to be added to the table, but these vectors will not be /// indexed and will not be searchable. pub fn on_nan_vectors(mut self, behavior: NaNVectorBehavior) -> Self { self.on_nan_vectors = behavior; @@ -953,8 +956,11 @@ mod tests { ); } + #[rstest::rstest] + #[case::nan(Some(f32::NAN))] + #[case::null(None)] #[tokio::test] - async fn test_add_rejects_nan_vectors() { + async fn test_add_rejects_nan_or_null_vectors(#[case] bad_value: Option) { let schema = Arc::new(Schema::new(vec![Field::new( "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), @@ -974,7 +980,12 @@ mod tests { FixedSizeListArray::try_new( Arc::new(Field::new("item", DataType::Float32, true)), 4, - Arc::new(Float32Array::from(vec![0.1, 0.2, f32::NAN, 0.4])), + Arc::new(Float32Array::from(vec![ + Some(0.1), + Some(0.2), + bad_value, + Some(0.4), + ])), None, ) .unwrap(), @@ -984,8 +995,8 @@ mod tests { let res = table.add(batch.clone()).execute().await; let err = res.unwrap_err(); assert!( - err.to_string().contains("NaN"), - "Expected error mentioning NaN values, but got: {err:?}" + err.to_string().contains("NaN or null"), + "Expected error mentioning NaN or null values, but got: {err:?}" ); table diff --git a/rust/lancedb/src/table/datafusion/reject_nan.rs b/rust/lancedb/src/table/datafusion/reject_nan.rs index 084c9722b..462216929 100644 --- a/rust/lancedb/src/table/datafusion/reject_nan.rs +++ b/rust/lancedb/src/table/datafusion/reject_nan.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! A DataFusion projection that rejects vectors containing NaN values. +//! A DataFusion projection that rejects vectors containing NaN or null elements. use std::sync::{Arc, LazyLock}; @@ -31,10 +31,12 @@ fn is_vector_field(field: &Field) -> bool { } } -/// Wraps the input plan with a projection that checks vector columns for NaN values. +/// Wraps the input plan with a projection that checks vector columns for NaN or +/// null elements. /// /// Non-vector columns pass through unchanged. Vector columns are wrapped with a -/// UDF that returns the column as-is if no NaNs are present, or errors otherwise. +/// UDF that returns the column as-is if no NaN or null elements are present, or +/// errors otherwise. Whole null vectors pass through unchanged. pub fn reject_nan_vectors(input: Arc) -> Result> { let schema = input.schema(); let config = Arc::new(ConfigOptions::default()); @@ -70,7 +72,7 @@ pub fn reject_nan_vectors(input: Arc) -> Result datafusion_common::Result<()> { ) })?; - // Only inspect elements that are both in a valid parent row and non-null - // themselves. Values backing null parent rows or null child elements may - // contain garbage (including NaN) per the Arrow spec. - let has_nan = (0..fsl.len()).filter(|i| fsl.is_valid(*i)).any(|i| { + // Values backing null parent rows may contain garbage per the Arrow spec. + // A null child in a valid row is an invalid vector component, however: + // pandas can represent NaN components as Arrow nulls. + let has_bad_values = (0..fsl.len()).filter(|i| fsl.is_valid(*i)).any(|i| { let row = fsl.value(i); + if row.null_count() > 0 { + return true; + } match row.data_type() { DataType::Float16 => row .as_any() @@ -150,10 +155,10 @@ fn check_no_nans(array: &dyn Array) -> datafusion_common::Result<()> { } }); - if has_nan { + if has_bad_values { return Err(datafusion_common::DataFusionError::ArrowError( Box::new(arrow_schema::ArrowError::ComputeError( - "Vector column contains NaN values".to_string(), + "Vector column contains NaN or null values".to_string(), )), None, )); @@ -165,7 +170,7 @@ fn check_no_nans(array: &dyn Array) -> datafusion_common::Result<()> { #[cfg(test)] mod tests { use super::*; - use arrow_array::Float32Array; + use arrow_array::{Float16Array, Float32Array, Float64Array}; #[test] fn test_passes_clean_vectors() { @@ -209,23 +214,43 @@ mod tests { } #[test] - fn test_skips_null_elements_within_valid_row() { - // A valid row with null child elements: the underlying buffer may hold - // NaN but the null bitmap says they're absent — should not reject. - let values = Float32Array::from(vec![ - Some(1.0), - None, // null element — buffer may contain NaN - Some(3.0), - None, // null element - ]); + fn test_rejects_null_elements_within_valid_row() { + let arrays: Vec> = vec![ + Arc::new(Float16Array::from(vec![Some(half::f16::ONE), None])), + Arc::new(Float32Array::from(vec![Some(1.0), None])), + Arc::new(Float64Array::from(vec![Some(1.0), None])), + ]; + for values in arrays { + let fsl = FixedSizeListArray::try_new( + Arc::new(Field::new("item", values.data_type().clone(), true)), + 2, + values, + None, + ) + .unwrap(); + let err = check_no_nans(&fsl).unwrap_err(); + assert!(err.to_string().contains("null")); + } + } + + #[test] + fn test_skips_null_elements_in_null_rows_and_outside_slice() { let fsl = FixedSizeListArray::try_new( Arc::new(Field::new("item", DataType::Float32, true)), 2, - Arc::new(values), - None, // both rows are valid + Arc::new(Float32Array::from(vec![ + None, + Some(1.0), + Some(2.0), + Some(3.0), + None, + None, + ])), + Some(vec![true, true, false].into()), ) .unwrap(); - assert!(check_no_nans(&fsl).is_ok()); + assert!(check_no_nans(&fsl.slice(1, 2)).is_ok()); + assert!(check_no_nans(&fsl.slice(0, 2)).is_err()); } #[test] From 22fc2a2087c1ed78033eadb056b1aef63abd1b69 Mon Sep 17 00:00:00 2001 From: devjoinedthechat Date: Mon, 26 Oct 2026 11:17:14 +0100 Subject: [PATCH 105/180] fix(python)!: put OpenCLIP models in eval mode before embedding (#4536) `OpenClipEmbeddings` loads its model with `open_clip.create_model_and_transforms()`, which hands the model back in training mode (the open_clip README calls `model.eval()` right after it for that reason). `OpenClipEmbeddings` never switches it out of training mode, so layers that behave differently during training stay active while we embed: stochastic depth in the timm-based image towers (ViTamin, ConvNeXt, MobileCLIP2-L-14), dropout in the Hugging Face text towers (`xlm-roberta-*`, `roberta-ViT-B-32`, `nllb-clip-*`), and batch norm in the ResNet towers loaded with non-OpenAI weights. The `torch.no_grad()` blocks turn off autograd but don't change how these layers behave. The default `ViT-B-32` has none of those layers, which is probably why nobody has run into this. With dropout or stochastic depth active, the same input gives a different vector on every call, so the vector stored at ingestion and the one computed for an identical query don't match. With batch norm in training mode, an image's vector depends on the other images in its batch: ```python import numpy as np from PIL import Image from lancedb.embeddings import get_registry func = get_registry().get("open-clip").create(name="ViTamin-S", pretrained="datacomp1b") image = Image.new("RGB", (256, 256), "red") a = func.generate_image_embedding(image) b = func.generate_image_embedding(image) print(func._model.training, np.array_equal(a, b)) # before: True False # after: False True ``` The fix calls `model.eval()` once after loading, same as the SigLIP, ColPali and ImageBind embedding functions already do. The new test swaps in a stand-in for the `open_clip` module, so it runs without torch or a model download, and checks that the model handed back by `create_model_and_transforms` ends up in eval mode. BREAKING CHANGE: Embeddings change for OpenCLIP models with training-sensitive layers, including ViTamin, ConvNeXt, MobileCLIP2, Hugging Face RoBERTa/XLM-RoBERTa/NLLB text towers, and ResNet models loaded with non-OpenAI weights. For tables embedded with affected models, regenerate the stored embeddings in eval mode and rebuild their vector indexes before querying with the new embeddings. Rebuilding an index alone does not regenerate embeddings. The default ViT-B-32 model is unaffected. Co-authored-by: devjoinedthechat <235875317+devjoinedthechat@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/embeddings/open_clip.py | 3 ++ python/python/tests/test_embeddings.py | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/python/python/lancedb/embeddings/open_clip.py b/python/python/lancedb/embeddings/open_clip.py index 8b3f0eb06..6199ef271 100644 --- a/python/python/lancedb/embeddings/open_clip.py +++ b/python/python/lancedb/embeddings/open_clip.py @@ -49,6 +49,9 @@ class OpenClipEmbeddings(EmbeddingFunction): self.name, pretrained=self.pretrained ) model.to(self.device) + # open_clip returns the model in training mode, which keeps dropout, + # stochastic depth and batch norm in their training behaviour. + model.eval() self._model, self._preprocess = model, preprocess self._tokenizer = open_clip.get_tokenizer(self.name) self._ndims = None diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 207a3d253..3c968a821 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -1039,6 +1039,39 @@ def test_open_clip_opens_percent_encoded_file_uri(tmp_path): assert image.size == (4, 4) +def test_open_clip_model_in_eval_mode(): + """ + open_clip.create_model_and_transforms returns the model in training mode, + which leaves dropout, stochastic depth and batch norm in their training + behaviour. OpenCLIP must switch the model to eval mode before embedding. + """ + from lancedb.embeddings.open_clip import OpenClipEmbeddings + + class FakeModel: + training = True + + def to(self, device): + return self + + def eval(self): + self.training = False + return self + + open_clip = MagicMock() + open_clip.create_model_and_transforms.return_value = (FakeModel(), None, None) + + with patch( + "lancedb.embeddings.open_clip.attempt_import_or_raise", + return_value=open_clip, + ): + func = OpenClipEmbeddings(name="ViTamin-B", pretrained="datacomp1b") + + open_clip.create_model_and_transforms.assert_called_once_with( + "ViTamin-B", pretrained="datacomp1b" + ) + assert func._model.training is False + + def test_jina_generate_image_input_dict_local_path(tmp_path): """ JinaEmbeddings._generate_image_input_dict must accept a local image path From 66357275bb3cbf55e565113e3d8966cd0f7a291c Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:57:25 +0800 Subject: [PATCH 106/180] fix: inherit Lance defaults for IVF RQ quantization (#4585) `IvfRq()` forced `num_bits=1` through Python's Rust binding, overriding Lance's five-bit default. The shared native index creation path also substituted one bit when the Rust or Node builder left the value unset. Make Python's bit count optional and forward only explicit values. Use `RQBuildParams::default()` for an unset native bit count, and omit unset values when dispatching to pylance for accelerator builds. Update the Python, Rust, Node, and vector-index documentation. New indexes with an unset bit count now inherit Lance's default, currently five bits, across Python, Rust, and Node. Five-bit vector codes use roughly five times the storage of one-bit codes, plus other index overhead. This also changes reader compatibility: indexes created with `num_bits >= 2` use a newer on-disk layout that some older LanceDB versions cannot read. Upgrade readers to versions that support multi-bit IVF_RQ, or explicitly set `num_bits=1` (for example, `IvfRq(num_bits=1)` in Python) when sharing indexes with readers limited to one-bit IVF_RQ. Validation: - Reproduced six regression failures before the fix: one-bit default metadata, rejected `None`, and incorrect remote/accelerator forwarding. - After merging `main` through `b762ec22`, rebuilt both native bindings against Lance 15.0.0-beta.1. Python validation passed with 106 tests and 15 optional Ollama skips. Coverage includes the full index suite, omitted and explicit bit counts, reading Lance-created IVF_RQ indexes, accelerator forwarding, CUDA-unavailability handling, timeout validation, remote requests, and table/namespace listing behavior. - Rust formatting and Python package Ruff lint/format checks pass. Node `pnpm lint`, `pnpm build` (including TypeScript checks), `pnpm run docs`, the full connection suite, and the existing IVF_RQ regression pass. Generated documentation adds no further changes. The merge preserves upstream's explicit RaBitQ heading anchor alongside the `IvfRq()` example and five-bit default/reader-compatibility guidance. Repository-wide `ruff check .` still reports 49 existing errors in unchanged documentation examples under `docs/web-tests`; root formatting also finds 11 unchanged documentation example files. The Python package checks pass. Fixes #4582 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/src/js/interfaces/IvfRqOptions.md | 3 ++- docs/web/indexing/vector-index.mdx | 17 +++++++++++------ nodejs/lancedb/indices.ts | 3 ++- python/python/lancedb/index.py | 8 ++++++-- python/python/lancedb/table.py | 7 ++++++- python/python/tests/test_index.py | 14 ++++++++++++-- python/python/tests/test_remote_db.py | 11 +++++++++-- python/python/tests/test_table.py | 22 ++++++++++++++++++++++ python/src/index.rs | 8 +++++--- rust/lancedb/src/index/vector.rs | 3 +++ rust/lancedb/src/table/create_index.rs | 5 ++++- 11 files changed, 82 insertions(+), 19 deletions(-) diff --git a/docs/src/js/interfaces/IvfRqOptions.md b/docs/src/js/interfaces/IvfRqOptions.md index 6b48cf653..298565a62 100644 --- a/docs/src/js/interfaces/IvfRqOptions.md +++ b/docs/src/js/interfaces/IvfRqOptions.md @@ -58,7 +58,8 @@ Number of bits per dimension for residual quantization. This value controls how much each residual component is compressed. The more bits, the more accurate the index will be but the slower search. Typical values -are small integers; the default is 1 bit per dimension. +are small integers. If unset, uses Lance's default (currently 5 bits per +dimension). Set to 1 for maximum compression. *** diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index b26e0c295..037d75f8d 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -58,7 +58,7 @@ Lance with `index_type`. | If your priority is... | Use this index | Why | Approx. compression ratio | Python config class | | :--- | :--- | :--- | :--- | :--- | -| Maximum compression | `IVF_RQ` | IVF indexing with RaBitQ quantization | Around `1/32` of raw size | `IvfRq` | +| Maximum compression | `IVF_RQ` | IVF indexing with RaBitQ quantization | Around `1/32` of raw size with `num_bits=1` | `IvfRq` | | Higher accuracy at small dimensions (`dimension <= 256`) | `IVF_PQ` | IVF indexing with product quantization | Usually `1/64` to `1/16` of raw size (depends on `num_sub_vectors`) | `IvfPq` | | Best recall/latency trade-off | `IVF_HNSW_SQ` | IVF-HNSW indexing with scalar | Typically a little larger than `1/4` of raw size | `IvfHnswSq` | | Highest recall / no quantization | `IVF_HNSW_FLAT` | IVF-HNSW indexing with no quantization; embedded library only | Around raw vector size plus HNSW graph overhead | `IvfHnswFlat` | @@ -377,7 +377,7 @@ which has been compressed to $4$ chunks $\times 8$-bit integers $= 32$ bits of q RaBitQ is an advanced quantization technique that outperforms PQ in several ways. It needs no codebook to train, estimates distances very quickly at query-time, -and crucially, quantizes each vector in (with some small overhead) just **one bit per dimension!** +and can quantize each vector in (with some small overhead) as little as **one bit per dimension!** In practice, RaBitQ compresses a $1024$-dimensional `float32` vector into just a few thousand bits, while maintaining good recall. The inner workings of RaBitQ quantization are rather mathematically dense. It generates a quantization codebook by @@ -385,14 +385,19 @@ applying a uniformly random, approximately distance-preserving orthogonal transf where $d$ is the dimensionality of the dataset. We defer the details, and an elegant theoretical error bound, to [the original paper.](https://arxiv.org/pdf/2405.12497) ##### Using RaBitQ {#using-rabitq} -Use RaBitQ quantization by selecting quantized index types ending in the suffix `RQ`. For example, call `create_index` with `index_type="IVF_RQ"`. +Use RaBitQ quantization by selecting quantized index types ending in the suffix `RQ`. For example, import `IvfRq` from `lancedb.index` and call `table.create_index("vector", config=IvfRq())`. Note that when using `IVF_RQ`, the dimension of the dataset must be a multiple of `8`. `num_bits` determines how many bits are used to quantize each dimension. -`1` is the standard RaBitQ setting. Increase to `2`, `4`, or `8` bits to achieve better recall for additional storage and query-time compute. +By default, Python, Rust, and Node leave this unset and inherit Lance's default, currently `5` bits. +Higher values improve recall at the cost of additional storage and query-time compute. +To retain the previous one-bit default and maximum compression, explicitly set `num_bits=1` (for example, `IvfRq(num_bits=1)` in Python). +Five-bit quantized vector codes use roughly five times the storage of one-bit codes; total index size also includes other overhead. -RaBitQ-quantized indexes computed with `num_bits >= 2` use a newer on-disk layout, and cannot be read by some older LanceDB versions. +RaBitQ-quantized indexes computed with `num_bits >= 2` use a newer on-disk layout and cannot be read by some older LanceDB versions. +The new five-bit default therefore affects reader compatibility as well as index size. +Upgrade readers to versions that support multi-bit IVF_RQ before creating indexes with the default settings, or explicitly set `num_bits=1` when sharing indexes with readers that support only one-bit IVF_RQ. See this [blog post](https://lancedb.com/blog/feature-rabitq-quantization/) for further discussion and benchmarking of LanceDB's RaBitQ implementation. @@ -410,7 +415,7 @@ among all integral multiples $\{j \times 10^5: -128 \leq j \leq 127 \}$. | Parameter | Description | | :--- | :--- | -| `num_bits` | Bits per dimension for quantization. Only applies to `IVF_PQ`/`IVF_HNSW_PQ` (default `8`) and `IVF_RQ` (default `1`, RaBitQ); not used by `IVF_FLAT`/`IVF_SQ`/`IVF_HNSW_FLAT`/`IVF_HNSW_SQ`. Higher values improve accuracy at the cost of additional storage. | +| `num_bits` | Bits per dimension for quantization. Only applies to `IVF_PQ`/`IVF_HNSW_PQ` (default `8`) and `IVF_RQ` (`IvfRq()` inherits Lance's default, currently `5`, RaBitQ); not used by `IVF_FLAT`/`IVF_SQ`/`IVF_HNSW_FLAT`/`IVF_HNSW_SQ`. Higher values improve accuracy at the cost of additional storage. | `max_iterations` and `sample_rate` also affect quantizer training, but since they apply to every IVF/HNSW index type (not just quantized ones), they're documented as general [Build-time Parameters](/indexing/vector-index#build-time-parameters) instead. All three are passed as keyword arguments to `create_index`, alongside `index_type`: diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index 43d1cf1b5..0e383e984 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -131,7 +131,8 @@ export interface IvfRqOptions { * * This value controls how much each residual component is compressed. The more * bits, the more accurate the index will be but the slower search. Typical values - * are small integers; the default is 1 bit per dimension. + * are small integers. If unset, uses Lance's default (currently 5 bits per + * dimension). Set to 1 for maximum compression. */ numBits?: number; diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index cf3bf8e4f..80179f4a7 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -882,8 +882,12 @@ class IvfRq: num_partitions: int, default sqrt(num_rows) Number of IVF partitions to create. - num_bits: int, default 1 + num_bits: int, optional Number of bits to encode each dimension in the RabitQ codebook. + If None, uses Lance's default (currently 5), matching Rust and Node. + Set to 1 to retain the previous Python default and maximum compression. + Five-bit vector codes use roughly five times the storage of one-bit codes, + in addition to other index overhead. max_iterations: int, default 50 Max iterations to train kmeans when computing IVF partitions. @@ -897,7 +901,7 @@ class IvfRq: distance_type: Literal["l2", "cosine", "dot"] = "l2" num_partitions: Optional[int] = None - num_bits: int = 1 + num_bits: Optional[int] = None max_iterations: int = 50 sample_rate: int = 256 target_partition_size: Optional[int] = None diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 2ad7f821d..cc455f746 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3754,6 +3754,11 @@ class LanceTable(Table): cfg_type = type(config).__name__ lance_index_type = index_type_map.get(cfg_type, "IVF_PQ") + quantization_kwargs = {} + num_bits = getattr(config, "num_bits", 8) + if num_bits is not None: + quantization_kwargs["num_bits"] = num_bits + dataset.create_index( column=column, index_type=lance_index_type, @@ -3762,12 +3767,12 @@ class LanceTable(Table): num_sub_vectors=getattr(config, "num_sub_vectors", None), replace=replace, accelerator=acc, - num_bits=getattr(config, "num_bits", 8), m=getattr(config, "m", 20), ef_construction=getattr(config, "ef_construction", 300), target_partition_size=getattr( config, "target_partition_size", None ), + **quantization_kwargs, ) self.checkout_latest() return diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 0252a09ad..2ec14f6f8 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -421,13 +421,23 @@ async def test_create_4bit_ivfpq_index(some_table: AsyncTable): @pytest.mark.asyncio -async def test_create_ivfrq_index(some_table: AsyncTable): - await some_table.create_index("vector", config=IvfRq(num_bits=1)) +@pytest.mark.parametrize( + "config, expected_bits", + [ + pytest.param(IvfRq(), 5, id="default"), + pytest.param(IvfRq(num_bits=None), 5, id="none"), + pytest.param(IvfRq(num_bits=1), 1, id="one-bit"), + pytest.param(IvfRq(num_bits=4), 4, id="multi-bit"), + ], +) +async def test_create_ivfrq_index(some_table: AsyncTable, config, expected_bits): + await some_table.create_index("vector", config=config) indices = await some_table.list_indices() assert len(indices) == 1 assert indices[0].index_type == "IvfRq" assert indices[0].columns == ["vector"] assert indices[0].name == "vector_idx" + assert indices[0].index_details["compression"]["num_bits"] == expected_bits @pytest.mark.asyncio diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 95da3eba2..049a5fc58 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1593,7 +1593,10 @@ def test_remote_json_fts_config(server_version): assert request["block_size"] == 256 -def test_remote_create_index_new_api(caplog): +@pytest.mark.parametrize( + "rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}] +) +def test_remote_create_index_new_api(caplog, rq_kwargs): received_requests = [] def handler(request): @@ -1666,7 +1669,7 @@ def test_remote_create_index_new_api(caplog): table.create_index("category", config=BTree()) table.create_index("text", config=FTS(block_size=256)) # IvfRq via new API - table.create_index("vector", config=IvfRq(distance_type="l2")) + table.create_index("vector", config=IvfRq(distance_type="l2", **rq_kwargs)) table.create_index( "vector", config=IvfPq(distance_type="l2"), replace=False ) @@ -1691,6 +1694,10 @@ def test_remote_create_index_new_api(caplog): "vector", ] assert received_requests[2]["block_size"] == 256 + if rq_kwargs.get("num_bits") is None: + assert "num_bits" not in received_requests[3] + else: + assert received_requests[3]["num_bits"] == rq_kwargs["num_bits"] assert received_requests[4]["replace"] is False assert received_requests[5]["replace"] is False assert "replace is not supported" not in caplog.text diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 7d92b0e6d..3b3ccd122 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1751,6 +1751,28 @@ def test_create_index_async_returns_done_job(mem_db: DBConnection): job.cancel() +@pytest.mark.parametrize( + "rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}] +) +@patch("lancedb.table.LanceTable.to_lance") +def test_create_ivfrq_index_accelerator(mock_to_lance, mem_db: DBConnection, rq_kwargs): + from lancedb.index import IvfRq + + table = mem_db.create_table("test", [{"vector": [1.0] * 8}]) + torch = MagicMock() + torch.cuda.is_available.return_value = True + with patch.dict(sys.modules, {"torch": torch}): + table.create_index("vector", config=IvfRq(accelerator="cuda", **rq_kwargs)) + + kwargs = mock_to_lance.return_value.create_index.call_args.kwargs + assert kwargs["index_type"] == "IVF_RQ" + assert kwargs["accelerator"] == "cuda" + if rq_kwargs.get("num_bits") is None: + assert "num_bits" not in kwargs + else: + assert kwargs["num_bits"] == rq_kwargs["num_bits"] + + @pytest.mark.parametrize("method", ["create_index", "create_index_async"]) @pytest.mark.parametrize("wait_timeout", ["invalid", 1, []]) def test_create_index_invalid_wait_timeout(mem_db: DBConnection, method, wait_timeout): diff --git a/python/src/index.rs b/python/src/index.rs index d4e16a67e..c6c3fe17d 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -136,8 +136,10 @@ pub fn extract_index_params(source: &Option>) -> PyResult, - num_bits: u32, + num_bits: Option, max_iterations: u32, sample_rate: u32, target_partition_size: Option, diff --git a/rust/lancedb/src/index/vector.rs b/rust/lancedb/src/index/vector.rs index bce77a610..3e6794b54 100644 --- a/rust/lancedb/src/index/vector.rs +++ b/rust/lancedb/src/index/vector.rs @@ -362,6 +362,9 @@ impl IvfRqIndexBuilder { impl_distance_type_setter!(); impl_ivf_params_setter!(); + /// Set the number of bits used to encode each vector dimension. + /// + /// If unset, uses Lance's default (currently 5). Set to 1 for maximum compression. pub fn num_bits(mut self, num_bits: u32) -> Self { self.num_bits = Some(num_bits); self diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 3ac759bdd..1795b778e 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -355,7 +355,10 @@ impl NativeTable { index.sample_rate, index.max_iterations, ); - let rq_params = RQBuildParams::new(index.num_bits.unwrap_or(1) as u8); + let rq_params = index + .num_bits + .map(|num_bits| RQBuildParams::new(num_bits as u8)) + .unwrap_or_default(); let lance_idx_params = VectorIndexParams::with_ivf_rq_params( index.distance_type.into(), ivf_params, From 3dd579785edf209f0e410b339be89ba7cc71757d Mon Sep 17 00:00:00 2001 From: KarthikS Date: Mon, 26 Oct 2026 07:28:44 -0400 Subject: [PATCH 107/180] fix(python)!: align synchronous table method signatures (#4498) Closes #4396. Calls written against `Table` can fail or bind different arguments when used with `RemoteTable`. Align the affected sync signatures, positional order, and defaults; preserve renamed remote keywords as deprecated aliases. Share legacy vector configuration and tokenizer inference, forward index tuning and timeout options, and accept `fast_search` consistently. Preserve current upstream conversion behavior: local `to_polars(batch_size=...)` returns a LazyFrame; remote tables accept the same argument signature but raise the documented unsupported-operation error and direct callers to `table.search().to_polars()`. The abstract `Table` method retains its unsupported-operation error, with the implementation confined to `LanceTable`. Regression coverage checks argument binding, deprecated aliases, option forwarding, native behavior through both wrappers, HTTP index requests, and remote conversion rejection. The merge preserves current tokenizer defaults, remote query defaults, HNSW-PQ support, and unsupported-operation handling. Runtime validation at `c4fb01f2` (Linux x86_64, uv-managed Python 3.12.15): - Focused Ruff lint and formatting passed for all four changed Python files. - Rebuilt and installed the current native extension successfully with the repository's `ci` Cargo profile. - Seven regression suites passed: `test_errors.py`, `test_table_signatures.py`, `test_remote_db.py`, `test_table.py`, `test_index.py`, `test_fts.py`, and `test_query.py`: **874 passed, 1 deselected**, with slow and S3 tests excluded. - CI caught an abstract-base conversion regression in the initial merge. The existing error-contract test reproduced it locally (1 failed, 7 passed); restoring the implementation to `LanceTable` fixes it while preserving signature parity. - Full-root Ruff reports 49 lint errors and 11 files needing formatting, all in unchanged upstream `docs/web-tests` files. The four changed Python files pass both checks. - Validated against upstream `197403e8`, using Lance 15.0.0-beta.1 and LanceDB 0.41.0-beta.14 bindings. Historical validation before this merge: 618 tests passed and one was deselected. That result does not establish correctness of the current merge. The original client-side reproduction produced nine argument-binding errors without contacting a server; the initial regression suite failed 32 cases before the fix and passed 39 after it. Documentation review follow-up: restored the `batch_size` parameter description on the abstract `Table.to_polars` method so it appears in the public API reference. This adds six docstring lines and changes no runtime behavior. After this edit, all 47 focused error-contract and signature tests pass; changed-file Ruff lint/format and `git diff --check` pass. Repository-wide Ruff still reports the same 49 findings and 11 formatting files in unchanged `docs/web-tests`. The full documentation site and seven-suite runtime run were not repeated for this documentation-only follow-up. The reported ARM64 production-server deployment has not been recreated. HTTP integration tests use the repository's local mock server. BREAKING CHANGE: Remote synchronous table methods now use the positional argument order and defaults documented by `Table`. Migrate calls using the former remote-only positional order to named arguments, particularly `create_index` and `search`; pass `index_type` by keyword to `create_scalar_index`. Remote scalar and vector index creation now default to `replace=True`; specify `replace=False` to retain rejection of an existing index. Renamed remote keywords remain supported as deprecated aliases, as documented above. --------- Co-authored-by: Xuanwo --- docs/src/python/python.md | 19 + python/python/lancedb/remote/table.py | 343 ++++++++------- python/python/lancedb/table.py | 433 ++++++++++--------- python/python/tests/test_remote_db.py | 31 +- python/python/tests/test_table_signatures.py | 253 +++++++++++ 5 files changed, 733 insertions(+), 346 deletions(-) create mode 100644 python/python/tests/test_table_signatures.py diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 02ccced2c..4d0dfc87a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -297,6 +297,25 @@ listing a storage directory. ## Tables (Synchronous) +Local and remote tables use the same arguments for index creation, deletion, +index statistics, and search. For example, `table.delete(where="id = 1")`, +`table.create_index("cosine", 2)` (the deprecated vector API), and +`table.search([1.0, 1.0], fast_search=True)` work with either backend. +`fast_search=True` excludes rows that have not been indexed. + +`create_scalar_index` defaults to `replace=True` on both backends. Both scalar +and full-text index creation accept `wait_timeout`. Remote maintenance methods +accept the local options: cleanup and compaction warn that they are no-ops, +while `optimize` reports an unsupported operation. Removed Tantivy options +produce the same explanatory errors on both backends. + +The old remote keyword names `predicate` for `delete`, `index_name` for +`drop_index`, `index_uuid` for `index_stats`, and `column` for `create_fts_index` +remain available with deprecation warnings. Use `where`, `name`, `index_name`, +and `field_names`, respectively. For positional calls, use the argument order +documented by `Table` below; specify index options by keyword when migrating +code that used the former remote-only argument order. + ::: lancedb.table.Table ::: lancedb.table.FragmentStatistics diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index dd22dea48..faf15c987 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -4,7 +4,7 @@ from datetime import timedelta import deprecation import logging -from functools import cached_property +from functools import cached_property, wraps import os from typing import ( TYPE_CHECKING, @@ -42,19 +42,12 @@ from lancedb.index import ( FTS, BTree, Bitmap, - HnswFlat, - HnswPq, - HnswSq, - IvfFlat, - IvfPq, - IvfRq, - IvfSq, LabelList, ) from lancedb.job import Job from lancedb.functions import FunctionApplication, RefreshColumnResult from lancedb.remote.db import LOOP -from lancedb.table import IndexConfigType, KNOWN_METRICS +from lancedb.table import IndexConfigType, _maybe_add_fts_error_note import pyarrow as pa from lancedb.common import DATA, VEC, VECTOR_COLUMN_NAME @@ -69,7 +62,6 @@ from ..query import ( FullTextQuery, LanceQueryBuilder, LanceTakeQueryBuilder, - LanceVectorQueryBuilder, ) from ..table import ( AsyncTable, @@ -80,7 +72,7 @@ from ..table import ( Table, Tags, ) -from ..types import BaseTokenizerType +from ..types import BaseTokenizerType, ScalarIndexType from ..util import infer_vector_column_name if TYPE_CHECKING: @@ -88,6 +80,28 @@ if TYPE_CHECKING: import polars as pl +def _deprecated_keyword(old_name: str, new_name: str): + """Keep old remote-only keyword names without changing the Table signature.""" + + def decorate(method): + @wraps(method) + def wrapped(self, *args, **kwargs): + if old_name in kwargs: + if new_name in kwargs: + raise TypeError(f"Cannot specify both {old_name} and {new_name}") + warnings.warn( + f"{old_name} is deprecated; use {new_name} instead", + DeprecationWarning, + stacklevel=2, + ) + kwargs[new_name] = kwargs.pop(old_name) + return method(self, *args, **kwargs) + + return wrapped + + return decorate + + class RemoteTable(Table): def __init__( self, @@ -268,7 +282,7 @@ class RemoteTable(Table): """ return LOOP.run(self._table.to_lance(**kwargs)) - def to_polars(self, **kwargs) -> "pl.LazyFrame": + def to_polars(self, batch_size=None) -> "pl.LazyFrame": """Use ``table.search().to_polars()`` to read remote query results.""" raise NotImplementedError( "to_polars() is not supported for remote tables. " @@ -315,9 +329,10 @@ class RemoteTable(Table): self._table.tokenize(query, column=column, index_name=index_name) ) - def index_stats(self, index_uuid: str) -> Optional[IndexStatistics]: + @_deprecated_keyword("index_uuid", "index_name") + def index_stats(self, index_name: str) -> Optional[IndexStatistics]: """List all the stats of a specified index""" - return LOOP.run(self._table.index_stats(index_uuid)) + return LOOP.run(self._table.index_stats(index_name)) @deprecation.deprecated( deprecated_in="0.25.0", @@ -327,43 +342,38 @@ class RemoteTable(Table): def create_scalar_index( self, column: str, - index_type: Literal["BTREE", "BITMAP", "LABEL_LIST", "scalar"] = "scalar", *, - replace: bool = False, + replace: bool = True, + index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): - """Creates a scalar index. + """Create a scalar index on a column. .. deprecated:: 0.25.0 Use :meth:`create_index` with a BTree, Bitmap, or LabelList config instead. Example: ``table.create_index("column", config=BTree())`` - - Parameters - ---------- - column : str - The column to be indexed. Must be a boolean, integer, float, - or string column. - index_type : str - The index type of the scalar index. Must be "scalar" (BTREE), - "BTREE", "BITMAP", or "LABEL_LIST", - replace : bool - If True, replace the existing index with the new one. """ - if index_type == "scalar" or index_type == "BTREE": + if index_type == "scalar": + warnings.warn( + 'index_type="scalar" is deprecated; use "BTREE" instead', + DeprecationWarning, + stacklevel=2, + ) + index_type = "BTREE" + if index_type == "BTREE": config = BTree() elif index_type == "BITMAP": config = Bitmap() elif index_type == "LABEL_LIST": config = LabelList() else: - raise ValueError(f"Unknown index type: {index_type}") - - LOOP.run( + raise ValueError(f"Unknown index type {index_type}") + return LOOP.run( self._table.create_index( column, - config=config, replace=replace, + config=config, wait_timeout=wait_timeout, name=name, ) @@ -374,12 +384,16 @@ class RemoteTable(Table): current_version=__version__, details="Use create_index() with config=FTS() instead.", ) + @_deprecated_keyword("column", "field_names") def create_fts_index( self, - column: str, + field_names: Union[str, List[str]], *, + ordering_field_names: Optional[Union[str, List[str]]] = None, replace: bool = False, - wait_timeout: Optional[timedelta] = None, + writer_heap_size: Optional[int] = 1024 * 1024 * 1024, + use_tantivy: bool = False, + tokenizer_name: Optional[str] = None, with_position: bool = False, # tokenizer configs: base_tokenizer: BaseTokenizerType = "simple", @@ -395,6 +409,7 @@ class RemoteTable(Table): prefix_only: bool = False, block_size: int = 128, document_granularity: DocumentGranularity = DocumentGranularity.ROW, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): """Create a full-text search index on a column. @@ -403,31 +418,70 @@ class RemoteTable(Table): Use :meth:`create_index` with an FTS config instead. Example: ``table.create_index("text_column", config=FTS())`` """ + if use_tantivy: + raise ValueError( + "Tantivy-based FTS has been removed. " + "Remove use_tantivy and recreate the index with native FTS." + ) + if ordering_field_names is not None: + raise ValueError( + "ordering_field_names was only supported by the removed " + "Tantivy-based FTS implementation." + ) + if writer_heap_size != 1024 * 1024 * 1024: + raise ValueError( + "writer_heap_size was only supported by the removed " + "Tantivy-based FTS implementation." + ) + if not isinstance(field_names, str): + raise ValueError( + "Native FTS indexes can only be created on a single field " + "at a time. To search over multiple text fields, create a " + "separate FTS index for each field." + ) + + if tokenizer_name is None: + tokenizer_configs = { + "base_tokenizer": base_tokenizer, + "language": language, + "with_position": with_position, + "max_token_length": max_token_length, + "lower_case": lower_case, + "stem": stem, + "remove_stop_words": remove_stop_words, + "custom_stop_words": custom_stop_words, + "ascii_folding": ascii_folding, + "ngram_min_length": ngram_min_length, + "ngram_max_length": ngram_max_length, + "prefix_only": prefix_only, + } + else: + tokenizer_configs = self.infer_tokenizer_configs(tokenizer_name) + tokenizer_configs["custom_stop_words"] = custom_stop_words + config = FTS( - with_position=with_position, - base_tokenizer=base_tokenizer, - language=language, - max_token_length=max_token_length, - lower_case=lower_case, - stem=stem, - remove_stop_words=remove_stop_words, - custom_stop_words=custom_stop_words, - ascii_folding=ascii_folding, - ngram_min_length=ngram_min_length, - ngram_max_length=ngram_max_length, - prefix_only=prefix_only, block_size=block_size, document_granularity=document_granularity, + **tokenizer_configs, ) - LOOP.run( - self._table.create_index( - column, - config=config, - replace=replace, - wait_timeout=wait_timeout, - name=name, + + try: + LOOP.run( + self._table.create_index( + field_names, + replace=replace, + config=config, + name=name, + wait_timeout=wait_timeout, + ) ) - ) + except (ValueError, RuntimeError) as e: + _maybe_add_fts_error_note( + e, + base_tokenizer=config.base_tokenizer, + language=config.language, + ) + raise e # New unified API overload @overload @@ -437,6 +491,7 @@ class RemoteTable(Table): /, *, config: IndexConfigType, + replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., train: bool = ..., @@ -447,38 +502,56 @@ class RemoteTable(Table): def create_index( self, metric: Literal["l2", "cosine", "dot", "hamming"] = ..., - vector_column_name: str = ..., - index_cache_size: Optional[int] = ..., num_partitions: Optional[int] = ..., num_sub_vectors: Optional[int] = ..., - replace: Optional[bool] = ..., + vector_column_name: str = ..., + replace: bool = ..., accelerator: Optional[str] = ..., - index_type: Literal[ - "VECTOR", "IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ" - ] = ..., - wait_timeout: Optional[timedelta] = ..., - *, + index_cache_size: Optional[int] = ..., num_bits: int = ..., + index_type: Literal[ + "IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_RQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ" + ] = ..., + max_iterations: int = ..., + sample_rate: int = ..., + m: int = ..., + ef_construction: int = ..., + *, + wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., train: bool = ..., + target_partition_size: Optional[int] = ..., ) -> None: ... def create_index( self, metric: str = "l2", - vector_column_name: str = VECTOR_COLUMN_NAME, - index_cache_size: Optional[int] = None, num_partitions: Optional[int] = None, num_sub_vectors: Optional[int] = None, - replace: Optional[bool] = None, + vector_column_name: str = VECTOR_COLUMN_NAME, + replace: bool = True, accelerator: Optional[str] = None, - index_type="vector", - wait_timeout: Optional[timedelta] = None, - *, + index_cache_size: Optional[int] = None, num_bits: int = 8, + index_type: Literal[ + "IVF_FLAT", + "IVF_SQ", + "IVF_PQ", + "IVF_RQ", + "IVF_HNSW_SQ", + "IVF_HNSW_PQ", + "IVF_HNSW_FLAT", + ] = "IVF_PQ", + max_iterations: int = 50, + sample_rate: int = 256, + m: int = 20, + ef_construction: int = 300, + *, config: Optional[IndexConfigType] = None, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, train: bool = True, + target_partition_size: Optional[int] = None, ): """Create an index on a column. @@ -489,6 +562,24 @@ class RemoteTable(Table): argument plus separate ``vector_column_name`` / ``num_partitions`` / etc. parameters, and emits a ``DeprecationWarning``. + Parameters + ---------- + metric : str + For new API: the column name to index. + For legacy API: the distance metric ("l2", "cosine", "dot", "hamming"). + config : IndexConfigType, optional + The index configuration object. If provided, uses the new unified API. + Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq, + BTree, Bitmap, LabelList, Fm, FTS. + replace : bool, default True + Whether to replace an existing index on this column. + wait_timeout : timedelta, optional + Timeout to wait for async indexing to complete. + name : str, optional + Custom name for the index. + train : bool, default True + Whether to train the index with existing data. + Examples -------- New API (recommended): @@ -514,7 +605,6 @@ class RemoteTable(Table): vector_column_name, accelerator, index_cache_size, - replace, ) if is_legacy: @@ -530,6 +620,7 @@ class RemoteTable(Table): stacklevel=2, ) + # Legacy API: first arg is the distance metric column = vector_column_name if accelerator is not None: @@ -538,45 +629,27 @@ class RemoteTable(Table): "and will be ignored." ) - idx_type = index_type.upper() - if idx_type == "VECTOR" or idx_type == "IVF_PQ": - config = IvfPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - ) - elif idx_type == "IVF_RQ": - config = IvfRq( - distance_type=metric, - num_partitions=num_partitions, - num_bits=num_bits, - ) - elif idx_type == "IVF_SQ": - config = IvfSq(distance_type=metric, num_partitions=num_partitions) - elif idx_type == "IVF_HNSW_PQ": - config = HnswPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - ) - elif idx_type == "IVF_HNSW_SQ": - config = HnswSq(distance_type=metric, num_partitions=num_partitions) - elif idx_type == "IVF_HNSW_FLAT": - config = HnswFlat(distance_type=metric, num_partitions=num_partitions) - elif idx_type == "IVF_FLAT": - config = IvfFlat(distance_type=metric, num_partitions=num_partitions) - else: - raise ValueError( - f"Unknown vector index type: {idx_type}. Valid options are" - " 'IVF_FLAT', 'IVF_PQ', 'IVF_RQ', 'IVF_SQ'," - " 'IVF_HNSW_PQ', 'IVF_HNSW_SQ', 'IVF_HNSW_FLAT'" - ) + # Build config from legacy parameters + config = self._build_vector_config_from_legacy_params( + metric=metric, + index_type="IVF_PQ" + if index_type.upper() == "VECTOR" + else index_type.upper(), + num_partitions=num_partitions, + num_sub_vectors=num_sub_vectors, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + accelerator=None, + ) + else: column = metric - LOOP.run( + return LOOP.run( self._table.create_index( column, replace=replace, @@ -615,37 +688,6 @@ class RemoteTable(Table): ) ) - def _is_legacy_create_index_call( - self, - first_arg: str, - config: Optional[IndexConfigType], - num_partitions: Optional[int], - num_sub_vectors: Optional[int], - vector_column_name: str, - accelerator: Optional[str], - index_cache_size: Optional[int], - replace: Optional[bool], - ) -> bool: - """Detect if this is a legacy create_index call.""" - if config is not None: - return False - if any( - x is not None - for x in ( - num_partitions, - num_sub_vectors, - accelerator, - index_cache_size, - replace, - ) - ): - return True - if vector_column_name != VECTOR_COLUMN_NAME: - return True - if first_arg.lower() in KNOWN_METRICS: - return True - return False - def add( self, data: DATA, @@ -717,9 +759,10 @@ class RemoteTable(Table): query: Union[VEC, str] = None, vector_column_name: Optional[str] = None, query_type="auto", + ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, - ) -> LanceVectorQueryBuilder: + ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -810,6 +853,7 @@ class RemoteTable(Table): query, query_type, vector_column_name=vector_column_name, + ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], fast_search=fast_search, ) @@ -869,7 +913,8 @@ class RemoteTable(Table): self._table._do_merge(merge, new_data, on_bad_vectors, fill_value) ) - def delete(self, predicate: str) -> DeleteResult: + @_deprecated_keyword("predicate", "where") + def delete(self, where: Union[str, Expr]) -> DeleteResult: """Delete rows from the table. This can be used to delete a single row, many rows, all rows, or @@ -877,7 +922,7 @@ class RemoteTable(Table): Parameters ---------- - predicate: str + where: Union[str, Expr] The SQL where clause to use when deleting rows. - For example, 'x = 2' or 'x IN (1, 2, 3)'. @@ -921,7 +966,7 @@ class RemoteTable(Table): x vector _distance # doctest: +SKIP 0 2 [3.0, 4.0] 85.0 # doctest: +SKIP """ - return LOOP.run(self._table.delete(predicate)) + return LOOP.run(self._table.delete(where)) def update( self, @@ -983,7 +1028,12 @@ class RemoteTable(Table): self._table.update(where=where, updates=values, updates_sql=values_sql) ) - def cleanup_old_versions(self, *_): + def cleanup_old_versions( + self, + older_than: Optional[timedelta] = None, + *, + delete_unverified: bool = False, + ): """ cleanup_old_versions() is a no-op for remote tables. """ @@ -993,7 +1043,7 @@ class RemoteTable(Table): ) pass - def compact_files(self, *_): + def compact_files(self, *args, **kwargs): """ compact_files() is a no-op for remote tables. """ @@ -1008,12 +1058,14 @@ class RemoteTable(Table): *, cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, + retrain: bool = False, ): """optimize() is not supported for remote tables.""" return LOOP.run( self._table.optimize( cleanup_older_than=cleanup_older_than, delete_unverified=delete_unverified, + retrain=retrain, ) ) @@ -1121,8 +1173,9 @@ class RemoteTable(Table): """No-op for remote tables (no local shard writers).""" return LOOP.run(self._table.close_rte_writers()) - def drop_index(self, index_name: str): - return LOOP.run(self._table.drop_index(index_name)) + @_deprecated_keyword("index_name", "name") + def drop_index(self, name: str) -> None: + return LOOP.run(self._table.drop_index(name)) def prewarm_index(self, name: str) -> None: """Prewarm an index in the table. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index cc455f746..d2ff02683 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -265,10 +265,8 @@ if TYPE_CHECKING: OnBadVectorsType, AddMode, CreateMode, - VectorIndexType, ScalarIndexType, BaseTokenizerType, - DistanceType, ) # Type alias for index configuration objects @@ -1489,12 +1487,18 @@ class Table(ABC): """ raise NotImplementedError("to_lance is not supported for this table type") - def to_polars(self, **kwargs) -> "pl.LazyFrame": + def to_polars(self, batch_size=None) -> "pl.LazyFrame": """Return the table as a Polars LazyFrame. For remote tables, use ``table.search().to_polars()`` to convert query results to a Polars DataFrame. + Parameters + ---------- + batch_size: int, optional + Passed to Polars as the maximum row count for scanned PyArrow + record batches. + Note ---- The Polars streaming engine is not supported because it does not currently @@ -1507,6 +1511,193 @@ class Table(ABC): """ raise NotImplementedError("to_polars is not supported for this table type") + def _is_legacy_create_index_call( + self, + first_arg: str, + config: Optional[IndexConfigType], + num_partitions: Optional[int], + num_sub_vectors: Optional[int], + vector_column_name: str, + accelerator: Optional[str], + index_cache_size: Optional[int], + ) -> bool: + """Detect if this is a legacy create_index call.""" + # If config is provided, it's definitely the new API + if config is not None: + return False + + # If old-style parameters were explicitly set, it's legacy + if any( + x is not None + for x in (num_partitions, num_sub_vectors, accelerator, index_cache_size) + ): + return True + + # If vector_column_name differs from default, it's legacy + if vector_column_name != VECTOR_COLUMN_NAME: + return True + + # If first arg is a known metric, assume legacy + if first_arg.lower() in KNOWN_METRICS: + return True + + # Otherwise assume new API + return False + + def _build_vector_config_from_legacy_params( + self, + metric: str, + index_type: str, + num_partitions: Optional[int], + num_sub_vectors: Optional[int], + num_bits: int, + max_iterations: int, + sample_rate: int, + m: int, + ef_construction: int, + target_partition_size: Optional[int], + accelerator: Optional[str], + ) -> IndexConfigType: + """Build an index config object from legacy parameters.""" + if index_type == "IVF_FLAT": + return IvfFlat( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_SQ": + return IvfSq( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_PQ": + return IvfPq( + distance_type=metric, + num_partitions=num_partitions, + num_sub_vectors=num_sub_vectors, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_RQ": + return IvfRq( + distance_type=metric, + num_partitions=num_partitions, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_HNSW_PQ": + return HnswPq( + distance_type=metric, + num_partitions=num_partitions, + num_sub_vectors=num_sub_vectors, + num_bits=num_bits, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_HNSW_SQ": + return HnswSq( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + accelerator=accelerator, + ) + elif index_type == "IVF_HNSW_FLAT": + return HnswFlat( + distance_type=metric, + num_partitions=num_partitions, + max_iterations=max_iterations, + sample_rate=sample_rate, + m=m, + ef_construction=ef_construction, + target_partition_size=target_partition_size, + ) + else: + raise ValueError(f"Unknown index type {index_type}") + + @staticmethod + def infer_tokenizer_configs(tokenizer_name: str) -> dict: + if tokenizer_name == "default": + return { + "base_tokenizer": "simple", + "language": "English", + "max_token_length": 40, + "lower_case": True, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } + elif tokenizer_name == "raw": + return { + "base_tokenizer": "raw", + "language": "English", + "max_token_length": None, + "lower_case": False, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } + elif tokenizer_name == "whitespace": + return { + "base_tokenizer": "whitespace", + "language": "English", + "max_token_length": None, + "lower_case": False, + "stem": False, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } + + # or it's with language stemming with pattern like "en_stem" + if len(tokenizer_name) != 7: + raise ValueError(f"Invalid tokenizer name {tokenizer_name}") + lang = tokenizer_name[:2] + if tokenizer_name[-5:] != "_stem": + raise ValueError(f"Invalid tokenizer name {tokenizer_name}") + if lang not in lang_mapping: + raise ValueError(f"Invalid language code {lang}") + return { + "base_tokenizer": "simple", + "language": lang_mapping[lang], + "max_token_length": 40, + "lower_case": True, + "stem": True, + "remove_stop_words": False, + "ascii_folding": False, + "ngram_min_length": 3, + "ngram_max_length": 3, + "prefix_only": False, + } + # New unified API overload @overload def create_index( @@ -1532,14 +1723,16 @@ class Table(ABC): replace: bool = ..., accelerator: Optional[str] = ..., index_cache_size: Optional[int] = ..., - *, - index_type: VectorIndexType = ..., - wait_timeout: Optional[timedelta] = ..., num_bits: int = ..., + index_type: Literal[ + "IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_RQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ" + ] = ..., max_iterations: int = ..., sample_rate: int = ..., m: int = ..., ef_construction: int = ..., + *, + wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., train: bool = ..., target_partition_size: Optional[int] = ..., @@ -1547,22 +1740,30 @@ class Table(ABC): def create_index( self, - metric: DistanceType = "l2", + metric: str = "l2", num_partitions: Optional[int] = None, num_sub_vectors: Optional[int] = None, vector_column_name: str = VECTOR_COLUMN_NAME, replace: bool = True, accelerator: Optional[str] = None, index_cache_size: Optional[int] = None, - *, - index_type: VectorIndexType = "IVF_PQ", - wait_timeout: Optional[timedelta] = None, num_bits: int = 8, + index_type: Literal[ + "IVF_FLAT", + "IVF_SQ", + "IVF_PQ", + "IVF_RQ", + "IVF_HNSW_SQ", + "IVF_HNSW_PQ", + "IVF_HNSW_FLAT", + ] = "IVF_PQ", max_iterations: int = 50, sample_rate: int = 256, m: int = 20, ef_construction: int = 300, + *, config: Optional[IndexConfigType] = None, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, train: bool = True, target_partition_size: Optional[int] = None, @@ -2019,6 +2220,7 @@ class Table(ABC): query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -3816,130 +4018,6 @@ class LanceTable(Table): ) ) - def _is_legacy_create_index_call( - self, - first_arg: str, - config: Optional[IndexConfigType], - num_partitions: Optional[int], - num_sub_vectors: Optional[int], - vector_column_name: str, - accelerator: Optional[str], - index_cache_size: Optional[int], - ) -> bool: - """Detect if this is a legacy create_index call.""" - # If config is provided, it's definitely the new API - if config is not None: - return False - - # If old-style parameters were explicitly set, it's legacy - if any( - x is not None - for x in (num_partitions, num_sub_vectors, accelerator, index_cache_size) - ): - return True - - # If vector_column_name differs from default, it's legacy - if vector_column_name != VECTOR_COLUMN_NAME: - return True - - # If first arg is a known metric, assume legacy - if first_arg.lower() in KNOWN_METRICS: - return True - - # Otherwise assume new API - return False - - def _build_vector_config_from_legacy_params( - self, - metric: str, - index_type: str, - num_partitions: Optional[int], - num_sub_vectors: Optional[int], - num_bits: int, - max_iterations: int, - sample_rate: int, - m: int, - ef_construction: int, - target_partition_size: Optional[int], - accelerator: Optional[str], - ) -> IndexConfigType: - """Build an index config object from legacy parameters.""" - if index_type == "IVF_FLAT": - return IvfFlat( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_SQ": - return IvfSq( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_PQ": - return IvfPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_RQ": - return IvfRq( - distance_type=metric, - num_partitions=num_partitions, - num_bits=num_bits, - max_iterations=max_iterations, - sample_rate=sample_rate, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_HNSW_PQ": - return HnswPq( - distance_type=metric, - num_partitions=num_partitions, - num_sub_vectors=num_sub_vectors, - num_bits=num_bits, - max_iterations=max_iterations, - sample_rate=sample_rate, - m=m, - ef_construction=ef_construction, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_HNSW_SQ": - return HnswSq( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - m=m, - ef_construction=ef_construction, - target_partition_size=target_partition_size, - accelerator=accelerator, - ) - elif index_type == "IVF_HNSW_FLAT": - return HnswFlat( - distance_type=metric, - num_partitions=num_partitions, - max_iterations=max_iterations, - sample_rate=sample_rate, - m=m, - ef_construction=ef_construction, - target_partition_size=target_partition_size, - ) - else: - raise ValueError(f"Unknown index type {index_type}") - def drop_index(self, name: str) -> None: """ Drops an index from the table @@ -4050,6 +4128,7 @@ class LanceTable(Table): *, replace: bool = True, index_type: ScalarIndexType = "BTREE", + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): """Create a scalar index on a column. @@ -4058,6 +4137,13 @@ class LanceTable(Table): Use :meth:`create_index` with a BTree, Bitmap, or LabelList config instead. Example: ``table.create_index("column", config=BTree())`` """ + if index_type == "scalar": + warnings.warn( + 'index_type="scalar" is deprecated; use "BTREE" instead', + DeprecationWarning, + stacklevel=2, + ) + index_type = "BTREE" if index_type == "BTREE": config = BTree() elif index_type == "BITMAP": @@ -4067,7 +4153,13 @@ class LanceTable(Table): else: raise ValueError(f"Unknown index type {index_type}") return LOOP.run( - self._table.create_index(column, replace=replace, config=config, name=name) + self._table.create_index( + column, + replace=replace, + config=config, + wait_timeout=wait_timeout, + name=name, + ) ) @deprecation.deprecated( @@ -4099,6 +4191,7 @@ class LanceTable(Table): prefix_only: bool = False, block_size: int = 128, document_granularity: DocumentGranularity = DocumentGranularity.ROW, + wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): """Create a full-text search index on a column. @@ -4163,6 +4256,7 @@ class LanceTable(Table): replace=replace, config=config, name=name, + wait_timeout=wait_timeout, ) ) except (ValueError, RuntimeError) as e: @@ -4173,69 +4267,6 @@ class LanceTable(Table): ) raise e - @staticmethod - def infer_tokenizer_configs(tokenizer_name: str) -> dict: - if tokenizer_name == "default": - return { - "base_tokenizer": "simple", - "language": "English", - "max_token_length": 40, - "lower_case": True, - "stem": False, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - elif tokenizer_name == "raw": - return { - "base_tokenizer": "raw", - "language": "English", - "max_token_length": None, - "lower_case": False, - "stem": False, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - elif tokenizer_name == "whitespace": - return { - "base_tokenizer": "whitespace", - "language": "English", - "max_token_length": None, - "lower_case": False, - "stem": False, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - - # or it's with language stemming with pattern like "en_stem" - if len(tokenizer_name) != 7: - raise ValueError(f"Invalid tokenizer name {tokenizer_name}") - lang = tokenizer_name[:2] - if tokenizer_name[-5:] != "_stem": - raise ValueError(f"Invalid tokenizer name {tokenizer_name}") - if lang not in lang_mapping: - raise ValueError(f"Invalid language code {lang}") - return { - "base_tokenizer": "simple", - "language": lang_mapping[lang], - "max_token_length": 40, - "lower_case": True, - "stem": True, - "remove_stop_words": False, - "ascii_folding": False, - "ngram_min_length": 3, - "ngram_max_length": 3, - "prefix_only": False, - } - def add( self, data: DATA, @@ -4386,6 +4417,7 @@ class LanceTable(Table): query_type: Literal["vector"] = "vector", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceVectorQueryBuilder: ... @overload @@ -4396,6 +4428,7 @@ class LanceTable(Table): query_type: Literal["fts"] = "fts", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceFtsQueryBuilder: ... @overload @@ -4408,6 +4441,7 @@ class LanceTable(Table): query_type: Literal["hybrid"] = "hybrid", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceHybridQueryBuilder: ... @overload @@ -4418,6 +4452,7 @@ class LanceTable(Table): query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceEmptyQueryBuilder: ... def search( @@ -4429,6 +4464,7 @@ class LanceTable(Table): query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + fast_search: Optional[bool] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/) @@ -4513,6 +4549,7 @@ class LanceTable(Table): vector_column_name=vector_column_name, ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], + fast_search=fast_search, ) @classmethod diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 049a5fc58..db3394735 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1155,8 +1155,9 @@ def test_table_create_indices(): # Test create_fts_index with custom name (legacy method) with pytest.warns(DeprecationWarning, match="create_fts_index"): table.create_fts_index( - "text", + field_names="text", wait_timeout=timedelta(seconds=2), + tokenizer_name="en_stem", block_size=256, custom_stop_words=["cloud"], name="custom_fts_idx", @@ -1165,6 +1166,8 @@ def test_table_create_indices(): # Test create_index with custom name (legacy form: vector_column_name kwarg) with pytest.warns(DeprecationWarning, match="create_index"): table.create_index( + "cosine", + 2, vector_column_name="vector", wait_timeout=timedelta(seconds=10), name="custom_vector_idx", @@ -1177,7 +1180,8 @@ def test_table_create_indices(): scalar_req = received_requests[0] assert "name" in scalar_req assert scalar_req["name"] == "custom_scalar_idx" - assert scalar_req["replace"] is False + # The wire protocol omits replace=True (the server default). + assert "replace" not in scalar_req # Check FTS index request has custom name fts_req = received_requests[1] @@ -1186,18 +1190,39 @@ def test_table_create_indices(): assert fts_req["replace"] is False assert fts_req["block_size"] == 256 assert fts_req["custom_stop_words"] == ["cloud"] + assert fts_req["language"] == "English" + assert fts_req["stem"] is True # Check vector index request has custom name vector_req = received_requests[2] assert "name" in vector_req assert vector_req["name"] == "custom_vector_idx" assert "replace" not in vector_req + assert vector_req["metric_type"] == "cosine" + assert vector_req["num_partitions"] == 2 + + with pytest.warns(DeprecationWarning, match="create_index"): + table.create_index( + index_type="IVF_HNSW_SQ", + num_partitions=1, + m=10, + ef_construction=50, + max_iterations=12, + sample_rate=64, + ) + tuned_req = received_requests[-1] + assert tuned_req["index_type"] == "IVF_HNSW_SQ" + assert tuned_req["num_partitions"] == 1 + assert tuned_req["m"] == 10 + assert tuned_req["ef_construction"] == 50 + assert tuned_req["max_iterations"] == 12 + assert tuned_req["sample_rate"] == 64 table.wait_for_index(["custom_scalar_idx"], timedelta(seconds=2)) table.wait_for_index( ["custom_fts_idx", "custom_vector_idx"], timedelta(seconds=2) ) - table.drop_index("custom_vector_idx") + table.drop_index(name="custom_vector_idx") table.drop_index("custom_scalar_idx") table.drop_index("custom_fts_idx") diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py new file mode 100644 index 000000000..346935b2b --- /dev/null +++ b/python/python/tests/test_table_signatures.py @@ -0,0 +1,253 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta +import inspect +from unittest.mock import AsyncMock, MagicMock + +import lancedb +from lancedb.expr import col +from lancedb.index import BTree, FTS, HnswSq, IvfPq +from lancedb.remote.table import RemoteTable +from lancedb.table import LanceTable, Table +import pyarrow as pa +import pytest + + +@pytest.mark.parametrize( + "method", + [ + "delete", + "drop_index", + "index_stats", + "create_index", + "create_scalar_index", + "create_fts_index", + "search", + "cleanup_old_versions", + "compact_files", + "optimize", + "to_polars", + ], +) +def test_sync_table_signatures(method): + """A Table call must bind the same arguments on either backend.""" + + def parameters(cls): + return [ + (p.name, p.kind, p.default) + for p in inspect.signature(getattr(cls, method)).parameters.values() + ] + + assert parameters(Table) == parameters(LanceTable) == parameters(RemoteTable) + + +@pytest.fixture(params=[LanceTable, RemoteTable], ids=["local", "remote"]) +def sync_table(request, monkeypatch): + """Exercise real sync wrappers with a recording async backend.""" + handle = MagicMock() + handle.name = "test" + handle.create_index = AsyncMock() + handle.delete = AsyncMock() + handle.drop_index = AsyncMock() + handle.index_stats = AsyncMock() + if request.param is RemoteTable: + table = RemoteTable(handle, "test_db") + else: + table = LanceTable.__new__(LanceTable) + table._table = handle + monkeypatch.setattr(table, "_ensure_no_legacy_fts_index", lambda: None) + return table, handle + + +def test_sync_keyword_names(sync_table): + table, handle = sync_table + predicate = col("id") == 1 + table.delete(where=predicate) + handle.delete.assert_awaited_once() + expected = predicate._inner if isinstance(table, LanceTable) else predicate + assert handle.delete.await_args.args[0] is expected + table.drop_index(name="vector_idx") + handle.drop_index.assert_awaited_once_with("vector_idx") + table.index_stats(index_name="vector_idx") + handle.index_stats.assert_awaited_once_with("vector_idx") + + +def test_legacy_vector_positional_arguments(sync_table): + table, handle = sync_table + with pytest.warns(DeprecationWarning): + table.create_index("cosine", 2) + args, kwargs = handle.create_index.await_args + assert args == ("vector",) + assert isinstance(kwargs["config"], IvfPq) + assert kwargs["config"].distance_type == "cosine" + assert kwargs["config"].num_partitions == 2 + assert kwargs["replace"] is True + + +def test_vector_tuning_options(sync_table): + table, handle = sync_table + timeout = timedelta(seconds=2) + with pytest.warns(DeprecationWarning): + table.create_index( + index_type="IVF_HNSW_SQ", + num_partitions=1, + m=10, + ef_construction=50, + max_iterations=12, + sample_rate=64, + target_partition_size=1000, + wait_timeout=timeout, + name="custom_idx", + replace=False, + train=False, + ) + kwargs = handle.create_index.await_args.kwargs + config = kwargs.pop("config") + assert isinstance(config, HnswSq) + for name, value in { + "num_partitions": 1, + "m": 10, + "ef_construction": 50, + "max_iterations": 12, + "sample_rate": 64, + "target_partition_size": 1000, + }.items(): + assert getattr(config, name) == value + assert kwargs == dict( + wait_timeout=timeout, name="custom_idx", replace=False, train=False + ) + + +def test_scalar_defaults_and_wait_timeout(sync_table): + table, handle = sync_table + timeout = timedelta(seconds=2) + with pytest.warns(DeprecationWarning): + table.create_scalar_index("id", wait_timeout=timeout) + kwargs = handle.create_index.await_args.kwargs + assert isinstance(kwargs["config"], BTree) + assert kwargs["replace"] is True + assert kwargs["wait_timeout"] == timeout + + +def test_fts_tokenizer_and_wait_timeout(sync_table): + table, handle = sync_table + timeout = timedelta(seconds=2) + with pytest.warns(DeprecationWarning): + table.create_fts_index( + field_names="text", + tokenizer_name="en_stem", + replace=True, + wait_timeout=timeout, + custom_stop_words=["example"], + ) + args, kwargs = handle.create_index.await_args + assert args == ("text",) + assert kwargs["replace"] is True + assert kwargs["wait_timeout"] == timeout + config = kwargs["config"] + assert isinstance(config, FTS) + assert config.language == "English" + assert config.stem is True + assert config.custom_stop_words == ["example"] + + +@pytest.mark.parametrize( + "kwargs, message", + [ + ({"use_tantivy": True}, "Tantivy-based FTS has been removed"), + ({"ordering_field_names": "id"}, "ordering_field_names"), + ({"writer_heap_size": 123}, "writer_heap_size"), + ({"tokenizer_name": "invalid"}, "Invalid tokenizer name"), + ], +) +def test_fts_unsupported_options(sync_table, kwargs, message): + table, handle = sync_table + with pytest.warns(DeprecationWarning), pytest.raises(ValueError, match=message): + table.create_fts_index("text", **kwargs) + handle.create_index.assert_not_awaited() + + +@pytest.mark.parametrize( + "method, kwargs", + [ + ( + "cleanup_old_versions", + {"older_than": timedelta(days=1), "delete_unverified": True}, + ), + ("compact_files", {"target_rows_per_fragment": 1000}), + ], +) +def test_remote_maintenance_options_warn(method, kwargs): + table = RemoteTable(MagicMock(name="test"), "test_db") + with pytest.warns(UserWarning, match="no-op"): + getattr(table, method)(**kwargs) + + +def test_remote_optimize_options(): + handle = MagicMock() + handle.optimize = AsyncMock(side_effect=NotImplementedError("remote optimize")) + table = RemoteTable(handle, "test_db") + age = timedelta(days=1) + with pytest.raises(NotImplementedError, match="remote optimize"): + table.optimize(cleanup_older_than=age, delete_unverified=True, retrain=True) + handle.optimize.assert_awaited_once_with( + cleanup_older_than=age, delete_unverified=True, retrain=True + ) + + +@pytest.mark.parametrize( + "method, old, new, value", + [ + ("delete", "predicate", "where", "id = 1"), + ("drop_index", "index_name", "name", "vector_idx"), + ("index_stats", "index_uuid", "index_name", "vector_idx"), + ("create_fts_index", "column", "field_names", "text"), + ], +) +def test_deprecated_remote_keywords(method, old, new, value): + handle = MagicMock() + handle.name = "test" + target = "create_index" if method == "create_fts_index" else method + setattr(handle, target, AsyncMock()) + table = RemoteTable(handle, "test_db") + with pytest.warns(DeprecationWarning, match=f"{old} is deprecated"): + getattr(table, method)(**{old: value}) + assert getattr(handle, target).await_args.args == (value,) + with pytest.raises(TypeError, match="Cannot specify both"): + getattr(table, method)(**{old: value, new: value}) + + +@pytest.mark.parametrize("remote_wrapper", [False, True], ids=["local", "remote"]) +def test_sync_search_and_polars(tmp_path, remote_wrapper): + """Use the native engine through both sync wrappers, without a cloud service.""" + local = lancedb.connect(tmp_path).create_table( + "test", + [{"id": 1, "text": "quick fox", "vector": [1.0, 1.0]}], + ) + table = RemoteTable(local._table, "test_db") if remote_wrapper else local + table.create_index("text", config=FTS()) + assert table.search("quick", query_type="fts").to_arrow()["id"].to_pylist() == [1] + # Both backends must accept the deprecated ordering argument in the same slot. + with pytest.warns(DeprecationWarning, match="ordering_field_name"): + table.search("quick", None, "fts", "id", ["text"]) + fast = table.search([1.0, 1.0], fast_search=True).to_arrow() + assert len(fast) == 0 # No vector index: fast_search excludes unindexed rows. + assert table.search([1.0, 1.0]).to_arrow()["id"].to_pylist() == [1] + if remote_wrapper: + with pytest.raises(NotImplementedError, match=r"table.search\(\).to_polars"): + table.to_polars(batch_size=1) + assert table.search().to_polars()["id"].to_list() == [1] + else: + assert table.to_polars(batch_size=1).collect()["id"].to_list() == [1] + table.delete(where="id = 1") + assert table.count_rows() == 0 + + +def test_index_replacement_defaults(tmp_path): + local = lancedb.connect(tmp_path).create_table("test", pa.table({"id": [1]})) + table = RemoteTable(local._table, "test_db") + for sync in [local, table]: + with pytest.warns(DeprecationWarning): + sync.create_scalar_index("id") + assert len(list(table.list_indices())) == 1 From 982b2a1229ecbce435ed10a24bd0e54d1228f7ca Mon Sep 17 00:00:00 2001 From: KarthikS Date: Mon, 26 Oct 2026 08:12:53 -0400 Subject: [PATCH 108/180] fix(python): restore sync remote connection and table API parity (#4473) Fixes #4400. Sync remote connections fail on `uri`, `len(db)`, and `name in db`, and remote tables lack `namespace`, `id`, and `replace_field_metadata`. Share the paginated connection helpers and table identifier contract through the base classes, and delegate remote metadata replacement to the existing async implementation. Unsupported remote session and read-consistency properties raise explicit `NotImplementedError`s. Reconciled with main at `3dd57978`, including the synchronous method signatures from #4498. The local session fix has already landed in #4433, so this PR preserves its supplied-session-or-None contract and adds no Rust/PyO3 session access. Namespace connections retain their writable properties. Existing custom `Table` subclasses remain instantiable: `namespace` defaults to a fresh empty list, and deprecated `replace_field_metadata` delegates to `update_field_metadata` with `replace=True` while retaining its `None` return. Native and remote overrides are preserved. Regression tests instantiate an old-style subclass through normal ABC class creation and verify identifiers, independent namespace lists, deprecation, and exact metadata delegation. Historical validation at `03c43f7b` before the latest main integration and subclass compatibility repair, Ubuntu x86-64, Python 3.12.13: - Rebuilt the native extension with the repository `ci` profile and locked Python dependencies. - 273 tests passed across `test_sync_api_parity.py`, `test_db.py`, `test_remote_db.py`, and `test_session.py`. - 84 namespace and catalog compatibility tests passed (357 tests total). - Python SDK lint and formatting pass (158 files); changed-file checks and `git diff --check` pass. - Repository-wide lint/format checks report existing issues in unchanged `docs/web-tests` files (49 lint findings and 11 formatting files). These are outside this patch. Remote tests use the existing HTTP fixtures through the rebuilt native client; the original aarch64 server deployment was not recreated. Validation after merging main `3dd57978` and the compatibility repair (macOS ARM64, uv-managed Python 3.12.12, rebuilt editable native extension): - 60 focused parity, signature, and error-contract tests passed. - 381 database, remote, session, namespace, catalog, and sync parity tests passed; 2 platform-dependent tests skipped. - The two new subclass regressions fail against the pre-repair implementation with the expected abstract-member instantiation error, then pass with the repair. - Python SDK Ruff lint/format passes (167 files); repository-wide findings remain confined to unchanged docs/web-tests (49 lint findings, 11 formatting files). --------- Co-authored-by: Xuanwo --- python/python/lancedb/db.py | 33 ++-- python/python/lancedb/remote/db.py | 19 ++- python/python/lancedb/remote/table.py | 12 ++ python/python/lancedb/table.py | 40 ++++- python/python/tests/test_sync_api_parity.py | 170 ++++++++++++++++++++ 5 files changed, 251 insertions(+), 23 deletions(-) create mode 100644 python/python/tests/test_sync_api_parity.py diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 9ed772e1c..b6dfe8fb8 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -823,8 +823,26 @@ class DBConnection(EnforceOverrides): @property def uri(self) -> str: + """The URI of this database.""" return self._uri + def _all_table_names(self) -> Generator[str, None, None]: + page_token = None + while True: + response = self.list_tables(page_token=page_token) + yield from response.tables + page_token = response.page_token + if not page_token: + return + + def __len__(self) -> int: + """Return the number of tables in the root namespace across all pages.""" + return sum(1 for _ in self._all_table_names()) + + def __contains__(self, name: str) -> bool: + """Return whether the root namespace contains the named table.""" + return name in self._all_table_names() + def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. @@ -1609,21 +1627,6 @@ class LanceDBConnection(DBConnection): ) ) - def _all_table_names(self) -> Generator[str, None, None]: - page_token = None - while True: - response = self.list_tables(page_token=page_token) - yield from response.tables - page_token = response.page_token - if not page_token: - return - - def __len__(self) -> int: - return sum(1 for _ in self._all_table_names()) - - def __contains__(self, name: str) -> bool: - return name in self._all_table_names() - @override def create_table( self, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index c11e01ff4..4ffd3ac4a 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -47,7 +47,7 @@ from ..secrets import EnvVarSecret, SecretInfo from ..view import ViewDescription if TYPE_CHECKING: - from .._lancedb import JobInfo + from .._lancedb import JobInfo, Session from ..embeddings import EmbeddingFunctionConfig from lance_namespace import ( LanceNamespace, @@ -240,6 +240,23 @@ class RemoteDBConnection(DBConnection): def __repr__(self) -> str: return f"RemoteConnect(name={self.db_name})" + @property + @override + def uri(self) -> str: + return self._conn.uri + + @property + def session(self) -> Optional["Session"]: + """Remote connections do not expose a local cache session.""" + raise NotImplementedError("session is not supported by remote connections") + + @property + def read_consistency_interval(self) -> Optional[timedelta]: + """Remote connections do not expose a local read consistency interval.""" + raise NotImplementedError( + "read_consistency_interval is not supported by remote connections" + ) + @override def serialize(self) -> str: if getattr(self, "_catalog_oauth", False): diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index faf15c987..6b7835470 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -192,6 +192,18 @@ class RemoteTable(Table): """The name of the table""" return self._name + @property + def namespace(self) -> List[str]: + return self._namespace_path + + @deprecation.deprecated( + deprecated_in="0.33.1", + current_version=__version__, + details="Use update_field_metadata() instead.", + ) + def replace_field_metadata(self, field_name: str, new_metadata: Dict[str, str]): + LOOP.run(self._table.replace_field_metadata(field_name, new_metadata)) + def __repr__(self) -> str: return f"RemoteTable({self.db_name}.{self.name})" diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index d2ff02683..f1e538c14 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1360,6 +1360,16 @@ class Table(ABC): """The name of this Table""" raise NotImplementedError("name is not supported for this table type") + @property + def namespace(self) -> List[str]: + """Return the namespace path of the table (empty for the root namespace).""" + return [] + + @property + def id(self) -> str: + """Return the full identifier of the table (namespace$name).""" + return "$".join(self.namespace + [self.name]) + @property @abstractmethod def version(self) -> int: @@ -3106,6 +3116,29 @@ class Table(ABC): version: the new table version after the update. """ + @deprecation.deprecated( + deprecated_in="0.33.1", + current_version=__version__, + details="Use update_field_metadata() instead.", + ) + def replace_field_metadata(self, field_name: str, new_metadata: Dict[str, str]): + """Replace all metadata of a field in the schema. + + .. deprecated:: 0.33.1 + Use [update_field_metadata][lancedb.table.Table.update_field_metadata] + with ``replace=True`` instead. + + Parameters + ---------- + field_name: str + The name of the field whose metadata is replaced. + new_metadata: dict + The new metadata, replacing all existing keys. + """ + self.update_field_metadata( + {"path": field_name, "metadata": new_metadata, "replace": True} + ) + @abstractmethod def drop_columns(self, columns: Iterable[str]) -> DropColumnsResult: """ @@ -3315,13 +3348,6 @@ class LanceTable(Table): """Return the namespace path of the table.""" return self._namespace_path - @property - def id(self) -> str: - """Return the full identifier of the table (namespace$name).""" - if self._namespace_path: - return "$".join(self._namespace_path + [self.name]) - return self.name - @classmethod async def from_inner(cls, tbl: LanceDBTable): from .db import AsyncConnection, LanceDBConnection diff --git a/python/python/tests/test_sync_api_parity.py b/python/python/tests/test_sync_api_parity.py new file mode 100644 index 000000000..a12efd0c9 --- /dev/null +++ b/python/python/tests/test_sync_api_parity.py @@ -0,0 +1,170 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta +import json +from urllib.parse import parse_qs, urlparse + +import lancedb +from lancedb.table import Table +import pytest + +from test_remote_db import mock_lancedb_connection + + +@pytest.fixture +def legacy_table(): + """Implement the pre-existing abstract API without the two new members.""" + + def unsupported(self, *args, **kwargs): + raise NotImplementedError + + def update_field_metadata(self, updates): + self.metadata_updates.append(updates) + return object() # The deprecated wrapper must not expose this result. + + # Supply concrete implementations through normal ABC class creation. Leave + # namespace and replace_field_metadata inherited, as an old subclass would. + implementations = { + name: unsupported + for name in Table.__abstractmethods__ + if name not in {"namespace", "replace_field_metadata"} + } + implementations.update( + name=property(lambda self: "legacy"), + update_field_metadata=update_field_metadata, + ) + legacy_class = type("LegacyTable", (Table,), implementations) + table = legacy_class() + table.metadata_updates = [] + return table + + +def test_legacy_table_namespace_and_id(legacy_table): + assert legacy_table.namespace == [] + assert legacy_table.id == "legacy" + namespace = legacy_table.namespace + namespace.append("changed") + assert legacy_table.namespace == [] + assert legacy_table.id == "legacy" + + +def test_legacy_table_replace_field_metadata(legacy_table): + with pytest.warns(DeprecationWarning, match="update_field_metadata"): + result = legacy_table.replace_field_metadata("nested.field", {"a": "b"}) + assert result is None + assert legacy_table.metadata_updates == [ + {"path": "nested.field", "metadata": {"a": "b"}, "replace": True} + ] + + +def respond(request, body): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(body).encode()) + + +def test_remote_uri(): + with mock_lancedb_connection(lambda request: respond(request, {})) as db: + assert db.uri == "db://dev" + + +@pytest.mark.parametrize("attribute", ["session", "read_consistency_interval"]) +def test_remote_unsupported_properties(attribute): + with mock_lancedb_connection(lambda request: respond(request, {})) as db: + with pytest.raises(NotImplementedError, match=attribute): + getattr(db, attribute) + + +@pytest.mark.parametrize("tables", [[], ["first", "last"]]) +def test_remote_len_and_contains_follow_pages(tables): + requests = [] + + def handler(request): + requests.append(request.path) + query = parse_qs(urlparse(request.path).query) + if tables and "page_token" not in query: + respond(request, {"tables": [tables[0]], "page_token": "opaque-next"}) + else: + if tables: + assert query["page_token"] == ["opaque-next"] + respond(request, {"tables": tables[1:]}) + + with mock_lancedb_connection(handler) as db: + assert len(db) == len(tables) + assert ("last" in db) == bool(tables) + assert "missing" not in db + requests.clear() + assert ("first" in db) == bool(tables) + assert len(requests) == 1 + + +@pytest.mark.parametrize("namespace", [[], ["parent", "child"]]) +def test_remote_table_identifiers(namespace): + def handler(request): + respond(request, {"version": 1, "schema": {"fields": []}}) + + with mock_lancedb_connection(handler) as db: + table = db.open_table("rfm", namespace_path=namespace) + assert table.namespace == namespace + assert table.id == "$".join(namespace + ["rfm"]) + + +def test_remote_replace_field_metadata(): + updates = [] + + def handler(request): + if request.path.endswith("/describe/"): + respond(request, {"version": 1, "schema": {"fields": []}}) + else: + assert request.path == "/v1/table/rfm/update_field_metadata/" + body = request.rfile.read(int(request.headers["Content-Length"])) + updates.append(json.loads(body)) + respond(request, {"version": 2}) + + with mock_lancedb_connection(handler) as db: + table = db.open_table("rfm") + with pytest.warns(DeprecationWarning, match="update_field_metadata"): + assert table.replace_field_metadata("id", {"a": "b"}) is None + assert updates == [ + {"updates": [{"path": "id", "metadata": {"a": "b"}, "replace": True}]} + ] + + +@pytest.mark.parametrize("custom_session", [False, True]) +def test_local_properties_and_metadata(tmp_path, custom_session): + supplied = lancedb.Session() if custom_session else None + db = lancedb.connect( + tmp_path, session=supplied, read_consistency_interval=timedelta(seconds=5) + ) + session = db.session + assert session is supplied + before = session.size_bytes if session is not None else 0 + table = db.create_table("rfm", [{"id": i} for i in range(3)]) + assert table.to_arrow().num_rows == 3 + if supplied is not None: + assert supplied.size_bytes > before + assert db.read_consistency_interval == timedelta(seconds=5) + assert table.namespace == [] + assert table.id == "rfm" + with pytest.warns(DeprecationWarning): + table.replace_field_metadata("id", {"old": "value"}) + with pytest.warns(DeprecationWarning): + table.replace_field_metadata("id", {"a": "b"}) + assert table.schema.field("id").metadata == {b"a": b"b"} + + +def test_namespace_connection_properties_remain_writable(tmp_path): + session = lancedb.Session() + interval = timedelta(seconds=5) + with lancedb.connect_namespace( + "dir", + {"root": str(tmp_path)}, + session=session, + read_consistency_interval=interval, + ) as db: + assert db.session is session + assert db.read_consistency_interval == interval + db.read_consistency_interval = timedelta(0) + assert db.read_consistency_interval == timedelta(0) From 180eaaf68eae595e0948f3bb2f02974d4cf0535e Mon Sep 17 00:00:00 2001 From: KarthikS Date: Mon, 26 Oct 2026 09:31:13 -0400 Subject: [PATCH 109/180] fix!: reject unsupported remote connection and table options (#4486) Fixes #4399. Remote connections currently discard local-only settings, including table write options that determine storage format. The synchronous Python client also binds the fourth positional `create_table` argument to `on_bad_vectors`, so an intended overwrite is sent as a create. This change aligns the remote Python signature with `DBConnection.create_table`, preserves the legacy remote timeout keywords, and raises `ValueError` for other unknown connection keywords. The shared Rust client rejects unsupported connection, create, and open options before sending HTTP requests; open validation also runs before a table-cache hit. Python reports these as `NotImplementedError`, including explicit `enable_v2_manifest_paths=False`. Supported Enterprise connection-level storage options remain available. This implements option 2 from the issue: explicit rejection. It deliberately does not add unverified server write parameters. Calls that previously supplied ignored options must omit them to use server-managed storage and caching. Database URI prefixes are already preserved on current main and are unchanged here. Regression tests cover Python sync/async, TypeScript create/open calls, and the Rust remote client, including empty-table creation, overwrite mode, and cached table handles. Python API documentation describes the behavior and corrected positional order. Reconciled with main at `0ea932da`, preserving upstream blob and error-handling tests and updating the Python test that previously expected open options to be ignored. Validation on the merged source: - Rebuilt the Python native extension; 304 tests passed across remote options, database, remote database, and session suites. - Rust remote database suite: 135 passed. Rebuilt the Node native extension; TypeScript remote suite: 62 passed. TypeScript compilation and documentation generation passed. - Full Python SDK lint and formatting pass (159 files); full TypeScript lint and formatting pass (66 files). Rust formatting and `git diff --check` pass. - Repository-wide Python lint/format reports existing issues in unchanged `docs/web-tests` files (49 lint findings and 11 formatting files). Environment: Ubuntu under WSL2, Linux x86-64, CPython 3.12.13, Rust 1.97.0, and Node.js 22.16.0. Locked dependencies and the repository `ci` build profile. Remote tests use HTTP fixtures; this does not claim validation against the original ARM64 single-node deployment. Documentation review follow-up: added a draft Enterprise migration note in `docs/web/basics/sdk.mdx`. It explains that `db://` connections reject local session/cache and per-table storage/write options, while supported connection-level Enterprise storage options remain available. Following the repository's release conventions, the note stays in an MDX comment below the migration list until the behavior is released. Vale 3.24.0 with the pinned LanceDB style package reports no findings; `git diff --check` passes. This follow-up changes documentation only. BREAKING CHANGE: Remote connections now reject unsupported local session/cache and per-table storage/write options instead of silently ignoring them. Callers must omit these options and use server-managed storage and caching; supported Enterprise connection-level storage options remain available. Integration with current main preserves its synchronous API signatures, including the remote `create_table(mode=None)` default, and the table compatibility defaults. The positional-order repair is already on main via #4608; this PR retains the distinct unsupported-option rejection behavior. CI follow-up: the inherited IVF search-effort test occasionally measured recall 0.375 against its unchanged 0.5 threshold after random index training. A matching local reproducer observed this once in 30 builds. The fixture now places the eight exact neighbors together, preserving the 16-partition setup, two writes, all probe/precedence assertions, and the recall threshold. The adjusted fixture returned recall 1.0 in 100 builds; the full query and remote suites passed (102 tests). This stabilizes test data and does not change search behavior or promise production recall. --------- Co-authored-by: Xuanwo --- docs/src/python/python.md | 11 ++ docs/web/basics/sdk.mdx | 7 + nodejs/__test__/query.test.ts | 16 +- nodejs/__test__/remote.test.ts | 49 ++++++ python/python/lancedb/__init__.py | 15 ++ python/python/lancedb/remote/db.py | 37 +++-- python/python/tests/test_remote_db.py | 10 +- python/python/tests/test_remote_options.py | 154 ++++++++++++++++++ rust/lancedb/src/connection.rs | 19 +++ rust/lancedb/src/connection/create_table.rs | 5 + rust/lancedb/src/remote/db.rs | 164 +++++++++++++++++++- 11 files changed, 460 insertions(+), 27 deletions(-) create mode 100644 python/python/tests/test_remote_options.py diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 4d0dfc87a..356b49ae7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -20,6 +20,17 @@ pip install lancedb The following methods describe the synchronous API client. There is also an [asynchronous API client](#connections-asynchronous). +Connections to `db://` databases reject local-only options with +`NotImplementedError`. These include `session` and `manifest_enabled=True` on +connect, per-table storage and write options on create, and `index_cache_size`, +`storage_options`, or `location` on open (where the method accepts them). +Omit these options to use server-managed storage and caching. Connection-level +`storage_options` supported by an Enterprise deployment remain available. + +The synchronous remote `create_table` uses the same positional order as the +local API: `name, data, schema, mode, exist_ok, on_bad_vectors, fill_value, +embedding_functions`. Prefer keyword arguments for optional parameters. + ## Connections (Synchronous) ::: lancedb.connect diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index fc386bc7a..b20fc1662 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -92,6 +92,13 @@ manages background maintenance. [background maintenance](/maintenance/background-jobs) rather than calling the embedded table's `optimize()` method. +{/* Draft for the remote option validation release. +- **Remove local storage and cache settings.** `db://` connections reject local + sessions, table cache settings, and per-table storage and write options. Omit + these options so Enterprise manages storage and caching. Connection-level + storage options supported by your Enterprise deployment remain available. +*/} + For SQL connection details, see [SQL](/basics/sql). For the operating model and deployment options, see [LanceDB Enterprise](/enterprise). diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index 786f04015..068e55c2f 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -538,11 +538,17 @@ describe("IVF search effort", () => { const db = await connect(directory.name); const rows = Array.from({ length: 512 }, (_, id) => ({ id, - vector: Array.from( - { length: 16 }, - (_, j) => - (Math.floor(id / 32) === j ? 1 : 0) + Math.sin(id * 17 + j) * 0.001, - ), + // Keep all eight exact neighbors together even if random IVF training + // splits the first cluster. This tests effort, not training recall. + vector: + id < 8 + ? [...vector] + : Array.from( + { length: 16 }, + (_, j) => + (Math.floor(id / 32) === j ? 1 : 0) + + Math.sin(id * 17 + j) * 0.001, + ), })); table = await db.createTable("effort", rows.slice(0, 256)); await table.add(rows.slice(256)); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 7e9479f94..d443537b0 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -98,6 +98,55 @@ async function withMockDatabase( } describe("remote connection", () => { + it.each([ + { dataStorageVersion: "2.0" }, + { enableV2ManifestPaths: false }, + { storageOptions: { bogusOptionXyz: "1" } }, + ])("rejects local create options %j before sending data", async (options) => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res.writeHead(200).end(); + }, + async (db) => { + await expect( + db.createTable("test", [{ value: 1 }], { + ...options, + mode: "overwrite", + }), + ).rejects.toThrow(/write_options.*remote/); + await expect( + db.createEmptyTable( + "test", + new Schema([new Field("value", new Int64(), true)]), + options, + ), + ).rejects.toThrow(/write_options.*remote/); + }, + ); + expect(requests).toEqual([]); + }); + + it.each([{ indexCacheSize: 5 }, { storageOptions: { x: "y" } }])( + "rejects local open options %j before sending a request", + async (options) => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res.writeHead(200).end(); + }, + async (db) => { + await expect( + db.openTable("test", undefined, options), + ).rejects.toThrow(/not supported for remote/); + }, + ); + expect(requests).toEqual([]); + }, + ); + it.each([false, true])( "normalizes remote blob writes (range target: %s)", async (wide) => { diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index a3aa55209..5e879f61d 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -281,6 +281,21 @@ def connect( "uri is required when not connecting through a namespace client" ) if isinstance(uri, str) and uri.startswith("db://"): + # Preserve the deprecated remote timeout options, but validate all other + # unknown keywords just as the local connection does. + unknown_kwargs = { + key: value + for key, value in kwargs.items() + if key not in ("connection_timeout", "read_timeout") + } + if unknown_kwargs: + raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}") + if session is not None: + raise NotImplementedError("session is not supported for remote connections") + if manifest_enabled: + raise NotImplementedError( + "manifest_enabled is not supported for remote connections" + ) if api_key is None: api_key = os.environ.get("LANCEDB_API_KEY") if api_key is None: diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 4ffd3ac4a..291cc52d6 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -7,7 +7,6 @@ from __future__ import annotations from dataclasses import replace from datetime import timedelta import json -import logging from concurrent.futures import ThreadPoolExecutor import sys from typing import ( @@ -502,18 +501,14 @@ class RemoteDBConnection(DBConnection): if namespace_path is None: namespace_path = [] - if storage_options is not None: - logging.info( - "storage_options is ignored for remote tables" - " (storage is managed; set storage_options on connect() instead)" + table = LOOP.run( + self._conn.open_table( + name, + namespace_path=namespace_path, + storage_options=storage_options, + index_cache_size=index_cache_size, ) - if index_cache_size is not None: - logging.info( - "index_cache_size is ignored for remote tables" - " (there is no local cache to configure)" - ) - - table = LOOP.run(self._conn.open_table(name, namespace_path=namespace_path)) + ) tbl = RemoteTable( table, self.db_name, @@ -593,6 +588,9 @@ class RemoteDBConnection(DBConnection): embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None, *, namespace_path: Optional[List[str]] = None, + storage_options: Optional[Dict[str, str]] = None, + data_storage_version: Optional[str] = None, + enable_v2_manifest_paths: Optional[bool] = None, ) -> Table: """Create a [Table][lancedb.table.Table] in the database. @@ -632,6 +630,12 @@ class RemoteDBConnection(DBConnection): embedding_functions: list of EmbeddingFunctionConfig, optional The embedding functions to store in the table schema and use to generate vectors when creating the table or adding data. + storage_options: dict, optional + Not supported for remote table creation. Raises NotImplementedError. + data_storage_version: str, optional + Not supported for remote table creation. Raises NotImplementedError. + enable_v2_manifest_paths: bool, optional + Not supported for remote table creation. Raises NotImplementedError. Returns ------- @@ -698,6 +702,14 @@ class RemoteDBConnection(DBConnection): LanceTable(table4) """ + for option, value in ( + ("data_storage_version", data_storage_version), + ("enable_v2_manifest_paths", enable_v2_manifest_paths), + ): + if value is not None: + raise NotImplementedError( + f"{option} is not supported for remote table creation" + ) if exist_ok: if mode == "create": mode = "exist_ok" @@ -719,6 +731,7 @@ class RemoteDBConnection(DBConnection): on_bad_vectors=on_bad_vectors, fill_value=fill_value, embedding_functions=embedding_functions, + storage_options=storage_options, ) ) return RemoteTable( diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index db3394735..32f999d18 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1823,12 +1823,12 @@ def test_remote_unsupported_legacy_hnsw_pq(): ) -def test_remote_python_only_messages(caplog): +def test_remote_python_only_messages(): with mock_lancedb_connection(remote_unsupported_handler) as db: - with caplog.at_level("INFO"): - table = db.open_table("test", storage_options={}, index_cache_size=1) - assert "storage_options is ignored for remote tables" in caplog.text - assert "index_cache_size is ignored for remote tables" in caplog.text + for options in [{"storage_options": {}}, {"index_cache_size": 1}]: + with pytest.raises(NotImplementedError, match=next(iter(options))): + db.open_table("test", **options) + table = db.open_table("test") for method in ["to_arrow", "to_pandas", "to_polars"]: with pytest.raises(NotImplementedError) as error: getattr(table, method)() diff --git a/python/python/tests/test_remote_options.py b/python/python/tests/test_remote_options.py new file mode 100644 index 000000000..2022aa29d --- /dev/null +++ b/python/python/tests/test_remote_options.py @@ -0,0 +1,154 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import inspect +from urllib.parse import parse_qs, urlparse + +import lancedb +import pyarrow as pa +import pytest + +from test_remote_db import mock_lancedb_connection, mock_lancedb_connection_async + + +@pytest.mark.parametrize("uri", ["memory://", "db://dev"]) +def test_unknown_connect_options(uri): + with pytest.raises(ValueError, match="Unknown keyword arguments.*bogus"): + lancedb.connect(uri, api_key="fake", bogus=1) + + +@pytest.mark.parametrize("option", ["session", "manifest_enabled"]) +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_remote_connect_rejects_local_options(option, asynchronous): + value = lancedb.Session() if option == "session" else True + with pytest.raises(NotImplementedError, match=option): + if asynchronous: + await lancedb.connect_async("db://dev", api_key="fake", **{option: value}) + else: + lancedb.connect("db://dev", api_key="fake", **{option: value}) + + +def test_remote_create_signature(): + from lancedb.db import DBConnection + from lancedb.remote.db import RemoteDBConnection + + expected = inspect.signature(DBConnection.create_table).parameters + actual = inspect.signature(RemoteDBConnection.create_table).parameters + assert list(actual) == list(expected) + for name in expected: + assert actual[name].kind == expected[name].kind + if name == "mode": + # Remote connections retain their existing server-default mode. + assert actual[name].default is None + else: + assert actual[name].default == expected[name].default + + +def test_remote_create_positional_mode(): + modes = [] + + def handler(request): + assert urlparse(request.path).path == "/v1/table/ct_pos/create/" + modes.append(parse_qs(urlparse(request.path).query)["mode"]) + request.send_response(200) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + data = [{"value": 1}] + db.create_table("ct_pos", data, None, "overwrite") + db.create_table("ct_pos", data, None, "overwrite") + db.create_table("ct_pos", data, None, "create", True) + with pytest.raises(ValueError, match="Invalid mode"): + db.create_table("ct_pos", data, None, "drop") + assert modes == [["overwrite"], ["overwrite"], ["exist_ok"]] + + +CREATE_OPTIONS = [ + {"new_table_data_storage_version": "2.0"}, + {"new_table_enable_v2_manifest_paths": "false"}, + {"bogus_option_xyz": "1"}, +] + + +@pytest.mark.parametrize("storage_options", CREATE_OPTIONS) +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.asyncio +async def test_remote_create_rejects_write_options(storage_options, empty): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + + kwargs = {"schema": pa.schema([("value", pa.int64())])} + if not empty: + kwargs["data"] = [{"value": 1}] + async with mock_lancedb_connection_async(handler) as db: + with pytest.raises(NotImplementedError, match="write_options.*remote"): + await db.create_table("t", storage_options=storage_options, **kwargs) + assert requests == [] + + +@pytest.mark.parametrize( + "options", + [ + {"data_storage_version": "2.0"}, + {"enable_v2_manifest_paths": False}, + {"storage_options": {"x": "1"}}, + ], +) +def test_sync_remote_create_rejects_write_options(options): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + with pytest.raises(NotImplementedError, match="remote"): + db.create_table("t", [{"value": 1}], **options) + assert requests == [] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options", [{"index_cache_size": 10}, {"storage_options": {"x": "y"}}] +) +@pytest.mark.asyncio +async def test_remote_open_rejects_local_options(options, asynchronous): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') + + if asynchronous: + async with mock_lancedb_connection_async(handler) as db: + with pytest.raises(NotImplementedError, match="remote"): + await db.open_table("t", **options) + else: + with mock_lancedb_connection(handler) as db: + with pytest.raises(NotImplementedError, match="remote"): + db.open_table("t", **options) + assert requests == [] + + +@pytest.mark.asyncio +async def test_remote_open_rejects_location(): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200) + request.end_headers() + request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') + + async with mock_lancedb_connection_async(handler) as db: + with pytest.raises(NotImplementedError, match="location.*remote"): + await db.open_table("t", location="/tmp/zzz") + assert requests == [] diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 26afef5e8..bff97bf31 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -174,6 +174,8 @@ impl OpenTableBuilder { /// Advanced parameters that can be used to customize table reads /// + /// Remote connections reject these parameters with [`Error::NotSupported`]. + /// /// If set, these will take precedence over any overlapping `OpenTableOptions` options pub fn lance_read_params(mut self, params: ReadParams) -> Self { self.request.lance_read_params = Some(params); @@ -1530,6 +1532,7 @@ impl ConnectBuilder { /// Enable or disable manifest-backed directory namespace mode for local /// native connections. + /// Remote connections reject enabling this option with [`Error::NotSupported`]. /// /// When enabled, the connection uses the directory namespace database /// directly for all table operations and forces @@ -1565,6 +1568,7 @@ impl ConnectBuilder { } /// Set a custom session for object stores and caching. + /// Remote connections reject this option with [`Error::NotSupported`]. /// /// By default, a new session with default configuration will be created. /// This method allows you to provide a custom session with your own @@ -1596,6 +1600,21 @@ impl ConnectBuilder { fn execute_remote(self) -> Result { use crate::remote::db::RemoteDatabaseOptions; + for (option, provided) in [ + ("session", self.request.session.is_some()), + ("manifest_enabled", self.request.manifest_enabled), + ( + "namespace_client_properties", + !self.request.namespace_client_properties.is_empty(), + ), + ] { + if provided { + return Err(Error::NotSupported { + message: format!("{option} is not supported for remote connections"), + }); + } + } + let mut merged_options = self.request.options.clone(); Self::apply_env_defaults(&ENV_VARS_TO_STORAGE_OPTS, &mut merged_options); let sql_host_override = merged_options.get(OPT_REMOTE_SQL_HOST_OVERRIDE).cloned(); diff --git a/rust/lancedb/src/connection/create_table.rs b/rust/lancedb/src/connection/create_table.rs index 39cc82ec0..9d4408ba7 100644 --- a/rust/lancedb/src/connection/create_table.rs +++ b/rust/lancedb/src/connection/create_table.rs @@ -45,6 +45,9 @@ impl CreateTableBuilder { } /// Apply the given write options when writing the initial data + /// + /// Remote connections reject explicit Lance write parameters with + /// [`Error::NotSupported`] instead of silently using server defaults. pub fn write_options(mut self, write_options: WriteOptions) -> Self { self.request.write_options = write_options; self @@ -70,6 +73,8 @@ impl CreateTableBuilder { /// Set multiple options for the storage layer. /// + /// Table-level storage options are not supported by remote connections. + /// /// Options already set on the connection will be inherited by the table, /// but can be overridden here. /// diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index d33565653..5c299dc5a 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1481,6 +1481,23 @@ impl Database for RemoteDatabase { } async fn create_table(&self, mut request: CreateTableRequest) -> Result> { + // The remote create endpoint does not transmit Lance write parameters. + // Reject them before consuming data or issuing a request, especially + // for overwrite: silently using the server's format can lose intent. + for (option, provided) in [ + ( + "write_options (including storage_options)", + request.write_options.lance_write_params.is_some(), + ), + ("location", request.location.is_some()), + ("namespace_client", request.namespace_client.is_some()), + ] { + if provided { + return Err(Error::NotSupported { + message: format!("{option} is not supported for remote table creation"), + }); + } + } let data_schema = request.data.schema(); let body = stream_as_body(request.data.scan_as_stream())?; @@ -1605,6 +1622,23 @@ impl Database for RemoteDatabase { } async fn open_table(&self, request: OpenTableRequest) -> Result> { + // Validate before looking in the cache as well as before sending HTTP. + for (option, provided) in [ + ("index_cache_size", request.index_cache_size.is_some()), + ( + "lance_read_params (including storage_options)", + request.lance_read_params.is_some(), + ), + ("location", request.location.is_some()), + ("namespace_client", request.namespace_client.is_some()), + ("managed_versioning", request.managed_versioning.is_some()), + ] { + if provided { + return Err(Error::NotSupported { + message: format!("{option} is not supported for remote table access"), + }); + } + } let identifier = build_table_identifier(&request.name, &request.namespace_path)?; let cache_key = build_cache_key(&request.name, &request.namespace_path); @@ -2504,14 +2538,14 @@ mod tests { let table = conn.open_table("table1").execute().await.unwrap(); assert_eq!(table.name(), "table1"); - // Storage options should be ignored. - let table = conn + // Per-table storage options must not be silently ignored. + let result = conn .open_table("table1") .storage_option("key", "value") .execute() - .await - .unwrap(); - assert_eq!(table.name(), "table1"); + .await; + assert!(matches!(result, Err(Error::NotSupported { message }) + if message.contains("storage_options"))); } #[tokio::test] @@ -2735,6 +2769,126 @@ mod tests { ); } + #[rstest] + #[case("new_table_data_storage_version", "2.0")] + #[case("new_table_enable_v2_manifest_paths", "false")] + #[case("bogus_option_xyz", "1")] + #[tokio::test] + async fn test_create_rejects_local_storage_options(#[case] key: &str, #[case] value: &str) { + let conn = Connection::new_with_handler(|_| -> http::Response<&'static str> { + panic!("must not send a create request") + }); + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])); + let data = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + for builder in [ + conn.create_table("table1", data), + conn.create_empty_table("table1", schema), + ] { + let result = builder + .mode(CreateTableMode::Overwrite) + .storage_option(key, value) + .execute() + .await; + assert!(matches!(result, Err(Error::NotSupported { message }) + if message.contains("write_options") && message.contains("remote"))); + } + } + + #[tokio::test] + async fn test_create_rejects_local_write_params_and_location() { + let conn = Connection::new_with_handler(|_| -> http::Response<&'static str> { + panic!("must not send a create request") + }); + let schema = Arc::new(Schema::empty()); + for builder in [ + conn.create_empty_table("table1", schema.clone()) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams::default()), + }), + conn.create_empty_table("table1", schema) + .location("/tmp/elsewhere"), + ] { + assert!(matches!( + builder.execute().await, + Err(Error::NotSupported { .. }) + )); + } + } + + #[rstest] + #[tokio::test] + async fn test_open_rejects_local_options_even_when_cached(#[values(false, true)] cached: bool) { + let mut db = super::RemoteDatabase::new_mock(|request| { + assert_eq!(request.url().path(), "/v1/table/table1/create/"); + http::Response::builder().status(200).body("").unwrap() + }); + db.table_cache = moka::future::Cache::new(10); + let table_cache = db.table_cache.clone(); + let conn = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + if cached { + conn.create_empty_table("table1", Arc::new(Schema::empty())) + .execute() + .await + .unwrap(); + } + assert_eq!( + table_cache + .get(&build_cache_key("table1", &[])) + .await + .is_some(), + cached + ); + for (option, builder) in [ + ( + "index_cache_size", + conn.open_table("table1").index_cache_size(10), + ), + ( + "storage_options", + conn.open_table("table1").storage_option("x", "y"), + ), + ("location", conn.open_table("table1").location("/tmp/zzz")), + ( + "managed_versioning", + conn.open_table("table1").managed_versioning(false), + ), + ( + "lance_read_params", + conn.open_table("table1") + .lance_read_params(Default::default()), + ), + ] { + let result = builder.execute().await; + assert!(matches!(result, Err(Error::NotSupported { message }) + if message.contains(option) && message.contains("remote"))); + } + } + + #[tokio::test] + async fn test_connect_rejects_local_options() { + for (option, builder) in [ + ( + "manifest_enabled", + ConnectBuilder::new("db://dev").manifest_enabled(true), + ), + ( + "namespace_client_properties", + ConnectBuilder::new("db://dev").namespace_client_properties([("root", "/tmp/db")]), + ), + ] { + let result = builder.api_key("fake").region("us-east-1").execute().await; + assert!(matches!(result, Err(Error::NotSupported { message }) + if message.contains(option) && message.contains("remote"))); + } + } + #[rstest] #[case::matching(Field::new("a", DataType::Int32, false), true)] #[case::different_name(Field::new("x", DataType::Int32, false), false)] From 7952ee2a71d5bb921d097f3cd81f8039bf014818 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:31:19 +0800 Subject: [PATCH 110/180] fix(python): cover FP16 GPU index queries (#3819) Keep FP16 vectors through IVF-PQ index creation and search in the synchronous and asynchronous quickstarts. Add native and conditional CUDA regression coverage using a float64 query against an explicitly typed FP16 column. This is test and documentation-example coverage for dtype preservation already present in Lance; it does not change production code. Related #2120. Validation on `bbad20940632b21a9ee85bdcb46b4cc19dbd65e3` with Python 3.12.12, Lance 15.0.0-beta.1, PyArrow 24.0.0, and Torch 2.14.1: - The native FP16 parameter, Arrow FP16 ingestion test, and both quickstarts passed: 4 passed, 1 CUDA-only skip. - The two affected test files passed: 386 passed, 1 CUDA-only skip (`-m "not slow and not s3_test"`). - Ruff 0.9.9 lint and formatting checks passed for the Python package. Real CUDA execution has not been performed. Torch is installed, but `torch.cuda.is_available()` is false; `test_create_f16_table[cuda]` skips with `CUDA not available`. The native CPU result does not establish that the original GPU failure is resolved. Issue #2120 remains open for verification on an actual CUDA device. Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/tests/docs/test_basic.py | 16 ++-------------- python/python/tests/test_table.py | 26 +++++++++++++++++++++----- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/python/python/tests/docs/test_basic.py b/python/python/tests/docs/test_basic.py index 35d7aac10..ef68114aa 100644 --- a/python/python/tests/docs/test_basic.py +++ b/python/python/tests/docs/test_basic.py @@ -91,19 +91,13 @@ def test_quickstart(tmp_path): } ) # --8<-- [end:alter_columns_vector] - # Change it back since we can get a panic with fp16 - tbl.alter_columns( - { - "path": "vector", - "data_type": pa.list_(pa.float32(), list_size=2), - } - ) # --8<-- [start:drop_columns] tbl.drop_columns(["dbl_price"]) # --8<-- [end:drop_columns] # --8<-- [start:create_index] tbl.create_index(num_sub_vectors=1) # --8<-- [end:create_index] + tbl.search([100, 100]).limit(2).to_pandas() # --8<-- [start:delete_rows] tbl.delete("item = 'fizz'") # --8<-- [end:delete_rows] @@ -185,13 +179,6 @@ async def test_quickstart_async(tmp_path): } ) # --8<-- [end:alter_columns_async_vector] - # Change it back since we can get a panic with fp16 - await tbl.alter_columns( - { - "path": "vector", - "data_type": pa.list_(pa.float32(), list_size=2), - } - ) # --8<-- [start:drop_columns_async] await tbl.drop_columns(["dbl_price"]) # --8<-- [end:drop_columns_async] @@ -200,6 +187,7 @@ async def test_quickstart_async(tmp_path): # --8<-- [start:create_index_async] await tbl.create_index("vector") # --8<-- [end:create_index_async] + await tbl.vector_search([100, 100]).limit(2).to_pandas() # --8<-- [start:delete_rows_async] await tbl.delete("item = 'fizz'") # --8<-- [end:delete_rows_async] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 3b3ccd122..97f65b180 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3965,26 +3965,42 @@ def test_create_f16_table_from_arrow_data(mem_db: DBConnection): assert "s-2" in expected["text"].to_pylist() -def test_create_f16_table(mem_db: DBConnection): +@pytest.mark.parametrize("accelerator", [None, "cuda"]) +def test_create_f16_table(tmp_path, accelerator): + if accelerator == "cuda": + torch = pytest.importorskip("torch") + if not torch.cuda.is_available(): + pytest.skip("CUDA not available") + class MyTable(LanceModel): text: str vector: Vector(32, value_type=pa.float16()) rng = np.random.default_rng(42) + vectors = rng.standard_normal((512, 32)).astype(np.float16) df = pa.table( { "text": [f"s-{i}" for i in range(512)], - "vector": [rng.standard_normal(32).astype(np.float16) for _ in range(512)], + "vector": list(vectors), } ) - table = mem_db.create_table( + db = lancedb.connect(tmp_path) + table = db.create_table( "f16_tbl", schema=MyTable, ) table.add(df) - table.create_index(num_partitions=2, num_sub_vectors=2) + table.create_index( + "vector", + config=IvfPq( + num_partitions=2, + num_sub_vectors=2, + accelerator=accelerator, + ), + ) - query = df["vector"][2].as_py() + # Match the issue's float64 query against an explicitly typed float16 column. + query = vectors[2].astype(np.float64) expected = table.search(query).limit(2).to_arrow() assert "s-2" in expected["text"].to_pylist() From 436c2095800a8bf59f40e9c8cad75e2bfe714450 Mon Sep 17 00:00:00 2001 From: Drew Date: Mon, 26 Oct 2026 09:37:28 -0700 Subject: [PATCH 111/180] docs: document Blob V2 in the multimodal guide (#4623) --- .github/workflows/rust.yml | 6 + Cargo.lock | 12 + Cargo.toml | 7 +- docs/web-tests/blob-v2/README.md | 55 + docs/web-tests/blob-v2/py/pytest.ini | 3 + docs/web-tests/blob-v2/py/requirements.txt | 8 + .../web-tests/blob-v2/py/test_blob_pylance.py | 154 ++ docs/web-tests/blob-v2/py/test_multimodal.py | 204 +++ docs/web-tests/blob-v2/rs/Cargo.toml | 21 + docs/web-tests/blob-v2/rs/multimodal.rs | 344 ++++ docs/web-tests/blob-v2/ts/multimodal.test.ts | 204 +++ docs/web-tests/blob-v2/ts/package-lock.json | 1565 +++++++++++++++++ docs/web-tests/blob-v2/ts/package.json | 16 + docs/web-tests/py/test_multimodal.py | 161 +- docs/web-tests/rs/multimodal.rs | 46 +- docs/web-tests/ts/multimodal.test.ts | 26 +- docs/web/ingestion/create-table.mdx | 3 +- docs/web/management/table.mdx | 481 +++-- docs/web/snippets/blob_pylance.mdx | 6 + docs/web/snippets/multimodal.mdx | 72 +- docs/web/sql/data-types.mdx | 15 +- docs/web/sql/ddl/table.mdx | 1 + 22 files changed, 3157 insertions(+), 253 deletions(-) create mode 100644 docs/web-tests/blob-v2/README.md create mode 100644 docs/web-tests/blob-v2/py/pytest.ini create mode 100644 docs/web-tests/blob-v2/py/requirements.txt create mode 100644 docs/web-tests/blob-v2/py/test_blob_pylance.py create mode 100644 docs/web-tests/blob-v2/py/test_multimodal.py create mode 100644 docs/web-tests/blob-v2/rs/Cargo.toml create mode 100644 docs/web-tests/blob-v2/rs/multimodal.rs create mode 100644 docs/web-tests/blob-v2/ts/multimodal.test.ts create mode 100644 docs/web-tests/blob-v2/ts/package-lock.json create mode 100644 docs/web-tests/blob-v2/ts/package.json create mode 100644 docs/web/snippets/blob_pylance.mdx diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 17fe3a7b4..ffd2162c6 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -11,6 +11,7 @@ on: - rust-toolchain.toml - deny.toml - rust/** + - docs/web-tests/blob-v2/rs/** - nodejs/Cargo.toml - python/Cargo.toml - .github/workflows/rust.yml @@ -222,6 +223,11 @@ jobs: run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests - name: Run examples run: cargo run --profile ci --all-features --example simple --locked + - name: Run blob v2 docs example + # Python and TypeScript blob docs tests install preview packages. + # Those builds are not guaranteed to remain available for more than + # 6 months, so they stay a manual run. This example uses the workspace crate. + run: cargo run --profile ci --all-features -p lancedb-blob-v2-docs --example multimodal --locked remote: timeout-minutes: 30 diff --git a/Cargo.lock b/Cargo.lock index 03f4b0864..bbd41c0b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5796,6 +5796,18 @@ dependencies = [ "webbrowser", ] +[[package]] +name = "lancedb-blob-v2-docs" +version = "0.0.0" +dependencies = [ + "arrow-array", + "arrow-schema", + "futures-util", + "lancedb", + "tempfile", + "tokio", +] + [[package]] name = "lancedb-nodejs" version = "0.41.0-beta.14" diff --git a/Cargo.toml b/Cargo.toml index 870ef5d07..3027ee065 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,10 @@ [workspace] -members = ["rust/lancedb", "nodejs", "python"] +members = [ + "rust/lancedb", + "nodejs", + "python", + "docs/web-tests/blob-v2/rs", +] resolver = "2" [workspace.package] diff --git a/docs/web-tests/blob-v2/README.md b/docs/web-tests/blob-v2/README.md new file mode 100644 index 000000000..c0f75cdc6 --- /dev/null +++ b/docs/web-tests/blob-v2/README.md @@ -0,0 +1,55 @@ +# Blob v2 documentation tests + +`docs/web-tests/ts` pins `@lancedb/lancedb` 0.31.0 and `docs/web-tests/rs` pins `lancedb` 0.31.0. Those releases do not include `blob()`. Run the Blob v2 examples here. + +## Python + +`lancedb==0.41.0b10` from the LanceDB package index, without pylance. PyPI `lancedb` 0.40.0 does not provide `lancedb.blob()`. + +```shell +python3.13 -m venv .venv +.venv/bin/pip install -r docs/web-tests/blob-v2/py/requirements.txt +.venv/bin/python -m pytest docs/web-tests/blob-v2/py/test_multimodal.py +``` + +`test_blob_pylance.py` checks custom thresholds and `to_pandas()` in `lazy` and `bytes` mode. Those calls import pylance. Use a second virtualenv. `test_multimodal.py` fails if `lance` can be imported. Snippets from this file are written to `docs/web/snippets/blob_pylance.mdx`. + +This install is for the optional tests only. The public guide does not tell users to bypass the dependency resolver. PyPI `pylance` 13.0.0 requires `lance-namespace<0.12`, and `lancedb==0.41.0b10` requires `lance-namespace>=0.13`, so `lancedb[pylance]` does not resolve. The three tests passed with pylance installed after the base requirements, without its own dependency pin. + +```shell +python3.13 -m venv .venv-pylance +.venv-pylance/bin/pip install -r docs/web-tests/blob-v2/py/requirements.txt +.venv-pylance/bin/pip install --no-deps pylance==13.0.0 +.venv-pylance/bin/python -m pytest docs/web-tests/blob-v2/py/test_blob_pylance.py +``` + +## TypeScript + +`@lancedb/lancedb@0.41.0-beta.8`. Node.js 22.6 or newer. `npm test` passes `--experimental-strip-types`, which Node added in 22.6.0. + +```shell +cd docs/web-tests/blob-v2/ts +npm ci +npm test +``` + +## Rust + +crates.io `lancedb` 0.40.0 does not include `blob()`. This example builds the workspace crate, `lancedb` 0.41.0-beta.10. Pass `--features remote` so this checkout compiles. The example uses a local database. The Rust workflow runs this example. It is not a default feature, so a workspace build without `remote` does not turn that feature on for the rest of the workspace. + +```shell +cargo run -p lancedb-blob-v2-docs --features remote --example multimodal +``` + +## CI + +Python and TypeScript above install preview packages. Pre-release builds are not guaranteed to stay available for more than 6 months, so those runs are not required PR checks. Run them when the guide's pins change. The Rust example is the in-repo check. + +Regenerate snippets from the repository root: + +```shell +python3 docs/web-tests/mdx_snippets_gen.py \ + -s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs \ + -s docs/web-tests/blob-v2/py -s docs/web-tests/blob-v2/ts -s docs/web-tests/blob-v2/rs \ + -o docs/web/snippets +``` diff --git a/docs/web-tests/blob-v2/py/pytest.ini b/docs/web-tests/blob-v2/py/pytest.ini new file mode 100644 index 000000000..17c9e9cb4 --- /dev/null +++ b/docs/web-tests/blob-v2/py/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +asyncio_mode = auto +testpaths = test_multimodal.py diff --git a/docs/web-tests/blob-v2/py/requirements.txt b/docs/web-tests/blob-v2/py/requirements.txt new file mode 100644 index 000000000..c90c8d622 --- /dev/null +++ b/docs/web-tests/blob-v2/py/requirements.txt @@ -0,0 +1,8 @@ +--extra-index-url https://pypi.fury.io/lancedb/ + +lancedb==0.41.0b10 +numpy==2.2.6 +pandas==2.3.3 +pillow==12.1.1 +pytest==8.4.2 +pytest-asyncio==1.2.0 diff --git a/docs/web-tests/blob-v2/py/test_blob_pylance.py b/docs/web-tests/blob-v2/py/test_blob_pylance.py new file mode 100644 index 000000000..8f66088a7 --- /dev/null +++ b/docs/web-tests/blob-v2/py/test_blob_pylance.py @@ -0,0 +1,154 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Blob reads that import pylance. + +Install pylance==13.0.0 with --no-deps after lancedb==0.41.0b10. +See docs/web-tests/blob-v2/README.md. +""" + +import lance +import lancedb +import numpy as np +import pyarrow as pa +import pytest + + +def test_blob_api_to_pandas(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("video"), + ] + ) + tbl = db.create_table( + "videos", + data=[ + {"id": 1, "video": b"fake_video_bytes_1"}, + {"id": 2, "video": b"fake_video_bytes_2"}, + ], + schema=schema, + mode="overwrite", + ) + + # --8<-- [start:blob_api_to_pandas] + df_lazy = tbl.to_pandas() + + df_bytes = tbl.to_pandas(blob_mode="bytes") + + df_desc = tbl.to_pandas(blob_mode="descriptions") + + arrow_bytes = tbl.to_arrow(blob_mode="bytes") + + df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) + # --8<-- [end:blob_api_to_pandas] + + assert len(df_lazy) == 2 + assert all(isinstance(value, lance.BlobFile) for value in df_lazy["video"]) + assert isinstance(df_bytes["video"].iloc[0], bytes) + assert df_bytes["video"].tolist() == [ + b"fake_video_bytes_1", + b"fake_video_bytes_2", + ] + assert arrow_bytes["video"].to_pylist() == [ + b"fake_video_bytes_1", + b"fake_video_bytes_2", + ] + assert "_rowid" not in df_bytes.columns + assert len(df_desc) == 2 + assert set(df_desc["video"].iloc[0]) == { + "kind", + "position", + "size", + "blob_id", + "blob_uri", + } + assert len(df_typed) == 2 + + +@pytest.mark.asyncio +async def test_query_to_pandas_kwargs(tmp_path): + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("vector", pa.list_(pa.float32(), 128)), + lancedb.blob("video"), + ] + ) + data = [ + { + "id": i, + "vector": np.random.rand(128).astype(np.float32), + "video": f"fake_video_bytes_{i}".encode(), + } + for i in range(10) + ] + + db = lancedb.connect(tmp_path / "sync") + tbl = db.create_table("search_demo", data=data, schema=schema, mode="overwrite") + + async_db = await lancedb.connect_async(str(tmp_path / "async")) + tbl_async = await async_db.create_table( + "search_demo", data=data, schema=schema, mode="overwrite" + ) + + query_vector = np.random.rand(128).astype(np.float32) + + # --8<-- [start:query_to_pandas_kwargs] + df_lazy = ( + tbl.search().where("id = 1").select(["id", "video"]).to_pandas(blob_mode="lazy") + ) + + df_bytes = await ( + tbl_async.query() + .where("id = 1") + .select(["id", "video"]) + .to_pandas(blob_mode="bytes") + ) + + df_vec = ( + tbl.search(query_vector) + .limit(2) + .select(["id", "video"]) + .to_pandas(blob_mode="bytes", split_blocks=True, self_destruct=True) + ) + # --8<-- [end:query_to_pandas_kwargs] + + assert len(df_lazy) == 1 + assert "_rowid" not in df_bytes.columns + assert len(df_bytes) == 1 + assert df_bytes["video"].iloc[0] == b"fake_video_bytes_1" + assert len(df_vec) == 2 + assert isinstance(df_vec["video"].iloc[0], bytes) + + +def test_append_keeps_table_blob_thresholds(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("video", inline_size_threshold=64 * 1024), + ] + ) + tbl = db.create_table("videos", schema=schema) + other = pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("video", inline_size_threshold=8 * 1024), + ] + ) + payload = b"x" * (20 * 1024) + tbl.add( + pa.table( + [pa.array([1], type=pa.int64()), lance.blob_array([payload])], + schema=other, + ) + ) + + stored = tbl.schema.field("video").metadata[ + b"lance-encoding:blob-inline-size-threshold" + ] + assert stored == b"65536" + descriptor = tbl.search().select(["video"]).to_arrow(blob_mode="descriptions") + assert descriptor.column("video")[0].as_py()["kind"] == 0 diff --git a/docs/web-tests/blob-v2/py/test_multimodal.py b/docs/web-tests/blob-v2/py/test_multimodal.py new file mode 100644 index 000000000..bf14ba57b --- /dev/null +++ b/docs/web-tests/blob-v2/py/test_multimodal.py @@ -0,0 +1,204 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import importlib.util + +import lancedb +import pyarrow as pa + +if importlib.util.find_spec("lance") is not None: + raise RuntimeError( + "Blob v2 documentation tests must run without pylance. " + "Install docs/web-tests/blob-v2/py/requirements.txt into a fresh virtualenv." + ) + +INLINE_MAX = 64 * 1024 +DEDICATED_MIN = 4 * 1024 * 1024 + + +def test_blob_api_definition(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + # --8<-- [start:blob_api_setup] + import lancedb + + db = lancedb.connect("./blob_db") + # --8<-- [end:blob_api_setup] + assert db.list_tables().tables == [] + + # --8<-- [start:blob_api_schema] + import lancedb + import pyarrow as pa + + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("label", pa.string()), + lancedb.blob("image"), + ] + ) + # --8<-- [end:blob_api_schema] + image = schema.field("image").type + assert image.extension_name == "lance.blob.v2" + assert type(image).__module__ == "lancedb.schema" + + # --8<-- [start:blob_api_ingest] + import io + from PIL import Image + + def jpeg_with_make(color, make): + image = Image.new("RGB", (8, 8), color=color) + exif = Image.Exif() + exif[0x010F] = make + buf = io.BytesIO() + image.save(buf, format="JPEG", exif=exif) + return buf.getvalue() + + tbl = db.create_table( + "photos", + data=[ + {"id": 1, "label": "red", "image": jpeg_with_make("red", "TestCam")}, + {"id": 2, "label": "blue", "image": jpeg_with_make("blue", "OtherCam")}, + ], + schema=schema, + mode="overwrite", + ) + # --8<-- [end:blob_api_ingest] + assert len(tbl) == 2 + + # --8<-- [start:blob_api_bytes] + rows = ( + tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes") + ) + # --8<-- [end:blob_api_bytes] + assert len(rows) == 1 + assert rows[0]["id"] == 1 + assert "_rowid" not in rows[0] + assert rows[0]["image"].startswith(b"\xff\xd8") + + # --8<-- [start:blob_api_files] + from PIL import ExifTags + + rows = tbl.search().where("id = 1").select(["label"]).with_row_id(True).to_list() + with tbl.fetch_blob_files("image", [rows[0]["_rowid"]])[0] as image_file: + make = Image.open(image_file).getexif().get(ExifTags.Base.Make) + print(rows[0]["label"], make) + # --8<-- [end:blob_api_files] + assert rows[0]["label"] == "red" + assert make == "TestCam" + + # --8<-- [start:blob_api_fetch] + rows = tbl.search().select(["id"]).with_row_id(True).to_list() + row_ids = [row["_rowid"] for row in rows] + payloads = tbl.fetch_blobs("image", row_ids) + # --8<-- [end:blob_api_fetch] + assert all(payload.startswith(b"\xff\xd8") for payload in payloads.to_pylist()) + + # --8<-- [start:blob_api_ranges] + slices = tbl.fetch_blob_ranges("image", [(row_ids[0], 0, 2)]) + + with tbl.fetch_blob_files("image", [row_ids[0]])[0] as image_file: + parts = image_file.read_ranges([(0, 2)]) + # --8<-- [end:blob_api_ranges] + assert slices.to_pylist() == [b"\xff\xd8"] + assert parts == [b"\xff\xd8"] + + +def test_eager_query_returns_blob_bytes_without_row_id(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + payload = b"inline-bytes" + tbl = db.create_table( + "photos", + data=[{"id": 1, "image": payload}], + schema=schema, + ) + + rows = ( + tbl.search().where("id = 1").select(["id", "image"]).to_list(blob_mode="bytes") + ) + arrow_bytes = ( + tbl.search().where("id = 1").select(["id", "image"]).to_arrow(blob_mode="bytes") + ) + described = tbl.to_pandas(blob_mode="descriptions") + + assert rows == [{"id": 1, "image": payload}] + assert "_rowid" not in rows[0] + assert arrow_bytes.column("image").to_pylist() == [payload] + assert "_rowid" not in arrow_bytes.column_names + assert described["image"].iloc[0]["kind"] == 0 + + +def test_deferred_fetch_reads_blob_by_row_id(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + payload = b"deferred-bytes" + tbl = db.create_table( + "photos", + data=[{"id": 1, "image": payload}], + schema=schema, + ) + + described = ( + tbl.search() + .where("id = 1") + .select(["id", "image"]) + .to_list(blob_mode="descriptions") + ) + assert described[0]["image"]["kind"] == 0 + assert "_rowid" not in described[0] + + found = tbl.search().where("id = 1").select(["id"]).with_row_id(True).to_list() + row_id = found[0]["_rowid"] + fetched = tbl.fetch_blobs("image", [row_id]).to_pylist() + with tbl.fetch_blob_files("image", [row_id])[0] as handle: + streamed = handle.read() + + assert fetched == [payload] + assert streamed == payload + + +def _marked(size, marker): + payload = bytearray(size) + payload[0] = marker + payload[-1] = marker + return bytes(payload) + + +def test_storage_tiers_round_trip(tmp_path): + cases = [ + (1, _marked(INLINE_MAX, 11), 0), + (2, _marked(INLINE_MAX + 1, 22), 1), + (3, _marked(DEDICATED_MIN, 33), 1), + (4, _marked(DEDICATED_MIN + 1, 44), 2), + ] + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + tbl = db.create_table( + "tiers", + data=[{"id": row_id, "image": payload} for row_id, payload, _kind in cases], + schema=schema, + ) + + described = { + row["id"]: row["image"] + for row in tbl.search() + .select(["id", "image"]) + .to_list(blob_mode="descriptions") + } + located = { + row["id"]: row["_rowid"] + for row in tbl.search().select(["id"]).with_row_id(True).to_list() + } + fetched = { + row_id: tbl.fetch_blobs("image", [located[row_id]]).to_pylist()[0] + for row_id, _payload, _kind in cases + } + + for row_id, payload, kind in cases: + descriptor = described[row_id] + assert descriptor["kind"] == kind + assert descriptor["size"] == len(payload) + assert fetched[row_id] == payload + with tbl.fetch_blob_files("image", [located[row_id]])[0] as handle: + assert handle.read_range(0, 1) == payload[:1] + assert handle.read_range(len(payload) - 1, 1) == payload[-1:] diff --git a/docs/web-tests/blob-v2/rs/Cargo.toml b/docs/web-tests/blob-v2/rs/Cargo.toml new file mode 100644 index 000000000..f96fde230 --- /dev/null +++ b/docs/web-tests/blob-v2/rs/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "lancedb-blob-v2-docs" +version = "0.0.0" +edition.workspace = true +publish = false +license.workspace = true + +[features] +remote = ["lancedb/remote"] + +[dependencies] +arrow-array = { workspace = true } +arrow-schema = { workspace = true } +futures-util = "0.3" +lancedb = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } + +[[example]] +name = "multimodal" +path = "multimodal.rs" diff --git a/docs/web-tests/blob-v2/rs/multimodal.rs b/docs/web-tests/blob-v2/rs/multimodal.rs new file mode 100644 index 000000000..257bc01c1 --- /dev/null +++ b/docs/web-tests/blob-v2/rs/multimodal.rs @@ -0,0 +1,344 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +// --8<-- [start:blob_api_imports] +use std::sync::Arc; + +use arrow_array::{ + Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array, +}; +use arrow_schema::{DataType, Field, Schema}; +use futures_util::TryStreamExt; +use lancedb::blob::{BlobRangeRequest, blob}; +use lancedb::connect; +use lancedb::database::CreateTableMode; +use lancedb::query::{ExecutableQuery, QueryBase}; +// --8<-- [end:blob_api_imports] + +use arrow_array::{StructArray, UInt8Array}; + +const INLINE_MAX: usize = 64 * 1024; +const DEDICATED_MIN: usize = 4 * 1024 * 1024; + +#[tokio::main] +async fn main() { + tutorial().await; + deferred_fetch().await; + storage_tiers().await; +} + +async fn tutorial() { + let temp_dir = tempfile::tempdir().unwrap(); + let original_dir = std::env::current_dir().unwrap(); + std::env::set_current_dir(temp_dir.path()).unwrap(); + + // --8<-- [start:blob_api_setup] + let db = connect("./blob_db").execute().await.unwrap(); + // --8<-- [end:blob_api_setup] + + // --8<-- [start:blob_api_schema] + let blob_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("label", DataType::Utf8, true), + blob("image", true), + ])); + // --8<-- [end:blob_api_schema] + + // --8<-- [start:blob_api_ingest] + let blob_table = db + .create_empty_table("photos", blob_schema) + .mode(CreateTableMode::Overwrite) + .execute() + .await + .unwrap(); + + let input_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("label", DataType::Utf8, true), + Field::new("image", DataType::LargeBinary, true), + ])); + let input_batch = RecordBatch::try_new( + input_schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1_i64, 2_i64])), + Arc::new(StringArray::from(vec![Some("door"), Some("window")])), + Arc::new(LargeBinaryArray::from_iter_values([ + b"inline_image_bytes".as_slice(), + b"second_image_bytes".as_slice(), + ])), + ], + ) + .unwrap(); + let input_reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(input_batch)].into_iter(), input_schema), + ); + blob_table.add(input_reader).execute().await.unwrap(); + // --8<-- [end:blob_api_ingest] + assert_eq!(blob_table.count_rows(None).await.unwrap(), 2); + + // --8<-- [start:blob_api_files] + let batches = blob_table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_ids = batches[0] + .column_by_name("_rowid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec(); + + let handles = blob_table + .fetch_blob_files("image", &row_ids[..1]) + .await + .unwrap(); + let header = handles[0].as_ref().unwrap().read_range(0..6).await.unwrap(); + handles[0].as_ref().unwrap().close().await.unwrap(); + // --8<-- [end:blob_api_files] + assert_eq!(header.as_ref(), b"inline"); + + // --8<-- [start:blob_api_fetch] + let payloads = blob_table.fetch_blobs("image", &row_ids).await.unwrap(); + // --8<-- [end:blob_api_fetch] + assert_eq!(payloads.len(), 2); + + // --8<-- [start:blob_api_ranges] + let slices = blob_table + .fetch_blob_ranges( + "image", + [ + BlobRangeRequest::new(row_ids[0], 0, 6), + BlobRangeRequest::new(row_ids[1], 0, 6), + BlobRangeRequest::new(row_ids[1], 7, 5), + ], + ) + .await + .unwrap(); + + let second_handles = blob_table + .fetch_blob_files("image", &row_ids[1..2]) + .await + .unwrap(); + let second_image = second_handles[0].as_ref().unwrap(); + let parts = second_image.read_ranges(&[0..6, 7..12]).await.unwrap(); + second_image.close().await.unwrap(); + // --8<-- [end:blob_api_ranges] + assert_eq!(slices.value(0), b"inline"); + assert_eq!(slices.value(1), b"second"); + assert_eq!(slices.value(2), b"image"); + assert_eq!(parts[0].as_ref(), b"second"); + assert_eq!(parts[1].as_ref(), b"image"); + + std::env::set_current_dir(original_dir).unwrap(); +} + +async fn deferred_fetch() { + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("image", true), + ])); + let table = db + .create_empty_table("photos", schema) + .execute() + .await + .unwrap(); + let input_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("image", DataType::LargeBinary, true), + ])); + let batch = RecordBatch::try_new( + input_schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1_i64])), + Arc::new(LargeBinaryArray::from_iter_values([ + b"deferred-bytes".as_slice() + ])), + ], + ) + .unwrap(); + let reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(batch)].into_iter(), input_schema), + ); + table.add(reader).execute().await.unwrap(); + + let described = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(descriptor_kind(&described[0], 0), 0); + assert!(described[0].column_by_name("_rowid").is_none()); + + let located = table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_id = located[0] + .column_by_name("_rowid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(0); + let payloads = table.fetch_blobs("image", &[row_id]).await.unwrap(); + let handles = table.fetch_blob_files("image", &[row_id]).await.unwrap(); + let streamed = handles[0] + .as_ref() + .unwrap() + .read_range(0..payloads.value(0).len() as u64) + .await + .unwrap(); + handles[0].as_ref().unwrap().close().await.unwrap(); + + assert_eq!(payloads.value(0), b"deferred-bytes"); + assert_eq!(streamed.as_ref(), b"deferred-bytes"); +} + +async fn storage_tiers() { + let cases = [ + (1_i64, marked(INLINE_MAX, 11), 0_u8), + (2_i64, marked(INLINE_MAX + 1, 22), 1_u8), + (3_i64, marked(DEDICATED_MIN, 33), 1_u8), + (4_i64, marked(DEDICATED_MIN + 1, 44), 2_u8), + ]; + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("image", true), + ])); + let table = db + .create_empty_table("tiers", schema) + .execute() + .await + .unwrap(); + let input_schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("image", DataType::LargeBinary, true), + ])); + let batch = RecordBatch::try_new( + input_schema.clone(), + vec![ + Arc::new(Int64Array::from_iter_values(cases.iter().map(|row| row.0))), + Arc::new(LargeBinaryArray::from_iter_values( + cases.iter().map(|row| row.1.as_slice()), + )), + ], + ) + .unwrap(); + let reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(batch)].into_iter(), input_schema), + ); + table.add(reader).execute().await.unwrap(); + + let described = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let located = table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut kind_by_id = std::collections::HashMap::new(); + for batch in &described { + let ids = batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + kind_by_id.insert(ids.value(row), descriptor_kind(batch, row)); + } + } + let mut row_id_by_id = std::collections::HashMap::new(); + for batch in &located { + let ids = batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let row_ids = batch + .column_by_name("_rowid") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + row_id_by_id.insert(ids.value(row), row_ids.value(row)); + } + } + + for (id, payload, kind) in &cases { + assert_eq!(kind_by_id[id], *kind); + let row_id = row_id_by_id[id]; + let fetched = table.fetch_blobs("image", &[row_id]).await.unwrap(); + assert_eq!(fetched.value(0), payload.as_slice()); + let handles = table.fetch_blob_files("image", &[row_id]).await.unwrap(); + let handle = handles[0].as_ref().unwrap(); + let head = handle.read_range(0..1).await.unwrap(); + let tail = handle + .read_range((payload.len() - 1) as u64..payload.len() as u64) + .await + .unwrap(); + handle.close().await.unwrap(); + assert_eq!(head.as_ref(), &payload[..1]); + assert_eq!(tail.as_ref(), &payload[payload.len() - 1..]); + } +} + +fn marked(size: usize, marker: u8) -> Vec { + let mut payload = vec![0_u8; size]; + payload[0] = marker; + payload[size - 1] = marker; + payload +} + +fn descriptor_kind(batch: &RecordBatch, row: usize) -> u8 { + let image = batch + .column_by_name("image") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap_or_else(|| panic!("image column was {}", batch.schema())); + image + .column_by_name("kind") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .value(row) +} diff --git a/docs/web-tests/blob-v2/ts/multimodal.test.ts b/docs/web-tests/blob-v2/ts/multimodal.test.ts new file mode 100644 index 000000000..b253ee9b2 --- /dev/null +++ b/docs/web-tests/blob-v2/ts/multimodal.test.ts @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { chdir, cwd } from "node:process"; +import { test } from "node:test"; +import * as arrow from "apache-arrow"; +import { Buffer } from "node:buffer"; +import * as lancedb from "@lancedb/lancedb"; + +const INLINE_MAX = 64 * 1024; +const DEDICATED_MIN = 4 * 1024 * 1024; + +function marked(size: number, marker: number): Buffer { + const payload = Buffer.alloc(size); + payload[0] = marker; + payload[payload.length - 1] = marker; + return payload; +} + +function kindOf(value: unknown): number { + assert.equal(typeof value, "object"); + assert.ok(value !== null); + const kind = (value as { kind?: unknown }).kind; + assert.equal(typeof kind, "number"); + return kind; +} + +test("blob column tutorial", async () => { + const directory = mkdtempSync(join(tmpdir(), "blob-v2-")); + const previous = cwd(); + chdir(directory); + try { + // --8<-- [start:blob_api_setup] + const db = await lancedb.connect("./blob_db"); + // --8<-- [end:blob_api_setup] + + // --8<-- [start:blob_api_schema] + const blobSchema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + new arrow.Field("label", new arrow.Utf8()), + lancedb.blob("image"), + ]); + // --8<-- [end:blob_api_schema] + + // --8<-- [start:blob_api_ingest] + const blobTable = await db.createEmptyTable("photos", blobSchema, { + mode: "overwrite", + }); + + await blobTable.add([ + { id: 1n, label: "door", image: Buffer.from("inline_image_bytes") }, + { id: 2n, label: "window", image: Buffer.from("second_image_bytes") }, + ]); + // --8<-- [end:blob_api_ingest] + assert.equal(await blobTable.countRows(), 2); + + // --8<-- [start:blob_api_files] + const rows = await blobTable + .query() + .select(["id", "label"]) + .withRowId() + .toArray(); + const rowIds = rows.map((row) => row._rowid as bigint); + + const [image] = await blobTable.fetchBlobFiles("image", [rowIds[0]!]); + const header = await image!.readRange(0n, 6n); + await image!.close(); + // --8<-- [end:blob_api_files] + assert.equal(header.toString("utf8"), "inline"); + + // --8<-- [start:blob_api_fetch] + const payloads = await blobTable.fetchBlobs("image", rowIds); + // --8<-- [end:blob_api_fetch] + assert.equal(payloads.length, 2); + + // --8<-- [start:blob_api_ranges] + const [secondImage] = await blobTable.fetchBlobFiles("image", [rowIds[1]!]); + const parts = await secondImage!.readRanges([ + { start: 0n, end: 6n }, + { start: 7n, end: 12n }, + ]); + await secondImage!.close(); + // --8<-- [end:blob_api_ranges] + assert.deepEqual( + parts.map((part) => part.toString("utf8")), + ["second", "image"], + ); + + // --8<-- [start:blob_api_bytes_mode] + const withBytes = await blobTable + .query() + .select(["id", "image"]) + .toArray({ blobMode: "bytes" }); + const firstImage: Uint8Array | null = withBytes[0].image; + // --8<-- [end:blob_api_bytes_mode] + assert.equal(Buffer.from(firstImage!).toString("utf8"), "inline_image_bytes"); + assert.equal(Object.hasOwn(withBytes[0], "_rowid"), false); + } finally { + chdir(previous); + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("eager query returns blob bytes without a row id", async () => { + const directory = mkdtempSync(join(tmpdir(), "blob-v2-eager-")); + try { + const db = await lancedb.connect(directory); + const schema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + lancedb.blob("image"), + ]); + const table = await db.createEmptyTable("photos", schema); + const payload = Buffer.from("inline-bytes"); + await table.add([{ id: 1n, image: payload }]); + + const rows = await table + .query() + .where("id = 1") + .select(["id", "image"]) + .toArray({ blobMode: "bytes" }); + + assert.equal(rows.length, 1); + assert.equal(Object.hasOwn(rows[0], "_rowid"), false); + assert.equal(Buffer.from(rows[0].image).toString("utf8"), "inline-bytes"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("deferred fetch reads a blob by row id", async () => { + const directory = mkdtempSync(join(tmpdir(), "blob-v2-deferred-")); + try { + const db = await lancedb.connect(directory); + const schema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + lancedb.blob("image"), + ]); + const table = await db.createEmptyTable("photos", schema); + await table.add([{ id: 1n, image: Buffer.from("deferred-bytes") }]); + + const described = await table + .query() + .where("id = 1") + .select(["id", "image"]) + .toArray(); + assert.equal(kindOf(described[0].image), 0); + assert.equal(Object.hasOwn(described[0], "_rowid"), false); + + const found = await table.query().where("id = 1").select(["id"]).withRowId().toArray(); + const rowId = found[0]._rowid as bigint; + const payloads = await table.fetchBlobs("image", [rowId]); + const [handle] = await table.fetchBlobFiles("image", [rowId]); + const streamed = await handle!.readRange(0n, handle!.size()); + await handle!.close(); + + assert.equal(Buffer.from(payloads[0]).toString("utf8"), "deferred-bytes"); + assert.equal(Buffer.from(streamed).toString("utf8"), "deferred-bytes"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("storage tiers round-trip", async () => { + const cases = [ + { id: 1n, image: marked(INLINE_MAX, 11), kind: 0 }, + { id: 2n, image: marked(INLINE_MAX + 1, 22), kind: 1 }, + { id: 3n, image: marked(DEDICATED_MIN, 33), kind: 1 }, + { id: 4n, image: marked(DEDICATED_MIN + 1, 44), kind: 2 }, + ]; + const directory = mkdtempSync(join(tmpdir(), "blob-v2-tiers-")); + try { + const db = await lancedb.connect(directory); + const schema = new arrow.Schema([ + new arrow.Field("id", new arrow.Int64()), + lancedb.blob("image"), + ]); + const table = await db.createEmptyTable("tiers", schema); + await table.add(cases.map(({ id, image }) => ({ id, image }))); + + const described = await table.query().select(["id", "image"]).toArray(); + const located = await table.query().select(["id"]).withRowId().toArray(); + const rowIdByValue = new Map(located.map((row) => [row.id as bigint, row._rowid as bigint])); + + for (const item of cases) { + const descriptor = described.find((row) => row.id === item.id); + assert.ok(descriptor); + assert.equal(kindOf(descriptor.image), item.kind); + const rowId = rowIdByValue.get(item.id); + assert.ok(rowId !== undefined); + const [payload] = await table.fetchBlobs("image", [rowId]); + assert.deepEqual(Buffer.from(payload), item.image); + const [handle] = await table.fetchBlobFiles("image", [rowId]); + const streamed = await handle!.read(); + await handle!.close(); + assert.deepEqual(streamed, item.image); + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/docs/web-tests/blob-v2/ts/package-lock.json b/docs/web-tests/blob-v2/ts/package-lock.json new file mode 100644 index 000000000..9426f2b18 --- /dev/null +++ b/docs/web-tests/blob-v2/ts/package-lock.json @@ -0,0 +1,1565 @@ +{ + "name": "lancedb-blob-v2-docs", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "lancedb-blob-v2-docs", + "version": "0.0.0", + "dependencies": { + "@lancedb/lancedb": "0.41.0-beta.8", + "apache-arrow": "21.2.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@huggingface/jinja": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.3.4.tgz", + "integrity": "sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/transformers": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-3.0.2.tgz", + "integrity": "sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@huggingface/jinja": "^0.3.0", + "onnxruntime-node": "1.19.2", + "onnxruntime-web": "1.21.0-dev.20241024-d9ca84ef96", + "sharp": "^0.33.5" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.2.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "license": "ISC", + "optional": true, + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@lancedb/lancedb": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb/-/lancedb-0.41.0-beta.8.tgz", + "integrity": "sha512-W6Sw1rJgJJAT75jXom2fkNvE976iH8EO74ShytymS6sEzCj63gQXQqCYg+jPvQva/dnvYQiOeOGsdkGDFwKmlA==", + "cpu": [ + "x64", + "arm64" + ], + "license": "Apache-2.0", + "os": [ + "darwin", + "linux", + "win32" + ], + "dependencies": { + "@opentelemetry/api": "^1.9.0", + "reflect-metadata": "^0.2.2" + }, + "engines": { + "node": ">= 22" + }, + "optionalDependencies": { + "@huggingface/transformers": "3.0.2", + "@lancedb/lancedb-darwin-arm64": "0.41.0-beta.8", + "@lancedb/lancedb-linux-arm64-gnu": "0.41.0-beta.8", + "@lancedb/lancedb-linux-arm64-musl": "0.41.0-beta.8", + "@lancedb/lancedb-linux-x64-gnu": "0.41.0-beta.8", + "@lancedb/lancedb-linux-x64-musl": "0.41.0-beta.8", + "@lancedb/lancedb-win32-arm64-msvc": "0.41.0-beta.8", + "@lancedb/lancedb-win32-x64-msvc": "0.41.0-beta.8", + "openai": "4.29.2" + }, + "peerDependencies": { + "@types/node": ">=22", + "apache-arrow": ">=15.0.0 <22.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@lancedb/lancedb-darwin-arm64": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-darwin-arm64/-/lancedb-darwin-arm64-0.41.0-beta.8.tgz", + "integrity": "sha512-M1o7VQmB1th9L8YnOqXlxruB1jW6Gns9rTS5H5rCzjv25CTEq/mw9uwl6jrDlLiuVSLWJ89Jj2EDUMH8ZKkEbw==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-arm64-gnu": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-gnu/-/lancedb-linux-arm64-gnu-0.41.0-beta.8.tgz", + "integrity": "sha512-X5lJ2JWMHIrvq/IkkHPjQ3v6myv2jZKK/eayiLe/8Wasxt6LIm9Z7KJYLtXpp5y+kqncAmMRP+BaAJAY02FgvQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-arm64-musl": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-musl/-/lancedb-linux-arm64-musl-0.41.0-beta.8.tgz", + "integrity": "sha512-9reTx4gKOIZlx1hNp3s+O2tMv56aF0bp+kt22+XniwL6xLhVyMlyp+cRnhReVqbvu3Ykqe1lZEQO8U3EXuxSFg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-x64-gnu": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-gnu/-/lancedb-linux-x64-gnu-0.41.0-beta.8.tgz", + "integrity": "sha512-tu9RvxpNNVeUOIWrjmsZgufP+ebBvNES0x4D4qHpPsUJXwdR/LJ4QjON57NvuyQ9CZTUL7Rdk8xbzg+nvlmAaQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-linux-x64-musl": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-musl/-/lancedb-linux-x64-musl-0.41.0-beta.8.tgz", + "integrity": "sha512-EFMuG0GaFO0BPNfY/XRo66nDKKq3ndyiq/t+P4P500cagDtFgCpZphhF8Q+BkQpQ1b+ZgVS2Uaxu5tOyo0SPhg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-win32-arm64-msvc": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-arm64-msvc/-/lancedb-win32-arm64-msvc-0.41.0-beta.8.tgz", + "integrity": "sha512-+vKZHO0CzZgoqqu9izXP2Ea0fBQ/PtolNz3B9JZItR5nc2w12bknA57K1sS06H74BBU9Yie2hDHNt3qzdPBEdw==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@lancedb/lancedb-win32-x64-msvc": { + "version": "0.41.0-beta.8", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-x64-msvc/-/lancedb-win32-x64-msvc-0.41.0-beta.8.tgz", + "integrity": "sha512-qSgWdgh9TzUiurd658ynzD4BxI/6E9yih7HFuFxvi8S+Zcp/NNiDpgrMWLQn/KfvorVJg9XBO8nhZMtg34UTGw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 18" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz", + "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/@types/node": { + "version": "25.9.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.9.tgz", + "integrity": "sha512-b4e2xxj/yMeT2hNlD6x7zNFiQK2Dlmkb9CQ6v3/1G2RezKN4YS2lcEv8lzGm1mhs4f2lM4yNAMI/zUDBZBBt7w==", + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "optional": true, + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agentkeepalive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", + "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/apache-arrow": { + "version": "21.2.0", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.2.0.tgz", + "integrity": "sha512-Hxe6Agq26gQOM954qpzYSllJBPJl+e16U5CkfuMUhLrNba+5nKkttIVlflaovN6oaTratqMGAO8H5u/aNhmHWQ==", + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^25.2.0", + "flatbuffers": "^25.1.24", + "json-with-bigint": "^3.5.3", + "tslib": "^2.6.2" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT", + "optional": true + }, + "node_modules/base-64": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz", + "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==", + "optional": true + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "license": "MIT", + "optional": true, + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT", + "optional": true + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "license": "MIT", + "optional": true, + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "optional": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/digest-fetch": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/digest-fetch/-/digest-fetch-1.3.0.tgz", + "integrity": "sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==", + "license": "ISC", + "optional": true, + "dependencies": { + "base-64": "^0.1.0", + "md5": "^2.3.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", + "license": "MIT", + "optional": true + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 14" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC", + "optional": true + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "optional": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/is-arrayish": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", + "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", + "license": "MIT", + "optional": true + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "license": "MIT", + "optional": true + }, + "node_modules/json-with-bigint": { + "version": "3.5.12", + "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.12.tgz", + "integrity": "sha512-uwbF/wSSuOgC7qqlq27Xp5B6a2MHVug3t0idZdTqu0JnlFvgJuH7ju+KAk/J06C7GfhoYy2gnb9wz2INqcne7w==", + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/md5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "optional": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT", + "optional": true + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "optional": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/onnxruntime-common": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.19.2.tgz", + "integrity": "sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==", + "license": "MIT", + "optional": true + }, + "node_modules/onnxruntime-node": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.19.2.tgz", + "integrity": "sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "onnxruntime-common": "1.19.2", + "tar": "^7.0.1" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.21.0-dev.20241024-d9ca84ef96", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.21.0-dev.20241024-d9ca84ef96.tgz", + "integrity": "sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "flatbuffers": "^1.12.0", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.20.0-dev.20241016-2b8fc5529b", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web/node_modules/flatbuffers": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", + "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==", + "license": "SEE LICENSE IN LICENSE.txt", + "optional": true + }, + "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { + "version": "1.20.0-dev.20241016-2b8fc5529b", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.20.0-dev.20241016-2b8fc5529b.tgz", + "integrity": "sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==", + "license": "MIT", + "optional": true + }, + "node_modules/openai": { + "version": "4.29.2", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.29.2.tgz", + "integrity": "sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "digest-fetch": "^1.3.0", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/openai/node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "license": "MIT", + "optional": true, + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/openai/node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "license": "MIT", + "optional": true + }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT", + "optional": true + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", + "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", + "license": "MIT", + "optional": true, + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/tar": { + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", + "license": "BlueOak-1.0.0", + "optional": true, + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT", + "optional": true + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "license": "MIT" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause", + "optional": true + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/docs/web-tests/blob-v2/ts/package.json b/docs/web-tests/blob-v2/ts/package.json new file mode 100644 index 000000000..f39495edd --- /dev/null +++ b/docs/web-tests/blob-v2/ts/package.json @@ -0,0 +1,16 @@ +{ + "name": "lancedb-blob-v2-docs", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "test": "node --experimental-strip-types --test multimodal.test.ts" + }, + "engines": { + "node": ">=22.6.0" + }, + "dependencies": { + "@lancedb/lancedb": "0.41.0-beta.8", + "apache-arrow": "21.2.0" + } +} diff --git a/docs/web-tests/py/test_multimodal.py b/docs/web-tests/py/test_multimodal.py index cb4a647c3..dbce74ca8 100644 --- a/docs/web-tests/py/test_multimodal.py +++ b/docs/web-tests/py/test_multimodal.py @@ -1,137 +1,134 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import io import pytest +import lancedb +import numpy as np +import pyarrow as pa + try: + # --8<-- [start:multimodal_imports] + import io import lancedb import numpy as np import pyarrow as pa - import io from PIL import Image + # --8<-- [end:multimodal_imports] except ImportError: pass -# --8<-- [start:multimodal_imports] -import lancedb -import pyarrow as pa -import pandas as pd -import numpy as np -import io -from PIL import Image -# --8<-- [end:multimodal_imports] def test_multimodal_ingestion(db_path_factory): - # Ensure dependencies are available pytest.importorskip("PIL") - pytest.importorskip("lancedb") - pytest.importorskip("numpy") # --8<-- [start:create_dummy_data] - # Create some dummy images def create_dummy_image(color): - img = Image.new('RGB', (100, 100), color=color) + img = Image.new("RGB", (100, 100), color=color) buf = io.BytesIO() - img.save(buf, format='PNG') + img.save(buf, format="PNG") return buf.getvalue() - # Create dataset with metadata, vectors, and image blobs data = [ { "id": 1, "filename": "red_square.png", "vector": np.random.rand(128).astype(np.float32), - "image_blob": create_dummy_image('red'), - "label": "red" + "image_blob": create_dummy_image("red"), + "label": "red", }, { "id": 2, "filename": "blue_square.png", "vector": np.random.rand(128).astype(np.float32), - "image_blob": create_dummy_image('blue'), - "label": "blue" - } + "image_blob": create_dummy_image("blue"), + "label": "blue", + }, ] # --8<-- [end:create_dummy_data] # --8<-- [start:define_schema] - # Define schema explicitly to ensure image_blob is treated as binary - schema = pa.schema([ - pa.field("id", pa.int32()), - pa.field("filename", pa.string()), - pa.field("vector", pa.list_(pa.float32(), 128)), - pa.field("image_blob", pa.binary()), # Important: Use pa.binary() for blobs - pa.field("label", pa.string()) - ]) + schema = pa.schema( + [ + pa.field("id", pa.int32()), + pa.field("filename", pa.string()), + pa.field("vector", pa.list_(pa.float32(), 128)), + pa.field("image_blob", pa.binary()), + pa.field("label", pa.string()), + ] + ) # --8<-- [end:define_schema] - db_uri = db_path_factory("multimodal_db") - db = lancedb.connect(db_uri) + db = lancedb.connect(db_path_factory("multimodal_db")) # --8<-- [start:ingest_data] tbl = db.create_table("images", data=data, schema=schema, mode="overwrite") # --8<-- [end:ingest_data] - + assert len(tbl) == 2 # --8<-- [start:search_data] - # Search for similar images query_vector = np.random.rand(128).astype(np.float32) results = tbl.search(query_vector).limit(1).to_pandas() # --8<-- [end:search_data] # --8<-- [start:process_results] - # Convert back to PIL Image for _, row in results.iterrows(): - image_bytes = row['image_blob'] + image_bytes = row["image_blob"] image = Image.open(io.BytesIO(image_bytes)) print(f"Retrieved image: {row['filename']}, Size: {image.size}") - # You can now use 'image' with other libraries or display it # --8<-- [end:process_results] - + assert len(results) == 1 -def test_blob_api_definition(db_path_factory): - # --8<-- [start:blob_api_schema] + +def test_legacy_blob_api_definition(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + # --8<-- [start:legacy_blob_api_schema] import pyarrow as pa # Define schema with Blob API metadata for lazy loading - schema = pa.schema([ - pa.field("id", pa.int64()), - pa.field( - "video", - pa.large_binary(), - metadata={"lance-encoding:blob": "true"} # Enable Blob API - ), - ]) - # --8<-- [end:blob_api_schema] + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field( + "video", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, # Enable Blob API + ), + ] + ) + # --8<-- [end:legacy_blob_api_schema] - # --8<-- [start:blob_api_ingest] + # --8<-- [start:legacy_blob_api_ingest] import lancedb - db = lancedb.connect(db_path_factory("blob_db")) - + db = lancedb.connect("./blob_db") + # Create sample data data = [ {"id": 1, "video": b"fake_video_bytes_1"}, - {"id": 2, "video": b"fake_video_bytes_2"} + {"id": 2, "video": b"fake_video_bytes_2"}, ] - + # Create the table tbl = db.create_table("videos", data=data, schema=schema) - # --8<-- [end:blob_api_ingest] + # --8<-- [end:legacy_blob_api_ingest] assert len(tbl) == 2 -def test_blob_api_to_pandas(db_path_factory): - db = lancedb.connect(db_path_factory("blob_to_pandas_db")) - schema = pa.schema([ - pa.field("id", pa.int64()), - pa.field( - "video", - pa.large_binary(), - metadata={"lance-encoding:blob": "true"}, - ), - ]) +def test_legacy_blob_api_to_pandas(db_path_factory): + db = lancedb.connect(db_path_factory("legacy_blob_to_pandas_db")) + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field( + "video", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, + ), + ] + ) tbl = db.create_table( "videos", data=[ @@ -142,7 +139,7 @@ def test_blob_api_to_pandas(db_path_factory): mode="overwrite", ) - # --8<-- [start:blob_api_to_pandas] + # --8<-- [start:legacy_blob_api_to_pandas] # Default: blob columns come back lazily df_lazy = tbl.to_pandas() @@ -154,7 +151,7 @@ def test_blob_api_to_pandas(db_path_factory): # Forward extra kwargs to PyArrow's to_pandas df_typed = tbl.to_pandas(split_blocks=True, self_destruct=True) - # --8<-- [end:blob_api_to_pandas] + # --8<-- [end:legacy_blob_api_to_pandas] assert len(df_lazy) == 2 assert isinstance(df_bytes["video"].iloc[0], bytes) @@ -167,16 +164,18 @@ def test_blob_api_to_pandas(db_path_factory): @pytest.mark.asyncio -async def test_query_to_pandas_kwargs(db_path_factory): - schema = pa.schema([ - pa.field("id", pa.int64()), - pa.field("vector", pa.list_(pa.float32(), 128)), - pa.field( - "video", - pa.large_binary(), - metadata={"lance-encoding:blob": "true"}, - ), - ]) +async def test_legacy_query_to_pandas_kwargs(db_path_factory): + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("vector", pa.list_(pa.float32(), 128)), + pa.field( + "video", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, + ), + ] + ) data = [ { "id": i, @@ -186,11 +185,11 @@ async def test_query_to_pandas_kwargs(db_path_factory): for i in range(10) ] - db = lancedb.connect(db_path_factory("query_to_pandas_db")) + db = lancedb.connect(db_path_factory("legacy_query_to_pandas_db")) tbl = db.create_table("search_demo", data=data, schema=schema, mode="overwrite") async_db = await lancedb.connect_async( - str(db_path_factory("query_to_pandas_async_db")) + str(db_path_factory("legacy_query_to_pandas_async_db")) ) tbl_async = await async_db.create_table( "search_demo", data=data, schema=schema, mode="overwrite" @@ -198,7 +197,8 @@ async def test_query_to_pandas_kwargs(db_path_factory): query_vector = np.random.rand(128).astype(np.float32) - # --8<-- [start:query_to_pandas_kwargs] + # fmt: off + # --8<-- [start:legacy_query_to_pandas_kwargs] # Plain scan query: blob_mode is supported end to end df_lazy = ( tbl.search() @@ -223,7 +223,8 @@ async def test_query_to_pandas_kwargs(db_path_factory): .select(["id", "vector"]) .to_pandas(split_blocks=True, self_destruct=True) ) - # --8<-- [end:query_to_pandas_kwargs] + # --8<-- [end:legacy_query_to_pandas_kwargs] + # fmt: on assert len(df_lazy) == 1 assert len(df_bytes) == 1 diff --git a/docs/web-tests/rs/multimodal.rs b/docs/web-tests/rs/multimodal.rs index 8cae02eee..f9531d2d5 100644 --- a/docs/web-tests/rs/multimodal.rs +++ b/docs/web-tests/rs/multimodal.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use arrow_array::types::Float32Type; use arrow_array::{ - BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch, + Array, BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, }; use arrow_schema::{DataType, Field, Schema}; @@ -83,8 +83,9 @@ async fn main() { ], ) .unwrap(); - let image_reader: Box = - Box::new(RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone())); + let image_reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()), + ); let table = db .create_table("images", image_reader) .mode(CreateTableMode::Overwrite) @@ -137,42 +138,45 @@ async fn main() { let search_rows: usize = results.iter().map(|batch| batch.num_rows()).sum(); assert_eq!(search_rows, 1); - // --8<-- [start:blob_api_schema] - let blob_metadata = HashMap::from([( + // --8<-- [start:legacy_blob_api_schema] + let legacy_blob_metadata = HashMap::from([( "lance-encoding:blob".to_string(), "true".to_string(), )]); - let blob_schema = Schema::new(vec![ + let legacy_blob_schema = Schema::new(vec![ Field::new("id", DataType::Int64, false), - Field::new("video", DataType::LargeBinary, true).with_metadata(blob_metadata), + Field::new("video", DataType::LargeBinary, true).with_metadata(legacy_blob_metadata), ]); - // --8<-- [end:blob_api_schema] + // --8<-- [end:legacy_blob_api_schema] - // --8<-- [start:blob_api_ingest] - let blob_rows = vec![ + // --8<-- [start:legacy_blob_api_ingest] + let legacy_blob_rows = vec![ (1_i64, b"fake_video_bytes_1".to_vec()), (2_i64, b"fake_video_bytes_2".to_vec()), ]; - let blob_schema = Arc::new(blob_schema); - let blob_batch = RecordBatch::try_new( - blob_schema.clone(), + let legacy_blob_schema = Arc::new(legacy_blob_schema); + let legacy_blob_batch = RecordBatch::try_new( + legacy_blob_schema.clone(), vec![ - Arc::new(Int64Array::from_iter_values(blob_rows.iter().map(|row| row.0))), + Arc::new(Int64Array::from_iter_values( + legacy_blob_rows.iter().map(|row| row.0), + )), Arc::new(LargeBinaryArray::from_iter_values( - blob_rows.iter().map(|row| row.1.as_slice()), + legacy_blob_rows.iter().map(|row| row.1.as_slice()), )), ], ) .unwrap(); - let blob_reader: Box = - Box::new(RecordBatchIterator::new(vec![Ok(blob_batch)].into_iter(), blob_schema)); - let blob_table = db - .create_table("videos", blob_reader) + let legacy_blob_reader: Box = Box::new( + RecordBatchIterator::new(vec![Ok(legacy_blob_batch)].into_iter(), legacy_blob_schema), + ); + let legacy_blob_table = db + .create_table("legacy_videos", legacy_blob_reader) .mode(CreateTableMode::Overwrite) .execute() .await .unwrap(); - // --8<-- [end:blob_api_ingest] - assert_eq!(blob_table.count_rows(None).await.unwrap(), 2); + // --8<-- [end:legacy_blob_api_ingest] + assert_eq!(legacy_blob_table.count_rows(None).await.unwrap(), 2); } diff --git a/docs/web-tests/ts/multimodal.test.ts b/docs/web-tests/ts/multimodal.test.ts index ac9a8201e..32672a6a3 100644 --- a/docs/web-tests/ts/multimodal.test.ts +++ b/docs/web-tests/ts/multimodal.test.ts @@ -75,8 +75,8 @@ test("multimodal snippets (async)", async () => { // --8<-- [end:process_results] expect(results).toHaveLength(1); - // --8<-- [start:blob_api_schema] - const blobSchema = new arrow.Schema([ + // --8<-- [start:legacy_blob_api_schema] + const legacyBlobSchema = new arrow.Schema([ new arrow.Field("id", new arrow.Int64()), new arrow.Field( "video", @@ -85,20 +85,24 @@ test("multimodal snippets (async)", async () => { new Map([["lance-encoding:blob", "true"]]), ), ]); - // --8<-- [end:blob_api_schema] + // --8<-- [end:legacy_blob_api_schema] - // --8<-- [start:blob_api_ingest] - const blobData = lancedb.makeArrowTable( + // --8<-- [start:legacy_blob_api_ingest] + const legacyBlobData = lancedb.makeArrowTable( [ { id: 1, video: Buffer.from("fake_video_bytes_1") }, { id: 2, video: Buffer.from("fake_video_bytes_2") }, ], - { schema: blobSchema }, + { schema: legacyBlobSchema }, ); - const blobTable = await db.createTable("videos", blobData, { - mode: "overwrite", - }); - // --8<-- [end:blob_api_ingest] - expect(await blobTable.countRows()).toBe(2); + const legacyBlobTable = await db.createTable( + "legacy_videos", + legacyBlobData, + { + mode: "overwrite", + }, + ); + // --8<-- [end:legacy_blob_api_ingest] + expect(await legacyBlobTable.countRows()).toBe(2); }); }); diff --git a/docs/web/ingestion/create-table.mdx b/docs/web/ingestion/create-table.mdx index 0921de22e..535ea83e3 100644 --- a/docs/web/ingestion/create-table.mdx +++ b/docs/web/ingestion/create-table.mdx @@ -146,7 +146,8 @@ You can define a custom Arrow schema for the table. This is useful when you want An explicit schema also determines which columns accept missing values (`null`). If later writes omit a non-nullable column, or provide actual nulls for it, ingestion fails; nullable columns can be omitted or written with null values. Without an explicit schema, Python infers list-like vector -values as fixed-size `float32` vector fields from the observed dimension. +values as fixed-size `float32` vector fields from the observed dimension. For images, audio, video, or +other binary columns whose payloads should load on demand, declare a [blob column](/management/table#multimodal-blob-v2) in the schema. For Python ingestion, malformed vectors fail by default (`on_bad_vectors="error"`). This includes vectors with incorrect sizes, NaNs, or null components, including pandas NaNs converted to Arrow diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index ed9883277..d817d4fa0 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -110,15 +110,40 @@ import { PyProcessResults as ProcessResults, TsProcessResults as TsProcessResults, RsProcessResults as RsProcessResults, + PyBlobApiSetup as BlobApiSetup, + TsBlobApiSetup as TsBlobApiSetup, + RsBlobApiImports as RsBlobApiImports, + RsBlobApiSetup as RsBlobApiSetup, PyBlobApiSchema as BlobApiSchema, TsBlobApiSchema as TsBlobApiSchema, RsBlobApiSchema as RsBlobApiSchema, PyBlobApiIngest as BlobApiIngest, + PyBlobApiBytes as BlobApiBytes, TsBlobApiIngest as TsBlobApiIngest, RsBlobApiIngest as RsBlobApiIngest, + PyBlobApiFiles as BlobApiFiles, + TsBlobApiFiles as TsBlobApiFiles, + RsBlobApiFiles as RsBlobApiFiles, + PyBlobApiFetch as BlobApiFetch, + TsBlobApiFetch as TsBlobApiFetch, + RsBlobApiFetch as RsBlobApiFetch, + PyBlobApiRanges as BlobApiRanges, + TsBlobApiRanges as TsBlobApiRanges, + RsBlobApiRanges as RsBlobApiRanges, + TsBlobApiBytesMode as TsBlobApiBytesMode, + PyLegacyBlobApiSchema as LegacyBlobApiSchema, + TsLegacyBlobApiSchema as TsLegacyBlobApiSchema, + RsLegacyBlobApiSchema as RsLegacyBlobApiSchema, + PyLegacyBlobApiIngest as LegacyBlobApiIngest, + TsLegacyBlobApiIngest as TsLegacyBlobApiIngest, + RsLegacyBlobApiIngest as RsLegacyBlobApiIngest, + PyLegacyBlobApiToPandas as LegacyBlobApiToPandas, + PyLegacyQueryToPandasKwargs as LegacyQueryToPandasKwargs, +} from '/snippets/multimodal.mdx'; +import { PyBlobApiToPandas as BlobApiToPandas, PyQueryToPandasKwargs as QueryToPandasKwargs, -} from '/snippets/multimodal.mdx'; +} from '/snippets/blob_pylance.mdx'; A table stores data in rows and columns and keeps a history of committed versions. Queries read table data, writes update it, and indexes accelerate @@ -307,138 +332,280 @@ extension types and pseudo-columns. ## Multimodal data {#multimodal} -Binary data (images, audio, video, model artifacts) lives in the table -beside the structured columns and embeddings that describe it, and is governed -by the same versioning and search. +Store images, audio, video, and documents alongside structured columns and +embeddings in the same versioned table. -Small values go in an ordinary `binary` column. Large ones go in a **blob** -column, stored out of line so a scan over the other columns stays fast. See -[Data types](/sql/data-types#blobs) for how the two differ to a reader. +Use `blob` columns for these payloads. Small values stay inline in the data +file, up to 64 KiB by default, and larger values are stored outside it. -### Store binary data {#multimodal-store-binary-data} +### Blob columns {#multimodal-blob-v2} -To store binary data, define a binary Arrow field in your schema (`pa.binary()` in Python, `Binary` in TypeScript, and `DataType::Binary` in Rust). + +Blob V2 is in early access. + -#### 1\. Setup and imports {#multimodal-1-setup-and-imports} +A `blob` column keeps metadata separate from the payload bytes, so queries can +filter rows without loading the blobs. -First, import the necessary libraries for LanceDB and Arrow in your SDK. +Most queries return descriptors, which contain metadata about the blob instead +of its bytes. You can +[read the bytes in the query results](#multimodal-blob-query-results) or +[fetch them by row ID](#multimodal-read-blobs). + +In Python, plain `to_pandas()` scans can also return `BlobFile` handles when +`pylance` is installed. + +When you write raw bytes, Lance chooses a storage layout based on the payload +size. A descriptor's `kind` tells you which one was used: + +| Storage mode | `kind` | Default placement | Storage behavior | +| --- | --- | --- | --- | +| `Inline` | `0` | Up to 64 KiB | Stored in the main data file. | +| `Packed` | `1` | Above 64 KiB, up to 4 MiB | Packed with other blobs into a shared sidecar file, up to 1 GiB per file by default. | +| `Dedicated` | `2` | Above 4 MiB | Stored in its own raw sidecar file. | +| `Managed` | `4` or `5` | Out-of-line values when managed storage is enabled | Stored in a Lance-owned object independently of the data file. | + +Managed storage must be enabled separately. See +[Managed blobs](#managed-blobs) for details. `kind=5` identifies a Managed +object using an explicitly registered base. + +Lance uses the default thresholds unless you customize them. Explicitly +configured thresholds are stored in the table schema and preserved on append. + +#### Setup {#multimodal-blob-v2-setup} + +Import the SDK and open a local database. The examples in this section use `db`. - {MultimodalImports} + {BlobApiSetup} - {TsMultimodalImports} + {TsMultimodalImports}{"\n"}{TsBlobApiSetup} - {RsMultimodalImports} + {RsBlobApiImports}{"\n"}{RsBlobApiSetup} -#### 2\. Prepare data {#multimodal-2-prepare-data} +#### Define a blob schema {#multimodal-blob-v2-schema} -For this example, we'll create some dummy in-memory images. In a real application, you would read these from files or an API. The key is to convert your data (image, audio, etc.) into a raw `bytes` object. +Declare a blob column with `lancedb.blob()` in Python and TypeScript, or +`blob()` in Rust: - {CreateDummyData} + {BlobApiSchema} - {TsCreateDummyData} + {TsBlobApiSchema} - {RsCreateDummyData} + {RsBlobApiSchema} -#### 3\. Define the schema {#multimodal-3-define-the-schema} +#### Ingest blobs {#multimodal-blob-v2-ingest} -When creating the table, it is **highly recommended** to define the schema explicitly. This ensures that your binary data is correctly interpreted as a `binary` type by Arrow/LanceDB and not as a generic string or list. +Pass raw bytes for each blob value. In Python, a blob column accepts `bytes`. +In TypeScript, it accepts a `Buffer`. The Python example creates two JPEGs +with EXIF metadata, which we'll read using a blob handle below. - {DefineSchema} + {BlobApiIngest} - {TsDefineSchema} + {TsBlobApiIngest} - {RsDefineSchema} + {RsBlobApiIngest} -#### 4\. Ingest data {#multimodal-4-ingest-data} +#### Read bytes in query results {#multimodal-blob-query-results} -Now, create the table using the data and the defined schema. +Python and TypeScript can return blob bytes in query results without +collecting `_rowid`. Rust uses [`fetch_blobs`](#multimodal-read-blobs) with +row IDs instead. + +##### Python {#multimodal-blob-python} + +`to_list(blob_mode="bytes")` returns the `image` bytes from the `photos` table +above: - {IngestData} - - - - {TsIngestData} - - - - {RsIngestData} + {BlobApiBytes} -### Retrieve and use blobs {#multimodal-retrieve-and-use-blobs} +In the Python SDK, `Table.to_pandas()`, `Table.to_arrow()`, and the query builder +methods `to_pandas()`, `to_arrow()`, and `to_list()` accept a `blob_mode` +argument: -When you search your LanceDB table, you can retrieve the binary column just like any other metadata. +| `blob_mode` | `to_pandas()` | `to_arrow()` and `to_list()` | +| --- | --- | --- | +| `"lazy"` | Default. Plain scans return seekable `BlobFile` handles. Vector, full-text, hybrid, and ordered queries return descriptor dicts. | Default. Returns descriptors carrying `_lance_row_id` so the result table can be passed to `fetch_blobs` or `fetch_blob_files`. | +| `"descriptions"` | Returns descriptor dicts with `kind`, `position`, `size`, `blob_id`, and `blob_uri`. | Returns the 5-field descriptor without `_lance_row_id`. | +| `"bytes"` | Materializes each blob as `bytes` in the DataFrame. | Materializes each blob as `large_binary` in Arrow or `bytes` in Python dicts. | + +`to_pandas(blob_mode="lazy")` and `to_pandas(blob_mode="bytes")` require +pylance. Without it they raise `ImportError`. `to_arrow()`, +`to_list(blob_mode="bytes")`, `to_pandas(blob_mode="descriptions")`, and the +fetch methods do not. + +`blob_mode="bytes"` requires a local table snapshot, so remote and in-memory +tables raise `NotImplementedError`. On a remote table, `Table.to_pandas()` and +`Table.to_arrow()` aren't supported, and a query's `to_pandas()` also raises in +the default `"lazy"` mode because it would open `BlobFile` handles. Query with +`blob_mode="descriptions"`, then read bytes with `fetch_blobs` or +`fetch_blob_files`. + +`blob_mode="bytes"` materializes top-level and struct-nested blob columns. It +raises `ValueError` when the selected columns include blobs +inside a list. Select those columns with `blob_mode="descriptions"`, or leave +them out of the projection. Extra keyword arguments on +`to_pandas()`, such as `split_blocks` and `self_destruct`, are forwarded to +PyArrow. + +###### Optional pandas examples {#multimodal-blob-pandas} + +These examples require pylance. The query example expects `tbl_async`, +`query_vector`, and a `video` column, which the `photos` table does not define. - {SearchData} - - - - {TsSearchData} - - - - {RsSearchData} + {BlobApiToPandas} -#### Convert bytes back to objects {#multimodal-convert-bytes-back-to-objects} - -Once you have the bytes back from the search result, you can decode them into the original format (for example, an image object or audio buffer). +Sync and async query builders accept the same `blob_mode` values: - {ProcessResults} + {QueryToPandasKwargs} + + + +##### TypeScript {#multimodal-blob-typescript} + +In TypeScript, `toArray()` and `toArrow()` accept a `blobMode` option: + +| `blobMode` | Result | +| --- | --- | +| `"descriptions"` | Default. Returns descriptors. | +| `"bytes"` | Returns each top-level blob as bytes, or `null` for a null blob. Blobs nested in a struct or list keep their descriptors. | + +With `"bytes"`, the rows and the bytes come from the same table version. If the +table changes while the query runs, the query runs again, up to three times: + + + + {TsBlobApiBytesMode} + + + +#### Read blobs on demand {#multimodal-read-blobs} + +Query the rows you want and pass their `_rowid` values to a fetch method. +`fetch_blob_files` opens a seekable handle and loads bytes only when you read. +The Python example opens the JPEG from the ingest step and reads its EXIF +Make tag with Pillow. TypeScript and Rust read the first bytes from the handle. + + + + {BlobApiFiles} - {TsProcessResults} + {TsBlobApiFiles} - {RsProcessResults} + {RsBlobApiFiles} +The other fetch methods load bytes directly: + +| Need | Python | TypeScript | Rust | +| --- | --- | --- | --- | +| Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | +| Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | + +- `fetch_blobs` returns the full bytes for each row ID in order. Null blobs + produce null entries, and empty blobs produce empty byte strings. +- `fetch_blob_files` loads bytes when you call `read`, `read_range`, or + `read_ranges`. Range reads don't move the file cursor. Null blobs produce + null handles. +- `fetch_blob_ranges` takes `(row_id, offset, length)` requests and returns one + slice per request, in order. A request list can repeat a row to read more + than one slice of that blob. + + + + {BlobApiFetch} + + + + {TsBlobApiFetch} + + + + {RsBlobApiFetch} + + + +Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, +`read_ranges` reads more than one slice of one blob. Python takes +`(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an +exclusive `end`, and Rust takes `start..end` ranges: + + + + {BlobApiRanges} + + + + {TsBlobApiRanges} + + + + {RsBlobApiRanges} + + + +#### Notes and limits {#multimodal-blob-notes} + +Blob fetches fail if any requested row ID is missing or deleted. With stable +row IDs enabled, IDs remain valid across compaction. + +A blob field can sit at the top level of the schema or inside a struct or list. +Struct-nested blob columns use dotted paths such as `clip.video` in the fetch +APIs. Blobs inside lists can be written and queried as descriptors. A table +row ID does not address one list element, so `blob_columns()`, `fetch_blobs`, +`fetch_blob_files`, and `blob_mode="bytes"` can't return those bytes. + +See the Lance [blob guide](https://lance.org/guide/blob/) for the storage format. + ### Managed blobs (Blob v2) {#managed-blobs} -Use `lancedb.blob()` for images, audio, videos, and other binary values whose -payloads should load separately from the rest of a row. Write Python `bytes` -normally. Set the table schema metadata `lance.blob.managed` to `true` to -store small values inline and larger values in managed objects under the table's `_blobs/` directory. Medium values can share a packed -object; large values use a dedicated object. +Set the table schema metadata `lance.blob.managed` to `true` on a table with +[`lancedb.blob()`](#multimodal-blob-v2) columns to store small values inline and +larger values in managed objects under the table's `_blobs/` directory. Medium +values can share a packed object, and large values use a dedicated object. The table owns these objects. You do not upload them separately, keep an object -catalog, or delete their files yourself. A descriptor records where to read the -bytes. Compaction preserves the descriptor and its payload object, so merging -table fragments does not rewrite the blob payloads. +catalog, or delete their files yourself. Compaction preserves each descriptor +and its payload object, so merging table fragments does not rewrite the blob +payloads. Use an SDK and Enterprise deployment that support Blob v2 Managed storage. @@ -484,16 +651,10 @@ assert by_id[1] == b"" assert len(by_id[2]) == 102400 ``` -`None` is a null value; `b""` is a present, empty blob. `fetch_blobs` returns -bytes in the order of the supplied row IDs. It materializes the selected -payloads, so fetch bounded batches when blobs are large. Row IDs belong to -their table; fetch them from the same table and snapshot that produced the -query result. - -Keep descriptors opaque in application code. Their representation can differ -between inline values, Managed objects, and externally referenced blobs. For -streaming and range reads, see the -[Lance blob guide](https://lance.org/guide/blob/). +`fetch_blobs` materializes the selected payloads in memory, so fetch bounded +batches when blobs are large. Row IDs belong to their table and snapshot. Keep +descriptors opaque in application code, because their representation can differ +between inline values and Managed objects. #### Derived blobs and maintenance {#managed-blobs-lifecycle} @@ -509,92 +670,190 @@ any of its contained blobs is still referenced. ### Legacy large-binary blobs {#multimodal-large-blobs-blob-api} -The schema below describes the earlier large-binary Blob API. It is distinct -from the `lancedb.blob()` schema above; changing the field's metadata alone does -not migrate an existing column to Blob v2. - -For larger files like high-resolution images or videos, Lance provides a specialized **Blob API**. By using a large-binary Arrow type (`pa.large_binary()` in Python, `LargeBinary` in TypeScript, and `DataType::LargeBinary` in Rust) and specific metadata, you enable **lazy loading** and optimized encoding. This allows you to work with massive datasets without loading all binary data into memory upfront. +Use [`lancedb.blob()`](#multimodal-blob-v2) for new tables. The sections below +cover existing tables that use the V1 large-binary Blob API +(`pa.large_binary()` in Python, `LargeBinary` in TypeScript, and +`DataType::LargeBinary` in Rust with `{"lance-encoding:blob": "true"}` field +metadata). Changing a field's metadata alone does not migrate an existing V1 +column to Blob v2. #### 1\. Define a blob schema {#multimodal-1-define-a-blob-schema} -To use the Blob API, you must mark the column with `{"lance-encoding:blob": "true"}` metadata. +V1 blob columns use a `large_binary` field marked with `{"lance-encoding:blob": "true"}` metadata: - {BlobApiSchema} + {LegacyBlobApiSchema} - {TsBlobApiSchema} + {TsLegacyBlobApiSchema} - {RsBlobApiSchema} + {RsLegacyBlobApiSchema} #### 2\. Ingest large blobs {#multimodal-2-ingest-large-blobs} -You can then ingest data normally, and Lance will handle the optimized storage. +Write raw bytes to a V1 blob column: - {BlobApiIngest} + {LegacyBlobApiIngest} - {TsBlobApiIngest} + {TsLegacyBlobApiIngest} - {RsBlobApiIngest} + {RsLegacyBlobApiIngest} - -For more advanced usage, including random access and file-like reading of blobs, see the -Lance format's [blob API documentation](https://lance.org/guide/blob/). - - #### 3\. Convert blob tables to pandas {#multimodal-3-convert-blob-tables-to-pandas} -When you call `to_pandas()` on a local LanceDB table that contains Blob API columns, the `blob_mode` argument controls how those columns materialize. This is available in the Python SDK on local tables; remote tables raise `NotImplementedError`. - -`blob_mode` accepts: - -- `"lazy"` (default): returns blob columns as lazy `BlobFile` objects without eagerly materializing their payloads. Use this when you want to stream blob bytes on demand or only inspect a subset of rows. Namespace-backed local tables also use the Lance native blob-aware pandas conversion for lazy blobs; in-memory datasets fall back to the standard PyArrow `to_pandas()` path. -- `"bytes"`: eagerly materializes each blob as `bytes`. Use this when you need the raw payload in the DataFrame, for example to decode an image or audio clip in-process. -- `"descriptions"`: returns blob descriptors (offsets, sizes, and positions) instead of the data itself. Use this when you want to plan I/O without paying the cost of loading every blob. - -`"bytes"` is not supported on in-memory tables. - -Extra keyword arguments are forwarded to the underlying PyArrow / Lance pandas conversion, so you can also pass options like `split_blocks` or `self_destruct`: +On local tables with V1 blob columns, `to_pandas()` in Python accepts `blob_mode` +(`"lazy"`, `"bytes"`, or `"descriptions"`). Remote tables raise +`NotImplementedError`, and `"bytes"` is not supported on in-memory tables. +Extra keyword arguments such as `split_blocks` or `self_destruct` are forwarded +to the PyArrow / Lance pandas conversion: - {BlobApiToPandas} + {LegacyBlobApiToPandas} -Query builders also accept `blob_mode` on their `to_pandas()` method: - -- Plain scans support `"lazy"`, `"bytes"`, and `"descriptions"` with filters, projections, aliases, `limit`, and `offset`. -- Vector, FTS, hybrid, and ordered queries can't materialize blob columns through `to_pandas()`; omit blob columns from the projection for those query shapes. -- This works on both sync and async query builders. Extra PyArrow kwargs like `split_blocks` and `self_destruct` are still forwarded. +On query builders with V1 blob columns, plain scans support `"lazy"`, `"bytes"`, +and `"descriptions"`. Vector, FTS, hybrid, and ordered queries cannot +materialize V1 blob columns through `to_pandas()`, so omit those columns from +the projection: - {QueryToPandasKwargs} + {LegacyQueryToPandasKwargs} + + + +### Store binary data {#multimodal-store-binary-data} + +Use a `binary` column when the query should return the raw bytes. Declare it as `pa.binary()` in Python, `Binary` in TypeScript, and `DataType::Binary` in Rust. + +#### 1\. Setup and imports {#multimodal-1-setup-and-imports} + +Import LanceDB and Arrow in your SDK. + + + + {MultimodalImports} + + + + {TsMultimodalImports} + + + + {RsMultimodalImports} + + + +#### 2\. Prepare data {#multimodal-2-prepare-data} + +Encode each image or file into raw bytes before writing. + + + + {CreateDummyData} + + + + {TsCreateDummyData} + + + + {RsCreateDummyData} + + + +#### 3\. Define the schema {#multimodal-3-define-the-schema} + +Declare the schema explicitly so Arrow and LanceDB store the field as `binary` instead of inferring a string or integer list. + + + + {DefineSchema} + + + + {TsDefineSchema} + + + + {RsDefineSchema} + + + +#### 4\. Ingest data {#multimodal-4-ingest-data} + +Create the table from the rows and schema. + + + + {IngestData} + + + + {TsIngestData} + + + + {RsIngestData} + + + +### Retrieve binary data {#multimodal-retrieve-and-use-blobs} + +When you search the table, select the `binary` column alongside your metadata columns. + + + + {SearchData} + + + + {TsSearchData} + + + + {RsSearchData} + + + +#### Convert bytes back to objects {#multimodal-convert-bytes-back-to-objects} + +Decode the returned bytes into an image or media buffer in your application. + + + + {ProcessResults} + + + + {TsProcessResults} + + + + {RsProcessResults} ### Other modalities {#multimodal-other-modalities} -The `pa.binary()` and `pa.large_binary()` types are universal. You can use this same pattern for other types of multimodal data: - -- **Audio:** Read `.wav` or `.mp3` files as bytes. -- **Video:** Store video transitions or full clips using the Blob API. -- **PDFs/Documents:** Store the raw file content for document search. +For PDFs, audio recordings, and other files, keep searchable fields in separate +columns so you can filter rows before fetching blob bytes. ### bfloat16 {#multimodal-bfloat16} diff --git a/docs/web/snippets/blob_pylance.mdx b/docs/web/snippets/blob_pylance.mdx new file mode 100644 index 000000000..eb0bd74d6 --- /dev/null +++ b/docs/web/snippets/blob_pylance.mdx @@ -0,0 +1,6 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const PyBlobApiToPandas = "df_lazy = tbl.to_pandas()\n\ndf_bytes = tbl.to_pandas(blob_mode=\"bytes\")\n\ndf_desc = tbl.to_pandas(blob_mode=\"descriptions\")\n\narrow_bytes = tbl.to_arrow(blob_mode=\"bytes\")\n\ndf_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)\n"; + +export const PyQueryToPandasKwargs = "df_lazy = (\n tbl.search().where(\"id = 1\").select([\"id\", \"video\"]).to_pandas(blob_mode=\"lazy\")\n)\n\ndf_bytes = await (\n tbl_async.query()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\")\n)\n\ndf_vec = (\n tbl.search(query_vector)\n .limit(2)\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\", split_blocks=True, self_destruct=True)\n)\n"; + diff --git a/docs/web/snippets/multimodal.mdx b/docs/web/snippets/multimodal.mdx index f41af6629..19180dfd0 100644 --- a/docs/web/snippets/multimodal.mdx +++ b/docs/web/snippets/multimodal.mdx @@ -1,28 +1,52 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyBlobApiIngest = "import lancedb\n\ndb = lancedb.connect(db_path_factory(\"blob_db\"))\n \n# Create sample data\ndata = [\n {\"id\": 1, \"video\": b\"fake_video_bytes_1\"},\n {\"id\": 2, \"video\": b\"fake_video_bytes_2\"}\n]\n \n# Create the table\ntbl = db.create_table(\"videos\", data=data, schema=schema)\n"; +export const PyBlobApiBytes = "rows = (\n tbl.search().where(\"id = 1\").select([\"id\", \"image\"]).to_list(blob_mode=\"bytes\")\n)\n"; -export const PyBlobApiSchema = "import pyarrow as pa\n\n# Define schema with Blob API metadata for lazy loading\nschema = pa.schema([\n pa.field(\"id\", pa.int64()),\n pa.field(\n \"video\", \n pa.large_binary(), \n metadata={\"lance-encoding:blob\": \"true\"} # Enable Blob API\n ),\n])\n"; +export const PyBlobApiFetch = "rows = tbl.search().select([\"id\"]).with_row_id(True).to_list()\nrow_ids = [row[\"_rowid\"] for row in rows]\npayloads = tbl.fetch_blobs(\"image\", row_ids)\n"; -export const PyBlobApiToPandas = "# Default: blob columns come back lazily\ndf_lazy = tbl.to_pandas()\n\n# Materialize blob bytes eagerly\ndf_bytes = tbl.to_pandas(blob_mode=\"bytes\")\n\n# Return descriptors instead of payloads\ndf_desc = tbl.to_pandas(blob_mode=\"descriptions\")\n\n# Forward extra kwargs to PyArrow's to_pandas\ndf_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)\n"; +export const PyBlobApiFiles = "from PIL import ExifTags\n\nrows = tbl.search().where(\"id = 1\").select([\"label\"]).with_row_id(True).to_list()\nwith tbl.fetch_blob_files(\"image\", [rows[0][\"_rowid\"]])[0] as image_file:\n make = Image.open(image_file).getexif().get(ExifTags.Base.Make)\nprint(rows[0][\"label\"], make)\n"; -export const PyCreateDummyData = "# Create some dummy images\ndef create_dummy_image(color):\n img = Image.new('RGB', (100, 100), color=color)\n buf = io.BytesIO()\n img.save(buf, format='PNG')\n return buf.getvalue()\n\n# Create dataset with metadata, vectors, and image blobs\ndata = [\n {\n \"id\": 1,\n \"filename\": \"red_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image('red'),\n \"label\": \"red\"\n },\n {\n \"id\": 2,\n \"filename\": \"blue_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image('blue'),\n \"label\": \"blue\"\n }\n]\n"; +export const PyBlobApiIngest = "import io\nfrom PIL import Image\n\ndef jpeg_with_make(color, make):\n image = Image.new(\"RGB\", (8, 8), color=color)\n exif = Image.Exif()\n exif[0x010F] = make\n buf = io.BytesIO()\n image.save(buf, format=\"JPEG\", exif=exif)\n return buf.getvalue()\n\ntbl = db.create_table(\n \"photos\",\n data=[\n {\"id\": 1, \"label\": \"red\", \"image\": jpeg_with_make(\"red\", \"TestCam\")},\n {\"id\": 2, \"label\": \"blue\", \"image\": jpeg_with_make(\"blue\", \"OtherCam\")},\n ],\n schema=schema,\n mode=\"overwrite\",\n)\n"; -export const PyDefineSchema = "# Define schema explicitly to ensure image_blob is treated as binary\nschema = pa.schema([\n pa.field(\"id\", pa.int32()),\n pa.field(\"filename\", pa.string()),\n pa.field(\"vector\", pa.list_(pa.float32(), 128)),\n pa.field(\"image_blob\", pa.binary()), # Important: Use pa.binary() for blobs\n pa.field(\"label\", pa.string())\n])\n"; +export const PyBlobApiRanges = "slices = tbl.fetch_blob_ranges(\"image\", [(row_ids[0], 0, 2)])\n\nwith tbl.fetch_blob_files(\"image\", [row_ids[0]])[0] as image_file:\n parts = image_file.read_ranges([(0, 2)])\n"; + +export const PyBlobApiSchema = "import lancedb\nimport pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64()),\n pa.field(\"label\", pa.string()),\n lancedb.blob(\"image\"),\n ]\n)\n"; + +export const PyBlobApiSetup = "import lancedb\n\ndb = lancedb.connect(\"./blob_db\")\n"; + +export const PyCreateDummyData = "def create_dummy_image(color):\n img = Image.new(\"RGB\", (100, 100), color=color)\n buf = io.BytesIO()\n img.save(buf, format=\"PNG\")\n return buf.getvalue()\n\ndata = [\n {\n \"id\": 1,\n \"filename\": \"red_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image(\"red\"),\n \"label\": \"red\",\n },\n {\n \"id\": 2,\n \"filename\": \"blue_square.png\",\n \"vector\": np.random.rand(128).astype(np.float32),\n \"image_blob\": create_dummy_image(\"blue\"),\n \"label\": \"blue\",\n },\n]\n"; + +export const PyDefineSchema = "schema = pa.schema(\n [\n pa.field(\"id\", pa.int32()),\n pa.field(\"filename\", pa.string()),\n pa.field(\"vector\", pa.list_(pa.float32(), 128)),\n pa.field(\"image_blob\", pa.binary()),\n pa.field(\"label\", pa.string()),\n ]\n)\n"; export const PyIngestData = "tbl = db.create_table(\"images\", data=data, schema=schema, mode=\"overwrite\")\n"; -export const PyMultimodalImports = "import lancedb\nimport pyarrow as pa\nimport pandas as pd\nimport numpy as np\nimport io\nfrom PIL import Image\n"; +export const PyLegacyBlobApiIngest = "import lancedb\n\ndb = lancedb.connect(\"./blob_db\")\n\n# Create sample data\ndata = [\n {\"id\": 1, \"video\": b\"fake_video_bytes_1\"},\n {\"id\": 2, \"video\": b\"fake_video_bytes_2\"},\n]\n\n# Create the table\ntbl = db.create_table(\"videos\", data=data, schema=schema)\n"; -export const PyProcessResults = "# Convert back to PIL Image\nfor _, row in results.iterrows():\n image_bytes = row['image_blob']\n image = Image.open(io.BytesIO(image_bytes))\n print(f\"Retrieved image: {row['filename']}, Size: {image.size}\")\n # You can now use 'image' with other libraries or display it\n"; +export const PyLegacyBlobApiSchema = "import pyarrow as pa\n\n# Define schema with Blob API metadata for lazy loading\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64()),\n pa.field(\n \"video\",\n pa.large_binary(),\n metadata={\"lance-encoding:blob\": \"true\"}, # Enable Blob API\n ),\n ]\n)\n"; -export const PyQueryToPandasKwargs = "# Plain scan query: blob_mode is supported end to end\ndf_lazy = (\n tbl.search()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"lazy\")\n)\n\n# Same call shape works on async query builders\ndf_bytes = await (\n tbl_async.query()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\")\n)\n\n# Vector / FTS / hybrid queries can't materialize blob columns,\n# so omit them from the projection\ndf_vec = (\n tbl.search(query_vector)\n .limit(10)\n .select([\"id\", \"vector\"])\n .to_pandas(split_blocks=True, self_destruct=True)\n)\n"; +export const PyLegacyBlobApiToPandas = "# Default: blob columns come back lazily\ndf_lazy = tbl.to_pandas()\n\n# Materialize blob bytes eagerly\ndf_bytes = tbl.to_pandas(blob_mode=\"bytes\")\n\n# Return descriptors instead of payloads\ndf_desc = tbl.to_pandas(blob_mode=\"descriptions\")\n\n# Forward extra kwargs to PyArrow's to_pandas\ndf_typed = tbl.to_pandas(split_blocks=True, self_destruct=True)\n"; -export const PySearchData = "# Search for similar images\nquery_vector = np.random.rand(128).astype(np.float32)\nresults = tbl.search(query_vector).limit(1).to_pandas()\n"; +export const PyLegacyQueryToPandasKwargs = "# Plain scan query: blob_mode is supported end to end\ndf_lazy = (\n tbl.search()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"lazy\")\n)\n\n# Same call shape works on async query builders\ndf_bytes = await (\n tbl_async.query()\n .where(\"id = 1\")\n .select([\"id\", \"video\"])\n .to_pandas(blob_mode=\"bytes\")\n)\n\n# Vector / FTS / hybrid queries can't materialize blob columns,\n# so omit them from the projection\ndf_vec = (\n tbl.search(query_vector)\n .limit(10)\n .select([\"id\", \"vector\"])\n .to_pandas(split_blocks=True, self_destruct=True)\n)\n"; -export const TsBlobApiIngest = "const blobData = lancedb.makeArrowTable(\n [\n { id: 1, video: Buffer.from(\"fake_video_bytes_1\") },\n { id: 2, video: Buffer.from(\"fake_video_bytes_2\") },\n ],\n { schema: blobSchema },\n);\nconst blobTable = await db.createTable(\"videos\", blobData, {\n mode: \"overwrite\",\n});\n"; +export const PyMultimodalImports = "import io\nimport lancedb\nimport numpy as np\nimport pyarrow as pa\nfrom PIL import Image\n"; -export const TsBlobApiSchema = "const blobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\n \"video\",\n new arrow.LargeBinary(),\n true,\n new Map([[\"lance-encoding:blob\", \"true\"]]),\n ),\n]);\n"; +export const PyProcessResults = "for _, row in results.iterrows():\n image_bytes = row[\"image_blob\"]\n image = Image.open(io.BytesIO(image_bytes))\n print(f\"Retrieved image: {row['filename']}, Size: {image.size}\")\n"; + +export const PySearchData = "query_vector = np.random.rand(128).astype(np.float32)\nresults = tbl.search(query_vector).limit(1).to_pandas()\n"; + +export const TsBlobApiBytesMode = "const withBytes = await blobTable\n .query()\n .select([\"id\", \"image\"])\n .toArray({ blobMode: \"bytes\" });\nconst firstImage: Uint8Array | null = withBytes[0].image;\n"; + +export const TsBlobApiFetch = "const payloads = await blobTable.fetchBlobs(\"image\", rowIds);\n"; + +export const TsBlobApiFiles = "const rows = await blobTable\n .query()\n .select([\"id\", \"label\"])\n .withRowId()\n .toArray();\nconst rowIds = rows.map((row) => row._rowid as bigint);\n\nconst [image] = await blobTable.fetchBlobFiles(\"image\", [rowIds[0]!]);\nconst header = await image!.readRange(0n, 6n);\nawait image!.close();\n"; + +export const TsBlobApiIngest = "const blobTable = await db.createEmptyTable(\"photos\", blobSchema, {\n mode: \"overwrite\",\n});\n\nawait blobTable.add([\n { id: 1n, label: \"door\", image: Buffer.from(\"inline_image_bytes\") },\n { id: 2n, label: \"window\", image: Buffer.from(\"second_image_bytes\") },\n]);\n"; + +export const TsBlobApiRanges = "const [secondImage] = await blobTable.fetchBlobFiles(\"image\", [rowIds[1]!]);\nconst parts = await secondImage!.readRanges([\n { start: 0n, end: 6n },\n { start: 7n, end: 12n },\n]);\nawait secondImage!.close();\n"; + +export const TsBlobApiSchema = "const blobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\"label\", new arrow.Utf8()),\n lancedb.blob(\"image\"),\n]);\n"; + +export const TsBlobApiSetup = "const db = await lancedb.connect(\"./blob_db\");\n"; export const TsCreateDummyData = "const createDummyImage = (color: string): Uint8Array => {\n const pngHeader = Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]);\n return Buffer.concat([Buffer.from(pngHeader), Buffer.from(color, \"utf8\")]);\n};\n\nconst data = [\n {\n id: 1,\n filename: \"red_square.png\",\n vector: Array.from({ length: 128 }, (_, i) => (i % 16) / 16),\n image_blob: createDummyImage(\"red\"),\n label: \"red\",\n },\n {\n id: 2,\n filename: \"blue_square.png\",\n vector: Array.from({ length: 128 }, (_, i) => ((i + 8) % 16) / 16),\n image_blob: createDummyImage(\"blue\"),\n label: \"blue\",\n },\n];\n"; @@ -30,23 +54,41 @@ export const TsDefineSchema = "const schema = new arrow.Schema([\n new arrow.Fi export const TsIngestData = "const multimodalData = lancedb.makeArrowTable(data, { schema });\nconst tbl = await db.createTable(\"images\", multimodalData, {\n mode: \"overwrite\",\n});\n"; +export const TsLegacyBlobApiIngest = "const legacyBlobData = lancedb.makeArrowTable(\n [\n { id: 1, video: Buffer.from(\"fake_video_bytes_1\") },\n { id: 2, video: Buffer.from(\"fake_video_bytes_2\") },\n ],\n { schema: legacyBlobSchema },\n);\nconst legacyBlobTable = await db.createTable(\n \"legacy_videos\",\n legacyBlobData,\n {\n mode: \"overwrite\",\n },\n);\n"; + +export const TsLegacyBlobApiSchema = "const legacyBlobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\n \"video\",\n new arrow.LargeBinary(),\n true,\n new Map([[\"lance-encoding:blob\", \"true\"]]),\n ),\n]);\n"; + export const TsMultimodalImports = "import * as arrow from \"apache-arrow\";\nimport { Buffer } from \"node:buffer\";\nimport * as lancedb from \"@lancedb/lancedb\";\n"; export const TsProcessResults = "for (const row of results) {\n const imageBytes = row.image_blob as Uint8Array;\n console.log(\n `Retrieved image: ${row.filename}, Byte length: ${imageBytes.length}`,\n );\n}\n"; export const TsSearchData = "const queryVector = Array.from({ length: 128 }, (_, i) => (i % 16) / 16);\nconst results = await tbl.search(queryVector).limit(1).toArray();\n"; -export const RsBlobApiIngest = "let blob_rows = vec![\n (1_i64, b\"fake_video_bytes_1\".to_vec()),\n (2_i64, b\"fake_video_bytes_2\".to_vec()),\n];\n\nlet blob_schema = Arc::new(blob_schema);\nlet blob_batch = RecordBatch::try_new(\n blob_schema.clone(),\n vec![\n Arc::new(Int64Array::from_iter_values(blob_rows.iter().map(|row| row.0))),\n Arc::new(LargeBinaryArray::from_iter_values(\n blob_rows.iter().map(|row| row.1.as_slice()),\n )),\n ],\n)\n.unwrap();\nlet blob_reader: Box =\n Box::new(RecordBatchIterator::new(vec![Ok(blob_batch)].into_iter(), blob_schema));\nlet blob_table = db\n .create_table(\"videos\", blob_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; +export const RsBlobApiFetch = "let payloads = blob_table.fetch_blobs(\"image\", &row_ids).await.unwrap();\n"; -export const RsBlobApiSchema = "let blob_metadata = HashMap::from([(\n \"lance-encoding:blob\".to_string(),\n \"true\".to_string(),\n)]);\nlet blob_schema = Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"video\", DataType::LargeBinary, true).with_metadata(blob_metadata),\n]);\n"; +export const RsBlobApiFiles = "let batches = blob_table\n .query()\n .with_row_id()\n .execute()\n .await\n .unwrap()\n .try_collect::>()\n .await\n .unwrap();\nlet row_ids = batches[0]\n .column_by_name(\"_rowid\")\n .unwrap()\n .as_any()\n .downcast_ref::()\n .unwrap()\n .values()\n .to_vec();\n\nlet handles = blob_table\n .fetch_blob_files(\"image\", &row_ids[..1])\n .await\n .unwrap();\nlet header = handles[0].as_ref().unwrap().read_range(0..6).await.unwrap();\nhandles[0].as_ref().unwrap().close().await.unwrap();\n"; + +export const RsBlobApiImports = "use std::sync::Arc;\n\nuse arrow_array::{\n Array, Int64Array, LargeBinaryArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array,\n};\nuse arrow_schema::{DataType, Field, Schema};\nuse futures_util::TryStreamExt;\nuse lancedb::blob::{BlobRangeRequest, blob};\nuse lancedb::connect;\nuse lancedb::database::CreateTableMode;\nuse lancedb::query::{ExecutableQuery, QueryBase};\n"; + +export const RsBlobApiIngest = "let blob_table = db\n .create_empty_table(\"photos\", blob_schema)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n\nlet input_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"label\", DataType::Utf8, true),\n Field::new(\"image\", DataType::LargeBinary, true),\n]));\nlet input_batch = RecordBatch::try_new(\n input_schema.clone(),\n vec![\n Arc::new(Int64Array::from(vec![1_i64, 2_i64])),\n Arc::new(StringArray::from(vec![Some(\"door\"), Some(\"window\")])),\n Arc::new(LargeBinaryArray::from_iter_values([\n b\"inline_image_bytes\".as_slice(),\n b\"second_image_bytes\".as_slice(),\n ])),\n ],\n)\n.unwrap();\nlet input_reader: Box = Box::new(\n RecordBatchIterator::new(vec![Ok(input_batch)].into_iter(), input_schema),\n);\nblob_table.add(input_reader).execute().await.unwrap();\n"; + +export const RsBlobApiRanges = "let slices = blob_table\n .fetch_blob_ranges(\n \"image\",\n [\n BlobRangeRequest::new(row_ids[0], 0, 6),\n BlobRangeRequest::new(row_ids[1], 0, 6),\n BlobRangeRequest::new(row_ids[1], 7, 5),\n ],\n )\n .await\n .unwrap();\n\nlet second_handles = blob_table\n .fetch_blob_files(\"image\", &row_ids[1..2])\n .await\n .unwrap();\nlet second_image = second_handles[0].as_ref().unwrap();\nlet parts = second_image.read_ranges(&[0..6, 7..12]).await.unwrap();\nsecond_image.close().await.unwrap();\n"; + +export const RsBlobApiSchema = "let blob_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"label\", DataType::Utf8, true),\n blob(\"image\", true),\n]));\n"; + +export const RsBlobApiSetup = "let db = connect(\"./blob_db\").execute().await.unwrap();\n"; export const RsCreateDummyData = "let create_dummy_image = |color: u8| -> Vec {\n let mut png_like = vec![137, 80, 78, 71, 13, 10, 26, 10];\n png_like.push(color);\n png_like\n};\n\nlet data = vec![\n (\n 1_i32,\n \"red_square.png\",\n vec![0.1_f32; 128],\n create_dummy_image(1),\n \"red\",\n ),\n (\n 2_i32,\n \"blue_square.png\",\n vec![0.2_f32; 128],\n create_dummy_image(2),\n \"blue\",\n ),\n];\n"; export const RsDefineSchema = "let schema = Schema::new(vec![\n Field::new(\"id\", DataType::Int32, false),\n Field::new(\"filename\", DataType::Utf8, false),\n Field::new(\n \"vector\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 128),\n false,\n ),\n Field::new(\"image_blob\", DataType::Binary, false),\n Field::new(\"label\", DataType::Utf8, false),\n]);\n"; -export const RsIngestData = "let schema = Arc::new(schema);\nlet image_batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(Int32Array::from_iter_values(data.iter().map(|row| row.0))),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.1))),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n data.iter()\n .map(|row| Some(row.2.iter().copied().map(Some).collect::>())),\n 128,\n ),\n ),\n Arc::new(BinaryArray::from_iter_values(\n data.iter().map(|row| row.3.as_slice()),\n )),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.4))),\n ],\n)\n.unwrap();\nlet image_reader: Box =\n Box::new(RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()));\nlet table = db\n .create_table(\"images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; +export const RsIngestData = "let schema = Arc::new(schema);\nlet image_batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(Int32Array::from_iter_values(data.iter().map(|row| row.0))),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.1))),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n data.iter()\n .map(|row| Some(row.2.iter().copied().map(Some).collect::>())),\n 128,\n ),\n ),\n Arc::new(BinaryArray::from_iter_values(\n data.iter().map(|row| row.3.as_slice()),\n )),\n Arc::new(StringArray::from_iter_values(data.iter().map(|row| row.4))),\n ],\n)\n.unwrap();\nlet image_reader: Box = Box::new(\n RecordBatchIterator::new(vec![Ok(image_batch)].into_iter(), schema.clone()),\n);\nlet table = db\n .create_table(\"images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; -export const RsMultimodalImports = "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse arrow_array::types::Float32Type;\nuse arrow_array::{\n BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch,\n RecordBatchIterator, StringArray,\n};\nuse arrow_schema::{DataType, Field, Schema};\nuse futures_util::TryStreamExt;\nuse lancedb::connect;\nuse lancedb::database::CreateTableMode;\nuse lancedb::query::{ExecutableQuery, QueryBase};\n"; +export const RsLegacyBlobApiIngest = "let legacy_blob_rows = vec![\n (1_i64, b\"fake_video_bytes_1\".to_vec()),\n (2_i64, b\"fake_video_bytes_2\".to_vec()),\n];\n\nlet legacy_blob_schema = Arc::new(legacy_blob_schema);\nlet legacy_blob_batch = RecordBatch::try_new(\n legacy_blob_schema.clone(),\n vec![\n Arc::new(Int64Array::from_iter_values(\n legacy_blob_rows.iter().map(|row| row.0),\n )),\n Arc::new(LargeBinaryArray::from_iter_values(\n legacy_blob_rows.iter().map(|row| row.1.as_slice()),\n )),\n ],\n)\n.unwrap();\nlet legacy_blob_reader: Box = Box::new(\n RecordBatchIterator::new(vec![Ok(legacy_blob_batch)].into_iter(), legacy_blob_schema),\n);\nlet legacy_blob_table = db\n .create_table(\"legacy_videos\", legacy_blob_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; + +export const RsLegacyBlobApiSchema = "let legacy_blob_metadata = HashMap::from([(\n \"lance-encoding:blob\".to_string(),\n \"true\".to_string(),\n)]);\nlet legacy_blob_schema = Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\"video\", DataType::LargeBinary, true).with_metadata(legacy_blob_metadata),\n]);\n"; + +export const RsMultimodalImports = "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse arrow_array::types::Float32Type;\nuse arrow_array::{\n Array, BinaryArray, FixedSizeListArray, Int32Array, Int64Array, LargeBinaryArray, RecordBatch,\n RecordBatchIterator, StringArray,\n};\nuse arrow_schema::{DataType, Field, Schema};\nuse futures_util::TryStreamExt;\nuse lancedb::connect;\nuse lancedb::database::CreateTableMode;\nuse lancedb::query::{ExecutableQuery, QueryBase};\n"; export const RsProcessResults = "for batch in &results {\n let filenames = batch\n .column_by_name(\"filename\")\n .unwrap()\n .as_any()\n .downcast_ref::()\n .unwrap();\n let images = batch\n .column_by_name(\"image_blob\")\n .unwrap()\n .as_any()\n .downcast_ref::()\n .unwrap();\n\n for row in 0..batch.num_rows() {\n let image_bytes = images.value(row);\n println!(\n \"Retrieved image: {}, Byte length: {}\",\n filenames.value(row),\n image_bytes.len()\n );\n }\n}\n"; diff --git a/docs/web/sql/data-types.mdx b/docs/web/sql/data-types.mdx index 863212385..051368525 100644 --- a/docs/web/sql/data-types.mdx +++ b/docs/web/sql/data-types.mdx @@ -3,7 +3,7 @@ title: "SQL data types" sidebarTitle: "Data Types" description: "How Lance columns appear to SQL, including the types SQL has no name for." icon: shapes -keywords: ["sql types", "arrow", "cast", "pseudo-columns", "vector", "blob", "json"] +keywords: ["sql types", "arrow", "cast", "pseudo-columns", "vector", "json"] --- Enterprise [SQL runs in LanceDB Enterprise.](/sql) @@ -61,7 +61,7 @@ describes the full mapping. ## Types SQL has no name for {#no-name} -Three column kinds you will meet that no SQL type name covers. +Some column kinds have no SQL type name. ### Vectors {#vectors} @@ -94,17 +94,6 @@ WHERE json_get_int(data, 'status') = 200 `json_get`, its typed variants, and `json_extract` are **index-accelerated** by a JSON scalar index. See [Functions](/sql/scalar-functions#json). -### Blobs {#blobs} - -A blob column is read either as its binary contents or as a **description**: a -pointer plus metadata, without fetching the bytes. That choice changes the -column's Arrow type, and therefore the schema your query sees. - - -The default reads blob columns as descriptions and other binary columns as -binary. A query selecting a blob column and expecting bytes gets a struct. - - ### bfloat16 {#bfloat16} Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 11e7a3900..2d1ac6cbc 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -16,6 +16,7 @@ CREATE TABLE recent AS SELECT * FROM documents WHERE created_at > now() - INTERV ``` Column types are Arrow types under SQL names. See [Data types](/sql/data-types). + A table inside a [namespace](/sql/ddl/namespace) is written as a dotted path: `prod.events.clicks`. From 311ded06d0cdd5beb18321a55de874c9c86f6322 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 27 Oct 2026 01:02:28 +0800 Subject: [PATCH 112/180] fix(ci): acknowledge Arrow-pinned zstd advisories (#4683) RustSec published four `zstd` advisories after #3819 merged, causing the `deny` job to fail on `main`. `arrow-ipc 58.x` pins `zstd ^0.13`, while the patched releases require `zstd >= 0.14.3`; moving to Arrow 59+ requires a coordinated DataFusion and Lance upgrade. This records temporary exceptions with their reachability rationale. LanceDB uses the `zstd::bulk` API through `arrow-ipc`; the affected `with_context`, seekable, and streaming-decoder APIs are not used, and the `zstd-sys` advisory is wasm32-only while wasm32 is not a shipped target. Validation: `cargo-deny 0.20.2` reports `advisories ok, bans ok, licenses ok, sources ok`. --- deny.toml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/deny.toml b/deny.toml index e4982c149..c7a79f469 100644 --- a/deny.toml +++ b/deny.toml @@ -119,6 +119,21 @@ ignore = [ # ship an updated aws-sigv4. # https://rustsec.org/advisories/RUSTSEC-2026-0387 { id = "RUSTSEC-2026-0387", reason = "crypto-bigint via aws-sigv4 (sigv4a); no fixed upstream aws-sigv4 release yet" }, + + # zstd: arrow-ipc 58.x pins zstd ^0.13, while the patches require zstd + # >=0.14.3, zstd-safe >=8.2.0, and zstd-sys >=2.1.2. Arrow 59+ updates the + # dependency, but it cannot be used until DataFusion and Lance move to the + # matching Arrow line. LanceDB uses zstd::bulk through arrow-ipc and does + # not use the affected with_context, seekable, or decompress_stream APIs. + # The zstd-sys advisory is wasm32-only, and wasm32 is not a shipped target. + # https://rustsec.org/advisories/RUSTSEC-2026-0391 + # https://rustsec.org/advisories/RUSTSEC-2026-0398 + # https://rustsec.org/advisories/RUSTSEC-2026-0403 + # https://rustsec.org/advisories/RUSTSEC-2026-0410 + { id = "RUSTSEC-2026-0391", reason = "zstd 0.13 via arrow-ipc 58; affected with_context API is unused" }, + { id = "RUSTSEC-2026-0398", reason = "zstd-safe 7 via arrow-ipc 58; affected seekable API is not enabled" }, + { id = "RUSTSEC-2026-0403", reason = "zstd-safe 7 via arrow-ipc 58; affected streaming decoder API is unused" }, + { id = "RUSTSEC-2026-0410", reason = "zstd-sys via arrow-ipc 58; advisory is wasm32-only and wasm32 is not a shipped target" }, ] From 3352bf49df65c0b226bbdb67ad9998402133ce52 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:59:52 +0800 Subject: [PATCH 113/180] fix(python): expose optimize compaction options (#3870) ## Summary - expose typed compaction options on synchronous and asynchronous table optimization - translate validated Python options into native Lance compaction settings - document the row-based steady-state limit and first-pass/source-budget caveats - carry the Lance beta.15 fragment-exclusion option through the typed Python API ## Root cause The native Python optimize binding always constructed default compaction settings, and the public AsyncTable API offered no way to lower the fragment row target. Wide-row fragments therefore remained compaction candidates on every later optimize call, repeatedly rewriting the accumulated table. ## Limitations This is an explicit row-based mitigation, not byte-native task sizing or a hard memory cap. Callers must derive target_rows_per_fragment from expected row size. Existing oversized fragments are rewritten whole on the first pass; max_bytes_per_file limits output file size rather than compaction memory; and source budgets admit whole planned tasks, so a budget below the first task performs no compaction. Splitting tasks by a byte budget or returning a planner error requires a Lance-side change. ## Validation - cargo check --release -p lancedb-python - cargo clippy --quiet -p lancedb-python - cargo fmt --all --check - ruff format --check python tests - ruff check python tests - uv run --no-sync pytest python/tests/test_table.py -k optimize_compaction -q (16 passed) Fixes #2325 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- CONTRIBUTING.md | 10 +- docs/src/python/python.md | 2 + .../web-tests/py/test_doc_storage_examples.py | 30 ++++ docs/web/maintenance/compaction.mdx | 40 ++++- docs/web/snippets/doc_storage_examples.mdx | 4 + python/python/lancedb/__init__.py | 3 +- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/remote/table.py | 2 + python/python/lancedb/table.py | 112 ++++++++++++- python/python/tests/test_table.py | 130 ++++++++++++++- python/src/table.rs | 148 +++++++++++++++++- rust/lancedb/src/table.rs | 4 +- rust/lancedb/src/table/optimize.rs | 2 +- rust/lancedb/tests/doc_storage_examples.rs | 76 +++++++++ 14 files changed, 548 insertions(+), 16 deletions(-) create mode 100644 rust/lancedb/tests/doc_storage_examples.rs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f7aeac21a..fa854317d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -106,11 +106,15 @@ at the same path when the published site is assembled. Four things to know before editing: **Code examples are not written into the pages.** They live in real tests under -`docs/web-tests/{py,ts,rs}`, are extracted into `docs/web/snippets/`, and are -imported by the pages. Edit the test, then regenerate from the repository root: +`docs/web-tests/{py,ts,rs}`, `docs/web-tests/blob-v2/{py,ts,rs}`, and +`rust/lancedb/tests`, are extracted into `docs/web/snippets/`, and are imported +by the pages. Edit the test, then regenerate from the repository root: ```bash -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 +uv run docs/web-tests/mdx_snippets_gen.py \ + -s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs \ + -s docs/web-tests/blob-v2/py -s docs/web-tests/blob-v2/ts -s docs/web-tests/blob-v2/rs \ + -s rust/lancedb/tests -o docs/web/snippets ``` Review the diff before committing: a few modules currently regenerate with diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 356b49ae7..2fefe91f3 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -329,6 +329,8 @@ code that used the former remote-only argument order. ::: lancedb.table.Table +::: lancedb.table.CompactionOptions + ::: lancedb.table.FragmentStatistics ::: lancedb.table.FragmentSummaryStats diff --git a/docs/web-tests/py/test_doc_storage_examples.py b/docs/web-tests/py/test_doc_storage_examples.py index 13bedb731..99ab4a514 100644 --- a/docs/web-tests/py/test_doc_storage_examples.py +++ b/docs/web-tests/py/test_doc_storage_examples.py @@ -7,6 +7,36 @@ import pyarrow as pa import pytest +def test_compaction_tuning(mem_db): + payload = b"x" * 1016 + table = mem_db.create_table( + "compaction_tuning", [{"id": i, "payload": payload} for i in range(32)] + ) + table.add([{"id": i, "payload": payload} for i in range(32, 64)]) + assert table.stats()["fragment_stats"]["num_fragments"] == 2 + + # --8<-- [start:storage_compaction_tuning] + from lancedb import CompactionOptions + + desired_fragment_bytes = 64 * 1024 + average_row_bytes = 1024 # Estimate from representative rows. + options: CompactionOptions = { + "target_rows_per_fragment": max(1, desired_fragment_bytes // average_row_bytes), + "batch_size": 16, + "num_threads": 1, + } + table.optimize(compaction_options=options) + # --8<-- [end:storage_compaction_tuning] + + assert table.stats()["fragment_stats"]["num_fragments"] == 1 + assert table.count_rows() == 64 + + table.add([{"id": 64, "payload": payload}]) + table.optimize(compaction_options=options) + assert table.stats()["fragment_stats"]["num_fragments"] == 2 + assert sorted(table.to_arrow()["id"].to_pylist()) == list(range(65)) + + def test_rebuild_vector_index(tmp_db): rng = np.random.default_rng(7) table = tmp_db.create_table( diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 5bee9c65e..5d2a9c42f 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -12,7 +12,7 @@ availability: background, and `optimize()` is not available there. --- -import { PyStorageRebuildVectorIndex } from '/snippets/doc_storage_examples.mdx'; +import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompactionTuning } from '/snippets/doc_storage_examples.mdx'; Every write commits a new table version, and versions accumulate: small files from frequent appends, superseded files from updates and deletes, and rows added @@ -104,3 +104,41 @@ table.optimize(cleanup_older_than=timedelta(days=1)) # reclaim space sooner ``` The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Build & Repair](/indexing/reindexing) for the breakdown. Updates also move rows out of the vector index, so they remain searchable but unindexed. Update or rebuild the index after large update batches. + +{/* +Draft for the Python compaction_options release. Keep this section unpublished +until the first supported release is confirmed. + +### Tune compaction for wide rows {#tune-wide-rows} + +For an existing local table, derive a fragment row target from the expected +row size. These examples use rows averaging 1 KiB and a 64 KiB fragment +target; choose sizes for your workload. Smaller scan batches and one compaction +task at a time can also reduce memory use. + + + + {PyStorageCompactionTuning} + + + {RsStorageCompactionTuning} + + + +The Rust example runs compaction only. Run pruning and index optimization +separately when needed; Python's `optimize()` includes those steps. + +TypeScript's `optimize()` does not currently expose the fragment row target, +scan batch size, or compaction thread count. These tuning examples apply to +Python and Rust local tables. + +Planning remains row based. The row target bounds later passes after existing +oversized fragments have been rewritten; the first pass rewrites those +fragments whole, so peak memory can exceed the target. `max_bytes_per_file` +limits output file size rather than compaction memory. + +The `max_source_rows` and `max_source_bytes` budgets admit whole planned tasks. +If the first task exceeds a budget, that run performs no compaction. See the +[CompactionOptions reference](https://lancedb.github.io/lancedb/python/python/#lancedb.table.CompactionOptions) +for all options and their limits. +*/} diff --git a/docs/web/snippets/doc_storage_examples.mdx b/docs/web/snippets/doc_storage_examples.mdx index 47e2da787..f3b6be6a6 100644 --- a/docs/web/snippets/doc_storage_examples.mdx +++ b/docs/web/snippets/doc_storage_examples.mdx @@ -1,4 +1,8 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} +export const PyStorageCompactionTuning = "from lancedb import CompactionOptions\n\ndesired_fragment_bytes = 64 * 1024\naverage_row_bytes = 1024 # Estimate from representative rows.\noptions: CompactionOptions = {\n \"target_rows_per_fragment\": max(1, desired_fragment_bytes // average_row_bytes),\n \"batch_size\": 16,\n \"num_threads\": 1,\n}\ntable.optimize(compaction_options=options)\n"; + export const PyStorageRebuildVectorIndex = "from lancedb.index import IvfFlat\n\ntable.create_index(\n \"vector\",\n config=IvfFlat(distance_type=\"l2\", num_partitions=4),\n replace=True,\n)\n"; +export const RsStorageCompactionTuning = "use lancedb::table::{CompactionOptions, OptimizeAction};\n\nlet desired_fragment_bytes: usize = 64 * 1024;\nlet average_row_bytes: usize = 1024; // Estimate from representative rows.\nlet options = CompactionOptions {\n target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1),\n batch_size: Some(16),\n num_threads: Some(1),\n ..Default::default()\n};\ntable\n .optimize(OptimizeAction::Compact {\n options,\n remap_options: None,\n })\n .await?;\n"; + diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 5e879f61d..6c71c6261 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -49,7 +49,7 @@ from .materialized_view import ( MaterializedViewDefinition, ) from .view import ViewDescription as ViewDescription -from .table import AsyncTable, Table +from .table import AsyncTable, CompactionOptions, Table from .types import BaseTokenizerType from ._lancedb import Session from .namespace import ( @@ -610,6 +610,7 @@ __all__ = [ "AsyncSqlQuery", "AsyncLanceNamespaceDBConnection", "AsyncTable", + "CompactionOptions", "FtsToken", "col", "Expr", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 0b4fc82f1..1f3cfa9ed 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -544,6 +544,7 @@ class Table: *, cleanup_since_ms: Optional[int] = None, delete_unverified: Optional[bool] = None, + compaction_options: Optional[Dict[str, Any]] = None, ) -> OptimizeStats: ... async def uri(self) -> str: ... async def initial_storage_options(self) -> Optional[Dict[str, str]]: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 6b7835470..935e07eec 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -67,6 +67,7 @@ from ..table import ( AsyncTable, BlobMode, Branches, + CompactionOptions, IndexStatistics, Query, Table, @@ -1071,6 +1072,7 @@ class RemoteTable(Table): cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, retrain: bool = False, + compaction_options: Optional[CompactionOptions] = None, ): """optimize() is not supported for remote tables.""" return LOOP.run( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index f1e538c14..048c46a6a 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -25,6 +25,7 @@ from typing import ( Optional, Sequence, Tuple, + TypedDict, Union, overload, ) @@ -285,6 +286,91 @@ IndexConfigType = Union[ FTS, ] + +class CompactionOptions(TypedDict, total=False): + """Options that control file compaction during table optimization. + + Unspecified options use Lance's defaults. + + Compaction planning is row based. Lowering ``target_rows_per_fragment`` + based on the expected row size can bound later compaction passes once + oversized fragments have been rewritten. It does not split an existing + fragment, so the first pass over an oversized fragment is not subject to + that bound. ``max_bytes_per_file`` limits output file size, not compaction + memory. Source budgets keep whole planned tasks; if the first task exceeds + a budget, that run performs no compaction work. + + Examples + -------- + Derive a steady-state row target from the expected row size: + + >>> desired_fragment_bytes = 750 * 1024 * 1024 + >>> average_row_bytes = 1_500_000 + >>> options: CompactionOptions = { + ... "target_rows_per_fragment": max( + ... 1, desired_fragment_bytes // average_row_bytes + ... ), + ... } + >>> await table.optimize(compaction_options=options) # doctest: +SKIP + """ + + target_rows_per_fragment: int + """Target rows per fragment; existing oversized fragments are not split.""" + + max_rows_per_group: int + """Maximum number of rows per row group (default: 1,024).""" + + max_bytes_per_file: Optional[int] + """Maximum output data-file size; this does not bound compaction memory.""" + + materialize_deletions: bool + """Whether to rewrite fragments containing deleted rows (default: True).""" + + materialize_deletions_threshold: float + """Minimum deleted-row fraction that makes a fragment eligible (default: 0.1).""" + + num_threads: Optional[int] + """Number of compaction tasks to run in parallel.""" + + batch_size: Optional[int] + """Number of rows per input scan batch.""" + + io_buffer_size: Optional[int] + """Maximum number of bytes queued in the input scan I/O buffer.""" + + defer_index_remap: bool + """Whether to defer index remapping during compaction (default: False).""" + + index_remap_mode: Literal["direct", "compact"] + """How to construct the old-to-new row-address mapping.""" + + compaction_mode: Optional[ + Literal["reencode", "try_binary_copy", "force_binary_copy"] + ] + """Whether compaction re-encodes data or uses binary copying.""" + + binary_copy_read_batch_bytes: Optional[int] + """Number of bytes read per batch during binary-copy compaction.""" + + max_source_fragments: Optional[int] + """Maximum number of source fragments compacted in one run.""" + + max_source_rows: Optional[int] + """Maximum live source rows per run, applied to whole planned tasks.""" + + max_source_bytes: Optional[int] + """Maximum source bytes per run, applied to whole planned tasks.""" + + excluded_fragment_ids: List[int] + """Fragment IDs to leave unchanged and use as planning boundaries.""" + + max_overlays_per_fragment: Optional[int] + """Maximum overlays before a fragment is fully compacted.""" + + data_storage_version: str + """Data-file version or release selector for compacted output.""" + + # Known distance metrics for legacy API detection KNOWN_METRICS = {"l2", "cosine", "dot", "hamming"} @@ -2767,6 +2853,7 @@ class Table(ABC): cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, retrain: bool = False, + compaction_options: Optional[CompactionOptions] = None, ): """ Optimize the on-disk data and indices for better performance. @@ -2806,6 +2893,11 @@ class Table(ABC): retrain: bool, default False This parameter is no longer used and is deprecated. + compaction_options: CompactionOptions, optional + Options that control file compaction. For large rows, derive a lower + ``target_rows_per_fragment`` from the expected row size to bound later + passes. This does not cap the first pass over an existing oversized + fragment; see [CompactionOptions][lancedb.table.CompactionOptions]. Notes ----- @@ -4893,6 +4985,7 @@ class LanceTable(Table): cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, retrain: bool = False, + compaction_options: Optional[CompactionOptions] = None, ): """ Optimize the on-disk data and indices for better performance. @@ -4932,6 +5025,11 @@ class LanceTable(Table): retrain: bool, default False This parameter is no longer used and is deprecated. + compaction_options: CompactionOptions, optional + Options that control file compaction. For large rows, derive a lower + ``target_rows_per_fragment`` from the expected row size to bound later + passes. This does not cap the first pass over an existing oversized + fragment; see [CompactionOptions][lancedb.table.CompactionOptions]. Notes ----- @@ -4945,6 +5043,7 @@ class LanceTable(Table): self._table._do_optimize( _optimize_cleanup_since_ms(cleanup_older_than, retrain), delete_unverified, + compaction_options, ) ) @@ -7620,6 +7719,7 @@ class AsyncTable: cleanup_older_than: Optional[timedelta] = None, delete_unverified: bool = False, retrain=False, + compaction_options: Optional[CompactionOptions] = None, ) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -7659,6 +7759,11 @@ class AsyncTable: retrain: bool, default False This parameter is no longer used and is deprecated. + compaction_options: CompactionOptions, optional + Options that control file compaction. For large rows, derive a lower + ``target_rows_per_fragment`` from the expected row size to bound later + passes. This does not cap the first pass over an existing oversized + fragment; see [CompactionOptions][lancedb.table.CompactionOptions]. Notes ----- @@ -7671,14 +7776,19 @@ class AsyncTable: return await self._do_optimize( _optimize_cleanup_since_ms(cleanup_older_than, retrain), delete_unverified, + compaction_options, ) async def _do_optimize( - self, cleanup_since_ms: Optional[int], delete_unverified: bool + self, + cleanup_since_ms: Optional[int], + delete_unverified: bool, + compaction_options: Optional[CompactionOptions] = None, ) -> OptimizeStats: return await self._inner.optimize( cleanup_since_ms=cleanup_since_ms, delete_unverified=delete_unverified, + compaction_options=compaction_options, ) async def list_indices(self) -> Iterable[IndexConfig]: diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 97f65b180..458f419ae 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -14,7 +14,7 @@ from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timedelta from decimal import Decimal, localcontext from time import sleep -from typing import List +from typing import Any, List from unittest.mock import MagicMock, patch import lancedb @@ -5014,6 +5014,134 @@ async def test_optimize(mem_db_async: AsyncConnection): assert await table.query().to_arrow() == pa.table({"x": [[1], [2]]}) +@pytest.mark.asyncio +async def test_optimize_compaction_options(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 1, + "batch_size": 1, + "num_threads": 1, + } + ) + assert stats.compaction.fragments_removed == 0 + assert stats.compaction.fragments_added == 0 + + stats = await table.optimize(compaction_options={"target_rows_per_fragment": 3}) + assert stats.compaction.fragments_removed == 2 + assert stats.compaction.fragments_added == 1 + + with pytest.raises(ValueError, match="Invalid compaction option: unknown"): + await table.optimize(compaction_options={"unknown": 1}) + + +def test_optimize_compaction_options_sync(mem_db: DBConnection): + table = mem_db.create_table("test", data=[{"x": 1}]) + with pytest.raises(ValueError, match="target_rows_per_fragment must be between"): + table.optimize(compaction_options={"target_rows_per_fragment": 0}) + + +@pytest.mark.parametrize("option", ["max_source_rows", "max_source_bytes"]) +@pytest.mark.asyncio +async def test_optimize_compaction_source_limits( + mem_db_async: AsyncConnection, option: str +): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + option: 1, + } + ) + assert stats.compaction.fragments_removed == 0 + assert stats.compaction.fragments_added == 0 + + +@pytest.mark.asyncio +async def test_optimize_compaction_data_storage_version( + mem_db_async: AsyncConnection, +): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + "data_storage_version": "2.2", + } + ) + assert stats.compaction.fragments_removed == 2 + assert stats.compaction.fragments_added == 1 + + table = await mem_db_async.create_table("cross_family", data=[{"x": 1}]) + await table.add([{"x": 2}]) + with pytest.raises(ValueError, match="V1 and V2 storage versions cannot be mixed"): + await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + "data_storage_version": "legacy", + } + ) + + +@pytest.mark.asyncio +async def test_optimize_compaction_excluded_fragments(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + await table.add([{"x": 2}]) + + stats = await table.optimize( + compaction_options={ + "target_rows_per_fragment": 3, + "excluded_fragment_ids": [0], + } + ) + assert stats.compaction.fragments_removed == 0 + assert stats.compaction.fragments_added == 0 + + stats = await table.optimize(compaction_options={"target_rows_per_fragment": 3}) + assert stats.compaction.fragments_removed == 2 + assert stats.compaction.fragments_added == 1 + + +@pytest.mark.parametrize( + ("option", "value", "message"), + [ + ("target_rows_per_fragment", 0, "must be between 1 and 4294967295"), + ("max_rows_per_group", 0, "must be between 1 and 4294967295"), + ("batch_size", 0, "must be between 1 and 4294967295"), + ("num_threads", 0, "must be greater than 0"), + ("target_rows_per_fragment", 2**32, "must be between 1 and 4294967295"), + ("max_rows_per_group", 2**32, "must be between 1 and 4294967295"), + ("batch_size", 2**32, "must be between 1 and 4294967295"), + ("io_buffer_size", 2**63, "must be at most 9223372036854775807"), + ("max_source_rows", 0, "must be greater than 0"), + ("max_source_bytes", 0, "must be greater than 0"), + ("data_storage_version", "invalid", "Unknown Lance storage version: invalid"), + ( + "excluded_fragment_ids", + [-1], + "must contain values between 0 and 4294967295", + ), + ( + "excluded_fragment_ids", + [2**32], + "must contain values between 0 and 4294967295", + ), + ], +) +@pytest.mark.asyncio +async def test_optimize_compaction_options_validation( + mem_db_async: AsyncConnection, option: str, value: Any, message: str +): + table = await mem_db_async.create_table("test", data=[{"x": 1}]) + with pytest.raises(ValueError, match=message): + await table.optimize(compaction_options={option: value}) + + @pytest.mark.asyncio async def test_optimize_delete_unverified(tmp_db_async: AsyncConnection, tmp_path): table = await tmp_db_async.create_table( diff --git a/python/src/table.rs b/python/src/table.rs index e58b8a139..62fc9e611 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -25,10 +25,12 @@ use arrow::{ pyarrow::{FromPyArrow, PyArrowType, ToPyArrow}, }; use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest}; +use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ - AddDataMode, ColumnAlteration, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken, - NewColumnTransform, OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable, + AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, + FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, + OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ @@ -107,6 +109,136 @@ enum PredicateArg { Sql(String), } +fn validate_positive_u32(value: u64, name: &str) -> PyResult { + if !(1..=u32::MAX as u64).contains(&value) { + return Err(PyValueError::new_err(format!( + "{name} must be between 1 and {}", + u32::MAX + ))); + } + Ok(value as usize) +} + +fn positive_u32(value: &Bound<'_, PyAny>, name: &str) -> PyResult { + validate_positive_u32(value.extract()?, name) +} + +fn optional_positive_u32(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + value + .extract::>()? + .map(|value| validate_positive_u32(value, name)) + .transpose() +} + +fn optional_positive_usize(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + let value: Option = value.extract()?; + if value == Some(0) { + return Err(PyValueError::new_err(format!( + "{name} must be greater than 0" + ))); + } + Ok(value) +} + +fn optional_positive_u64(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + let value: Option = value.extract()?; + if value == Some(0) { + return Err(PyValueError::new_err(format!( + "{name} must be greater than 0" + ))); + } + Ok(value) +} + +fn u32_list(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + value + .extract::>()? + .into_iter() + .map(|value| { + u32::try_from(value).map_err(|_| { + PyValueError::new_err(format!( + "{name} must contain values between 0 and {}", + u32::MAX + )) + }) + }) + .collect() +} + +fn optional_i64_bounded_u64(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + let value: Option = value.extract()?; + if value.is_some_and(|value| value > i64::MAX as u64) { + return Err(PyValueError::new_err(format!( + "{name} must be at most {}", + i64::MAX + ))); + } + Ok(value) +} + +fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult { + let mut parsed = CompactionOptions::default(); + let Some(options) = options else { + return Ok(parsed); + }; + + for (key, value) in options.iter() { + let key: String = key.extract()?; + match key.as_str() { + "target_rows_per_fragment" => { + parsed.target_rows_per_fragment = positive_u32(&value, &key)? + } + "max_rows_per_group" => parsed.max_rows_per_group = positive_u32(&value, &key)?, + "max_bytes_per_file" => parsed.max_bytes_per_file = value.extract()?, + "materialize_deletions" => parsed.materialize_deletions = value.extract()?, + "materialize_deletions_threshold" => { + parsed.materialize_deletions_threshold = value.extract()? + } + "num_threads" => parsed.num_threads = optional_positive_usize(&value, &key)?, + "batch_size" => parsed.batch_size = optional_positive_u32(&value, &key)?, + "io_buffer_size" => parsed.io_buffer_size = optional_i64_bounded_u64(&value, &key)?, + "defer_index_remap" => parsed.defer_index_remap = value.extract()?, + "index_remap_mode" => { + let mode: String = value.extract()?; + parsed.index_remap_mode = IndexRemapMode::try_from(mode.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string()))?; + } + "compaction_mode" => { + let mode: Option = value.extract()?; + parsed.compaction_mode = mode + .map(|mode| { + CompactionMode::try_from(mode.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string())) + }) + .transpose()?; + } + "binary_copy_read_batch_bytes" => { + parsed.binary_copy_read_batch_bytes = value.extract()? + } + "max_source_fragments" => parsed.max_source_fragments = value.extract()?, + "max_source_rows" => parsed.max_source_rows = optional_positive_usize(&value, &key)?, + "max_source_bytes" => parsed.max_source_bytes = optional_positive_u64(&value, &key)?, + "excluded_fragment_ids" => parsed.excluded_fragment_ids = u32_list(&value, &key)?, + "max_overlays_per_fragment" => parsed.max_overlays_per_fragment = value.extract()?, + "data_storage_version" => { + let version: String = value.extract()?; + parsed.data_storage_version = Some( + version + .parse::() + .map_err(|err| PyValueError::new_err(err.to_string()))?, + ); + } + _ => { + return Err(PyValueError::new_err(format!( + "Invalid compaction option: {key}" + ))); + } + } + } + + Ok(parsed) +} + /// Statistics about a compaction operation. #[pyclass(get_all, from_py_object)] #[derive(Clone, Debug)] @@ -1569,13 +1701,15 @@ impl Table { } /// Optimize the on-disk data by compacting and pruning old data, for better performance. - #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None))] - pub fn optimize( - self_: PyRef<'_, Self>, + #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))] + pub fn optimize<'py>( + self_: PyRef<'py, Self>, cleanup_since_ms: Option, delete_unverified: Option, - ) -> PyResult> { + compaction_options: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { let inner = self_.inner_ref()?.clone(); + let compaction_options = parse_compaction_options(compaction_options)?; let older_than = if let Some(ms) = cleanup_since_ms { if ms > i64::MAX as u64 { return Err(PyValueError::new_err(format!( @@ -1591,7 +1725,7 @@ impl Table { future_into_py(self_.py(), async move { let compaction_stats = inner .optimize(OptimizeAction::Compact { - options: lancedb::table::CompactionOptions::default(), + options: compaction_options, remap_options: None, }) .await diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 3fcf4bdb7..d6575b959 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -107,7 +107,9 @@ use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; pub use lance::dataset::scanner::DatasetRecordBatchStream; pub use lance_index::optimize::OptimizeOptions; -pub use optimize::{CompactionOptions, OptimizeAction, OptimizeStats}; +pub use optimize::{ + CompactionMode, CompactionOptions, IndexRemapMode, OptimizeAction, OptimizeStats, +}; pub use refresh::RefreshColumnResult; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; pub use schema_evolution::{ diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index ebe03359c..ee86e7989 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -16,7 +16,7 @@ use lance_index::optimize::OptimizeOptions; use log::info; pub use chrono::Duration; -pub use lance::dataset::optimize::CompactionOptions; +pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemapMode}; use super::NativeTable; use crate::error::Result; diff --git a/rust/lancedb/tests/doc_storage_examples.rs b/rust/lancedb/tests/doc_storage_examples.rs new file mode 100644 index 000000000..dd3acc597 --- /dev/null +++ b/rust/lancedb/tests/doc_storage_examples.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::ops::Range; +use std::sync::Arc; + +use arrow_array::{ + ArrayRef, BinaryArray, Int64Array, RecordBatch, RecordBatchIterator, RecordBatchReader, +}; + +fn wide_rows(ids: Range) -> anyhow::Result> { + let payload = [b'x'; 1016]; + let batch = RecordBatch::try_from_iter(vec![ + ( + "id", + Arc::new(Int64Array::from_iter_values(ids.clone())) as ArrayRef, + ), + ( + "payload", + Arc::new(BinaryArray::from_iter_values( + ids.map(|_| payload.as_slice()), + )) as ArrayRef, + ), + ])?; + let schema = batch.schema(); + Ok(Box::new(RecordBatchIterator::new( + std::iter::once(Ok(batch)), + schema, + ))) +} + +async fn tune_compaction(table: &lancedb::Table) -> lancedb::Result<()> { + // --8<-- [start:storage_compaction_tuning] + use lancedb::table::{CompactionOptions, OptimizeAction}; + + let desired_fragment_bytes: usize = 64 * 1024; + let average_row_bytes: usize = 1024; // Estimate from representative rows. + let options = CompactionOptions { + target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1), + batch_size: Some(16), + num_threads: Some(1), + ..Default::default() + }; + table + .optimize(OptimizeAction::Compact { + options, + remap_options: None, + }) + .await?; + // --8<-- [end:storage_compaction_tuning] + Ok(()) +} + +#[tokio::test] +async fn compaction_tuning() -> anyhow::Result<()> { + let directory = tempfile::tempdir()?; + let db = lancedb::connect(directory.path().to_str().unwrap()) + .execute() + .await?; + let table = db + .create_table("compaction_tuning", wide_rows(0..32)?) + .execute() + .await?; + table.add(wide_rows(32..64)?).execute().await?; + assert_eq!(table.stats().await?.fragment_stats.num_fragments, 2); + + tune_compaction(&table).await?; + assert_eq!(table.stats().await?.fragment_stats.num_fragments, 1); + assert_eq!(table.count_rows(None).await?, 64); + + table.add(wide_rows(64..65)?).execute().await?; + tune_compaction(&table).await?; + assert_eq!(table.stats().await?.fragment_stats.num_fragments, 2); + assert_eq!(table.count_rows(None).await?, 65); + Ok(()) +} From a9fb16ac447169d1429af75430e04a99a0402de6 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:40:06 +0800 Subject: [PATCH 114/180] fix: return cosine-scaled ANN distances (#3852) ## Summary - convert unrefined cosine ANN scores from normalized squared-L2 scale to the public cosine scale - translate public distance-range bounds to the internal ANN scale before execution - add regression coverage for indexed distances and range filtering while leaving refined, exact, and flat paths unchanged ## Root cause Cosine PQ, SQ, and RQ quantizers normalize vectors and search with squared L2 internally. The unrefined native query plan returned those internal scores directly, making the values twice the public cosine distance for unit-normalized embeddings. ## Validation - `cargo test --quiet --features remote --tests` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` - `cargo fmt --all -- --check` - rebuilt the Python extension and reran the issue reproduction through the Python API Fixes #3530 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- rust/lancedb/src/table/merge.rs | 321 ++++++++++++++ rust/lancedb/src/table/query.rs | 626 +++++++++++++++++++++++++++- rust/lancedb/src/table/query/lsm.rs | 4 + 3 files changed, 946 insertions(+), 5 deletions(-) diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 4b85a6ca8..24c5f55b3 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -2372,4 +2372,325 @@ mod lsm_tests { sstables.len() ); } + + #[tokio::test] + async fn lsm_cosine_distance_scale_and_mixed_tier_ordering() { + use arrow::array::{ + FixedSizeListArray, FixedSizeListBuilder, Float32Array, Float32Builder, + }; + use arrow::datatypes::Float32Type; + + use crate::index::Index; + use crate::index::vector::IvfPqIndexBuilder; + use datafusion_physical_plan::{ExecutionPlan, displayable}; + use lance::io::exec::ANNIvfSubIndexExec; + use std::any::Any; + + const DIM: usize = 8; + const N: usize = 256; + + fn normalized_vector(state: &mut u64) -> Vec { + let mut vector = (0..DIM) + .map(|_| { + *state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + ((*state >> 32) as u32 as f32 / u32::MAX as f32) * 2.0 - 1.0 + }) + .collect::>(); + let norm = vector.iter().map(|value| value * value).sum::().sqrt(); + vector.iter_mut().for_each(|value| *value /= norm); + vector + } + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new( + "vec", + DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, true)), + DIM as i32, + ), + false, + ), + ])); + let make_batch = |rows: Vec<(i64, Vec)>| { + let ids = rows.iter().map(|(id, _)| *id).collect::>(); + let mut vectors = FixedSizeListBuilder::new(Float32Builder::new(), DIM as i32); + for (_, vector) in &rows { + vectors.values().append_slice(vector); + vectors.append(true); + } + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int64Array::from(ids)), Arc::new(vectors.finish())], + ) + .unwrap() + }; + let first_result = |batches: &[RecordBatch]| { + let batch = &batches[0]; + let id = batch["id"].as_primitive::().value(0); + let distance = batch["_distance"].as_primitive::().value(0); + (id, distance) + }; + + let mut state = 42; + let base_rows = (0..N) + .map(|id| (id as i64, normalized_vector(&mut state))) + .collect::>(); + let query = normalized_vector(&mut state); + + let dir = tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let base = make_batch(base_rows.clone()); + let reader: Box = + Box::new(RecordBatchIterator::new(vec![Ok(base)], schema.clone())); + let table = conn + .create_table("cosine_lsm", reader) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table + .create_index( + &["vec"], + Index::IvfPq( + IvfPqIndexBuilder::default() + .distance_type(crate::DistanceType::Cosine) + .num_partitions(1) + .num_sub_vectors(1), + ), + ) + .name("vec_cosine".to_string()) + .execute() + .await + .unwrap(); + table + .enable_rte( + RTEWriteSpec::unsharded().with_maintained_indexes(vec!["vec_cosine".to_string()]), + ) + .await + .unwrap(); + + let base_only = table + .query() + .nearest_to(query.as_slice()) + .unwrap() + .limit(1) + .use_rte(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (base_id, public_distance) = first_result(&base_only); + + let lsm = table + .query() + .nearest_to(query.as_slice()) + .unwrap() + .limit(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (lsm_id, lsm_distance) = first_result(&lsm); + assert_eq!(lsm_id, base_id); + assert!( + (lsm_distance - public_distance).abs() < 1e-5, + "LSM cosine distance {lsm_distance} did not use the public scale {public_distance}" + ); + + // Add an exact memtable result whose distance lies between the public ANN + // score and its doubled internal score. Correctly normalized plans still + // rank the ANN row first; mixed units would incorrectly rank this row first. + assert!(public_distance > 0.0 && public_distance < 4.0 / 3.0); + let memtable_distance = public_distance * 1.5; + let cosine_similarity = 1.0 - memtable_distance; + let mut orthogonal = normalized_vector(&mut state); + let projection = orthogonal + .iter() + .zip(&query) + .map(|(left, right)| left * right) + .sum::(); + for (value, query_value) in orthogonal.iter_mut().zip(&query) { + *value -= projection * query_value; + } + let norm = orthogonal + .iter() + .map(|value| value * value) + .sum::() + .sqrt(); + orthogonal.iter_mut().for_each(|value| *value /= norm); + let sine = (1.0 - cosine_similarity * cosine_similarity).sqrt(); + let memtable_vector = query + .iter() + .zip(&orthogonal) + .map(|(query_value, orthogonal_value)| { + cosine_similarity * query_value + sine * orthogonal_value + }) + .collect::>(); + + let mut merge = table.merge_insert(&[]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let memtable = make_batch(vec![(N as i64, memtable_vector)]); + merge + .execute(Box::new(RecordBatchIterator::new( + vec![Ok(memtable)], + schema.clone(), + ))) + .await + .unwrap(); + + let mixed = table + .query() + .nearest_to(query.as_slice()) + .unwrap() + .limit(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (mixed_id, mixed_distance) = first_result(&mixed); + assert_eq!( + mixed_id, base_id, + "mixed LSM tiers must compare ANN and exact distances in public units" + ); + assert!((mixed_distance - public_distance).abs() < 1e-5); + + // Re-ingest every base row so the flushed SSTable generation owns a + // complete copy of the dataset. ANN ranking of the rebuilt index is an + // independent approximation, so exact row parity with the base scan is + // not guaranteed. + let mut merge = table.merge_insert(&[]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let upsert_batch = make_batch(base_rows.clone()); + merge + .execute(Box::new(RecordBatchIterator::new( + vec![Ok(upsert_batch)], + schema.clone(), + ))) + .await + .unwrap(); + assert!( + base_rows.iter().any(|(id, _)| *id == base_id), + "upsert source must still contain the nearest base row" + ); + + table.close_rte_writers().await.unwrap(); + let sstables = published_sstables(&table).await; + assert_eq!(sstables.len(), 1, "expected one published SSTable"); + assert_eq!( + sstables[0].count_rows(None).await.unwrap(), + N + 1, + "published SSTable must contain the complete replacement fixture" + ); + + // The public query sets no explicit refine factor. Because the upsert + // rewrote every base id, a newer generation exists, so the engine must + // auto-refine ANN results over the published SSTable. + let public_query = table.query().nearest_to(query.as_slice()).unwrap().limit(1); + + fn collect_ann_nodes<'a>( + node: &'a dyn ExecutionPlan, + target_uri: &str, + out: &mut Vec<&'a ANNIvfSubIndexExec>, + ) { + // Local datasets may report their path with a different separator on Windows. + if let Some(ann) = (node as &dyn Any).downcast_ref::() + && std::path::Path::new(ann.dataset().uri()) == std::path::Path::new(target_uri) + { + out.push(ann); + } + for child in node.children() { + collect_ann_nodes(child.as_ref(), target_uri, out); + } + } + + let plan = public_query + .create_plan(crate::query::QueryExecutionOptions::default()) + .await + .unwrap(); + let mut ann_nodes = Vec::new(); + collect_ann_nodes(plan.as_ref(), sstables[0].uri(), &mut ann_nodes); + assert!( + !ann_nodes.is_empty(), + "public plan must contain an ANN sub-index over the published SSTable" + ); + assert_eq!( + ann_nodes[0].query().refine_factor, + Some(1), + "engine must auto-refine the SSTable ANN results" + ); + println!( + "RTE LSM public query plan:\n{}", + displayable(plan.as_ref()).indent(true) + ); + + // Execute the same public query. + let published = public_query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let (published_id, published_distance) = first_result(&published); + assert!( + (0_i64..=N as i64).contains(&published_id), + "SSTable result id {published_id} must belong to the complete 0..={N} replacement fixture" + ); + + // The maintained ANN index may rank near-tied rows differently than + // the base scan, so the durable contract is distance correctness: the + // auto-refined result carries its own stored vector, and the query + // returns the analytical cosine distance of that exact vector. + let expected_distance = { + let published_vec = published[0]["vec"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .as_any() + .downcast_ref::() + .unwrap(); + // The query is a unit vector, so cosine distance is 1 - cos(q, v). + let dot = (0..DIM) + .map(|index| query[index] * published_vec.value(index)) + .sum::(); + let norm = (0..DIM) + .map(|index| published_vec.value(index) * published_vec.value(index)) + .sum::() + .sqrt(); + 1.0 - dot / norm + }; + assert!( + expected_distance > 0.0 && expected_distance.is_finite(), + "independent cosine oracle is degenerate: {expected_distance}" + ); + assert!( + (published_distance - expected_distance).abs() < 1e-5, + "SSTable ANN distance {published_distance} must match the analytical cosine distance {expected_distance} of its returned vector" + ); + println!( + "sstable_uri={} ann_nodes={} refine_factor={:?} observed_distance={} expected_cosine={}", + sstables[0].uri(), + ann_nodes.len(), + ann_nodes[0].query().refine_factor, + published_distance, + expected_distance, + ); + } } diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 4ad840350..dbb3dbc68 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -1,7 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use std::sync::Arc; +use std::{ + collections::{HashSet, VecDeque}, + sync::Arc, +}; mod lsm; @@ -17,15 +20,24 @@ use arrow::array::{AsArray, FixedSizeListBuilder, Float32Builder}; use arrow::datatypes::{Float32Type, UInt8Type}; use arrow_array::Array; use arrow_schema::{DataType, Schema}; -use datafusion_common::{Column, DataFusionError, SchemaError}; -use datafusion_physical_plan::ExecutionPlan; +use datafusion_common::{Column, DataFusionError, ScalarValue, SchemaError}; +use datafusion_expr::Operator; +use datafusion_physical_expr::expressions::{BinaryExpr, Column as PhysicalColumn, Literal}; +use datafusion_physical_plan::PhysicalExpr; use datafusion_physical_plan::projection::ProjectionExec; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::union::UnionExec; +use datafusion_physical_plan::{ExecutionPlan, with_new_children_if_necessary}; use lance::dataset::mem_wal::DatasetMemWalExt; use lance::dataset::scanner::DatasetRecordBatchStream; use lance::dataset::scanner::Scanner; +use lance::index::DatasetIndexInternalExt; +use lance::io::exec::{ANNIvfBatchExec, ANNIvfSubIndexExec}; use lance_datafusion::exec::{analyze_plan as lance_analyze_plan, execute_plan}; +use lance_index::IndexType; +use lance_index::metrics::NoOpMetricsCollector; +use lance_index::vector::DIST_COL; +use lance_linalg::distance::DistanceType as LanceDistanceType; use lance_namespace::LanceNamespace; use lance_namespace::models::{ QueryTableRequest as NsQueryTableRequest, QueryTableRequestColumns, @@ -409,10 +421,30 @@ pub async fn create_plan( scanner.order_by(Some(order_by.clone()))?; } - scanner + let mut plan = scanner .create_plan() .await - .map_err(|error| enrich_lance_field_not_found(error, schema)) + .map_err(|error| enrich_lance_field_not_found(error, schema))?; + let normalized_l2_indices = normalized_l2_ann_indices(plan.as_ref()).await?; + if !normalized_l2_indices.is_empty() { + // Rebuild only the affected ANN nodes with internal normalized squared-L2 + // bounds. Exact branches keep the public cosine bounds from `plan`. + let internal_plan = if query.lower_bound.is_some() || query.upper_bound.is_some() { + scanner.distance_range( + query.lower_bound.map(|bound| bound / COSINE_ANN_SCALE), + query.upper_bound.map(|bound| bound / COSINE_ANN_SCALE), + ); + scanner + .create_plan() + .await + .map_err(|error| enrich_lance_field_not_found(error, schema))? + } else { + plan.clone() + }; + plan = normalize_ann_branches(plan, internal_plan, &normalized_l2_indices)?; + } + + Ok(plan) } /// Replace DataFusion's top-level field candidates with qualified leaf paths. @@ -504,6 +536,242 @@ fn leaf_field_paths(schema: &Schema) -> Vec { //Helper functions below +const COSINE_ANN_SCALE: f32 = 0.5; + +#[derive(Clone, Copy)] +enum AnnExecRef<'a> { + Single(&'a ANNIvfSubIndexExec), + Batch(&'a ANNIvfBatchExec), +} + +impl<'a> AnnExecRef<'a> { + fn from_plan(plan: &'a dyn ExecutionPlan) -> Option { + if let Some(single) = plan.downcast_ref::() { + return Some(Self::Single(single)); + } + plan.downcast_ref::().map(Self::Batch) + } + + fn query(self) -> &'a lance_index::vector::Query { + match self { + Self::Single(ann) => ann.query(), + Self::Batch(ann) => ann.query(), + } + } + + fn dataset(self) -> &'a Arc { + match self { + Self::Single(ann) => ann.dataset(), + Self::Batch(ann) => ann.dataset(), + } + } + + fn indices(self) -> &'a [lance_table::format::IndexMetadata] { + match self { + Self::Single(ann) => ann.indices(), + Self::Batch(ann) => ann.indices(), + } + } + + fn query_count(self) -> Option { + match self { + Self::Single(_) => None, + Self::Batch(ann) => Some(ann.query_count()), + } + } + + fn same_kind(self, other: Self) -> bool { + matches!( + (self, other), + (Self::Single(_), Self::Single(_)) | (Self::Batch(_), Self::Batch(_)) + ) + } +} + +/// Find ANN index segments whose scores use normalized squared L2 for cosine search. +/// +/// Cosine PQ/SQ/RQ indices normalize their vectors and use squared L2 internally. This +/// preserves ranking, but squared L2 over unit vectors is twice the cosine distance. Flat +/// cosine indices calculate cosine directly, so they are not included. +async fn normalized_l2_ann_indices(plan: &dyn ExecutionPlan) -> Result> { + let mut ann_plans = Vec::new(); + find_ann_plans(plan, &mut ann_plans); + + let mut checked = HashSet::new(); + let mut normalized_l2 = HashSet::new(); + for ann in ann_plans { + if ann.query().metric_type != Some(LanceDistanceType::Cosine) { + continue; + } + for index in ann.indices() { + let uuid = index.uuid.to_string(); + if !checked.insert(uuid.clone()) { + continue; + } + let vector_index = ann + .dataset() + .open_vector_index(&ann.query().column, &index.uuid, &NoOpMetricsCollector) + .await?; + if matches!( + vector_index.index_type(), + IndexType::IvfPq + | IndexType::IvfSq + | IndexType::IvfRq + | IndexType::IvfHnswPq + | IndexType::IvfHnswSq + ) { + normalized_l2.insert(uuid); + } + } + } + Ok(normalized_l2) +} + +/// Normalize affected ANN outputs before their parent plan nodes consume them. +/// +/// This is used by planners that do not support distance ranges, such as the MemWAL +/// LSM planner. The standard scanner path rebuilds a second plan when it also needs +/// to translate range bounds, then calls [`normalize_ann_branches`] directly. +pub(super) async fn normalize_cosine_ann_branches( + plan: Arc, +) -> Result> { + let normalized_l2_indices = normalized_l2_ann_indices(plan.as_ref()).await?; + if normalized_l2_indices.is_empty() { + return Ok(plan); + } + normalize_ann_branches(plan.clone(), plan, &normalized_l2_indices) +} + +fn find_ann_plans<'a>(plan: &'a dyn ExecutionPlan, ann_plans: &mut Vec>) { + if let Some(ann) = AnnExecRef::from_plan(plan) { + ann_plans.push(ann); + return; + } + for child in plan.children() { + find_ann_plans(child.as_ref(), ann_plans); + } +} + +fn collect_ann_plans( + plan: &Arc, + ann_plans: &mut VecDeque>, +) { + if AnnExecRef::from_plan(plan.as_ref()).is_some() { + ann_plans.push_back(plan.clone()); + return; + } + for child in plan.children() { + collect_ann_plans(child, ann_plans); + } +} + +/// Replace normalized-L2 ANN nodes with equivalent nodes that use internal bounds, then +/// convert their output to the public cosine scale before any generic plan node consumes it. +fn normalize_ann_branches( + public_plan: Arc, + internal_plan: Arc, + normalized_l2_indices: &HashSet, +) -> Result> { + let mut internal_ann_plans = VecDeque::new(); + collect_ann_plans(&internal_plan, &mut internal_ann_plans); + let normalized = + replace_ann_branches(public_plan, &mut internal_ann_plans, normalized_l2_indices)?; + if !internal_ann_plans.is_empty() { + return Err(Error::Runtime { + message: "internal and public vector plans contained different ANN branches" + .to_string(), + }); + } + Ok(normalized) +} + +fn replace_ann_branches( + public_plan: Arc, + internal_ann_plans: &mut VecDeque>, + normalized_l2_indices: &HashSet, +) -> Result> { + if let Some(public_ann) = AnnExecRef::from_plan(public_plan.as_ref()) { + let internal_plan = internal_ann_plans + .pop_front() + .ok_or_else(|| Error::Runtime { + message: "internal vector plan was missing an ANN branch".to_string(), + })?; + let internal_ann = + AnnExecRef::from_plan(internal_plan.as_ref()).ok_or_else(|| Error::Runtime { + message: "internal vector plan contained a non-ANN branch where an ANN branch was expected" + .to_string(), + })?; + let same_indices = public_ann + .indices() + .iter() + .map(|index| &index.uuid) + .eq(internal_ann.indices().iter().map(|index| &index.uuid)); + if !public_ann.same_kind(internal_ann) + || public_ann.query_count() != internal_ann.query_count() + || public_ann.query().column != internal_ann.query().column + || public_ann.query().metric_type != internal_ann.query().metric_type + || !same_indices + { + return Err(Error::Runtime { + message: "internal and public vector plans had mismatched ANN branches".to_string(), + }); + } + + let normalized_count = public_ann + .indices() + .iter() + .filter(|index| normalized_l2_indices.contains(&index.uuid.to_string())) + .count(); + if normalized_count == 0 { + return Ok(public_plan); + } + if normalized_count != public_ann.indices().len() { + return Err(Error::Runtime { + message: "one ANN branch mixed public and normalized-L2 distance scales" + .to_string(), + }); + } + return scale_distance_column(internal_plan, COSINE_ANN_SCALE); + } + + let children = public_plan + .children() + .into_iter() + .cloned() + .map(|child| replace_ann_branches(child, internal_ann_plans, normalized_l2_indices)) + .collect::>>()?; + Ok(with_new_children_if_necessary(public_plan, children)?) +} + +fn scale_distance_column( + plan: Arc, + scale: f32, +) -> Result> { + let schema = plan.schema(); + if schema.column_with_name(DIST_COL).is_none() { + return Ok(plan); + } + + let expressions: Vec<(Arc, String)> = schema + .fields() + .iter() + .enumerate() + .map(|(index, field)| { + let column: Arc = Arc::new(PhysicalColumn::new(field.name(), index)); + let expression = if field.name() == DIST_COL { + let scale: Arc = + Arc::new(Literal::new(ScalarValue::Float32(Some(scale)))); + Arc::new(BinaryExpr::new(column, Operator::Multiply, scale)) + as Arc + } else { + column + }; + (expression, field.name().clone()) + }) + .collect(); + Ok(Arc::new(ProjectionExec::try_new(expressions, plan)?)) +} + // Take many execution plans and map them into a single plan that adds // a query_index column and unions them. pub(crate) fn create_multi_vector_plan( @@ -1622,6 +1890,354 @@ mod tests { "plan should add query_index column, got:\n{display}" ); } + #[rstest::rstest] + #[case::modern(false)] + #[case::legacy(true)] + #[tokio::test] + async fn test_cosine_pq_distance_uses_public_cosine_scale(#[case] legacy: bool) { + use arrow_array::{ + Float32Array, Int32Array, RecordBatch, + types::{Float32Type, Int32Type}, + }; + use arrow_schema::{DataType, Field, Schema}; + + use crate::connect; + use crate::index::{Index, vector::IvfPqIndexBuilder}; + use lance::index::{ + DatasetIndexExt, + vector::{IndexFileVersion, VectorIndexParams}, + }; + + fn normalized_vector(state: &mut u64, dimension: usize) -> Vec { + let mut vector = (0..dimension) + .map(|_| { + *state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + ((*state >> 32) as u32 as f32 / u32::MAX as f32) * 2.0 - 1.0 + }) + .collect::>(); + let norm = vector.iter().map(|value| value * value).sum::().sqrt(); + vector.iter_mut().for_each(|value| *value /= norm); + vector + } + + fn distances(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch[DIST_COL] + .as_primitive::() + .values() + .to_vec() + }) + .collect() + } + + let conn = connect("memory://").execute().await.unwrap(); + let dimension = 8; + let num_rows = 256; + let mut state = 42; + let values = (0..num_rows) + .flat_map(|_| normalized_vector(&mut state, dimension)) + .collect::>(); + let query_vector = normalized_vector(&mut state, dimension); + let vectors = Arc::new(fixed_size_list_array(values, dimension as i32)); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vectors.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from_iter_values(0..num_rows)), vectors], + ) + .unwrap(); + let table = conn + .create_table("test_cosine_pq_distance", batch) + .execute() + .await + .unwrap(); + if legacy { + let mut dataset = (*table.dataset().unwrap().get().await.unwrap()).clone(); + dataset + .create_index( + &["vector"], + IndexType::Vector, + None, + VectorIndexParams::ivf_pq(1, 8, 1, LanceDistanceType::Cosine, 10) + .version(IndexFileVersion::Legacy), + true, + ) + .await + .unwrap(); + table.dataset().unwrap().update(dataset); + } else { + table + .create_index( + &["vector"], + Index::IvfPq( + IvfPqIndexBuilder::default() + .distance_type(crate::DistanceType::Cosine) + .num_partitions(1) + .num_sub_vectors(1), + ), + ) + .execute() + .await + .unwrap(); + } + + let expected_index_version = if legacy { "Legacy" } else { "V3" }; + let index_file_version = { + let dataset = table.dataset().unwrap().get().await.unwrap(); + let metadata = dataset + .load_indices() + .await + .unwrap() + .first() + .unwrap() + .clone(); + let index = dataset + .open_vector_index("vector", &metadata.uuid, &NoOpMetricsCollector) + .await + .unwrap(); + index.statistics().unwrap()["index_file_version"] + .as_str() + .unwrap() + .to_string() + }; + assert_eq!(index_file_version, expected_index_version); + + let plan = table + .dataset() + .unwrap() + .get() + .await + .unwrap() + .scan() + .nearest("vector", &Float32Array::from(query_vector.clone()), 5) + .unwrap() + .create_plan() + .await + .unwrap(); + let mut ann_plans = Vec::new(); + find_ann_plans(plan.as_ref(), &mut ann_plans); + assert!(!ann_plans.is_empty()); + + let approximate = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(5) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let refined = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(5) + .refine_factor(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let approximate_distances = distances(&approximate); + let refined_distances = distances(&refined); + assert_eq!(approximate_distances.len(), 5); + assert_eq!(approximate_distances.len(), refined_distances.len()); + for (approximate, refined) in approximate_distances.iter().zip(&refined_distances) { + assert!( + (approximate - refined).abs() < 1e-5, + "approximate cosine distance {approximate} did not use the public scale; refined distance was {refined}" + ); + } + + // Distance range bounds are public cosine distances too. Lance applies them to + // internal ANN scores, so the planner must translate the bounds before execution. + let nearest = approximate_distances[0]; + let ranged = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(1) + .distance_range(Some(nearest - 1e-5), Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let ranged_distances = distances(&ranged); + assert_eq!(ranged_distances.len(), 1); + assert!((ranged_distances[0] - nearest).abs() < 1e-5); + + if !legacy { + fn batch_distances_by_query( + batches: &[RecordBatch], + query_count: usize, + ) -> Vec> { + let mut distances = vec![Vec::new(); query_count]; + for batch in batches { + let query_index_column = batch["query_index"].as_primitive::(); + let distance_column = batch[DIST_COL].as_primitive::(); + for row in 0..batch.num_rows() { + let query_index = query_index_column.value(row) as usize; + distances[query_index].push(distance_column.value(row)); + } + } + distances + } + + fn sorted(mut values: Vec) -> Vec { + values.sort_by(|left, right| left.partial_cmp(right).unwrap()); + values + } + + let batch_query = table + .vector_search(query_vector.as_slice()) + .unwrap() + .add_query_vector(query_vector.as_slice()) + .unwrap() + .nprobes(1) + .unwrap() + .limit(5); + let batch_plan = batch_query.explain_plan(false).await.unwrap(); + assert!(batch_plan.contains("ANNIvfBatch"), "{batch_plan}"); + let batched = batch_query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batched_distances = batch_distances_by_query(&batched, 2); + let expected_distances = sorted(approximate_distances.clone()); + for (query_index, actual) in batched_distances.into_iter().enumerate() { + assert_eq!( + actual.len(), + expected_distances.len(), + "query {query_index} returned the wrong number of rows" + ); + for (actual, expected) in sorted(actual).into_iter().zip(&expected_distances) { + assert!( + (actual - expected).abs() < 1e-5, + "batch distance {actual} for query {query_index} must use single-query public scale {expected}" + ); + } + } + + let batched_ranged = table + .vector_search(query_vector.as_slice()) + .unwrap() + .add_query_vector(query_vector.as_slice()) + .unwrap() + .nprobes(1) + .unwrap() + .limit(1) + .distance_range(None, Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batched_ranged_distances = batch_distances_by_query(&batched_ranged, 2); + for (query_index, query_distances) in batched_ranged_distances.into_iter().enumerate() { + assert_eq!( + query_distances.len(), + 1, + "public cosine range must return one hit for query {query_index}" + ); + assert!( + (query_distances[0] - nearest).abs() < 1e-5, + "ranged batch distance {} for query {query_index} must match {nearest}", + query_distances[0] + ); + } + } + + let refined_ranged = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(1) + .refine_factor(1) + .distance_range(None, Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + distances(&refined_ranged).len(), + 1, + "refinement must not apply public cosine bounds to internal ANN scores" + ); + + let aliased = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(1) + .select(Select::dynamic(&[("aliased_distance", "_distance")])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batch = &aliased[0]; + let aliased_distance = batch["aliased_distance"] + .as_primitive::() + .value(0); + let public_distance = batch[DIST_COL].as_primitive::().value(0); + assert!( + (aliased_distance - public_distance).abs() < 1e-5, + "distance aliases and auto-projected distances must use the same public scale" + ); + + // Appended rows take an exact fallback branch. Its public range filter must stay + // independent of the translated ANN bounds before both branches are merged. + let mut orthogonal = normalized_vector(&mut state, dimension); + let projection = orthogonal + .iter() + .zip(&query_vector) + .map(|(left, right)| left * right) + .sum::(); + for (value, query_value) in orthogonal.iter_mut().zip(&query_vector) { + *value -= projection * query_value; + } + let norm = orthogonal + .iter() + .map(|value| value * value) + .sum::() + .sqrt(); + orthogonal.iter_mut().for_each(|value| *value /= norm); + let appended_vectors = Arc::new(fixed_size_list_array(orthogonal, dimension as i32)); + let appended = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![num_rows])), appended_vectors], + ) + .unwrap(); + table.add(appended).execute().await.unwrap(); + + let mixed = table + .vector_search(query_vector.as_slice()) + .unwrap() + .limit(5) + .distance_range(None, Some(nearest + 1e-5)) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mixed_distances = distances(&mixed); + assert_eq!(mixed_distances.len(), 1); + assert!((mixed_distances[0] - nearest).abs() < 1e-5); + } #[tokio::test] async fn test_create_plan_applies_approx_mode_to_ann_query() { diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 0cc240291..7af52e572 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -130,6 +130,10 @@ pub(super) async fn create_lsm_plan( .await? }; + // Normalize cosine ANN arms before LSM merge and sort nodes compare their + // distances with exact SSTable and memtable arms. + let plan = super::normalize_cosine_ann_branches(plan).await?; + // Lance appends the primary-key columns internally for dedup and keeps them in // the output; drop the ones the user did not request so the projection matches. restore_projection(plan, &query, &pk_columns) From e3dce2cbad45c14422a077dfb34ee68050173827 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:27:27 +0800 Subject: [PATCH 115/180] fix(rust): prevent oversized SQ remap panics (#3861) ## Summary - preflight IVF-SQ and IVF-HNSW-SQ storage segments touched by compaction - preserve unknown legacy fragment coverage as conservatively affected - cover both fixed-size vector and multivector SQ storage dimensions - reject only affected partitions whose fixed-size-list child exceeds Arrow's `u32` take-index limit - return an actionable `InvalidInput` error before Arrow can panic ## Root cause Arrow 58 builds fixed-size-list child indices with `u32`. For a large SQ partition, `partition_rows * vector_dimension` can exceed `u32::MAX`; the child range then wraps inside `take_fixed_size_list`, producing the reported `ArrayData::slice` assertion during index remapping. The preflight now reads raw segment metadata, mirrors Lance's fragment-bitmap selection (including `None` as affected/unknown), opens only affected vector segments, and checks their actual storage quantizer and partition sizes. It derives the stored dimension for both `FixedSizeList` vectors and flattened `List` multivectors. Stable-row-ID datasets, deferred remapping, custom remappers, unaffected segments, non-SQ indexes, safe partitions, and no-op compactions are unchanged. Because the upstream Arrow kernel still has the limit, an affected index must be recreated with default IVF partitioning (or enough partitions to stay below the reported maximum) before compaction. This changes the failure from a process panic to a targeted recovery error; it does not silently alter index structure. ## Validation - `cargo fmt --all -- --check` - `cargo test --quiet --features aws,remote -p lancedb table::optimize::tests --lib` - `cargo test --quiet --features remote -p lancedb table::create_index::tests::test_create_index_ivf_hnsw_sq` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples -- -A clippy::redundant-pub-crate` (the allowance is for pre-existing Rust 1.97 warnings in remote-table code) Fixes #2866 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- Cargo.lock | 1 + Cargo.toml | 1 + docs/web/maintenance/compaction.mdx | 18 ++ rust/lancedb/Cargo.toml | 1 + rust/lancedb/src/table/optimize.rs | 351 +++++++++++++++++++++++++++- 5 files changed, 363 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bbd41c0b1..e4a2eaada 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5789,6 +5789,7 @@ dependencies = [ "tokenizers", "tokio", "tonic", + "tracing", "url", "urlencoding", "uuid", diff --git a/Cargo.toml b/Cargo.toml index 3027ee065..22dec8c0c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,6 +82,7 @@ serde_json = { version = "1", features = ["preserve_order"] } tempfile = "3.5.0" tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } tonic = { version = "0.14", features = ["tls-native-roots", "tls-aws-lc"] } +tracing = "0.1" uuid = { version = "1.7.0", features = ["v4", "v7"] } chrono = { version = "0.4", default-features = false, features = ["clock"] } diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 5d2a9c42f..8b0a8c86f 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -23,6 +23,24 @@ three; a deployment handles them in the background and does not support Run optimization as regular table maintenance, particularly after many small writes or a large ingest. +{/* +Draft for the OSS compaction SQ partition check release. Keep this section +unpublished until that behavior ships. + +### Recover from an oversized SQ partition {#oversized-sq-partition} + +Compacting a table with an IVF scalar-quantized (SQ) vector index can stop +before rewriting files if an affected partition is too large to remap. The +error identifies the index, segment, partition size, and vector dimension +instead of letting the remap fail at Arrow's fixed-size-list `u32` +child-array limit. + +Rebuild the affected vector index with enough IVF partitions to keep each +partition at or below `floor(u32::MAX / dimension)` vectors, then retry the +optimize. Rebuilding with the default IVF partitioning can also choose enough +partitions. +*/} + ## Optimize a table {#what-it-does} ```python diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index c18db11fe..4a2e2318e 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -55,6 +55,7 @@ moka = { workspace = true } pin-project = { workspace = true } tokio = { workspace = true, features = ["io-util", "net", "time"] } log.workspace = true +tracing.workspace = true async-trait = { workspace = true } bytes = { workspace = true } futures.workspace = true diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index ee86e7989..657385762 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -6,20 +6,183 @@ //! This module contains the implementation of optimization operations that help //! maintain good performance for LanceDB tables. -use std::sync::Arc; +use std::{ + collections::HashSet, + sync::{Arc, Mutex}, +}; +use arrow_schema::DataType; use chrono::{DateTime, Utc}; use lance::dataset::cleanup::{CleanupPolicyBuilder, RemovalStats}; -use lance::dataset::optimize::{CompactionMetrics, IndexRemapperOptions, compact_files}; -use lance::index::DatasetIndexExt; +use lance::dataset::optimize::{ + CompactionMetrics, CompactionPlan, CompactionPlanner, IndexRemapperOptions, + compact_files_with_planner, plan_compaction, +}; +use lance::index::{DatasetIndexExt, DatasetIndexInternalExt}; +use lance_core::utils::tracing::{DATASET_COMPACTING_EVENT, TRACE_DATASET_EVENTS}; +use lance_index::IndexType; +use lance_index::metrics::NoOpMetricsCollector; use lance_index::optimize::OptimizeOptions; -use log::info; +use log::{debug, info}; +use super::NativeTable; +use crate::error::{Error, Result}; pub use chrono::Duration; pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemapMode}; -use super::NativeTable; -use crate::error::Result; +const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64; + +struct PrecomputedCompactionPlanner { + plan: Mutex>, +} + +impl PrecomputedCompactionPlanner { + fn new(plan: CompactionPlan) -> Self { + Self { + plan: Mutex::new(Some(plan)), + } + } +} + +#[async_trait::async_trait] +impl CompactionPlanner for PrecomputedCompactionPlanner { + async fn plan(&self, dataset: &lance::Dataset) -> lance::Result { + let plan = self + .plan + .lock() + .map_err(|_| lance_core::Error::internal("precomputed compaction plan lock poisoned"))? + .take() + .ok_or_else(|| { + lance_core::Error::internal("precomputed compaction plan was already consumed") + })?; + debug_assert_eq!(dataset.manifest().version, plan.read_version()); + Ok(plan) + } +} + +fn sq_vector_dimension(data_type: &DataType) -> Option { + match data_type { + DataType::FixedSizeList(_, dimension) => Some(*dimension), + DataType::List(field) => match field.data_type() { + DataType::FixedSizeList(_, dimension) => Some(*dimension), + _ => None, + }, + _ => None, + } +} + +fn segment_touches_fragments( + fragment_ids: Option>, + affected_fragments: &HashSet, +) -> bool { + fragment_ids.is_none_or(|fragment_ids| { + fragment_ids + .into_iter() + .any(|fragment| affected_fragments.contains(&(fragment as u64))) + }) +} + +fn oversized_sq_partition( + partition_sizes: impl IntoIterator, + dimension: u64, +) -> Option { + partition_sizes.into_iter().find(|partition_size| { + partition_size + .checked_mul(dimension) + .is_none_or(|child_len| child_len > MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX) + }) +} + +async fn validate_sq_index_remapping( + dataset: &lance::Dataset, + options: &CompactionOptions, + has_custom_remapper: bool, +) -> Result { + let plan = plan_compaction(dataset, options).await?; + if options.defer_index_remap || has_custom_remapper || dataset.manifest().uses_stable_row_ids() + { + return Ok(plan); + } + + if plan.tasks.is_empty() { + return Ok(plan); + } + let affected_fragments: HashSet = plan + .tasks + .iter() + .flat_map(|task| task.fragments.iter().map(|fragment| fragment.id)) + .collect(); + + for segment in dataset.load_indices().await?.iter() { + if !segment_touches_fragments( + segment + .fragment_bitmap + .as_ref() + .map(|fragment_bitmap| fragment_bitmap.iter()), + &affected_fragments, + ) { + continue; + } + let Some(field_id) = segment.fields.first() else { + continue; + }; + let Some(field) = dataset.schema().field_by_id(*field_id) else { + continue; + }; + let data_type = field.data_type(); + let Some(dimension) = sq_vector_dimension(&data_type) else { + continue; + }; + let dimension = u64::try_from(dimension).map_err(|_| Error::InvalidInput { + message: format!( + "SQ index '{}' has an invalid vector dimension of {}", + segment.name, dimension + ), + })?; + + let field_path = dataset.schema().field_path(*field_id)?; + let vector_index = match dataset + .open_vector_index(&field_path, &segment.uuid, &NoOpMetricsCollector) + .await + { + Ok(vector_index) => vector_index, + Err(error) => { + // The default remapper also treats an index it cannot open as + // unusable and drops it, so it cannot reach the SQ take kernel. + debug!( + "Skipping remap preflight for index segment {} because it could not be opened: {}", + segment.uuid, error + ); + continue; + } + }; + if !matches!( + vector_index.index_type(), + IndexType::IvfSq | IndexType::IvfHnswSq + ) { + continue; + } + + let partition_sizes = (0..vector_index.total_partitions()) + .map(|partition_id| vector_index.partition_size(partition_id) as u64); + if let Some(partition_size) = oversized_sq_partition(partition_sizes, dimension) { + let max_partition_size = MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX / dimension; + return Err(Error::InvalidInput { + message: format!( + "Cannot compact table because SQ index '{}' segment {} has a partition with {} vectors of dimension {}. Arrow's fixed-size-list take kernel cannot remap partitions whose child array exceeds {} values. Recreate the index with default IVF partitioning, or enough partitions to keep each partition at or below {} vectors, before compacting.", + segment.name, + segment.uuid, + partition_size, + dimension, + MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX, + max_partition_size, + ), + }); + } + } + + Ok(plan) +} /// Optimize the dataset. /// @@ -193,7 +356,7 @@ pub(crate) async fn cleanup_old_versions_before( /// This can be run after making several small appends to optimize the table /// for faster reads. /// -/// This calls into [lance::dataset::optimize::compact_files]. +/// This calls into [lance::dataset::optimize::compact_files_with_planner]. pub(crate) async fn compact_files_impl( table: &NativeTable, options: CompactionOptions, @@ -201,7 +364,10 @@ pub(crate) async fn compact_files_impl( ) -> Result { table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); - let metrics = compact_files(&mut dataset, options, remap_options).await?; + tracing::info!(target: TRACE_DATASET_EVENTS, event=DATASET_COMPACTING_EVENT, uri = dataset.uri()); + let plan = validate_sq_index_remapping(&dataset, &options, remap_options.is_some()).await?; + let planner = PrecomputedCompactionPlanner::new(plan); + let metrics = compact_files_with_planner(&mut dataset, remap_options, &planner).await?; table.dataset.update(dataset); Ok(metrics) } @@ -263,13 +429,14 @@ pub(crate) async fn execute_optimize( #[cfg(test)] mod tests { + use super::{oversized_sq_partition, segment_touches_fragments, sq_vector_dimension}; use arrow_array::{ Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, }; use arrow_schema::{DataType, Field, Schema}; use lance_arrow::FixedSizeListArrayExt; use rstest::rstest; - use std::sync::Arc; + use std::{collections::HashSet, sync::Arc}; use crate::connect; use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; @@ -279,6 +446,172 @@ mod tests { use crate::table::{CompactionOptions, OptimizeAction, OptimizeStats}; use futures::TryStreamExt; + /// Regression test for https://github.com/lancedb/lancedb/issues/2866. + #[test] + fn test_detect_oversized_sq_partition() { + const DIMENSION: u64 = 4095; + let safe_size = u32::MAX as u64 / DIMENSION; + + assert_eq!( + oversized_sq_partition([safe_size, safe_size + 1], DIMENSION), + Some(safe_size + 1) + ); + assert_eq!( + oversized_sq_partition([safe_size / 2, safe_size / 2 + 1], DIMENSION), + None + ); + } + + #[test] + fn test_segment_touches_fragments_includes_unknown_coverage() { + let affected_fragments = HashSet::from([7]); + + assert!(segment_touches_fragments( + Some([7_u32]), + &affected_fragments + )); + assert!(!segment_touches_fragments( + Some([8_u32]), + &affected_fragments + )); + assert!(segment_touches_fragments( + None::<[u32; 0]>, + &affected_fragments + )); + } + + #[test] + fn test_sq_vector_dimension_includes_multivectors() { + const DIMENSION: i32 = 4095; + let vector = DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, false)), + DIMENSION, + ); + let multivector = DataType::List(Arc::new(Field::new("item", vector.clone(), false))); + + assert_eq!(sq_vector_dimension(&vector), Some(DIMENSION)); + assert_eq!(sq_vector_dimension(&multivector), Some(DIMENSION)); + assert_eq!(sq_vector_dimension(&DataType::Float32), None); + } + + #[tokio::test] + async fn test_compact_legacy_vector_index_with_unknown_fragment_coverage() { + use lance::Dataset; + use lance::index::vector::{IndexFileVersion, VectorIndexParams}; + use lance::index::{DatasetIndexExt, DatasetIndexInternalExt}; + use lance_index::IndexType; + use lance_linalg::distance::MetricType; + use lance_table::io::commit::write_manifest_file_to_path; + use object_store::ObjectStoreExt; + + const INDEX_NAME: &str = "legacy_ivf_pq"; + const ROWS: i32 = 128; + const DIMENSION: i32 = 8; + + let tmpdir = tempfile::tempdir().unwrap(); + let conn = connect(tmpdir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let vectors = FixedSizeListArray::try_new_from_values( + Float32Array::from_iter_values((0..ROWS).flat_map(|row| { + (0..DIMENSION).map(move |offset| (row * DIMENSION + offset) as f32) + })), + DIMENSION, + ) + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new( + "vector", + vectors.data_type().clone(), + false, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(vectors)]).unwrap(); + let table = conn + .create_table("test_legacy_vector_compact", batch.clone()) + .execute() + .await + .unwrap(); + table.add(batch.clone()).execute().await.unwrap(); + table.add(batch).execute().await.unwrap(); + let mut dataset = (*table.dataset().unwrap().get().await.unwrap()).clone(); + let mut params = VectorIndexParams::ivf_pq(1, 8, 1, MetricType::L2, 10); + params.version(IndexFileVersion::Legacy); + dataset + .create_index( + &["vector"], + IndexType::Vector, + Some(INDEX_NAME.to_string()), + ¶ms, + true, + ) + .await + .unwrap(); + table.dataset().unwrap().update(dataset); + + let dataset = table.dataset().unwrap().get().await.unwrap(); + let mut segments = dataset.load_indices_by_name(INDEX_NAME).await.unwrap(); + assert_eq!(segments.len(), 1); + let original = segments.pop().unwrap(); + let field_path = dataset.schema().field_path(original.fields[0]).unwrap(); + let vector_index = dataset + .open_vector_index( + &field_path, + &original.uuid, + &lance_index::metrics::NoOpMetricsCollector, + ) + .await + .unwrap(); + assert_eq!(vector_index.index_type(), IndexType::IvfPq); + assert_eq!( + vector_index.statistics().unwrap()["index_file_version"], + "Legacy" + ); + let mut legacy = original.clone(); + legacy.fragment_bitmap = None; + let object_store = dataset.object_store(None).await.unwrap(); + let mut manifest = dataset.manifest().clone(); + manifest.index_section = None; + manifest.transaction_section = None; + let manifest_path = dataset.manifest_location().path.clone(); + object_store.inner.delete(&manifest_path).await.unwrap(); + write_manifest_file_to_path( + object_store.as_ref(), + &mut manifest, + Some(vec![legacy]), + &manifest_path, + None, + ) + .await + .unwrap(); + let legacy_dataset = Dataset::open(dataset.uri()).await.unwrap(); + table.dataset().unwrap().update(legacy_dataset); + + let dataset = table.dataset().unwrap().get().await.unwrap(); + let description_error = dataset + .describe_indices(None) + .await + .err() + .expect("legacy coverage should be unknown to index descriptions"); + assert!( + description_error + .to_string() + .contains("Fragment bitmap is required") + ); + + let stats = table + .optimize(OptimizeAction::Compact { + options: CompactionOptions { + target_rows_per_fragment: 1_000, + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + assert!(stats.compaction.unwrap().fragments_removed > 0); + assert_eq!(table.count_rows(None).await.unwrap(), ROWS as usize * 3); + } + #[tokio::test] async fn test_optimize_compact_simple() { let conn = connect("memory://").execute().await.unwrap(); From fe07c25a0a822c4b314e470d8b73edb7bb29d918 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Mon, 26 Oct 2026 18:38:31 -0700 Subject: [PATCH 116/180] fix: refuse Function-bound writes by column instead of by table (#4686) A table with a Function binding rejected every update and merge_insert, whatever columns the write named: updating an unrelated column, or a merge that only inserts rows, failed with "not supported on a table with registered Function bindings". Expression computed columns on the same table accept those writes. Both paths now use the per-column guard that schema evolution already uses. An update is checked on its SET columns. A merge is checked on the columns a matched row would take from the source, every source column but the join keys; an insert-only merge is an append, and its new rows get their Function outputs from the next refresh. Writes to a binding's inputs or outputs are still refused, now naming the column. --- rust/lancedb/src/table/computed_columns.rs | 123 ++++++++++++++++++--- rust/lancedb/src/table/merge.rs | 99 ++++++++++++++++- rust/lancedb/src/table/schema_evolution.rs | 90 +-------------- rust/lancedb/src/table/update.rs | 26 ++++- 4 files changed, 233 insertions(+), 105 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index e86b350ee..fe4c17b1f 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -491,24 +491,6 @@ pub(crate) fn ensure_supported_function_metadata(schema: &ArrowSchema) -> Result ensure_computed_inputs_acyclic(schema, &bindings) } -/// Refuse `operation` outright on a table with a Function binding. For -/// operations that cannot say which columns they touch; the others use -/// [`ensure_not_function_bound`]. -pub(crate) fn ensure_no_function_bindings_for_mutation( - schema: &ArrowSchema, - operation: &str, -) -> Result<()> { - ensure_supported_function_metadata(schema)?; - if !function_bindings(schema)?.is_empty() { - return Err(Error::NotSupported { - message: format!( - "{operation} is not supported on a table with registered Function bindings" - ), - }); - } - Ok(()) -} - /// Refuse `operation` only when a path in `touched` names a column a Function /// binding depends on: an input's root, an output, or the assignment column. /// A binding stores those columns' exact Arrow fields, so editing one strands it. @@ -2406,6 +2388,111 @@ impl lance_datafusion::utils:: } } +/// Test fixtures for a table carrying a Function binding, shared by the +/// write-path tests. No local path declares a binding, so these stamp one +/// the way the server does. +#[cfg(test)] +pub(crate) mod test_support { + use arrow_array::record_batch; + + use super::{ + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, FUNCTION_BINDINGS_META_KEY, + ensure_supported_function_metadata, function_bindings_metadata, + function_computed_column_metadata, + }; + use crate::Table; + use crate::connect; + use crate::function::FunctionBinding; + + /// A table carrying the fixture binding: `title` and `body` are its + /// inputs, `search_text` and `search_token_count` its outputs, `spare` + /// nobody's. Stamped the way the server does it, since no local path + /// declares a binding. + pub async fn bound_table() -> Table { + let batch = record_batch!( + ("title", Utf8, ["a"]), + ("body", Utf8, ["b"]), + ("search_text", Utf8, ["a b"]), + ("search_token_count", Int64, [2]), + ("spare", Int32, [1]) + ) + .unwrap(); + bound_table_from(batch).await + } + + /// [`bound_table`] over a caller's batch, which must carry `title`, `body`, + /// `search_text` and `search_token_count`. + pub async fn bound_table_from(batch: arrow_array::RecordBatch) -> Table { + let conn = connect("memory://").execute().await.unwrap(); + let table = conn.create_table("bound", batch).execute().await.unwrap(); + stamp_bindings(&table, &[text_features_binding("")]).await; + table + } + + /// The fixture binding, its id and output names suffixed so a table can + /// carry more than one. + pub fn text_features_binding(suffix: &str) -> FunctionBinding { + let raw = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + ); + if suffix.is_empty() { + return FunctionBinding::from_json(raw).unwrap(); + } + FunctionBinding::from_json( + &raw.replace("fb_01K3TEXT", &format!("fb_01K3TEXT{suffix}")) + .replace("search_text", &format!("search_text{suffix}")) + .replace("search_token_count", &format!("search_token_count{suffix}")), + ) + .unwrap() + } + + /// Stamp bindings the way the server does it, since no local path + /// declares one: the envelope on the schema, a declaration marker on + /// every output field. + pub async fn stamp_bindings(table: &Table, bindings: &[FunctionBinding]) { + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .update_schema_metadata(vec![( + FUNCTION_BINDINGS_META_KEY.to_string(), + Some(function_bindings_metadata(bindings).unwrap()), + )]) + .await + .unwrap(); + let inputs = ["title".to_string(), "body".to_string()]; + let outputs = bindings + .iter() + .flat_map(|binding| { + let assignment = binding.assignment().map(|assignment| { + ( + assignment.output_name.clone(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + ) + }); + binding + .outputs() + .iter() + .map(|output| (output.output_name.clone(), output.output_ordinal)) + .chain(assignment) + .map(|(name, ordinal)| { + ( + dataset.schema().field(&name).unwrap().id as u32, + function_computed_column_metadata( + binding.binding_id(), + ordinal, + &inputs, + ), + ) + }) + .collect::>() + }) + .collect::>(); + dataset.replace_field_metadata(outputs).await.unwrap(); + native.dataset.update(dataset); + ensure_supported_function_metadata(&table.schema().await.unwrap()).unwrap(); + } +} + #[cfg(test)] mod tests { /// The gate's reproducer: the validator applies the same schema-level diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 24c5f55b3..91a0ed6ea 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -238,6 +238,21 @@ impl MergeInsertBuilder { canonicalize_merge_filter(self.when_not_matched_by_source_delete_filt.take())?; Ok(()) } + + /// The existing columns a matched row takes from `source`: every source + /// column but the join keys, which a match leaves equal. An insert-only + /// merge rewrites none; its new rows get Function outputs from the next + /// refresh, as appended rows do. + pub(crate) fn function_guarded_columns(&self, source: &Fields) -> Vec { + if !self.when_matched_update_all { + return Vec::new(); + } + source + .iter() + .filter(|field| !self.on.iter().any(|key| key == field.name())) + .map(|field| field.name().clone()) + .collect() + } } fn canonicalize_merge_filter(filter: Option) -> Result> { @@ -326,9 +341,10 @@ pub(crate) async fn execute_merge_insert( ) -> Result { params.canonicalize_filters()?; let schema = table.schema().await?; - super::computed_columns::ensure_no_function_bindings_for_mutation( + super::computed_columns::ensure_not_function_bound( schema.as_ref(), "merge_insert", + params.function_guarded_columns(new_data.schema().fields()), )?; // Normalize blob layouts and JSON extension metadata just as on append. // Keep arrow.json text labelled until Lance encodes it as JSONB. @@ -889,6 +905,87 @@ mod tests { assert_eq!(result.num_deleted_rows, (ROW_COUNT - 1) as u64); assert_eq!(table.count_rows(None).await.unwrap(), 1); } + + fn reader(batch: RecordBatch) -> Box { + let schema = batch.schema(); + Box::new(RecordBatchIterator::new(vec![Ok(batch)], schema)) + } + + /// Inserting rows through a merge is an append: the new rows' Function + /// outputs come from the next refresh, so a binding does not refuse it. + #[tokio::test] + async fn merge_insert_only_is_allowed_on_a_function_table() { + let table = crate::table::computed_columns::test_support::bound_table_from( + arrow_array::record_batch!( + ("id", Int32, [1]), + ("note", Utf8, ["n"]), + ("title", Utf8, ["a"]), + ("body", Utf8, ["b"]), + ("search_text", Utf8, ["a b"]), + ("search_token_count", Int64, [2]) + ) + .unwrap(), + ) + .await; + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_insert_all(); + let result = merge + .execute(reader( + arrow_array::record_batch!( + ("id", Int32, [2]), + ("note", Utf8, ["m"]), + ("title", Utf8, ["c"]), + ("body", Utf8, ["d"]) + ) + .unwrap(), + )) + .await + .unwrap(); + assert_eq!(result.num_inserted_rows, 1); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + } + + /// A matched row takes every non-key source column, so the merge is + /// refused only when one of those is a binding's input or output. + #[tokio::test] + async fn merge_update_on_a_function_table_refuses_only_bound_columns() { + let table = crate::table::computed_columns::test_support::bound_table_from( + arrow_array::record_batch!( + ("id", Int32, [1]), + ("note", Utf8, ["n"]), + ("title", Utf8, ["a"]), + ("body", Utf8, ["b"]), + ("search_text", Utf8, ["a b"]), + ("search_token_count", Int64, [2]) + ) + .unwrap(), + ) + .await; + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(None); + let result = merge + .execute(reader( + arrow_array::record_batch!(("id", Int32, [1]), ("note", Utf8, ["m"])).unwrap(), + )) + .await + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(None); + let err = merge + .execute(reader( + arrow_array::record_batch!(("id", Int32, [1]), ("title", Utf8, ["z"])).unwrap(), + )) + .await + .unwrap_err(); + assert!( + matches!(&err, crate::Error::InvalidInput { message } + if message.contains("merge_insert of 'title'") + && message.contains("a Function binding reads or writes it")), + "{err:?}" + ); + } } #[cfg(test)] diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index 1ad532d0a..f80e89ee7 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -459,96 +459,16 @@ mod tests { use crate::function::FunctionBinding; use crate::query::{ExecutableQuery, QueryBase, Select}; use crate::table::NewColumnTransform; + use crate::table::computed_columns::test_support::{ + bound_table, stamp_bindings, text_features_binding, + }; use crate::table::computed_columns::{ - FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, FUNCTION_BINDINGS_META_KEY, - ensure_supported_function_metadata, function_bindings, function_bindings_metadata, - function_computed_column_metadata, is_declaration_key, + FUNCTION_BINDINGS_META_KEY, ensure_supported_function_metadata, function_bindings, + is_declaration_key, }; use crate::{Error, Table}; use std::collections::HashMap; - /// A table carrying the fixture binding: `title` and `body` are its - /// inputs, `search_text` and `search_token_count` its outputs, `spare` - /// nobody's. Stamped the way the server does it, since no local path - /// declares a binding. - async fn bound_table() -> Table { - let conn = connect("memory://").execute().await.unwrap(); - let batch = record_batch!( - ("title", Utf8, ["a"]), - ("body", Utf8, ["b"]), - ("search_text", Utf8, ["a b"]), - ("search_token_count", Int64, [2]), - ("spare", Int32, [1]) - ) - .unwrap(); - let table = conn.create_table("bound", batch).execute().await.unwrap(); - stamp_bindings(&table, &[text_features_binding("")]).await; - table - } - - /// The fixture binding, its id and output names suffixed so a table can - /// carry more than one. - fn text_features_binding(suffix: &str) -> FunctionBinding { - let raw = include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" - ); - if suffix.is_empty() { - return FunctionBinding::from_json(raw).unwrap(); - } - FunctionBinding::from_json( - &raw.replace("fb_01K3TEXT", &format!("fb_01K3TEXT{suffix}")) - .replace("search_text", &format!("search_text{suffix}")) - .replace("search_token_count", &format!("search_token_count{suffix}")), - ) - .unwrap() - } - - /// Stamp bindings the way the server does it, since no local path - /// declares one: the envelope on the schema, a declaration marker on - /// every output field. - async fn stamp_bindings(table: &Table, bindings: &[FunctionBinding]) { - let native = table.as_native().unwrap(); - let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); - dataset - .update_schema_metadata(vec![( - FUNCTION_BINDINGS_META_KEY.to_string(), - Some(function_bindings_metadata(bindings).unwrap()), - )]) - .await - .unwrap(); - let inputs = ["title".to_string(), "body".to_string()]; - let outputs = bindings - .iter() - .flat_map(|binding| { - let assignment = binding.assignment().map(|assignment| { - ( - assignment.output_name.clone(), - FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, - ) - }); - binding - .outputs() - .iter() - .map(|output| (output.output_name.clone(), output.output_ordinal)) - .chain(assignment) - .map(|(name, ordinal)| { - ( - dataset.schema().field(&name).unwrap().id as u32, - function_computed_column_metadata( - binding.binding_id(), - ordinal, - &inputs, - ), - ) - }) - .collect::>() - }) - .collect::>(); - dataset.replace_field_metadata(outputs).await.unwrap(); - native.dataset.update(dataset); - ensure_supported_function_metadata(&table.schema().await.unwrap()).unwrap(); - } - fn metadata_update(path: &str) -> FieldMetadataUpdate { FieldMetadataUpdate { path: path.into(), diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index cec787ff8..aa325cd7c 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -94,9 +94,10 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; crate::materialized_view::ensure_not_a_view(&table.name, &dataset.schema().metadata, "update")?; - super::computed_columns::ensure_no_function_bindings_for_mutation( + super::computed_columns::ensure_not_function_bound( &arrow_schema::Schema::from(dataset.schema()), "update", + update.columns.iter().map(|(name, _)| name.as_str()), )?; super::computed_columns::ensure_not_written( &arrow_schema::Schema::from(dataset.schema()), @@ -445,4 +446,27 @@ mod tests { tbl.update().column("i", "i+1").execute().await.unwrap(); assert_eq!(0, tbl.count_rows(Some("i == 0".to_string())).await.unwrap()); } + + /// A Function binding protects only the columns it reads or writes; any + /// other column updates as on a plain table. + #[tokio::test] + async fn update_on_a_function_table_refuses_only_bound_columns() { + let table = crate::table::computed_columns::test_support::bound_table().await; + let result = table.update().column("spare", "7").execute().await.unwrap(); + assert_eq!(result.rows_updated, 1); + for column in ["title", "search_text"] { + let err = table + .update() + .column(column, "'x'") + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, crate::Error::InvalidInput { message } + if message.contains(&format!("update of '{column}'")) + && message.contains("a Function binding reads or writes it")), + "{column}: {err:?}" + ); + } + } } From 37b46f6b4f9bbc1c90deee27910cdccfc0cc4fde Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 27 Oct 2026 01:42:19 +0000 Subject: [PATCH 117/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.14=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.15?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 7dcefa69c..ebadc517a 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.14" +current_version = "0.41.0-beta.15" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index e4a2eaada..2844ae735 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5700,7 +5700,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.14" +version = "0.41.0-beta.15" dependencies = [ "ahash", "anyhow", @@ -5811,7 +5811,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.14" +version = "0.41.0-beta.15" dependencies = [ "arrow-array", "arrow-buffer", @@ -5836,7 +5836,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.14" +version = "0.41.0-beta.15" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 9dbccbc81..55f6009c3 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.14 + 0.41.0-beta.15 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 7c34a801a..c3a769c85 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.14 + 0.41.0-beta.15 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 2dc959887..e3cfb2781 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.14 + 0.41.0-beta.15 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index e343d68ca..e8abcf60a 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.14" +version = "0.41.0-beta.15" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 343483a8e..59602e4f4 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 4c3b93c81..5063b8cee 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 7679a422d..98b088c0f 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 6a62f8e8a..a24a6cc0d 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index d68341382..e1d6a690a 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 42a517310..88b68ff34 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index b116f2819..dfc492e82 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index f746f6daf..9b10144c7 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.14", + "version": "0.41.0-beta.15", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 265e4d270..b1581b366 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.14" +version = "0.41.0-beta.15" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 4a2e2318e..9015bcdd7 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.14" +version = "0.41.0-beta.15" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From dcbf5ce66a57dcc090e10b1d195c1c4a3b7080c3 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:11:39 +0800 Subject: [PATCH 118/180] fix: preserve null blob descriptor fields in SQL (#4571) SQL descriptor access returns NULL for every field of a NULL Blob v2 value, so `payload.size = 0` matches only empty blobs and `payload.size IS NULL` matches NULL blobs. DataFusion 54.1.0 extracts struct children without combining their validity with the parent struct. Lance descriptors keep nullness in the parent and can store zero-filled children beneath NULL blobs. The adapter derives the descriptor schema from Lance's default projection, marks descriptor children nullable, and masks them before SQL evaluation. Schema derivation requires no query request, and the mask handles struct and list nesting while preserving existing child nulls and value buffers without fetching blob bytes. Filter classification follows the referenced struct field path. Blob predicates stay above the mask; scalar siblings such as `extra.note` retain exact filter pushdown even when `extra.clip` is a blob. **Merge hold:** as requested in the [review discussion](https://github.com/lancedb/lancedb/pull/4571#issuecomment-6253443077), blob SQL INSERT compatibility remains pending a separate write-mode design. DataFusion uses the provider's single schema for reads and INSERT coercion, so the descriptor schema still rejects blob write structs. This follow-up does not restore those INSERTs; the merge should wait until the write contract is settled. Validation: - Reproduced the original NULL blob returning `kind = 0` before enabling the mask. - Reproduced both the extra remote query and lost nested sibling pushdown before the follow-up fixes. - All 441 DataFusion adapter tests passed after merging main at `e6789a41`, including SQL projections, filters, mixed predicates, LIMIT, COUNT, schema agreement, sliced arrays, nested structs, list variants, and EXPLAIN assertions for scalar sibling pushdown. The blob fixtures use the current four-field write format, and NULL-blob filtering is also covered with row IDs and row addresses enabled. - Remote constructor regression passed: one describe request and no query request, with nullable descriptor fields preserved. - `cargo fmt --all` - `cargo clippy --locked --profile ci -p lancedb --features remote --tests --examples -- -D warnings` Fixes #4569 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/remote/table.rs | 25 ++ rust/lancedb/src/table/datafusion.rs | 317 +++++++++++++- .../src/table/datafusion/blob_nulls.rs | 396 ++++++++++++++++++ 3 files changed, 730 insertions(+), 8 deletions(-) create mode 100644 rust/lancedb/src/table/datafusion/blob_nulls.rs diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 181ce61f9..29cf774fc 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5687,6 +5687,31 @@ mod tests { schema_describe_response(&schema) } + #[tokio::test] + async fn test_adapter_construction_only_describes_blob_schema() { + use datafusion_catalog::TableProvider; + + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let table = Table::new_with_handler("my_table", move |request| { + observed.fetch_add(1, Ordering::SeqCst); + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + blob_describe_response() + }); + + let adapter = + crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + let schema = adapter.schema(); + let DataType::Struct(fields) = schema.field_with_name("image").unwrap().data_type() else { + panic!("expected a blob descriptor"); + }; + assert!(fields.find("size").unwrap().1.is_nullable()); + assert!(fields.find("data").is_none()); + } + #[rstest] #[case(semver::Version::new(0, 1, 0))] #[case(semver::Version::new(0, 5, 0))] diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index e6a76c3f5..973ab0123 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -4,6 +4,7 @@ //! This module contains adapters to allow LanceDB tables to be used as DataFusion table providers. mod blob_coerce; +mod blob_nulls; pub mod cast; pub mod insert; pub mod reject_nan; @@ -25,7 +26,10 @@ use datafusion_physical_plan::{ }; use futures::{TryFutureExt, TryStreamExt}; use lance::dataset::{WriteMode, WriteParams}; -use lance_core::{ROW_ADDR, ROW_ADDR_FIELD, ROW_ID, ROW_ID_FIELD}; +use lance_core::{ + ROW_ADDR, ROW_ADDR_FIELD, ROW_ID, ROW_ID_FIELD, + datatypes::{Projection, Schema as LanceSchema}, +}; use super::{AnyQuery, BaseTable}; use crate::{ @@ -171,13 +175,14 @@ pub struct BaseTableAdapter { } impl BaseTableAdapter { + /// Create an adapter whose schema matches default scans, including blob descriptors. + /// + /// Deriving the descriptor schema does not execute a query or read blob payloads. pub async fn try_new(table: Arc) -> Result { - let schema = table - .schema() - .await? - .as_ref() - .clone() - .with_metadata(HashMap::default()); + let write_schema = table.schema().await?; + let schema = Projection::full(Arc::new(LanceSchema::try_from(write_schema.as_ref())?)) + .to_arrow_schema(); + let schema = blob_nulls::read_schema(&schema).with_metadata(HashMap::default()); Ok(Self { table, @@ -317,6 +322,7 @@ impl TableProvider for BaseTableAdapter { .create_plan(&AnyQuery::Query(query), options) .map_err(|err| DataFusionError::External(err.into())) .await?; + let plan = blob_nulls::mask_plan(plan)?; Ok(Arc::new(MetadataEraserExec::new(plan))) } @@ -324,7 +330,21 @@ impl TableProvider for BaseTableAdapter { &self, filters: &[&Expr], ) -> DataFusionResult> { - Ok(vec![TableProviderFilterPushDown::Exact; filters.len()]) + // Lance evaluates pushed filters before the descriptor validity mask. + // Keep predicates touching blobs above that mask, including IS NULL: + // the stored descriptor's children are not independently nullable. + filters + .iter() + .map(|filter| { + Ok( + if blob_nulls::references_descriptor(filter, &self.schema)? { + TableProviderFilterPushDown::Unsupported + } else { + TableProviderFilterPushDown::Exact + }, + ) + }) + .collect() } fn statistics(&self) -> Option { @@ -562,6 +582,287 @@ pub mod tests { } } + fn inline_blob_input(values: Vec>) -> arrow_array::ArrayRef { + use arrow_array::{Array, LargeBinaryArray, StructArray, UInt64Array}; + + let data = LargeBinaryArray::from(values); + let len = data.len(); + let nulls = data.nulls().cloned(); + let DataType::Struct(fields) = crate::blob("payload", true).data_type().clone() else { + unreachable!() + }; + Arc::new(StructArray::new( + fields, + vec![ + Arc::new(data), + Arc::new(StringArray::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + ], + nulls, + )) + } + + #[tokio::test] + async fn test_sql_blob_descriptor_nulls() { + use arrow_array::{UInt8Array, UInt64Array}; + use arrow_select::concat::concat_batches; + + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let blobs = inline_blob_input(vec![Some(b"hello"), Some(b""), None]); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + crate::blob("payload", true), + ])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3])), blobs], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let adapter = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let ctx = SessionContext::new_with_config(SessionConfig::new().with_batch_size(2)); + ctx.register_table("docs", adapter.clone()).unwrap(); + + let batches = ctx + .sql("SELECT id, payload.kind, payload.position, payload.size, payload.blob_id, payload.blob_uri FROM docs ORDER BY id") + .await.unwrap().collect().await.unwrap(); + let batch = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!(batch.num_rows(), 3); + assert_eq!( + batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(), + &UInt8Array::from(vec![Some(0), Some(0), None]) + ); + assert_eq!( + batch + .column(3) + .as_any() + .downcast_ref::() + .unwrap(), + &UInt64Array::from(vec![Some(5), Some(0), None]) + ); + for column in &batch.columns()[1..] { + assert!(!column.is_null(0)); + assert!(!column.is_null(1)); + assert!(column.is_null(2)); + } + + for (predicate, expected) in [ + ("payload.size = 0", vec![2]), + ("payload.kind = 0", vec![1, 2]), + ("payload.blob_uri = ''", vec![1, 2]), + ("payload.size IS NULL", vec![3]), + ("payload.size IS NOT NULL", vec![1, 2]), + ("payload.kind IS NULL", vec![3]), + ("payload.position IS NULL", vec![3]), + ("payload.blob_id IS NULL", vec![3]), + ("payload.blob_uri IS NULL", vec![3]), + ("payload IS NULL", vec![3]), + ("payload.size = 0 OR payload.size IS NULL", vec![2, 3]), + ("id > 1 AND payload.size = 0", vec![2]), + ] { + let batches = ctx + .sql(&format!( + "SELECT id FROM docs WHERE {predicate} ORDER BY id" + )) + .await + .unwrap() + .collect() + .await + .unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + assert_eq!(ids, expected, "{predicate}"); + } + + let batches = ctx + .sql("SELECT id FROM docs WHERE payload.size IS NULL LIMIT 1") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 3 + ); + let batches = ctx + .sql("SELECT COUNT(*), COUNT(payload.size) FROM docs") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 3 + ); + assert_eq!( + batches[0] + .column(1) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 2 + ); + assert!(ctx.sql("SELECT payload.data FROM docs").await.is_err()); + + // Whole-struct scans must agree with the declared schema too. + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + + // Opted-in system columns must compose with the descriptor schema and mask. + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap(); + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let expected = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + let expected = concat_batches(&adapter.schema(), &expected).unwrap(); + ctx.register_table("docs_with_system_columns", Arc::new(adapter)) + .unwrap(); + let batches = ctx + .sql("SELECT _rowaddr, _rowid, id FROM docs_with_system_columns WHERE payload.size IS NULL") + .await + .unwrap() + .collect() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + let columns = + [ROW_ADDR, ROW_ID, "id"].map(|name| expected.schema().index_of(name).unwrap()); + assert_eq!(actual, expected.project(&columns).unwrap().slice(2, 1)); + } + + #[tokio::test] + async fn test_nested_blob_sibling_filter_pushdown() { + use arrow_array::{Array, StructArray}; + + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let blobs = inline_blob_input(vec![Some(b"hello"), None, Some(b"")]); + let fields = vec![ + Arc::new(Field::new("note", DataType::Utf8, false)), + Arc::new(crate::blob("clip", true)), + Arc::new(Field::new("note.with.dot", DataType::Utf8, false)), + ]; + let extra = StructArray::new( + fields.into(), + vec![ + Arc::new(StringArray::from(vec!["note 7", "note 8", "note 9"])), + blobs, + Arc::new(StringArray::from(vec!["a", "b", "c"])), + ], + None, + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("extra", extra.data_type().clone(), false), + ])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let adapter = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let ctx = SessionContext::new(); + ctx.register_table("docs", adapter).unwrap(); + + for (predicate, pushed, expected) in [ + ("extra.note = 'note 7'", true, vec![1]), + ("extra.\"note.with.dot\" = 'b'", true, vec![2]), + ("extra.clip.size IS NULL", false, vec![2]), + ("get_field(extra, 'clip', 'size') = 0", false, vec![3]), + ("extra.clip IS NULL", false, vec![2]), + ( + "extra.note = 'note 7' OR extra.clip.size IS NULL", + false, + vec![1, 2], + ), + ] { + let sql = format!("SELECT id FROM docs WHERE {predicate}"); + let explain = ctx + .sql(&format!("EXPLAIN {sql}")) + .await + .unwrap() + .collect() + .await + .unwrap(); + let explain = explain + .iter() + .flat_map(|batch| batch.column(1).as_string::().iter()) + .flatten() + .collect::>() + .join("\n"); + assert_eq!(explain.contains("FilterExec"), !pushed, "{explain}"); + if pushed { + assert!(explain.contains("full_filters=["), "{explain}"); + } + let batches = ctx + .sql(&format!("{sql} ORDER BY id")) + .await + .unwrap() + .collect() + .await + .unwrap(); + let ids = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect::>(); + assert_eq!(ids, expected, "{predicate}"); + } + } + #[tokio::test] async fn test_system_columns_opt_in() { let fixture = TestFixture::new().await; diff --git a/rust/lancedb/src/table/datafusion/blob_nulls.rs b/rust/lancedb/src/table/datafusion/blob_nulls.rs new file mode 100644 index 000000000..7c0cbda42 --- /dev/null +++ b/rust/lancedb/src/table/datafusion/blob_nulls.rs @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Apply Blob v2 struct validity before DataFusion extracts descriptor fields. + +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use arrow_array::{ + Array, ArrayRef, FixedSizeListArray, LargeListArray, ListArray, RecordBatch, StructArray, + cast::AsArray, make_array, +}; +use arrow_buffer::NullBuffer; +use arrow_schema::{DataType, Field, FieldRef, Schema}; +use datafusion_common::{ + Result, + tree_node::{TreeNode, TreeNodeRecursion}, +}; +use datafusion_expr::{ColumnarValue, Expr}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::{PhysicalExpr, expressions::Column}; +use datafusion_physical_plan::{ExecutionPlan, projection::ProjectionExec}; +use lance_arrow::FieldExt; +use lance_core::datatypes::BlobV2Layout; + +fn is_descriptor(field: &Field) -> bool { + field.is_blob() + && matches!(field.data_type(), DataType::Struct(fields) + if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)) +} + +pub(super) fn has_descriptor(field: &Field) -> bool { + if is_descriptor(field) { + return true; + } + match field.data_type() { + DataType::Struct(fields) => fields.iter().any(|field| has_descriptor(field)), + DataType::List(item) | DataType::LargeList(item) | DataType::FixedSizeList(item, _) => { + has_descriptor(item) + } + _ => false, + } +} + +/// Resolve static struct accesses without confusing a scalar sibling with the +/// entire root column. Track descriptor ancestors too: `blob.size` is scalar, +/// but still requires the descriptor validity mask before evaluation. +fn referenced_field<'a>(expr: &Expr, schema: &'a Schema) -> Option<(&'a Field, bool)> { + match expr { + Expr::Column(column) => Some((schema.field_with_name(&column.name).ok()?, false)), + Expr::ScalarFunction(call) + if call.func.inner().downcast_ref::().is_some() => + { + let (base, path) = call.args.split_first()?; + let (mut field, mut within_descriptor) = referenced_field(base, schema)?; + for name in path { + let Expr::Literal(name, _) = name else { + return None; + }; + within_descriptor |= is_descriptor(field); + let DataType::Struct(fields) = field.data_type() else { + return None; + }; + field = fields.find(name.try_as_str().flatten()?)?.1; + } + Some((field, within_descriptor)) + } + _ => None, + } +} + +pub(super) fn references_descriptor(expr: &Expr, schema: &Schema) -> Result { + let mut found = false; + expr.apply(|expr| { + if let Some((field, within_descriptor)) = referenced_field(expr, schema) { + if within_descriptor || has_descriptor(field) { + found = true; + return Ok(TreeNodeRecursion::Stop); + } + // The complete path is safe. Do not revisit its root as a whole + // struct, which could contain an unrelated blob sibling. + return Ok(TreeNodeRecursion::Jump); + } + // Unknown/computed paths conservatively visit their arguments. + Ok(TreeNodeRecursion::Continue) + })?; + Ok(found) +} + +fn nullable_descriptor_fields(field: &FieldRef) -> FieldRef { + let data_type = match field.data_type() { + DataType::Struct(fields) if is_descriptor(field) => DataType::Struct( + fields + .iter() + .map(|field| Arc::new(field.as_ref().clone().with_nullable(true))) + .collect(), + ), + DataType::Struct(fields) => { + DataType::Struct(fields.iter().map(nullable_descriptor_fields).collect()) + } + DataType::List(item) => DataType::List(nullable_descriptor_fields(item)), + DataType::LargeList(item) => DataType::LargeList(nullable_descriptor_fields(item)), + DataType::FixedSizeList(item, size) => { + DataType::FixedSizeList(nullable_descriptor_fields(item), *size) + } + _ => return field.clone(), + }; + Arc::new(field.as_ref().clone().with_data_type(data_type)) +} + +pub(super) fn read_schema(schema: &Schema) -> Schema { + Schema::new_with_metadata( + schema + .fields() + .iter() + .map(nullable_descriptor_fields) + .collect::>(), + schema.metadata().clone(), + ) +} + +/// Preserve value buffers, offsets, metadata, and existing child nulls. Only +/// validity buffers are combined; this never materializes blob payloads. +fn mask_array(array: &ArrayRef, field: &Field, ancestors: Option<&NullBuffer>) -> Result { + if !has_descriptor(field) { + return Ok(array.clone()); + } + match field.data_type() { + DataType::Struct(fields) => { + let values = array.as_struct(); + let nulls = NullBuffer::union(values.nulls(), ancestors); + let columns = if is_descriptor(field) { + values + .columns() + .iter() + .map(|column| { + let nulls = NullBuffer::union(column.nulls(), nulls.as_ref()); + Ok(make_array( + column.to_data().into_builder().nulls(nulls).build()?, + )) + }) + .collect::>>()? + } else { + values + .columns() + .iter() + .zip(fields) + .map(|(column, field)| mask_array(column, field, nulls.as_ref())) + .collect::>>()? + }; + Ok(Arc::new(StructArray::try_new_with_length( + fields.clone(), + columns, + nulls, + values.len(), + )?)) + } + DataType::List(item) => { + let list = array.as_list::(); + Ok(Arc::new(ListArray::try_new( + item.clone(), + list.offsets().clone(), + mask_array(list.values(), item, None)?, + list.nulls().cloned(), + )?)) + } + DataType::LargeList(item) => { + let list = array.as_list::(); + Ok(Arc::new(LargeListArray::try_new( + item.clone(), + list.offsets().clone(), + mask_array(list.values(), item, None)?, + list.nulls().cloned(), + )?)) + } + DataType::FixedSizeList(item, size) => { + let list = array.as_fixed_size_list(); + Ok(Arc::new(FixedSizeListArray::try_new( + item.clone(), + *size, + mask_array(list.values(), item, None)?, + list.nulls().cloned(), + )?)) + } + _ => Ok(array.clone()), + } +} + +#[derive(Debug)] +struct MaskBlobNulls { + source: Arc, + field: FieldRef, +} + +impl fmt::Display for MaskBlobNulls { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "mask_blob_nulls({})", self.source) + } +} + +impl PartialEq for MaskBlobNulls { + fn eq(&self, other: &Self) -> bool { + self.source.eq(&other.source) && self.field == other.field + } +} + +impl Eq for MaskBlobNulls {} + +impl Hash for MaskBlobNulls { + fn hash(&self, state: &mut H) { + self.source.hash(state); + self.field.hash(state); + } +} + +impl PhysicalExpr for MaskBlobNulls { + fn return_field(&self, _input_schema: &Schema) -> Result { + Ok(self.field.clone()) + } + + fn evaluate(&self, batch: &RecordBatch) -> Result { + let source = self.source.evaluate(batch)?.into_array(batch.num_rows())?; + Ok(ColumnarValue::Array(mask_array( + &source, + &self.field, + None, + )?)) + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.source] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + assert_eq!(children.len(), 1); + Ok(Arc::new(Self { + source: children[0].clone(), + field: self.field.clone(), + })) + } + + fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self}") + } +} + +pub(super) fn mask_plan(input: Arc) -> Result> { + let schema = input.schema(); + if !schema.fields().iter().any(|field| has_descriptor(field)) { + return Ok(input); + } + let expressions = schema + .fields() + .iter() + .enumerate() + .map(|(index, field)| { + let source: Arc = Arc::new(Column::new(field.name(), index)); + let expression: Arc = if has_descriptor(field) { + Arc::new(MaskBlobNulls { + source, + field: nullable_descriptor_fields(field), + }) + } else { + source + }; + (expression, field.name().clone()) + }) + .collect::>(); + Ok(Arc::new(ProjectionExec::try_new(expressions, input)?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{StringArray, UInt8Array, UInt32Array, UInt64Array}; + use arrow_buffer::OffsetBuffer; + use lance_core::datatypes::BLOB_V2_DESC_FIELD; + + fn descriptor() -> (FieldRef, ArrayRef) { + let field = Arc::new(BLOB_V2_DESC_FIELD.clone().with_nullable(true)); + let field = nullable_descriptor_fields(&field); + let DataType::Struct(fields) = field.data_type() else { + unreachable!() + }; + let array = StructArray::new( + fields.clone(), + vec![ + Arc::new(UInt8Array::from(vec![0; 5])), + Arc::new(UInt64Array::from(vec![10; 5])), + Arc::new(UInt64Array::from(vec![ + Some(9), + Some(5), + Some(0), + Some(0), + None, + ])), + Arc::new(UInt32Array::from(vec![0; 5])), + Arc::new(StringArray::from(vec![""; 5])), + ], + Some(NullBuffer::from(vec![true, true, true, false, true])), + ); + (field, Arc::new(array)) + } + + #[test] + fn test_sliced_descriptor_preserves_child_nulls_and_buffers() { + let (field, array) = descriptor(); + let array = array.slice(1, 4); + let masked = mask_array(&array, &field, None).unwrap(); + let masked = masked.as_struct(); + let size = masked + .column_by_name("size") + .unwrap() + .as_primitive::(); + assert_eq!(size, &UInt64Array::from(vec![Some(5), Some(0), None, None])); + assert_eq!(masked.nulls(), array.nulls()); + for (input, output) in array.as_struct().columns().iter().zip(masked.columns()) { + assert_eq!(input.to_data().buffers(), output.to_data().buffers()); + assert!(output.is_null(2)); + } + + let empty = mask_array(&array.slice(0, 0), &field, None).unwrap(); + assert_eq!(empty.len(), 0); + } + + #[test] + fn test_nested_descriptor_inherits_struct_nulls() { + let (blob_field, array) = descriptor(); + let parent = Arc::new(Field::new( + "parent", + DataType::Struct(vec![blob_field.clone()].into()), + true, + )); + let array: ArrayRef = Arc::new(StructArray::new( + vec![blob_field].into(), + vec![array], + Some(NullBuffer::from(vec![true, false, true, true, true])), + )); + let array = array.slice(1, 3); + let masked = mask_array(&array, &parent, None).unwrap(); + let blob = masked.as_struct().column(0).as_struct(); + assert_eq!( + blob.nulls().unwrap(), + &NullBuffer::from(vec![false, true, false]) + ); + for column in blob.columns() { + assert!(column.is_null(0)); + assert!(!column.is_null(1)); + assert!(column.is_null(2)); + } + } + + #[test] + fn test_list_descriptor_masks_preserve_offsets_and_validity() { + let (item, values) = descriptor(); + let nulls = Some(NullBuffer::from(vec![true, false, true])); + let arrays: Vec = vec![ + Arc::new(ListArray::new( + item.clone(), + OffsetBuffer::new(vec![0, 1, 3, 5].into()), + values.clone(), + nulls.clone(), + )), + Arc::new(LargeListArray::new( + item.clone(), + OffsetBuffer::new(vec![0_i64, 1, 3, 5].into()), + values.clone(), + nulls, + )), + Arc::new(FixedSizeListArray::new(item.clone(), 1, values, None)), + ]; + for array in arrays { + let field = Field::new("blobs", array.data_type().clone(), true); + let masked = mask_array(&array, &field, None).unwrap(); + assert_eq!(masked.nulls(), array.nulls()); + assert_eq!(masked.to_data().buffers(), array.to_data().buffers()); + let values = match masked.data_type() { + DataType::List(_) => masked.as_list::().values(), + DataType::LargeList(_) => masked.as_list::().values(), + DataType::FixedSizeList(_, _) => masked.as_fixed_size_list().values(), + _ => unreachable!(), + }; + for column in values.as_struct().columns() { + assert!(column.is_null(3)); + } + assert_eq!( + mask_array(&array.slice(1, 1), &field, None).unwrap().len(), + 1 + ); + } + } +} From 8a4effa06a5d08deebf8336e936e45743a0fc538 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 27 Oct 2026 14:32:09 +0800 Subject: [PATCH 119/180] fix: gate experimental local functions behind an opt-in feature (#4688) Published SDK builds currently expose local SQL computed columns and materialized-view execution that are not ready for release. Add the opt-in `experimental-functions` Cargo feature to the Rust core and forward it through the Python and Node bindings; published packages leave it disabled. Local declarations and refreshes now return `NotSupported` before mutating tables or spawning jobs, including prepared materialized-view creation. Remote Cloud/Enterprise client operations, Python UDF packaging, ordinary eager `add_columns`, and access to existing data remain available. Stored metadata and write protections stay active, and shared server commit helpers remain usable. CI covers both feature configurations. Existing local execution tests run with the feature enabled; default-build regressions cover early rejection, unchanged table versions, existing metadata protections, and normal eager transforms. API and source-build documentation explain the opt-in. Validation: Rust library tests pass with the feature disabled (1,869 tests) and enabled (1,947 tests), plus three default-build integration regressions. Python and TypeScript bindings were rebuilt and tested in both configurations, including mocked remote requests; Rust formatting, Python package lint, TypeScript lint/build, and generated docs were checked. Repository-wide Ruff still reports 48 pre-existing errors in unchanged `docs/web-tests` files. --- .github/workflows/nodejs.yml | 8 +- .github/workflows/python.yml | 7 +- .github/workflows/rust.yml | 2 + docs/src/js/_media/CONTRIBUTING.md | 13 ++ docs/src/js/classes/Connection.md | 4 + docs/src/js/classes/MaterializedView.md | 1 + docs/src/js/classes/Table.md | 7 + docs/src/python/python.md | 10 +- .../add-computed-column.mdx | 9 +- .../materialized-views.mdx | 9 +- .../feature-engineering/refresh-column.mdx | 9 +- nodejs/CONTRIBUTING.md | 13 ++ nodejs/Cargo.toml | 1 + .../__test__/experimental_functions.test.ts | 44 ++++ nodejs/__test__/materialized_view.test.ts | 65 +++--- nodejs/__test__/table.test.ts | 8 +- nodejs/lancedb/connection.ts | 4 + nodejs/lancedb/materialized_view.ts | 1 + nodejs/lancedb/table.ts | 7 + nodejs/src/lib.rs | 6 + python/CONTRIBUTING.md | 12 ++ python/Cargo.toml | 1 + python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 16 +- python/python/lancedb/materialized_view.py | 7 +- python/python/lancedb/table.py | 38 +++- python/python/tests/conftest.py | 15 ++ .../tests/test_experimental_functions.py | 58 +++++ .../python/tests/test_materialized_views.py | 24 +++ python/python/tests/test_namespace.py | 24 ++- python/python/tests/test_table.py | 7 + python/src/lib.rs | 4 + rust/lancedb/Cargo.toml | 3 + rust/lancedb/src/lib.rs | 18 ++ rust/lancedb/src/materialized_view.rs | 29 +++ rust/lancedb/src/materialized_view/refresh.rs | 5 + rust/lancedb/src/table/add_columns.rs | 11 + rust/lancedb/src/table/computed_columns.rs | 120 +++++++++++ rust/lancedb/src/table/refresh.rs | 162 ++++++++++++++ rust/lancedb/src/table/schema_evolution.rs | 39 ++-- rust/lancedb/tests/experimental_functions.rs | 198 ++++++++++++++++++ 41 files changed, 955 insertions(+), 66 deletions(-) create mode 100644 nodejs/__test__/experimental_functions.test.ts create mode 100644 python/python/tests/test_experimental_functions.py create mode 100644 rust/lancedb/tests/experimental_functions.rs diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 2e290166e..e83c8d29f 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -79,11 +79,15 @@ jobs: # that dir is missing, so create an empty one for lint-only runs. run: mkdir -p ../dist && pnpm install --frozen-lockfile && pnpm lint-ci linux: - name: Linux (NodeJS ${{ matrix.node-version }}) + name: Linux (NodeJS ${{ matrix.node-version }}, ${{ matrix.features }}) timeout-minutes: 30 strategy: matrix: node-version: [ "22", "24", "26" ] + features: [ "default" ] + include: + - node-version: "24" + features: "experimental-functions" runs-on: "ubuntu-22.04" defaults: run: @@ -121,7 +125,7 @@ jobs: pnpm install --frozen-lockfile # No `--` separator: pnpm forwards it literally, which would # make napi-rs treat `--profile ci` as a cargo passthrough arg. - pnpm build:debug --profile ci + pnpm build:debug --profile ci --features ${{ matrix.features }} pnpm tsc - name: Setup examples working-directory: nodejs/examples diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 3608c24ca..a18ae5ad9 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -162,7 +162,10 @@ jobs: - name: Delete wheels run: rm -rf target/wheels platform: - name: "Mac" + name: "Mac: ${{ matrix.features }}" + strategy: + matrix: + features: ["default", "experimental-functions"] timeout-minutes: 30 runs-on: macos-14 defaults: @@ -188,7 +191,7 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - uses: ./.github/workflows/build_mac_wheel with: - args: --profile ci + args: --profile ci --features ${{ matrix.features }} - uses: ./.github/workflows/run_tests # Make sure wheels are not included in the Rust cache - name: Delete wheels diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index ffd2162c6..96b0f2bfb 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -261,6 +261,8 @@ jobs: sudo apt update sudo apt install -y protobuf-compiler libssl-dev - uses: rui314/setup-mold@v1 + - name: Test the default local Functions gate + run: cargo test --profile ci -p lancedb --features remote --test experimental_functions --locked - name: Run remote tests run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests diff --git a/docs/src/js/_media/CONTRIBUTING.md b/docs/src/js/_media/CONTRIBUTING.md index 2faa8cd37..2125cc8aa 100644 --- a/docs/src/js/_media/CONTRIBUTING.md +++ b/docs/src/js/_media/CONTRIBUTING.md @@ -50,6 +50,19 @@ pnpm install pnpm build ``` +Local SQL computed columns and materialized-view creation/refresh are experimental +and disabled in published packages. To opt in when building from this directory: + +```shell +pnpm build:debug --features experimental-functions +pnpm tsc +pnpm test --runInBand table.test.ts materialized_view.test.ts +``` + +Rebuild without `--features experimental-functions` to test the default package. +The tests detect the compiled feature; remote operations, metadata protections, +and ordinary eager `addColumns` transforms remain available in both builds. + Lint: ```shell diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index c110eb38c..ffe7106b7 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -180,6 +180,10 @@ abstract createMaterializedView( Define a materialized view named `name` over the table `source`. +Local creation and refresh require a source build with the +`experimental-functions` Cargo feature, disabled in published packages. +Remote Cloud/Enterprise operations do not require this feature. + The view is populated before creation returns. Set `withNoData` to create only its definition and empty backing table. The view is a normal table: it can be queried, indexed and searched, and it appears in `tableNames`. diff --git a/docs/src/js/classes/MaterializedView.md b/docs/src/js/classes/MaterializedView.md index 0e2413328..bb02f5dc2 100644 --- a/docs/src/js/classes/MaterializedView.md +++ b/docs/src/js/classes/MaterializedView.md @@ -64,6 +64,7 @@ refresh(options?): Promise ``` Recompute the view from its source. +Local refresh requires a source build with `experimental-functions`. Every refresh rebuilds the complete view. For local views, `sourceVersion` refreshes to that source version instead of the latest; diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 7cf87c405..80bba02a0 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -69,6 +69,10 @@ abstract addColumns(newColumnTransforms): Promise Add new columns with defined values. +Local computed-column declaration and refresh require a source build with +the `experimental-functions` Cargo feature. Published packages disable it; +remote Cloud/Enterprise operations remain available. + The `{ computed }` form stores the expression rather than evaluating it now: the column is committed with no values, and rows get them from [Table#refreshColumn](Table.md#refreshcolumn). Declaring one therefore costs the same on a @@ -1035,6 +1039,7 @@ abstract refreshColumn(column): Promise ``` Fill the rows of a computed column that hold no value yet. +Local refresh requires a source build with `experimental-functions`. Rows appended since the last refresh are filled by the next one, and rows whose inputs changed since they were computed are recomputed; @@ -1063,6 +1068,8 @@ abstract refreshColumnAsync(column): Promise Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh job instead of blocking until it completes. +Local refresh requires a source build with `experimental-functions`. +Remote Cloud/Enterprise jobs do not require this feature. The job may already be complete when returned; callers must not assume the column is filled until [Job.wait](Job.md#wait) resolves. Invalid input -- diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 2fefe91f3..5f87302ad 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -429,6 +429,13 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, ## Materialized Views (Synchronous) +In the 0.41 SDK release, local materialized-view creation and refresh require a +source build with the `experimental-functions` Cargo feature. Published Python +packages leave it disabled. Opening, reading, listing and dropping existing views +remain available, as do remote Cloud and Enterprise operations. The same feature +requirement applies to local SQL computed-column declaration and refresh; ordinary +eager `add_columns` transforms remain available. + On Cloud and Enterprise, creation accepts `auto_refresh_enabled` and `auto_refresh_interval_seconds`: @@ -443,7 +450,8 @@ view = db.create_materialized_view( Omit `auto_refresh_interval_seconds` to let the server determine when to refresh. These options also apply to asynchronous creation and creation jobs. Embedded -connections support manual refresh and reject automatic scheduling requests. +connections built with `experimental-functions` support manual refresh and reject +automatic scheduling requests. ::: lancedb.materialized_view.MaterializedView diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index c287d42f5..707a929f5 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -8,13 +8,20 @@ availability: oss: available enterprise: available summary: >- - Both offerings support computed columns. Enterprise requires the deployment to enable them; the embedded library evaluates them in your process. + Local computed columns require a source build with the experimental-functions Cargo feature. Enterprise requires the deployment to enable them. --- A computed column is declared with an expression and starts with no values. Declaring it is cheap on any table size, because nothing is evaluated until [a refresh](/feature-engineering/refresh-column) asks for it. + +In the 0.41 SDK release, local computed-column declaration and refresh require a +source build with the `experimental-functions` Cargo feature. Published Python +and TypeScript packages leave it disabled. Remote Cloud and Enterprise operations +do not require this feature. Ordinary eager `add_columns` transforms remain available. + + ## Add a computed column {#declare} ```python diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 1552c3638..30d2d1bc6 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -8,7 +8,7 @@ availability: oss: available enterprise: available summary: >- - Both offerings support materialized views. OSS refreshes run in your process; Enterprise runs the work on remote compute. See [Enterprise refreshes](#availability) for server compatibility requirements. + Local creation and refresh require a source build with the experimental-functions Cargo feature. Enterprise runs the work on remote compute. See [Enterprise refreshes](#availability) for server compatibility requirements. --- import { @@ -20,6 +20,13 @@ A materialized view stores the result of a query as a table. Use it to keep a filtered or transformed dataset that you can query, index and search repeatedly. Refresh the view after its source data changes. + +In the 0.41 SDK release, local materialized-view creation and refresh require a +source build with the `experimental-functions` Cargo feature. Published Python +and TypeScript packages leave it disabled. Opening, reading, listing and dropping +existing views remain available, as do remote Cloud and Enterprise operations. + + In SQL this is [`REFRESH MATERIALIZED VIEW`](/sql/refresh#refresh-materialized-view). diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ce36daa32..1aa511234 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -8,13 +8,20 @@ availability: oss: available enterprise: available summary: >- - Both offerings support column refresh. The embedded library runs it in your process; Enterprise runs it as a server job that must be enabled for your Enterprise cluster. + Local column refresh requires a source build with the experimental-functions Cargo feature. Enterprise runs it as a server job that must be enabled for your Enterprise cluster. --- Refresh a [computed column](/feature-engineering/add-computed-column) to fill new rows and recompute values whose inputs changed. The example below continues with the `doubled` column from the computed-column guide. + +In the 0.41 SDK release, local declaration and refresh require a source build +with the `experimental-functions` Cargo feature. Published Python and TypeScript +packages leave it disabled. Remote Cloud and Enterprise operations do not require +this feature; existing computed-column data remains readable in default builds. + + ```python Python icon="python" table.refresh_column("doubled") diff --git a/nodejs/CONTRIBUTING.md b/nodejs/CONTRIBUTING.md index 2faa8cd37..2125cc8aa 100644 --- a/nodejs/CONTRIBUTING.md +++ b/nodejs/CONTRIBUTING.md @@ -50,6 +50,19 @@ pnpm install pnpm build ``` +Local SQL computed columns and materialized-view creation/refresh are experimental +and disabled in published packages. To opt in when building from this directory: + +```shell +pnpm build:debug --features experimental-functions +pnpm tsc +pnpm test --runInBand table.test.ts materialized_view.test.ts +``` + +Rebuild without `--features experimental-functions` to test the default package. +The tests detect the compiled feature; remote operations, metadata protections, +and ordinary eager `addColumns` transforms remain available in both builds. + Lint: ```shell diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index e8abcf60a..4c86916eb 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -48,3 +48,4 @@ napi-build = "2.3.1" default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] +experimental-functions = ["lancedb/experimental-functions"] diff --git a/nodejs/__test__/experimental_functions.test.ts b/nodejs/__test__/experimental_functions.test.ts new file mode 100644 index 000000000..fdadb092f --- /dev/null +++ b/nodejs/__test__/experimental_functions.test.ts @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { connect } from "../lancedb"; +import { experimentalFunctionsEnabled } from "../lancedb/native"; + +const defaultBuildTest = experimentalFunctionsEnabled() ? it.skip : it; + +defaultBuildTest( + "rejects local Functions before mutating the database", + async () => { + const directory = await mkdtemp(join(tmpdir(), "lancedb-experimental-")); + try { + const db = await connect(directory); + const table = await db.createTable("source", [{ x: 1 }, { x: 2 }]); + const version = await table.version(); + const operations = [ + () => + table.addColumns({ + computed: [{ name: "doubled", valueSql: "x * 2" }], + }), + () => table.refreshColumn("x"), + () => table.refreshColumnAsync("x"), + () => db.createMaterializedView("blocked", "source"), + () => + db.createMaterializedView("blocked", "source", { withNoData: true }), + ]; + for (const operation of operations) { + await expect(operation()).rejects.toThrow("experimental-functions"); + } + expect(await table.version()).toBe(version); + expect(await db.tableNames()).toEqual(["source"]); + await table.addColumns([{ name: "eager", valueSql: "x * 2" }]); + expect((await table.query().toArray()).map((row) => row.eager)).toEqual([ + 2, 4, + ]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }, +); diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index 3852af717..2324e1fcf 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -8,8 +8,10 @@ import { DEFINITION_META_KEY, definitionFromMetadata, } from "../lancedb/materialized_view"; +import { experimentalFunctionsEnabled } from "../lancedb/native"; describe("materialized views", () => { + const experimentalTest = experimentalFunctionsEnabled() ? it : it.skip; let tmpDir: tmp.DirResult; let db: Connection; @@ -69,7 +71,7 @@ describe("materialized views", () => { ); }); - it("creates, refreshes and queries a view", async () => { + experimentalTest("creates, refreshes and queries a view", async () => { const view = await db.createMaterializedView("adults", "people", { select: ["name", ["shout", "upper(name)"]], where: "age >= 18", @@ -81,7 +83,7 @@ describe("materialized views", () => { expect(rows.map((r) => r.shout).sort()).toEqual(["ADA", "GRACE"]); }); - it("round-trips the definition", async () => { + experimentalTest("round-trips the definition", async () => { await db.createMaterializedView("adults", "people", { where: "age >= 18", }); @@ -92,7 +94,7 @@ describe("materialized views", () => { ); }); - it("fully refreshes after an append", async () => { + experimentalTest("fully refreshes after an append", async () => { const view = await db.createMaterializedView("copy", "people", { withNoData: true, }); @@ -108,7 +110,7 @@ describe("materialized views", () => { expect((await view.refresh()).mode).toBe("rebuild"); }); - it("lists views and rejects non-views", async () => { + experimentalTest("lists views and rejects non-views", async () => { await db.createMaterializedView("adults", "people", { where: "age >= 18", }); @@ -124,17 +126,20 @@ describe("materialized views", () => { expect(await collect(db.listMaterializedViews())).toEqual([]); }); - it("returns a job when dropping a view asynchronously", async () => { - await db.createMaterializedView("adults", "people"); + experimentalTest( + "returns a job when dropping a view asynchronously", + async () => { + await db.createMaterializedView("adults", "people"); - const job = await db.dropMaterializedViewAsync("adults"); - expect(job.id).toBeNull(); - expect(job.jobType).toBeNull(); - await job.wait(); - expect(await collect(db.listMaterializedViews())).toEqual([]); - }); + const job = await db.dropMaterializedViewAsync("adults"); + expect(job.id).toBeNull(); + expect(job.jobType).toBeNull(); + await job.wait(); + expect(await collect(db.listMaterializedViews())).toEqual([]); + }, + ); - it("rejects an invalid expression at create time", async () => { + experimentalTest("rejects an invalid expression at create time", async () => { await expect( db.createMaterializedView("bad", "people", { select: [["x", "missing + 1"]], @@ -149,16 +154,21 @@ describe("materialized views", () => { ).rejects.toThrow("non-negative integer"); } expect(await collect(db.listMaterializedViews())).toEqual([]); - - const view = await db.createMaterializedView("copy", "people"); - for (const sourceVersion of [-1, 1.5, Infinity, NaN]) { - await expect(view.refresh({ sourceVersion })).rejects.toThrow( - "non-negative integer", - ); - } }); - it("quotes bare select names", async () => { + experimentalTest( + "rejects invalid source versions before refreshing", + async () => { + const view = await db.createMaterializedView("copy", "people"); + for (const sourceVersion of [-1, 1.5, Infinity, NaN]) { + await expect(view.refresh({ sourceVersion })).rejects.toThrow( + "non-negative integer", + ); + } + }, + ); + + experimentalTest("quotes bare select names", async () => { await db.createTable("odd_names", [{ "order item": "widget" }]); const view = await db.createMaterializedView("quoted", "odd_names", { select: ["order item"], @@ -168,11 +178,14 @@ describe("materialized views", () => { expect(Number(result.rowsWritten)).toBe(1); }); - it("does not require stable row ids on the source", async () => { - await db.createTable("plain", [{ x: 1 }]); - const view = await db.createMaterializedView("v", "plain"); - expect(await view.table().countRows()).toBe(1); - }); + experimentalTest( + "does not require stable row ids on the source", + async () => { + await db.createTable("plain", [{ x: 1 }]); + const view = await db.createMaterializedView("v", "plain"); + expect(await view.table().countRows()).toBe(1); + }, + ); }); async function collect(items: AsyncIterable): Promise { diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index d848676cd..c9e1efcb6 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -47,6 +47,7 @@ import { register, } from "../lancedb/embedding"; import { Index } from "../lancedb/indices"; +import { experimentalFunctionsEnabled } from "../lancedb/native"; import { BooleanQuery, Occur, @@ -5477,13 +5478,14 @@ describe("LSM convergence and stats", () => { }); describe("computed columns", () => { + const experimentalTest = experimentalFunctionsEnabled() ? it : it.skip; let tmpDir: tmp.DirResult; beforeEach(() => { tmpDir = tmp.dirSync({ unsafeCleanup: true }); }); afterEach(() => tmpDir.removeCallback()); - it("declares a column and fills it on refresh", async () => { + experimentalTest("declares a column and fills it on refresh", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed", [{ x: 1 }, { x: 2 }]); @@ -5508,7 +5510,7 @@ describe("computed columns", () => { ); }); - it("returns a job handle from refreshColumnAsync", async () => { + experimentalTest("returns a job handle from refreshColumnAsync", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed_job", [{ x: 1 }, { x: 2 }]); @@ -5530,7 +5532,7 @@ describe("computed columns", () => { ); }); - it("fills rows added since the last refresh", async () => { + experimentalTest("fills rows added since the last refresh", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed_append", [{ x: 1 }]); diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 5f067eeef..80fe2c722 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -270,6 +270,10 @@ export abstract class Connection { /** * Define a materialized view named `name` over the table `source`. * + * Local creation and refresh require a source build with the + * `experimental-functions` Cargo feature, disabled in published packages. + * Remote Cloud/Enterprise operations do not require this feature. + * * The view is populated before creation returns. Set `withNoData` to create * only its definition and empty backing table. The view is a normal table: * it can be queried, indexed and searched, and it appears in `tableNames`. diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts index 7cf1690e0..cc209b14d 100644 --- a/nodejs/lancedb/materialized_view.ts +++ b/nodejs/lancedb/materialized_view.ts @@ -186,6 +186,7 @@ export class MaterializedView { /** * Recompute the view from its source. + * Local refresh requires a source build with `experimental-functions`. * * Every refresh rebuilds the complete view. For local views, * `sourceVersion` refreshes to that source version instead of the latest; diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 4ae1aefb8..4738b6140 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -594,6 +594,10 @@ export abstract class Table { /** * Add new columns with defined values. * + * Local computed-column declaration and refresh require a source build with + * the `experimental-functions` Cargo feature. Published packages disable it; + * remote Cloud/Enterprise operations remain available. + * * The `{ computed }` form stores the expression rather than evaluating it * now: the column is committed with no values, and rows get them from * {@link Table#refreshColumn}. Declaring one therefore costs the same on a @@ -632,6 +636,7 @@ export abstract class Table { /** * Fill the rows of a computed column that hold no value yet. + * Local refresh requires a source build with `experimental-functions`. * * Rows appended since the last refresh are filled by the next one, and * rows whose inputs changed since they were computed are recomputed; @@ -646,6 +651,8 @@ export abstract class Table { /** * Like {@link Table#refreshColumn}, but returns a handle to the refresh * job instead of blocking until it completes. + * Local refresh requires a source build with `experimental-functions`. + * Remote Cloud/Enterprise jobs do not require this feature. * * The job may already be complete when returned; callers must not assume * the column is filled until {@link Job.wait} resolves. Invalid input -- diff --git a/nodejs/src/lib.rs b/nodejs/src/lib.rs index f47bc113e..a92b8db98 100644 --- a/nodejs/src/lib.rs +++ b/nodejs/src/lib.rs @@ -30,6 +30,12 @@ mod session; mod table; mod util; +/// Whether this native binding was built with local experimental Functions. +#[napi] +pub fn experimental_functions_enabled() -> bool { + cfg!(feature = "experimental-functions") +} + #[napi(object)] #[derive(Debug)] pub struct ConnectionOptions { diff --git a/python/CONTRIBUTING.md b/python/CONTRIBUTING.md index 122677364..f86dea706 100644 --- a/python/CONTRIBUTING.md +++ b/python/CONTRIBUTING.md @@ -48,6 +48,18 @@ Build the package make develop ``` +Local SQL computed columns and materialized-view creation/refresh are experimental +and disabled in published packages. To opt in when building from this directory: + +```shell +uv run --extra tests --extra dev maturin develop --features experimental-functions --extras tests,dev +uv run --no-sync pytest python/tests -m experimental_functions +``` + +Rebuild without `--features experimental-functions` to test the default package. +The tests detect the compiled feature; remote operations, metadata protections, +and ordinary eager `add_columns` transforms remain available in both builds. + Format: ```shell diff --git a/python/Cargo.toml b/python/Cargo.toml index b1581b366..f84ab80a3 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -52,3 +52,4 @@ pyo3-build-config = { version = "0.28", features = ["abi3-py310"] } default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] +experimental-functions = ["lancedb/experimental-functions"] diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 1f3cfa9ed..333fca92e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -26,6 +26,8 @@ from lance_namespace import ( from .remote import ClientConfig from .types import BaseTokenizerType +_experimental_functions_enabled: bool + IvfHnswPq: type[HnswPq] = HnswPq IvfHnswSq: type[HnswSq] = HnswSq IvfHnswFlat: type[HnswFlat] = HnswFlat diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b6dfe8fb8..f38608188 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -626,6 +626,10 @@ class DBConnection(EnforceOverrides): ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + Local creation and refresh require a source build with the + ``experimental-functions`` Cargo feature. Published packages leave it + disabled; remote Cloud/Enterprise operations remain available. + The view is populated before creation returns. Pass ``with_no_data=True`` to create only its definition and empty backing table. The view is a normal table: it can be queried, indexed and @@ -1760,6 +1764,10 @@ class LanceDBConnection(DBConnection): auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. + + Local creation and refresh require a source build with the + ``experimental-functions`` Cargo feature. Published packages leave it + disabled; remote Cloud/Enterprise operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. @@ -1769,13 +1777,13 @@ class LanceDBConnection(DBConnection): >>> db = lancedb.connect("./.lancedb") >>> data = [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}] >>> table = db.create_table("people", data) - >>> view = db.create_materialized_view( + >>> view = db.create_materialized_view( # doctest: +SKIP ... "adults", ... "people", ... select=["name", ("shout", "upper(name)")], ... where="age >= 18", ... ) - >>> view.table.count_rows() + >>> view.table.count_rows() # doctest: +SKIP 1 """ LOOP.run( @@ -2846,6 +2854,10 @@ class AsyncConnection(object): auto_refresh_interval_seconds: Optional[float] = None, ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. + + Local creation and refresh require a source build with the + ``experimental-functions`` Cargo feature. Published packages leave it + disabled; remote Cloud/Enterprise operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 6342641ff..8efe31f05 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -2,7 +2,12 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors """Materialized views: tables defined by a query over a source table and -maintained by refresh. See ``DBConnection.create_materialized_view``.""" +maintained by refresh. See ``DBConnection.create_materialized_view``. + +Local creation and refresh require the ``experimental-functions`` Cargo feature +in a source build. Published packages disable it. Opening, reading, listing and +dropping existing views and remote Cloud/Enterprise operations remain available. +""" from __future__ import annotations diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 048c46a6a..6df109d6c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2988,6 +2988,10 @@ class Table(ABC): Function columns are supported only on LanceDB Cloud and Enterprise. computed: Dict[str, str], optional + Local declaration and refresh require a source build with the + ``experimental-functions`` Cargo feature, which published packages + do not enable. Remote Cloud/Enterprise operations remain available. + A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 field inherits Blob v2 semantics; other expressions derive their @@ -3029,11 +3033,11 @@ class Table(ABC): >>> import lancedb >>> db = lancedb.connect("./.lancedb") >>> table = db.create_table("computed_demo", [{"x": 1}, {"x": 2}]) - >>> table.add_columns(computed={"doubled": "x * 2"}) + >>> table.add_columns(computed={"doubled": "x * 2"}) # doctest: +SKIP AddColumnsResult(version=2) - >>> table.refresh_column("doubled") + >>> table.refresh_column("doubled") # doctest: +SKIP RefreshColumnResult(rows_filled=2, version=4) - >>> table.to_arrow().sort_by("x").to_pandas() + >>> table.to_arrow().sort_by("x").to_pandas() # doctest: +SKIP x doubled 0 1 2 1 2 4 @@ -3044,6 +3048,9 @@ class Table(ABC): """ Fill the rows of a computed column that hold no value yet. + Local refresh requires the ``experimental-functions`` Cargo feature + in a source build. Published packages leave it disabled. + Declared with ``add_columns(computed=...)``, a column starts empty and gets its values here. Rows appended since the last refresh are filled by the next one, and rows whose inputs changed since they were computed @@ -3070,6 +3077,9 @@ class Table(ABC): Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. + Local refresh requires a source build with ``experimental-functions``. + Remote Cloud/Enterprise jobs do not require this feature. + The job may already be complete when returned; callers must not assume the column is filled until :meth:`Job.wait` returns. Invalid input -- an unknown column, or one that is not computed -- raises here rather @@ -3087,13 +3097,13 @@ class Table(ABC): >>> import lancedb >>> db = lancedb.connect("./.lancedb") >>> table = db.create_table("computed_job_demo", [{"x": 1}, {"x": 2}]) - >>> table.add_columns(computed={"doubled": "x * 2"}) + >>> table.add_columns(computed={"doubled": "x * 2"}) # doctest: +SKIP AddColumnsResult(version=2) - >>> job = table.refresh_column_async("doubled") - >>> result = job.wait() - >>> result.rows_assigned + >>> job = table.refresh_column_async("doubled") # doctest: +SKIP + >>> result = job.wait() # doctest: +SKIP + >>> result.rows_assigned # doctest: +SKIP 2 - >>> job.status() + >>> job.status() # doctest: +SKIP 'finished' """ @@ -7195,6 +7205,10 @@ class AsyncTable: Function columns are supported only on LanceDB Cloud and Enterprise. computed: Dict[str, str], optional + Local declaration and refresh require a source build with the + ``experimental-functions`` Cargo feature, which published packages + do not enable. Remote Cloud/Enterprise operations remain available. + A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 field inherits Blob v2 semantics; other expressions derive their @@ -7314,6 +7328,9 @@ class AsyncTable: """ Fill the rows of a computed column that hold no value yet. + Local refresh requires the ``experimental-functions`` Cargo feature + in a source build. Published packages leave it disabled. + Declared with ``add_columns(computed=...)``, a column starts empty and gets its values here. Rows appended since the last refresh are filled by the next one, and rows whose inputs changed since they were computed @@ -7384,6 +7401,9 @@ class AsyncTable: Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. + Local refresh requires a source build with ``experimental-functions``. + Remote Cloud/Enterprise jobs do not require this feature. + The job may already be complete when returned; callers must not assume the column is filled until :meth:`AsyncJob.wait` resolves. Invalid input -- an unknown column, or one that is not computed -- raises here @@ -7409,7 +7429,7 @@ class AsyncTable: ... result = await job.wait() ... assert result.rows_assigned == 1 ... return await job.status() - >>> asyncio.run(refresh_in_background()) + >>> asyncio.run(refresh_in_background()) # doctest: +SKIP 'finished' """ return _typed_job( diff --git a/python/python/tests/conftest.py b/python/python/tests/conftest.py index 8567a9830..86c4f00bb 100644 --- a/python/python/tests/conftest.py +++ b/python/python/tests/conftest.py @@ -9,6 +9,21 @@ import pytest import pytest_asyncio +def pytest_configure(config): + config.addinivalue_line( + "markers", "experimental_functions: requires the experimental-functions build" + ) + + +def pytest_collection_modifyitems(items): + if lancedb._lancedb._experimental_functions_enabled: + return + skip = pytest.mark.skip(reason="requires the experimental-functions Cargo feature") + for item in items: + if item.get_closest_marker("experimental_functions"): + item.add_marker(skip) + + def pandas_string_type(): """Return the PyArrow string type that pandas uses for string columns. diff --git a/python/python/tests/test_experimental_functions.py b/python/python/tests/test_experimental_functions.py new file mode 100644 index 000000000..81de84606 --- /dev/null +++ b/python/python/tests/test_experimental_functions.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +import pytest + +pytestmark = pytest.mark.skipif( + lancedb._lancedb._experimental_functions_enabled, + reason="tests the default build without experimental-functions", +) + + +@pytest.mark.parametrize("namespace", [False, True]) +def test_default_build_rejects_local_functions(tmp_path, namespace): + db = ( + lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + if namespace + else lancedb.connect(tmp_path) + ) + table = db.create_table("source", [{"x": 1}, {"x": 2}]) + version = table.version + operations = [ + lambda: table.add_columns(computed={"doubled": "x * 2"}), + lambda: table.refresh_column("x"), + lambda: table.refresh_column_async("x"), + lambda: db.create_materialized_view("blocked", "source"), + lambda: db.create_materialized_view("blocked", "source", with_no_data=True), + lambda: db.create_materialized_view_async("blocked", "source"), + ] + for operation in operations: + with pytest.raises(NotImplementedError, match="experimental-functions"): + operation() + assert table.version == version + assert db.table_names() == ["source"] + table.add_columns({"eager": "x * 2"}) + assert table.to_arrow()["eager"].to_pylist() == [2, 4] + + +@pytest.mark.asyncio +async def test_async_default_build_rejects_local_functions(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("source", [{"x": 1}, {"x": 2}]) + version = await table.version() + operations = [ + lambda: table.add_columns(computed={"doubled": "x * 2"}), + lambda: table.refresh_column("x"), + lambda: table.refresh_column_async("x"), + lambda: db.create_materialized_view("blocked", "source"), + lambda: db.create_materialized_view("blocked", "source", with_no_data=True), + lambda: db.create_materialized_view_async("blocked", "source"), + ] + for operation in operations: + with pytest.raises(NotImplementedError, match="experimental-functions"): + await operation() + assert await table.version() == version + assert await db.table_names() == ["source"] + await table.add_columns({"eager": "x * 2"}) + assert (await table.query().to_arrow())["eager"].to_pylist() == [2, 4] diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index e2be9c0d4..337fcad78 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -173,6 +173,7 @@ def test_sync_remote_create_uses_public_async_connection(): assert calls[-1] == ("drop", "adults", ["analytics"]) +@pytest.mark.experimental_functions def test_create_refresh_and_query(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view( @@ -188,6 +189,7 @@ def test_create_refresh_and_query(tmp_path): assert sorted(row["shout"] for row in rows) == ["ADA", "GRACE"] +@pytest.mark.experimental_functions def test_create_and_refresh_jobs(tmp_path): db = make_db(tmp_path) create_job = db.create_materialized_view_async( @@ -212,6 +214,7 @@ def test_create_and_refresh_jobs(tmp_path): assert "adults" not in list(db.list_materialized_views()) +@pytest.mark.experimental_functions def test_definition_round_trips(tmp_path): db = make_db(tmp_path) db.create_materialized_view("adults", "people", where="age >= 18") @@ -222,6 +225,7 @@ def test_definition_round_trips(tmp_path): ) +@pytest.mark.experimental_functions def test_full_refresh_after_append(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("copy", "people", with_no_data=True) @@ -236,6 +240,7 @@ def test_full_refresh_after_append(tmp_path): assert view.refresh().mode == "rebuild" +@pytest.mark.experimental_functions def test_full_refresh_after_update(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("copy", "people", with_no_data=True) @@ -249,6 +254,7 @@ def test_full_refresh_after_update(tmp_path): assert sorted(row["age"] for row in rows) == [8, 36, 85] +@pytest.mark.experimental_functions def test_legacy_storage_source_update_rebuilds(tmp_path): db = lancedb.connect( tmp_path, @@ -265,6 +271,7 @@ def test_legacy_storage_source_update_rebuilds(tmp_path): assert sorted(row["age"] for row in rows) == [8, 36] +@pytest.mark.experimental_functions def test_direct_writes_to_a_view_are_refused(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("copy", "people") @@ -290,6 +297,7 @@ def test_direct_writes_to_a_view_are_refused(tmp_path): assert view.refresh().rows_written == 4 +@pytest.mark.experimental_functions def test_list_and_not_a_view(tmp_path): db = make_db(tmp_path) db.create_materialized_view("adults", "people", where="age >= 18") @@ -304,6 +312,7 @@ def test_list_and_not_a_view(tmp_path): assert list(db.list_materialized_views()) == [] +@pytest.mark.experimental_functions def test_invalid_expression_fails_at_create(tmp_path): db = make_db(tmp_path) with pytest.raises(Exception, match="missing"): @@ -311,6 +320,7 @@ def test_invalid_expression_fails_at_create(tmp_path): assert "bad" not in db.list_tables().tables +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_create_refresh_and_open(tmp_path): db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) @@ -332,6 +342,7 @@ async def test_async_create_refresh_and_open(tmp_path): assert [item async for item in db.list_materialized_views()] == ["shouts"] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_create_and_refresh_jobs(tmp_path): db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) @@ -358,6 +369,7 @@ async def test_async_create_and_refresh_jobs(tmp_path): assert "adults" not in [item async for item in db.list_materialized_views()] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_refresh_rebuilds(tmp_path): db = await lancedb.connect_async(tmp_path) @@ -372,6 +384,7 @@ async def test_async_refresh_rebuilds(tmp_path): assert result.rows_written == 2 +@pytest.mark.experimental_functions def test_source_does_not_require_stable_row_ids(tmp_path): db = lancedb.connect(tmp_path) db.create_table("plain", [{"x": 1}]) @@ -379,6 +392,7 @@ def test_source_does_not_require_stable_row_ids(tmp_path): assert view.table.count_rows() == 1 +@pytest.mark.experimental_functions def test_bare_select_names_are_quoted(tmp_path): db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) db.create_table("odd_names", [{"order item": "widget", "select": 2}]) @@ -396,6 +410,7 @@ def test_bare_select_names_are_quoted(tmp_path): assert rows[0]["select"] == 2 +@pytest.mark.experimental_functions def test_scalar_select_is_one_column(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("just_name", "people", select="name") @@ -405,6 +420,7 @@ def test_scalar_select_is_one_column(tmp_path): assert sorted(row["name"] for row in rows) == ["ada", "grace", "kid"] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_scalar_select_is_one_column(tmp_path): db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) @@ -415,6 +431,7 @@ async def test_async_scalar_select_is_one_column(tmp_path): assert set(rows[0]) == {"name"} +@pytest.mark.experimental_functions def test_limit_above_i64_max_is_refused(tmp_path): db = make_db(tmp_path) with pytest.raises(ValueError, match="exceeds the maximum"): @@ -434,6 +451,7 @@ def _namespace_db(tmp_path): ) +@pytest.mark.experimental_functions def test_namespace_connection_materialized_views(tmp_path): db = _namespace_db(tmp_path) db.create_table( @@ -464,6 +482,7 @@ def test_namespace_connection_materialized_views(tmp_path): assert list(db.list_materialized_views()) == [] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_namespace_connection_materialized_views(tmp_path): db = lancedb.connect_namespace_async( @@ -557,6 +576,7 @@ def test_stored_queries_and_legacy_layouts_are_read(): read(newer) +@pytest.mark.experimental_functions def test_local_materialized_view_listing_pages_and_resume(tmp_path): db = make_db(tmp_path) db.create_materialized_view("a_view", "people", with_no_data=True) @@ -646,6 +666,7 @@ async def test_async_remote_create_keeps_interval_unspecified(): assert native.calls[0][2]["auto_refresh_interval_seconds"] is None +@pytest.mark.experimental_functions @pytest.mark.parametrize( "options", [ @@ -673,12 +694,14 @@ def test_remote_create_rejects_invalid_interval_without_request(seconds): assert requests == [] +@pytest.mark.experimental_functions def test_namespace_forwards_automatic_refresh_request(tmp_path): db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) with pytest.raises(NotImplementedError, match="Cloud or Enterprise"): db.create_materialized_view("mv", "source", auto_refresh_enabled=True) +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_namespace_forwards_automatic_refresh_request(tmp_path): db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) @@ -686,6 +709,7 @@ async def test_async_namespace_forwards_automatic_refresh_request(tmp_path): await db.create_materialized_view("mv", "source", auto_refresh_enabled=True) +@pytest.mark.experimental_functions def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False) diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index b55da4d57..c70ba3d8e 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -16,6 +16,7 @@ import pyarrow as pa import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from lancedb.listing import AsyncListing, Listing +from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY from lancedb.namespace import _MAX_QUERY_K, _query_to_namespace_request from lancedb.query import Query from lancedb.table import AsyncTable, LanceTable @@ -359,7 +360,17 @@ class TestNamespaceConnection: def test_list_materialized_views(self): db = lancedb.connect_namespace("dir", {"root": self.temp_dir}) db.create_table("source", [{"id": 1}]) - db.create_materialized_view("view", "source", with_no_data=True) + # Model a stored view from an enabled build: listing must also work + # when local creation is disabled in the current build. + schema = pa.schema( + [("id", pa.int64())], + metadata={ + DEFINITION_META_KEY: json.dumps( + {"format": DEFINITION_FORMAT, "query": "SELECT id FROM source"} + ).encode() + }, + ) + db.create_table("view", schema=schema) names = db.list_materialized_views(page_limit=1) assert isinstance(names, Listing) @@ -872,7 +883,16 @@ class TestAsyncNamespaceConnection: async def test_list_materialized_views(self): db = lancedb.connect_namespace_async("dir", {"root": self.temp_dir}) await db.create_table("source", [{"id": 1}]) - await db.create_materialized_view("view", "source", with_no_data=True) + # Model a stored view independently of the local creation feature. + schema = pa.schema( + [("id", pa.int64())], + metadata={ + DEFINITION_META_KEY: json.dumps( + {"format": DEFINITION_FORMAT, "query": "SELECT id FROM source"} + ).encode() + }, + ) + await db.create_table("view", schema=schema) names = db.list_materialized_views(page_limit=1) assert isinstance(names, AsyncListing) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 458f419ae..21fce93d3 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5489,6 +5489,7 @@ async def test_async_search_runs_embedding_on_dedicated_executor( ) +@pytest.mark.experimental_functions def test_computed_column_declare_and_refresh(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("computed", [{"x": 1}, {"x": 2}]) @@ -5512,6 +5513,7 @@ def test_computed_column_rejects_transforms_and_computed_together(tmp_path): table.add_columns({"a": "x + 1"}, computed={"b": "x * 2"}) +@pytest.mark.experimental_functions def test_computed_column_blob_projection_inherits_semantics(tmp_path): schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) db = lancedb.connect(tmp_path) @@ -5535,6 +5537,7 @@ def test_computed_column_blob_projection_inherits_semantics(tmp_path): assert copied.to_pylist() == [b"hello", b"", None] +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_computed_column_async(tmp_path): db = await lancedb.connect_async(tmp_path) @@ -5553,6 +5556,7 @@ def test_function_errors_are_remote_only(tmp_path): table.function_errors() +@pytest.mark.experimental_functions def test_refresh_column_async_returns_job(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("computed_job", [{"x": 1}, {"x": 2}]) @@ -5581,6 +5585,7 @@ def test_refresh_column_async_returns_job(tmp_path): table.refresh_column_async("x") +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_refresh_column_async_job_async_table(tmp_path): db = await lancedb.connect_async(tmp_path) @@ -5597,6 +5602,7 @@ async def test_refresh_column_async_job_async_table(tmp_path): assert (await table.to_arrow())["tripled"].to_pylist() == [9] +@pytest.mark.experimental_functions @pytest.mark.parametrize("interval", [None, 300]) def test_computed_auto_refresh_options(tmp_path, interval): db = lancedb.connect(tmp_path) @@ -5635,6 +5641,7 @@ def test_auto_refresh_options_require_computed_columns(tmp_path): table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True) +@pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_computed_auto_refresh_uses_server_interval(tmp_path): db = await lancedb.connect_async(tmp_path) diff --git a/python/src/lib.rs b/python/src/lib.rs index 3814f2caf..71662add1 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -132,6 +132,10 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(expr_lit, m)?)?; m.add_function(wrap_pyfunction!(expr_func, m)?)?; m.add("__version__", env!("CARGO_PKG_VERSION"))?; + m.add( + "_experimental_functions_enabled", + cfg!(feature = "experimental-functions"), + )?; // Give the shared runtime a coordinated, bounded shutdown at normal // process exit -- see `shutdown_runtime` and `runtime::shutdown` for why. py.import("atexit")? diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 9015bcdd7..62029bb92 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -137,6 +137,9 @@ pprof = { version = "0.14", features = ["flamegraph"] } [features] default = [] +# Local SQL computed columns and materialized-view creation/refresh. +# Remote clients and shared server primitives do not require this feature. +experimental-functions = [] # Native spatial indexes and queries. Remote RTree requests do not require this feature. geo = ["lance/geo"] aws = [ diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 68521ff2c..8b1ad97c3 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -31,6 +31,11 @@ //! - `gcs` - Enable Google Cloud Storage object store support. //! - `oss` - Enable Alibaba Cloud OSS object store support. //! - `remote` - Enable remote client to connect to LanceDB cloud. +//! - `experimental-functions` - Opt in to local SQL computed-column declarations +//! and refresh, and local materialized-view creation and refresh. Disabled by +//! default, including in published Python and TypeScript packages. Remote +//! Cloud/Enterprise operations, reading existing data, metadata protections, +//! and ordinary eager `add_columns` transforms do not require this feature. //! - `huggingface` - Enable HuggingFace Hub integration for loading datasets from the Hub. //! - `fp16kernels` - Enable FP16 kernels for faster vector search on CPU. //! - `metrics` - Publish LanceDB's internal metrics through the @@ -229,6 +234,19 @@ pub use materialized_view::{ pub use metrics; pub use table::{FtsToken, Table}; +/// Gate local execution without hiding client types or metadata protections. +pub(crate) fn require_experimental_functions() -> Result<()> { + if !cfg!(feature = "experimental-functions") { + return Err(Error::NotSupported { + message: "local computed columns and materialized-view creation/refresh require \ + building LanceDB with the 'experimental-functions' Cargo feature; \ + official Python and TypeScript packages do not enable it" + .into(), + }); + } + Ok(()) +} + /// Tokenize a full-text search query using an explicit FTS tokenizer configuration. /// /// This does not require a table or FTS index. The tokenizer options are the diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 7ee76a160..b7124d930 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -9,6 +9,11 @@ //! query this version cannot maintain reads back as unrefreshable, not as a //! plain table. Queries, indexes and search work on the view unchanged; //! writes to its rows or stored columns are refused. +//! +//! Local creation and refresh require the `experimental-functions` Cargo +//! feature. Opening, reading, listing and dropping existing views, remote +//! client operations, and shared server commit primitives remain available +//! without it. mod grouped; pub use grouped::IVF_PARTITION; @@ -1245,6 +1250,7 @@ impl PreparedDeclaration { namespace_path: &[String], name: &str, ) -> Result { + crate::require_experimental_functions()?; ensure_no_source_cycle(&self.database, namespace_path, name, &self.definition).await?; let empty: Vec> = vec![]; @@ -1733,6 +1739,7 @@ impl CreateMaterializedViewBuilder { }) .await; } + crate::require_experimental_functions()?; Ok(Job::spawned(tokio::spawn(async move { self.execute_native().await.map(|_| ()) }))) @@ -1756,6 +1763,7 @@ impl CreateMaterializedViewBuilder { } async fn execute_native(self) -> Result { + crate::require_experimental_functions()?; if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { return Err(Error::NotSupported { message: "automatic materialized-view refresh requires Cloud or Enterprise" @@ -1879,6 +1887,7 @@ impl RefreshMaterializedViewBuilder { .refresh_materialized_view_async(self.source_version) .await; } + crate::require_experimental_functions()?; Ok(Job::spawned(tokio::spawn(async move { refresh::execute_refresh(&self.view.table, self.source_version).await }))) @@ -2061,6 +2070,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn refresh_always_rebuilds_without_source_row_ids() { let conn = connect("memory://").execute().await.unwrap(); let source = conn @@ -2124,6 +2137,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn a_view_cannot_lead_back_to_itself() { let conn = connect("memory://").execute().await.unwrap(); let rows = || record_batch!(("x", Int32, [1, 2])).unwrap(); @@ -2159,6 +2176,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn direct_writes_to_a_view_are_refused() { use arrow_schema::Schema; use datafusion::prelude::SessionContext; @@ -2295,6 +2316,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn indexes_and_optimize_still_apply_to_a_view() { use crate::index::Index; use crate::table::{CompactionOptions, OptimizeAction}; @@ -2339,6 +2364,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn computed_columns_of_a_view_are_still_filled_and_dropped() { use crate::table::computed_columns::{ COMPUTED_COLUMN_META_KEY, EXPRESSION_META_KEY, INPUTS_META_KEY, KIND_META_KEY, SQL_KIND, diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 6b4bb6d8a..1186ac576 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -72,6 +72,7 @@ pub(crate) async fn execute_refresh( view: &Table, pinned: Option, ) -> Result { + crate::require_experimental_functions()?; let native = view.as_native().ok_or_else(|| Error::NotSupported { message: "materialized views are supported only on local tables".into(), })?; @@ -576,6 +577,10 @@ mod tests { use crate::connect; #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn raced_first_full_refresh_lands_one_result() { let directory = tempfile::tempdir().unwrap(); let connection = connect(directory.path().to_str().unwrap()) diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 4f9cbb772..0f13718fd 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -69,6 +69,9 @@ impl AddColumnsBuilder { /// renamed, retyped or dropped while a declaration reads it, since the /// expression names it. /// + /// Local declaration and refresh require the `experimental-functions` + /// Cargo feature. Remote operations do not require this feature. + /// /// On LanceDB Cloud and Enterprise the expression is planned by the /// server, and the refresh runs as a server job -- see /// [`Table::refresh_column_async`](super::Table::refresh_column_async). @@ -252,6 +255,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn computed_options_commit_with_declaration() { let table = table_with_two_columns("options").await; let version = table.version().await.unwrap(); @@ -313,6 +320,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn omitted_refresh_interval_stays_unset() { let table = table_with_two_columns("server_interval").await; let version = table.version().await.unwrap(); diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index fe4c17b1f..942c43d4e 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -2631,6 +2631,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_declare_infers_type_and_inputs() { let table = table_with_ints("declare_infers").await; let initial = table.version().await.unwrap(); @@ -2698,6 +2702,10 @@ mod tests { /// The binding reaches the schema only if `AllNulls` carries per-field /// metadata through the commit. The whole representation rests on it. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_all_nulls_preserves_field_metadata() { let table = table_with_ints("metadata_survives").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -2722,6 +2730,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_declared_column_is_all_null() { let table = table_with_ints("declare_is_null").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -2746,6 +2758,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unknown_column_fails_at_declare_time() { let table = table_with_ints("unknown_input").await; let err = add_computed(&table, &[("bad".into(), "missing + 1".into())]) @@ -2758,6 +2774,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unparsable_expression_fails_at_declare_time() { let table = table_with_ints("bad_syntax").await; let err = add_computed(&table, &[("bad".into(), "x *".into())]) @@ -2778,6 +2798,10 @@ mod tests { /// resolution is missing. When a registry-aware planner exists this /// becomes a supported declaration rather than a new API. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unregistered_function_is_rejected_for_now() { let table = table_with_ints("udf_not_yet").await; let err = add_computed(&table, &[("vec".into(), "embed(x)".into())]) @@ -2795,6 +2819,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_existing_column_name_is_rejected() { let table = table_with_ints("name_taken").await; let err = add_computed(&table, &[("x".into(), "x * 2".into())]) @@ -2805,6 +2833,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_constant_expression_needs_no_inputs() { let table = table_with_ints("constant").await; add_computed(&table, &[("answer".into(), "42".into())]) @@ -2817,6 +2849,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_multiple_columns_in_one_commit() { let table = table_with_ints("multi").await; let initial = table.version().await.unwrap(); @@ -2839,6 +2875,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_duplicate_declaration_in_one_call_is_rejected() { let table = table_with_ints("dupe").await; let err = add_computed( @@ -2857,6 +2897,10 @@ mod tests { /// A batch may build on itself: one commit, and the later entry's inputs /// name the earlier one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_declaration_may_read_one_declared_before_it() { let table = table_with_ints("chain").await; let before = table.version().await.unwrap(); @@ -2909,6 +2953,10 @@ mod tests { /// Built-in functions type the column the same way an operator does. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_builtin_function_inference() { let conn = connect("memory://").execute().await.unwrap(); let batch = record_batch!(("name", Utf8, ["ada", "grace"]), ("n", Int32, [-1, 2])).unwrap(); @@ -2959,6 +3007,10 @@ mod tests { /// an ordinary column. Reported as absent it would be refreshable by /// nothing and redeclarable over, silently. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unrecognized_kind_is_reported_rather_than_hidden() { let table = table_with_ints("foreign_kind").await; super::add_foreign_kind(&table, "embedding", "udf").await; @@ -3002,6 +3054,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_inputs_are_deduplicated_and_sorted() { let conn = connect("memory://").execute().await.unwrap(); let batch = record_batch!(("b", Int32, [1, 2]), ("a", Int32, [3, 4])).unwrap(); @@ -3018,6 +3074,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dropping_an_input_is_refused() { let table = table_with_ints("drop_input").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -3032,6 +3092,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_renaming_an_input_is_refused() { let table = table_with_ints("rename_input").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -3050,6 +3114,10 @@ mod tests { /// Nothing resolves against nullability, so it is not a rebinding. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_altering_an_input_nullability_is_allowed() { let table = table_with_ints("nullable_input").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -3066,6 +3134,10 @@ mod tests { /// the counting and writing passes, so the declared value is incoherent. /// Refused at declare time. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_volatile_expression_is_refused() { let table = table_with_ints("volatile_expr").await; let err = add_computed(&table, &[("maybe".into(), "random() < 0.5".into())]) @@ -3082,6 +3154,10 @@ mod tests { /// constant, but the stored SQL still names `x`, so the recorded inputs /// must too -- otherwise dropping `x` is allowed and refresh breaks. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_inputs_survive_expression_optimization() { let table = table_with_ints("optimized_inputs").await; add_computed(&table, &[("flag".into(), "true OR x > 0".into())]) @@ -3099,6 +3175,10 @@ mod tests { /// The gate's reproducer: casting a computed column rewrites the field /// without its metadata, silently destroying the declaration. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_retyping_the_computed_column_is_refused() { use arrow_schema::DataType as ArrowDataType; @@ -3123,6 +3203,10 @@ mod tests { /// A declaration cannot be edited, fabricated or erased through field /// metadata: it is validated as a whole at declare time. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_declaration_metadata_is_immutable() { use crate::table::FieldMetadataUpdate; @@ -3170,6 +3254,10 @@ mod tests { /// The gate's reproducer: only refresh materializes a declared column; /// a direct write would store an arbitrary durable value. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_computed_column_cannot_be_written_directly() { let table = table_with_ints("direct_write").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -3211,6 +3299,10 @@ mod tests { /// The gate's reproducer: the reciprocal of the declare-under-spec check. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_installing_an_lsm_spec_over_computed_columns_is_refused() { use crate::table::RTEWriteSpec; @@ -3279,6 +3371,10 @@ mod tests { /// The gate's reproducer: SQL INSERT is a write path too. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_sql_insert_cannot_write_a_computed_column() { use datafusion::prelude::SessionContext; @@ -3378,6 +3474,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_sql_insert_omitting_computed_is_allowed() { use datafusion::prelude::SessionContext; @@ -3404,6 +3504,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_nested_computed_field_cannot_be_renamed() { let table = table_with_ints("computed_struct_rename").await; add_computed(&table, &[("payload".into(), "named_struct('a', x)".into())]) @@ -3422,6 +3526,10 @@ mod tests { /// Stale handles must not commit the computed/RTE state in either order. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_stale_handles_cannot_mix_computed_and_lsm() { use crate::table::RTEWriteSpec; @@ -3472,6 +3580,10 @@ mod tests { /// unset, retained SSTable rows survive without a live spec. The catch-up /// flag is the durable marker; declaration refuses on it. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_unset_with_retained_lsm_rows_cannot_admit_a_declaration() { use crate::table::RTEWriteSpec; use arrow_array::{Int64Array, RecordBatchIterator}; @@ -3523,6 +3635,10 @@ mod tests { /// A declaration does not read itself, so it travels with its binding. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dropping_the_computed_column_is_allowed() { let table = table_with_ints("drop_computed").await; add_computed(&table, &[("doubled".into(), "x * 2".into())]) @@ -4663,6 +4779,10 @@ mod tests { /// downstream binding's immutable input schema must not record them, or /// the first upstream refresh strands the table. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_computed_input_survives_upstream_refresh() { use arrow_array::{Int32Array, Int64Array, RecordBatch}; diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 8f7f576ff..c5eadeeaf 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -77,6 +77,7 @@ pub(crate) async fn execute_refresh_column( table: &NativeTable, column: &str, ) -> Result { + crate::require_experimental_functions()?; Ok(execute_refresh_column_with_source(table, column) .await? .result) @@ -300,6 +301,7 @@ pub(crate) async fn execute_refresh_column_async( table: &NativeTable, column: &str, ) -> Result> { + crate::require_experimental_functions()?; // Validate before spawning so bad input is reported by this call rather // than only by the job. table.dataset.ensure_mutable()?; @@ -731,6 +733,10 @@ mod tests { /// must not bake zeros from `a`'s placeholder null. It is refused, and /// names the input, until `a` is filled -- after every append too. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dependent_refresh_refuses_an_unfilled_input() { let table = table_with("dependent_refresh_order", vec![1, 2, 3]).await; table @@ -766,6 +772,10 @@ mod tests { /// declaration metadata and the dependency check: the recorded inputs /// are matched by name, never re-parsed as SQL. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_dependent_refresh_handles_awkward_column_names() { use arrow_array::{Int32Array, StructArray}; use arrow_schema::{DataType, Field, Fields}; @@ -820,6 +830,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_fills_a_declared_column() { let table = table_with("refresh_fills", vec![1, 2, 3]).await; let declared = declare_doubled(&table).await.unwrap(); @@ -848,6 +862,10 @@ mod tests { /// Values written after the last refresh must be reachable by another one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_fills_rows_appended_since_the_last_refresh() { let table = table_with("refresh_appended", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -868,6 +886,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_with_nothing_to_fill() { let table = table_with("refresh_noop", vec![1, 2, 3]).await; declare_doubled(&table).await.unwrap(); @@ -884,6 +906,10 @@ mod tests { /// A branch inherits the freshness main recorded: its first refresh /// fills nothing, and only its own appends after that. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_branch_inherits_freshness() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -919,6 +945,10 @@ mod tests { /// A shallow clone inherits the freshness its source recorded. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_shallow_clone_inherits_freshness() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -953,6 +983,10 @@ mod tests { /// settles at once instead of re-selecting the same rows forever: the /// second refresh finds the fragment signed and moves nothing. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_converges_on_a_null_result() { let table = table_with("refresh_null_result", vec![1, 2, 3]).await; let declared = table @@ -976,6 +1010,10 @@ mod tests { /// A filled row whose input moved is recomputed: the update rewrites /// the row into a fragment the stamp never signed, and only that one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_recomputes_a_row_whose_input_moved() { let table = table_with("refresh_mutation", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1009,6 +1047,10 @@ mod tests { /// Each stamp is a sidecar under `_computed/`; pruning old versions /// removes the sidecars only they referenced, and keeps the current one. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_pruning_drops_the_sidecars_of_pruned_versions() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -1050,6 +1092,10 @@ mod tests { /// Absolute timestamp pruning applies the same computed-column sidecar /// cleanup as duration-based pruning. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_absolute_pruning_drops_the_sidecars_of_pruned_versions() { let dir = tempfile::tempdir().unwrap(); let conn = connect(dir.path().to_str().unwrap()) @@ -1087,6 +1133,10 @@ mod tests { /// A deleted row is never computed and the rows that stay keep their /// values: a delete recomputes nothing and stamps nothing. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_delete_recomputes_nothing() { let table = table_with("refresh_delete", vec![1, 2, 3]).await; declare_doubled(&table).await.unwrap(); @@ -1106,6 +1156,10 @@ mod tests { /// signed ones is fresh: the refresh recomputes nothing and only records /// the new fragment. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_compaction_of_signed_fragments_recomputes_nothing() { let table = table_with("refresh_compact_signed", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1136,6 +1190,10 @@ mod tests { /// refresh keeps the null-fill contract and enrolls what it read from; /// from then on a moved input is recomputed like any other. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_an_unsigned_column_is_enrolled_by_its_first_refresh() { let table = table_with("refresh_legacy", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1188,6 +1246,10 @@ mod tests { /// column as null behind a covering data file. Those rows are still /// unfilled and a later refresh has to reach them. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_update_before_the_first_refresh() { let table = table_with("refresh_update_first", vec![1]).await; declare_doubled(&table).await.unwrap(); @@ -1203,6 +1265,10 @@ mod tests { /// for any of its rows: every live row is recomputed, the moved one /// included. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_compaction_of_an_unsigned_fragment_recomputes_it() { let table = table_with("refresh_mixed", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1236,6 +1302,10 @@ mod tests { /// computed column. Compaction cannot certify it, so the product is /// recomputed and the supplied value replaced. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_raw_append_values_are_not_trusted_after_compaction() { use arrow_array::RecordBatchIterator; use lance::Dataset; @@ -1288,6 +1358,10 @@ mod tests { /// An appended fragment holds no values, so compacting it into a signed /// one leaves the product fresh: only the appended rows are filled. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_compaction_with_an_appended_fragment_fills_only_its_rows() { let table = table_with("refresh_preserves", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1311,6 +1385,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_leaves_deleted_rows_alone() { let table = table_with("refresh_deleted", vec![1, 2, 3, 4]).await; declare_doubled(&table).await.unwrap(); @@ -1325,6 +1403,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_a_constant_expression() { let table = table_with("refresh_constant", vec![1, 2, 3]).await; table @@ -1341,6 +1423,10 @@ mod tests { /// A name needing quotes reaches the evaluator intact: it is carried as a /// projection alias, never spliced into SQL text. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_a_column_whose_name_needs_quoting() { let table = table_with("refresh_quoted", vec![1, 2, 3]).await; table @@ -1362,6 +1448,10 @@ mod tests { /// the probe buffers only until the first gained value and the rest flows /// through write_columns a batch at a time. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_streams_a_multi_batch_fragment() { let values: Vec = (0..20_000).collect(); let table = table_with("refresh_multi_batch", values.clone()).await; @@ -1381,6 +1471,10 @@ mod tests { /// The gate's reproducer: the commit must reuse the configured session, /// or registrations and caches vanish from the handle after a refresh. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_preserves_the_configured_session() { let session = Arc::new(lance::session::Session::default()); let conn = crate::connect("memory://") @@ -1404,6 +1498,10 @@ mod tests { /// The async form's job settles with the fill visible, like /// create_index's execute_async. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_async_job_waits_for_the_fill() { let table = table_with("refresh_async", vec![1, 2, 3]).await; declare_doubled(&table).await.unwrap(); @@ -1426,6 +1524,10 @@ mod tests { /// Bad input is reported by the call, not by the job. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_async_rejects_bad_input_before_spawning() { let table = table_with("refresh_async_bad", vec![1, 2, 3]).await; @@ -1437,6 +1539,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_async_job_reports_success_to_every_waiter() { let table = table_with("refresh_async_waiters", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); @@ -1449,6 +1555,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_rejects_a_plain_column() { let table = table_with("refresh_plain", vec![1, 2, 3]).await; let err = table.refresh_column("x").await.unwrap_err(); @@ -1456,6 +1566,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_rejects_an_unknown_column() { let table = table_with("refresh_missing", vec![1, 2, 3]).await; let err = table.refresh_column("nope").await.unwrap_err(); @@ -1465,6 +1579,10 @@ mod tests { /// The gate's reproducer: a poison value in a deleted row must not /// abort filling the live rows, since nobody can read it. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_deleted_rows_value_is_never_evaluated() { let table = table_with("refresh_deleted_poison", vec![1, 0]).await; table @@ -1484,6 +1602,10 @@ mod tests { /// input did not move is not: the untouched fragment is never read, so /// its poison input is never reached. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_only_a_moved_rows_value_is_re_evaluated() { let table = table_with("refresh_filled_poison", vec![1, 0]).await; table @@ -1515,6 +1637,10 @@ mod tests { /// The gate's reproducer: the old internal projection alias is an /// ordinary column name; a computed column may use it. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_a_column_named_like_the_old_alias() { let table = table_with("refresh_alias_name", vec![1, 2]).await; table @@ -1537,6 +1663,10 @@ mod tests { /// this pins behaviorally; the memory bound is structural -- the fill /// stream retains no batches at all. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_fills_a_late_gain_fragment() { let values: Vec = (0..20_000).collect(); let table = table_with("refresh_late_gain", values).await; @@ -1562,6 +1692,10 @@ mod tests { /// The gate's reproducer: a nested input declares, refreshes, and guards /// its root against invalidating schema changes. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_a_nested_input_declares_and_refreshes() { use arrow_array::{Int32Array, StructArray}; use arrow_schema::{DataType, Field, Fields}; @@ -1636,6 +1770,10 @@ mod tests { /// schema_evolution tests); refresh's own check covers a dataset another /// writer left in that state. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_refuses_a_foreign_lsm_state() { use crate::table::RTEWriteSpec; @@ -1669,6 +1807,10 @@ mod tests { /// After catch-up activation and unset, no spec remains but the catch-up /// flag still marks retained SSTable rows; refresh refuses on the flag. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_refuses_retained_catchup_state() { use crate::table::RTEWriteSpec; @@ -1719,6 +1861,10 @@ mod tests { /// A declaration of a kind this version cannot evaluate is refused by /// name, rather than mistaken for a plain column or fed to the SQL path. #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_rejects_a_kind_it_cannot_evaluate() { let table = table_with("refresh_foreign", vec![1, 2, 3]).await; super::super::computed_columns::add_foreign_kind(&table, "embedding", "udf").await; @@ -1754,6 +1900,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_inherits_and_publishes_blob_output() { use arrow_array::UInt64Array; use lance_arrow::{ @@ -1887,6 +2037,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_inherits_nested_struct_blob_input() { use arrow_array::{Int32Array, StructArray, UInt64Array}; use arrow_schema::{DataType, Field, Fields, Schema}; @@ -1952,6 +2106,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_preserves_list_shape_when_materializing_blob_input() { use arrow_array::{Int32Array, ListArray}; use arrow_buffer::{OffsetBuffer, ScalarBuffer}; @@ -2013,6 +2171,10 @@ mod tests { } #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] async fn test_refresh_inherits_external_blob_input() { use arrow_array::{Int32Array, StringArray, UInt64Array}; use arrow_schema::{DataType, Field, Schema}; diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index f80e89ee7..d78fc5102 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -133,6 +133,8 @@ pub(crate) async fn execute_declare( ) -> Result { use lance::dataset::mem_wal::DatasetMemWalExt; + crate::require_experimental_functions()?; + // An RTE write spec keeps visible rows in tiers refresh cannot reach; // checked against latest committed state, not this handle's snapshot. table.checkout_latest().await?; @@ -491,12 +493,14 @@ mod tests { .execute() .await .unwrap(); - table - .add_columns() - .computed("derived", "spare * 2") - .execute() - .await - .unwrap(); + if cfg!(feature = "experimental-functions") { + table + .add_columns() + .computed("derived", "spare * 2") + .execute() + .await + .unwrap(); + } table .update_field_metadata(&[metadata_update("eager")]) .await @@ -510,7 +514,10 @@ mod tests { let schema = table.schema().await.unwrap(); ensure_supported_function_metadata(&schema).unwrap(); assert_eq!(function_bindings(&schema).unwrap().len(), 1); - assert!(schema.field_with_name("derived").is_ok()); + assert_eq!( + schema.field_with_name("derived").is_ok(), + cfg!(feature = "experimental-functions") + ); assert!(schema.field_with_name("moved").is_err()); } @@ -578,14 +585,16 @@ mod tests { .await .unwrap_err(), ); - bound( - table - .add_columns() - .computed(column, "1") - .execute() - .await - .unwrap_err(), - ); + if cfg!(feature = "experimental-functions") { + bound( + table + .add_columns() + .computed(column, "1") + .execute() + .await + .unwrap_err(), + ); + } } bound( table diff --git a/rust/lancedb/tests/experimental_functions.rs b/rust/lancedb/tests/experimental_functions.rs new file mode 100644 index 000000000..f7cd022e3 --- /dev/null +++ b/rust/lancedb/tests/experimental_functions.rs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +#![cfg(not(feature = "experimental-functions"))] +#![recursion_limit = "256"] + +use std::collections::HashMap; + +use arrow_array::record_batch; +use futures::TryStreamExt; +use lancedb::materialized_view::{ + DEFINITION_META_KEY, definition_metadata_from_sql, prepare_declaration, +}; +use lancedb::table::NewColumnTransform; +use lancedb::table::computed_columns::{ + COMPUTED_COLUMN_META_KEY, EXPRESSION_META_KEY, INPUTS_META_KEY, KIND_META_KEY, computed_columns, +}; +use lancedb::{Error, MaterializedView, Result, connect}; + +fn assert_disabled(result: Result) { + match result { + Err(Error::NotSupported { message }) => { + assert!(message.contains("experimental-functions"), "{message}"); + } + _ => panic!("expected the experimental-functions feature error"), + } +} + +#[tokio::test] +async fn computed_operations_fail_before_mutation_or_job_creation() { + let db = connect("memory://").execute().await.unwrap(); + let table = db + .create_table("source", record_batch!(("x", Int32, [1, 2])).unwrap()) + .execute() + .await + .unwrap(); + let version = table.version().await.unwrap(); + assert_disabled( + table + .add_columns() + .computed("doubled", "x * 2") + .execute() + .await, + ); + assert_disabled(table.refresh_column("x").await); + assert_disabled(table.refresh_column_async("x").await); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!(table.schema().await.unwrap().fields().len(), 1); + + // The eager SQL transform remains an ordinary schema-evolution operation. + table + .add_columns() + .transform(NewColumnTransform::SqlExpressions(vec![( + "eager".into(), + "x * 2".into(), + )])) + .execute() + .await + .unwrap(); + assert_eq!( + table + .count_rows(Some("eager = x * 2".into())) + .await + .unwrap(), + 2 + ); +} + +#[tokio::test] +async fn existing_computed_metadata_remains_readable_and_protected() { + let db = connect("memory://").execute().await.unwrap(); + let table = db + .create_table( + "source", + record_batch!(("x", Int32, [1, 2]), ("doubled", Int32, [2, 4])).unwrap(), + ) + .execute() + .await + .unwrap(); + // Model a table previously written by an enabled build, without enabling + // the feature in this test binary through Cargo feature unification. + let wrapper = table.dataset().unwrap(); + let mut dataset = wrapper.get().await.unwrap().as_ref().clone(); + let field_id = dataset.schema().field("doubled").unwrap().id as u32; + dataset + .replace_field_metadata(vec![( + field_id, + HashMap::from([ + (COMPUTED_COLUMN_META_KEY.into(), "true".into()), + (KIND_META_KEY.into(), "sql".into()), + (EXPRESSION_META_KEY.into(), "x * 2".into()), + (INPUTS_META_KEY.into(), "[\"x\"]".into()), + ]), + )]) + .await + .unwrap(); + wrapper.update(dataset); + let version = table.version().await.unwrap(); + assert_eq!(computed_columns(&table.schema().await.unwrap()).len(), 1); + assert_eq!( + table + .count_rows(Some("doubled = x * 2".into())) + .await + .unwrap(), + 2 + ); + assert_disabled(table.refresh_column("doubled").await); + assert_disabled(table.refresh_column_async("doubled").await); + assert!( + table + .update() + .column("doubled", "42") + .execute() + .await + .is_err() + ); + assert!(table.drop_columns(&["x"]).await.is_err()); + assert_eq!(table.version().await.unwrap(), version); + table.drop_columns(&["doubled"]).await.unwrap(); +} + +#[tokio::test] +async fn views_cannot_be_created_or_refreshed_but_existing_data_is_accessible() { + let db = connect("memory://").execute().await.unwrap(); + let source = db + .create_table("source", record_batch!(("x", Int32, [1, 2])).unwrap()) + .execute() + .await + .unwrap(); + for with_no_data in [false, true] { + assert_disabled( + db.create_materialized_view("blocked", "source") + .with_no_data(with_no_data) + .execute() + .await, + ); + assert_disabled( + db.create_materialized_view("blocked", "source") + .with_no_data(with_no_data) + .execute_async() + .await, + ); + } + let prepared = prepare_declaration(&source, None, None, None) + .await + .unwrap(); + assert_disabled(prepared.clone().create("blocked").await); + assert_disabled(prepared.create_in(&[], "blocked").await); + assert!(matches!( + db.open_table("blocked").execute().await, + Err(Error::TableNotFound { .. }) + )); + + let table = db + .create_table("existing", record_batch!(("x", Int32, [1, 2])).unwrap()) + .execute() + .await + .unwrap(); + let wrapper = table.dataset().unwrap(); + let mut dataset = wrapper.get().await.unwrap().as_ref().clone(); + dataset + .update_schema_metadata(vec![( + DEFINITION_META_KEY.into(), + Some(definition_metadata_from_sql("SELECT x FROM source")), + )]) + .await + .unwrap(); + wrapper.update(dataset); + let version = table.version().await.unwrap(); + let view = MaterializedView::from_table(table.clone()).await.unwrap(); + assert_disabled(view.refresh().execute().await); + assert_disabled(view.refresh().execute_async().await); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); + assert_eq!( + db.open_materialized_view("existing") + .await + .unwrap() + .definition_sql(), + "SELECT x FROM source" + ); + assert_eq!( + db.list_materialized_views(Default::default()) + .try_collect::>() + .await + .unwrap(), + vec!["existing"] + ); + assert!( + table + .add(record_batch!(("x", Int32, [3])).unwrap()) + .execute() + .await + .is_err() + ); + assert!(table.delete("true").await.is_err()); + db.drop_materialized_view("existing", &[]).await.unwrap(); +} From 8887c82789c6e8db8f03848b66e0f6f58898c03e Mon Sep 17 00:00:00 2001 From: Avanish Garg Date: Tue, 27 Oct 2026 12:44:16 +0530 Subject: [PATCH 120/180] fix(python)!: raise on bool(Expr) instead of silently dropping predicates (#4682) Python's `and` / `or` / `not` and chained comparisons call `bool()` on an `Expr`. `Expr` had no `__bool__`, so that was always `True` and the filter silently lost a predicate: `where(lit(2) < col("id") < lit(5))` returned ids 0..4 (lower bound dropped), `(col("id") > 7) and (col("g") == 0)` returned all even ids, and `(a) or (b)` kept only `a` (see the issue for the repro and output). Changes (`python/python/lancedb/expr.py`, `python/python/lancedb/query.py`): - `Expr.__bool__` raises `TypeError("The truth value of an Expr is ambiguous. ...")` with a hint to use `&`, `|`, `~` with parentheses and `Expr.isin()` for membership. `TypeError` rather than `ValueError` because the object does not support truthiness at all (polars `Expr` and SQLAlchemy clauses raise `TypeError`; the codebase raises `TypeError` for unsupported `lit()` values). pandas, numpy and pyarrow `Expression` use `ValueError`. - `LanceHybridQueryBuilder` tested `if self._where:`, which would have started raising for every `.where(Expr)` on a hybrid query. It is now `isinstance(self._where, Expr) or self._where`, so an Expr is always applied and an empty SQL string is still skipped as before. - Notes section in the `Expr` docstring. Not changed: no other code in `python/python/lancedb` tests the truthiness of a filter or of an `Expr` (checked `where`/`filter`/`predicate`/`condition` handling in `query.py`, `table.py`, `remote/`, `merge.py`, `functions.py`, `pydantic.py`: they use `is None` / `isinstance`). Cross-SDK: `nodejs` has no `Expr` class on `main` yet, and JavaScript cannot overload `&&` / `||` / `!` either, so there is nothing equivalent to port; the Rust core is not affected. Behaviour changes to be aware of: code that already used `and` / `or` / `not` / chained comparisons on an `Expr` (which returned wrong rows) now raises `TypeError`. `x in [expr, ...]`, `any([...])` and `all([...])` on Exprs, and `==` between two `Query` objects whose `filter` are different Expr objects (pydantic compares the fields), now raise instead of returning a meaningless answer; `Expr` stays unhashable and `isinstance` / `is None` checks are unaffected. Tests (`python/python/tests/test_expr.py`): `TestExprTruthiness` (`bool`, `and`, `or`, `not`, chained comparison, `if`, list membership, `any`/`all` raise with a helpful message; `&`, `|`, `~` still combine) and `TestExprWhereBuilders` (plain, vector, FTS, hybrid and async `.where(Expr)` return the right rows, hybrid with an SQL string and with an empty string is unchanged, chained comparison is rejected before any query runs). With the source change stashed 11 of the new tests fail; with only `__bool__` added and the hybrid change reverted the hybrid test fails with the new `TypeError`, so it guards the second change. `test_expr.py`: 144 passed (123 before this change). Verification caveat: `main`'s Python layer is newer than the newest published wheel, so the tests were run against the 0.41.0b14 native module (`python/python/lancedb/expr.py` and `query.py` are identical to the wheel); the full suite (`pytest python/tests --ignore=python/tests/docs -m "not slow and not s3_test"`) has the identical 25 failures before and after (wheel/main skew in remote options, remote db, index and table tests; none in expr/query tests): 2604 passed before, 2625 passed after (the 21 new tests). `ruff format --check python` and `ruff check python` are clean. Not run: Rust build, Node tests, remote (cloud) tests. Fixes #4681 Co-authored-by: Xuanwo --- python/python/lancedb/expr.py | 20 ++++ python/python/lancedb/query.py | 5 +- python/python/tests/test_expr.py | 181 +++++++++++++++++++++++++++++++ 3 files changed, 205 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/expr.py b/python/python/lancedb/expr.py index 80d01e29a..f65fbd21a 100644 --- a/python/python/lancedb/expr.py +++ b/python/python/lancedb/expr.py @@ -79,6 +79,13 @@ class Expr: >>> from lancedb.expr import col, lit >>> filt = (col("age") > lit(18)) & (col("name").lower() == lit("alice")) >>> proj = {"double": col("x") * lit(2)} + + Notes + ----- + An ``Expr`` has no Python truth value: ``bool(expr)`` raises ``TypeError``. + Combine expressions with ``&``, ``|`` and ``~`` (wrapping each comparison in + parentheses) instead of ``and``, ``or`` and ``not``, and write a range as + ``(col("x") > 1) & (col("x") < 5)`` rather than ``1 < col("x") < 5``. """ # Make Expr unhashable so that == returns an Expr rather than being used @@ -89,6 +96,19 @@ class Expr: self._inner = inner self._column_path = column_path + def __bool__(self) -> bool: + # An Expr describes a predicate that the query engine evaluates per row, + # so it has no Python truth value. Without this, ``and`` / ``or`` / + # ``not`` and chained comparisons (``1 < col("x") < 5``) would silently + # keep a single operand and drop the rest of the filter. + raise TypeError( + "The truth value of an Expr is ambiguous. Combine expressions with " + "'&' (and), '|' (or) and '~' (not), and wrap each comparison in " + "parentheses, e.g. (col('x') > 1) & (col('x') < 5). Do not use " + "'and', 'or', 'not', 'in' or chained comparisons such as " + "1 < col('x') < 5; use Expr.isin() for membership." + ) + # ── comparisons ────────────────────────────────────────────────────────── def __eq__(self, other: ExprLike) -> "Expr": # type: ignore[override] diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 52f38d077..f888d4b42 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -3062,7 +3062,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): if columns: self._vector_query.select(columns) self._fts_query.select(columns) - if self._where: + # An Expr has no truth value (it raises on bool()), so test for it + # explicitly instead of relying on truthiness; an empty SQL string is + # still skipped. + if isinstance(self._where, Expr) or self._where: self._vector_query.where(self._where, not self._postfilter) self._fts_query.where(self._where, not self._postfilter) # WAL-PK-FUSION: without the fallback, `if self._with_row_id:`. diff --git a/python/python/tests/test_expr.py b/python/python/tests/test_expr.py index 6cfc09922..5d81b10c3 100644 --- a/python/python/tests/test_expr.py +++ b/python/python/tests/test_expr.py @@ -11,6 +11,7 @@ import pytest import lancedb from lancedb.expr import Expr, col, func, lit +from lancedb.index import FTS # ── unit tests for Expr construction ───────────────────────────────────────── @@ -383,6 +384,68 @@ class TestExprRepr: {e: 1} +class TestExprTruthiness: + """``bool(Expr)`` must raise instead of silently keeping one operand.""" + + def test_bool_raises(self): + with pytest.raises(TypeError, match="truth value of an Expr is ambiguous"): + bool(col("x") == 1) + + def test_bool_error_points_to_operators(self): + with pytest.raises(TypeError, match=r"'&'.*'\|'.*'~'"): + bool(col("x") > 1) + + def test_and_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + (col("id") > 7) and (col("g") == 0) # noqa: B015 + + def test_or_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + (col("id") > 7) or (col("g") == 0) # noqa: B015 + + def test_not_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + not (col("id") > 7) # noqa: B015 + + def test_chained_comparison_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + lit(2) < col("id") < lit(5) # noqa: B015 + with pytest.raises(TypeError, match="ambiguous"): + 2 < col("id") < 5 # noqa: B015 + + def test_if_raises(self): + with pytest.raises(TypeError, match="ambiguous"): + if col("x"): + pass + + def test_membership_in_list_raises(self): + # list membership evaluates ``item == expr`` and calls bool() on the + # result, which used to be silently (and wrongly) True. + with pytest.raises(TypeError, match="ambiguous"): + col("x") in [1, 2, 3] # noqa: B015 + + def test_any_all_raise(self): + with pytest.raises(TypeError, match="ambiguous"): + any([col("x") > 1]) + with pytest.raises(TypeError, match="ambiguous"): + all([col("x") > 1]) + + def test_operators_still_combine(self): + a, b = col("id") > 7, col("g") == 0 + assert (a & b).to_sql() == "((id > 7) AND (g = 0))" + assert (a | b).to_sql() == "((id > 7) OR (g = 0))" + assert (~a).to_sql() == "NOT (id > 7)" + assert ((lit(2) < col("id")) & (col("id") < lit(5))).to_sql() == ( + "((2 < id) AND (id < 5))" + ) + + def test_identity_and_isinstance_checks_do_not_use_truthiness(self): + e = col("x") == 1 + assert e is not None + assert isinstance(e, Expr) + assert e is e + + class TestExprReflexive: def test_reflexive_eq(self): e = 1 == col("x") @@ -791,3 +854,121 @@ class TestExprDatetimeTimezoneIntegration: sql = lit(ts).to_sql() # Must encode 10:00 wall clock, not 10:00+local_offset. assert "2024-07-01 10:00:00" in sql + + +# ── where(Expr) must never rely on the truthiness of the filter ────────────── + + +@pytest.fixture +def search_table(tmp_path): + db = lancedb.connect(str(tmp_path)) + data = pa.table( + { + "id": list(range(12)), + "g": [i % 2 for i in range(12)], + "text": ["keep" if i < 9 else "other" for i in range(12)], + "vector": pa.FixedSizeListArray.from_arrays( + pa.array([float(i) for i in range(12) for _ in range(2)], pa.float32()), + 2, + ), + } + ) + table = db.create_table("search", data) + table.create_index("text", config=FTS()) + return table + + +def _ids(rows): + return sorted(r["id"] for r in rows) + + +class TestExprWhereBuilders: + def test_chained_comparison_is_rejected_before_querying(self, search_table): + # The silent bug: this used to return ids 0..4 (lower bound dropped). + with pytest.raises(TypeError, match="ambiguous"): + search_table.search().where(lit(2) < col("id") < lit(5)) + + def test_plain_where_expr(self, search_table): + where = (lit(2) < col("id")) & (col("id") < lit(5)) + rows = search_table.search().where(where).limit(100).to_list() + assert _ids(rows) == [3, 4] + + def test_vector_where_expr(self, search_table): + where = (col("id") > lit(7)) & (col("g") == lit(0)) + rows = search_table.search([0.0, 0.0]).where(where).limit(100).to_list() + assert _ids(rows) == [8, 10] + + def test_fts_where_expr(self, search_table): + where = (col("id") > lit(3)) | (col("g") == lit(1)) + rows = ( + search_table.search("keep", query_type="fts") + .where(where) + .limit(100) + .to_list() + ) + # "keep" matches ids 0..8; filter keeps id > 3 or odd ids. + assert _ids(rows) == [1, 3, 4, 5, 6, 7, 8] + + def test_hybrid_where_expr(self, search_table): + # The hybrid builder used to test ``if self._where:``; that must not + # call bool() on an Expr now that it raises. + where = (col("id") > lit(3)) & (col("g") == lit(0)) + rows = ( + search_table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("keep") + .where(where) + .limit(100) + .to_list() + ) + # Hybrid search fuses the vector and FTS results, and the filter applies + # to both sides: the vector side alone returns every row passing it. + assert _ids(rows) == [4, 6, 8, 10] + + def test_hybrid_where_sql_string_still_works(self, search_table): + rows = ( + search_table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("keep") + .where("id > 3 AND g = 0") + .limit(100) + .to_list() + ) + assert _ids(rows) == [4, 6, 8, 10] + + def test_hybrid_empty_where_is_ignored(self, search_table): + rows = ( + search_table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("keep") + .where("") + .limit(100) + .to_list() + ) + assert _ids(rows) == list(range(12)) + + def test_repeated_where_expr_combines(self, search_table): + rows = ( + search_table.search() + .where(col("id") > lit(2)) + .where(col("id") < lit(5)) + .limit(100) + .to_list() + ) + assert _ids(rows) == [3, 4] + + def test_query_model_with_expr_filter(self, search_table): + query = search_table.search().where(col("id") > lit(2)).to_query_object() + assert isinstance(query.filter, Expr) + + @pytest.mark.asyncio + async def test_async_where_expr(self, tmp_path): + db = await lancedb.connect_async(str(tmp_path)) + table = await db.create_table( + "t", pa.table({"id": list(range(12)), "g": [i % 2 for i in range(12)]}) + ) + where = (col("id") > lit(7)) & (col("g") == lit(0)) + rows = await table.query().where(where).to_list() + assert _ids(rows) == [8, 10] + with pytest.raises(TypeError, match="ambiguous"): + table.query().where(lit(2) < col("id") < lit(5)) From 1edfa6077b4b1e70b01db8b91a73e14bd40773da Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:53:14 +0800 Subject: [PATCH 121/180] fix(python): allow phrase queries without a column (#4653) Quoted async full-text queries without `columns` carry an unset phrase column, but converting them to Python unwrapped it and raised `PanicException`. Python also required `PhraseQuery.column`, preventing callers from constructing the equivalent query object. Make the Python column optional and preserve `Option` in both Rust conversion directions, leaving column selection to query planning. Regression tests cover quoted strings and structured queries with omitted, `None`, and explicit columns, query reuse, JSON serialization, slop, and document granularity. Validation: - Reproduced both missing-column failures before the fix; explicit-column controls passed. - Rebuilt the extension with `uv run --extra tests --extra dev maturin develop --extras tests,dev`. - `cd python && uv run --no-sync --extra tests pytest python/tests/test_fts.py python/tests/test_query.py::test_query_serialization_async -q`: 85 passed. - `cargo fmt --all -- --check` and `ruff check python` pass; touched Python files pass formatting checks. - `cargo clippy --quiet -p lancedb-python --lib --features remote` passes. - Root-wide `ruff check .` reports 49 existing findings in unchanged documentation examples. Fixes #4651 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/query.py | 6 ++--- python/python/tests/test_fts.py | 46 +++++++++++++++++++++++++++++++++ python/src/query.rs | 8 +++--- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index f888d4b42..66aae06a6 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -591,8 +591,8 @@ class PhraseQuery(FullTextQuery): ---------- query : str The query string to match against. - column : str - The name of the column to match against. + column : str, optional + The column to match against. None leaves column selection to query planning. slop : int, default 0 The maximum number of intervening positions permitted in the phrase. document_granularity : DocumentGranularity, optional @@ -602,7 +602,7 @@ class PhraseQuery(FullTextQuery): """ query: str - column: str + column: Optional[str] = None slop: int = pydantic.Field(0, kw_only=True) document_granularity: Optional[DocumentGranularity] = pydantic.Field( None, kw_only=True diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 1dc2fd9a1..a02c4db28 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -584,6 +584,52 @@ async def test_search_fts_phrase_query_async(async_table): assert len(phrase_results) > 0 +@pytest.mark.asyncio +@pytest.mark.parametrize("columns", [None, ["text"]]) +async def test_phrase_query_to_query_object_async(tmp_path, columns): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "phrases", pa.table({"text": ["puppy runs fast", "cat sleeps"]}) + ) + await table.create_index("text", config=FTS(with_position=True)) + + query = table.query().nearest_to_text('"puppy runs"', columns=columns) + phrase = query.to_query_object().full_text_query.query + + expected = ( + PhraseQuery("puppy runs", "text") if columns else PhraseQuery("puppy runs") + ) + assert phrase == expected + results = await table.query().nearest_to_text(phrase).to_list() + assert [row["text"] for row in results] == ["puppy runs fast"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("column", [None, "text"]) +async def test_phrase_query_object_roundtrip_async(tmp_path, column): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "phrases", + pa.table({"text": ["puppy runs fast", "puppy often runs", "cat sleeps"]}), + ) + await table.create_index("text", config=FTS(with_position=True)) + phrase = PhraseQuery( + "puppy runs", column, slop=1, document_granularity=DocumentGranularity.ROW + ) + query = table.query().nearest_to_text(phrase) + + assert query.to_query_object().full_text_query.query == phrase + serialized = json.loads(phrase.to_json())["phrase"] + assert serialized["slop"] == 1 + assert serialized["document_granularity"] == "row" + assert serialized.get("column") == column + results = await query.to_list() + assert sorted(row["text"] for row in results) == [ + "puppy often runs", + "puppy runs fast", + ] + + def test_search_fts_specify_column(table): table.create_fts_index("text") table.create_fts_index("text2") diff --git a/python/src/query.rs b/python/src/query.rs index c9c4905c9..bf267443c 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -103,7 +103,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { } "PhraseQuery" => { let query = ob.getattr("query")?.extract()?; - let column = ob.getattr("column")?.extract()?; + let column = ob.getattr("column")?.extract::>()?; let slop = ob.getattr("slop")?.extract()?; let document_granularity = ob .getattr("document_granularity")? @@ -114,9 +114,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { }) .transpose()?; - let mut query = PhraseQuery::new(query) - .with_column(Some(column)) - .with_slop(slop); + let mut query = PhraseQuery::new(query).with_column(column).with_slop(slop); if let Some(document_granularity) = document_granularity { query = query.with_document_granularity(document_granularity); } @@ -213,7 +211,7 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { } namespace .getattr(intern!(py, "PhraseQuery"))? - .call((query.terms, query.column.unwrap()), Some(&kwargs)) + .call((query.terms, query.column), Some(&kwargs)) } FtsQuery::Boost(query) => { let positive = Self(query.positive.as_ref().clone()).into_pyobject(py)?; From 7fca4d666adf1d5f522ce8ac422117821da195ca Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:32:32 +0800 Subject: [PATCH 122/180] fix(python): preserve async query search options during serialization (#4659) Async `to_query_object()` dropped enabled `fast_search` on every query type and `postfilter` on plain and full-text queries. Re-executing a serialized fast search could therefore return unindexed rows. Copy enabled `fast_search` into the Python `Query` and serialize enabled plain/FTS postfilter from the Rust request's prefilter setting. Preserve the existing unset defaults: `None` for these options, with the vector query's existing `False` postfilter default. Validation: - Added 12 serialization cases across plain, FTS, and vector queries, covering both enabled and unset options, plus two FTS execution round-trip cases. Before the fix, nine cases failed, including returning an unindexed row after serialization. - Rebuilt the Python extension using the uv-managed environment. - Query tests and existing FTS fast-search tests: 192 passed, 1 slow test deselected. - Rust formatting and Python package lint/format checks pass. Repository-wide `ruff check .` reports 49 pre-existing errors in unchanged `docs/web-tests` files. Fixes #4658 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/query.py | 2 ++ python/python/tests/test_query.py | 50 +++++++++++++++++++++++++++++++ python/src/query.rs | 2 +- 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 66aae06a6..644b6571f 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -910,6 +910,8 @@ class Query(pydantic.BaseModel): query.filter = req.filter query.full_text_query = req.full_text_search query.columns = req.select + # Keep the unset value for this opt-in flag, as in the sync builders. + query.fast_search = req.fast_search or None query.with_row_id = req.with_row_id # use_rte is a genuine tri-state (None / True / False); preserve it as-is # so a round-tripped query keeps an explicit False. diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index cef985aa6..3d7c01fc5 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1977,6 +1977,56 @@ def test_query_serialization_sync(table: lancedb.table.Table): check_set_props(q, full_text_query=FullTextSearchQuery(columns=[], query="foo")) +@pytest.mark.asyncio +@pytest.mark.parametrize("query_type", ["plain", "fts", "vector"]) +@pytest.mark.parametrize("fast_search", [False, True]) +@pytest.mark.parametrize("postfilter", [False, True]) +async def test_query_serialization_async_search_options( + table_async: AsyncTable, query_type, fast_search, postfilter +): + query = table_async.query().where("id = 1") + if query_type == "fts": + query = query.nearest_to_text(MatchQuery("dog", "text")) + elif query_type == "vector": + query = query.nearest_to([1.0, 2.0]) + if fast_search: + query = query.fast_search() + if postfilter: + query = query.postfilter() + + serialized = query.to_query_object() + assert serialized.fast_search is (True if fast_search else None) + default_postfilter = False if query_type == "vector" else None + assert serialized.postfilter is (True if postfilter else default_postfilter) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fast_search", [False, True]) +async def test_query_serialization_async_fast_search_execution( + table_async, fast_search +): + await table_async.create_index("text", config=FTS()) + await table_async.add( + [ + { + "id": 3, + "vector": [5.0, 6.0], + "str_field": "c", + "float_field": 3.0, + "text": "unindexed dog", + } + ] + ) + query = table_async.query().nearest_to_text(MatchQuery("unindexed", "text")) + if fast_search: + query = query.fast_search() + + expected_ids = [] if fast_search else [3] + assert [row["id"] for row in await query.to_list()] == expected_ids + restored = table_async._sync_query_to_async(query.to_query_object()) + assert [row["id"] for row in await restored.to_list()] == expected_ids + + @pytest.mark.asyncio async def test_query_serialization_async(table_async: AsyncTable): # Simple queries diff --git a/python/src/query.rs b/python/src/query.rs index bf267443c..c2bd6afb3 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -377,7 +377,7 @@ impl From for PyQueryRequest { refine_factor: None, distance_type: None, bypass_vector_index: None, - postfilter: None, + postfilter: (!query_request.prefilter).then_some(true), norm: None, order_by: query_request .order_by From ad1212fb3269d1b02f9218deeae506f58f18df07 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 27 Oct 2026 17:35:43 +0800 Subject: [PATCH 123/180] chore: update Lance to v15.0.0-beta.2 (#4690) **Blocked on the corrected Lance release:** https://github.com/lance-format/lance/pull/10370 restores the `Send` contract required by downstream Function workers. Refresh this upgrade with that release before merging. Upgrade the Rust, Java, and Python Lance dependencies to https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.2. This brings in bounded vector-index consolidation without retraining (https://github.com/lance-format/lance/pull/10335) and deletion filtering for index entries whose fragment coverage was pruned (https://github.com/lance-format/lance/pull/10325). Synchronize the vendored `lance-arrow` with the release and retain its offset-safe validity patch. The existing `nullable_struct_merge` regression still panics with the unpatched release, so removing that patch would regress nullable nested queries. Refresh both lockfiles, including the `zstd-sys` version required by the new Lance encoding dependency. Update the custom memtable bitmap test adapter to train on row addresses, matching the new bitmap contract; remove its obsolete row-ID conversion. Preserve the Blob APIs' existing missing-row error messages when newer Lance rejects a missing fragment earlier in the read path. Retain upstream attribution in vendored sources while satisfying the repository license-header check. Validation of the compatibility fixes: all 58 Rust Blob integration tests and 219 Python Blob tests pass (one Python test skipped). Strict workspace Clippy, formatting, and diff checks pass. --- Cargo.lock | 163 +++-- Cargo.toml | 30 +- java/pom.xml | 2 +- python/pyproject.toml | 4 +- python/uv.lock | 202 +++--- python/vendor/lance-arrow/Cargo.toml | 5 +- python/vendor/lance-arrow/README.lancedb.md | 4 +- python/vendor/lance-arrow/src/lib.rs | 737 ++++++++++++++++++-- python/vendor/lance-arrow/src/stream.rs | 93 +-- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/src/blob.rs | 2 + rust/lancedb/src/table/merge.rs | 20 +- 12 files changed, 957 insertions(+), 307 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2844ae735..f189ba871 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -373,7 +373,7 @@ dependencies = [ "arrow-select", "flatbuffers", "lz4_flex", - "zstd", + "zstd 0.13.3", ] [[package]] @@ -3584,8 +3584,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5059,8 +5059,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arc-swap", "arrow", @@ -5135,7 +5135,7 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.1" +version = "15.0.0-beta.2" dependencies = [ "arrow-array", "arrow-buffer", @@ -5157,7 +5157,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "arrow-buffer", @@ -5171,7 +5171,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "arrow-schema", @@ -5180,8 +5180,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrayref", "crunchy", @@ -5191,8 +5191,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "arrow-buffer", @@ -5229,8 +5229,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow", "arrow-array", @@ -5246,10 +5246,11 @@ dependencies = [ "datafusion-functions", "datafusion-physical-expr", "futures", + "geodatafusion", "half", "lance-arrow", "lance-core", - "lance-geo", + "lance-datafusion-exec", "lance-jsonb", "log", "pin-project", @@ -5259,10 +5260,36 @@ dependencies = [ "tracing", ] +[[package]] +name = "lance-datafusion-exec" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +dependencies = [ + "arrow", + "arrow-array", + "arrow-schema", + "async-trait", + "datafusion-common", + "datafusion-execution", + "datafusion-expr", + "datafusion-functions", + "datafusion-physical-expr", + "datafusion-physical-plan", + "futures", + "half", + "lance-arrow", + "lance-core", + "lance-jsonb", + "log", + "pin-project", + "tokio", + "tracing", +] + [[package]] name = "lance-datagen" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow", "arrow-array", @@ -5279,8 +5306,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "proc-macro2", "quote", @@ -5289,8 +5316,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-arith", "arrow-array", @@ -5315,16 +5342,17 @@ dependencies = [ "num-traits", "prost", "prost-build", + "serde_json", "tokio", "tracing", "xxhash-rust", - "zstd", + "zstd 0.14.3", ] [[package]] name = "lance-file" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-arith", "arrow-array", @@ -5356,23 +5384,21 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ - "datafusion", "geo-traits", "geo-types", "geoarrow-array", "geoarrow-schema", - "geodatafusion", "lance-core", "serde", ] [[package]] name = "lance-index" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arc-swap", "arrow", @@ -5389,10 +5415,13 @@ dependencies = [ "blake3", "bytes", "crossbeam-queue", - "datafusion", "datafusion-common", + "datafusion-execution", "datafusion-expr", + "datafusion-functions", + "datafusion-functions-nested", "datafusion-physical-expr", + "datafusion-physical-plan", "dirs", "fst", "futures", @@ -5408,7 +5437,7 @@ dependencies = [ "lance-arrow-stats", "lance-bitpacking", "lance-core", - "lance-datafusion", + "lance-datafusion-exec", "lance-encoding", "lance-file", "lance-geo", @@ -5445,16 +5474,16 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "arrow-schema", "arrow-select", "async-trait", "bytes", - "datafusion", "datafusion-common", + "datafusion-execution", "datafusion-expr", "futures", "lance-core", @@ -5469,8 +5498,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow", "arrow-array", @@ -5513,8 +5542,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "byteorder", "ethnum", @@ -5531,8 +5560,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "arrow-schema", @@ -5546,8 +5575,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow", "async-trait", @@ -5561,8 +5590,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arc-swap", "arrow", @@ -5616,8 +5645,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "arrow-buffer", @@ -5631,8 +5660,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow", "arrow-array", @@ -5672,8 +5701,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "arrow-array", "arrow-schema", @@ -5686,8 +5715,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.1#46a7cfe1fba5efa1f90deea4c7b14d414b991409" +version = "15.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" dependencies = [ "frostem", "icu_segmenter", @@ -7692,7 +7721,7 @@ dependencies = [ "streaming-iterator", "strength_reduce", "version_check", - "zstd", + "zstd 0.13.3", ] [[package]] @@ -12016,7 +12045,16 @@ version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" dependencies = [ - "zstd-safe", + "zstd-safe 7.2.4", +] + +[[package]] +name = "zstd" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" +dependencies = [ + "zstd-safe 8.2.0", ] [[package]] @@ -12029,10 +12067,19 @@ dependencies = [ ] [[package]] -name = "zstd-sys" -version = "2.0.16+zstd.1.5.7" +name = "zstd-safe" +version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index 22dec8c0c..40040c329 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,21 +18,21 @@ categories = ["database-implementations"] rust-version = "1.94.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { version = "=15.0.0-beta.1", tag = "v15.0.0-beta.1", git = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.1", default-features = false, "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.1", "tag" = "v15.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { version = "=15.0.0-beta.1", path = "python/vendor/lance-arrow" } +lance = { "version" = "=15.0.0-beta.2", default-features = false, "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.2", default-features = false, "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.2", default-features = false, "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { version = "=15.0.0-beta.2", path = "python/vendor/lance-arrow" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index e3cfb2781..96262a8e9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.1 + 15.0.0-beta.2 2.18.11 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index a0de6509c..ac9281248 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -46,7 +46,7 @@ repository = "https://github.com/lancedb/lancedb" [project.optional-dependencies] pylance = [ # Keep the minimum in the bundled Lance major and compatible with tests below. - "pylance>=15.0.0b1", + "pylance>=15.0.0b2", ] # A library only needs the OpenTelemetry API; the application supplies and # configures the SDK (the actual exporter/reader). See @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow<25", "pyarrow-stubs>=16.0", - "pylance==15.0.0b1", + "pylance==15.0.0b2", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 99bcb439c..329a9ef24 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -799,7 +799,7 @@ name = "cuda-bindings" version = "13.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "cuda-pathfinder" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/a9/21/8464d133752951c154feafb3b65c297e7d80f301183d220bec4c830f1441/cuda_bindings-13.3.1-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:120fcc53d57903df529c3486962c56528cba5b7d6c57c99537320ed9922c8b86", size = 6073403, upload-time = "2026-05-29T23:11:36.22Z" }, @@ -834,37 +834,37 @@ wheels = [ [package.optional-dependencies] cublas = [ - { name = "nvidia-cublas", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cublas" }, ] cudart = [ - { name = "nvidia-cuda-runtime", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cuda-runtime" }, ] cufft = [ - { name = "nvidia-cufft", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cufft" }, ] cufile = [ - { name = "nvidia-cufile", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufile" }, ] cupti = [ - { name = "nvidia-cuda-cupti", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cuda-cupti" }, ] curand = [ - { name = "nvidia-curand", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-curand" }, ] cusolver = [ - { name = "nvidia-cusolver", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cusolver" }, ] cusparse = [ - { name = "nvidia-cusparse", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cusparse" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-cuda-nvrtc" }, ] nvtx = [ - { name = "nvidia-nvtx", marker = "(python_full_version < '3.14' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "nvidia-nvtx" }, ] [[package]] @@ -1023,7 +1023,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -1440,16 +1440,16 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "cachetools", marker = "python_full_version < '3.11'" }, - { name = "certifi", marker = "python_full_version < '3.11'" }, - { name = "httpx", marker = "python_full_version < '3.11'" }, - { name = "ibm-cos-sdk", marker = "python_full_version < '3.11'" }, - { name = "lomond", marker = "python_full_version < '3.11'" }, - { name = "packaging", marker = "python_full_version < '3.11'" }, - { name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "requests", marker = "python_full_version < '3.11'" }, - { name = "tabulate", marker = "python_full_version < '3.11'" }, - { name = "urllib3", marker = "python_full_version < '3.11'" }, + { name = "cachetools" }, + { name = "certifi" }, + { name = "httpx" }, + { name = "ibm-cos-sdk" }, + { name = "lomond" }, + { name = "packaging" }, + { name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" } }, + { name = "requests" }, + { name = "tabulate" }, + { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/c7/56/2e3df38a1f13062095d7bde23c87a92f3898982993a15186b1bfecbd206f/ibm_watsonx_ai-1.3.42.tar.gz", hash = "sha256:ee5be59009004245d957ce97d1227355516df95a2640189749487614fef674ff", size = 688651, upload-time = "2025-10-01T13:35:41.527Z" } wheels = [ @@ -1468,17 +1468,17 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "cachetools", marker = "python_full_version >= '3.11'" }, - { name = "certifi", marker = "python_full_version >= '3.11'" }, - { name = "httpx", marker = "python_full_version >= '3.11'" }, - { name = "ibm-cos-sdk", marker = "python_full_version >= '3.11'" }, - { name = "lomond", marker = "python_full_version >= '3.11'" }, - { name = "packaging", marker = "python_full_version >= '3.11'" }, - { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, + { name = "cachetools" }, + { name = "certifi" }, + { name = "httpx" }, + { name = "ibm-cos-sdk" }, + { name = "lomond" }, + { name = "packaging" }, + { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" }, { name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "requests", marker = "python_full_version >= '3.11'" }, - { name = "tabulate", marker = "python_full_version >= '3.11'" }, - { name = "urllib3", marker = "python_full_version >= '3.11'" }, + { name = "requests" }, + { name = "tabulate" }, + { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/29/a3/c756b534696ab2f3f29882fdb7ca7198b7a5c94e10c0a3a327853d6d6b79/ibm_watsonx_ai-1.5.14.tar.gz", hash = "sha256:a756488bd57e87c0fc51be42dcba871143cfe0ac1e805c497c5047e1e4f13e9d", size = 735804, upload-time = "2026-06-22T12:32:43.85Z" } wheels = [ @@ -1554,17 +1554,17 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "colorama", marker = "python_full_version < '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version < '3.11'" }, - { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, - { name = "jedi", marker = "python_full_version < '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version < '3.11'" }, - { name = "pexpect", marker = "python_full_version < '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version < '3.11'" }, - { name = "pygments", marker = "python_full_version < '3.11'" }, - { name = "stack-data", marker = "python_full_version < '3.11'" }, - { name = "traitlets", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { name = "exceptiongroup" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/40/18/f8598d287006885e7136451fdea0755af4ebcbfe342836f24deefaed1164/ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624", size = 5513971, upload-time = "2026-03-27T10:02:13.94Z" } wheels = [ @@ -1583,18 +1583,18 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "colorama", marker = "python_full_version >= '3.11' and sys_platform == 'win32'" }, - { name = "decorator", marker = "python_full_version >= '3.11'" }, - { name = "ipython-pygments-lexers", marker = "python_full_version >= '3.11'" }, - { name = "jedi", marker = "python_full_version >= '3.11'" }, - { name = "matplotlib-inline", marker = "python_full_version >= '3.11'" }, - { name = "pexpect", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "prompt-toolkit", marker = "python_full_version >= '3.11'" }, - { name = "psutil", marker = "python_full_version >= '3.11' and sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, - { name = "pygments", marker = "python_full_version >= '3.11'" }, - { name = "stack-data", marker = "python_full_version >= '3.11'" }, - { name = "traitlets", marker = "python_full_version >= '3.11'" }, - { name = "typing-extensions", marker = "python_full_version == '3.11.*'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "decorator" }, + { name = "ipython-pygments-lexers" }, + { name = "jedi" }, + { name = "matplotlib-inline" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "prompt-toolkit" }, + { name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, + { name = "pygments" }, + { name = "stack-data" }, + { name = "traitlets" }, + { name = "typing-extensions", marker = "python_full_version < '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/53/59/165d3b4d75cc34add3122c4417ecb229085140ac573103c223cd01dde96f/ipython-9.15.0.tar.gz", hash = "sha256:da2819ce2aa83135257df830660b1176d986c3d2876db24df01974fa955b2756", size = 4442580, upload-time = "2026-06-26T11:03:35.913Z" } wheels = [ @@ -1606,7 +1606,7 @@ name = "ipython-pygments-lexers" version = "1.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pygments", marker = "python_full_version >= '3.11'" }, + { name = "pygments" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" } wheels = [ @@ -1854,9 +1854,9 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "lance-namespace-urllib3-client" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c0/e7/d5d46594678ee479c0eda830c47b2f5c46133bd100e84e9aa6e01306eca7/lance_namespace-0.13.0.tar.gz", hash = "sha256:24554a0997bdb39595c6e4cb3ac6722069f6cd3bd1a74e7acbba7bfaf774a40d", size = 11636, upload-time = "2026-09-14T02:47:03.871523Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c0/e7/d5d46594678ee479c0eda830c47b2f5c46133bd100e84e9aa6e01306eca7/lance_namespace-0.13.0.tar.gz", hash = "sha256:24554a0997bdb39595c6e4cb3ac6722069f6cd3bd1a74e7acbba7bfaf774a40d", size = 11636, upload-time = "2026-09-14T02:47:03.871Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e7/47/cfa33cca1ba7c749fd2918cfc5c8ded788f378cc6424d23e4fead5a14125/lance_namespace-0.13.0-py3-none-any.whl", hash = "sha256:438c7b17aef421c21c138196e715f2510d62f07e865372047f87c1e75e618c7a", size = 13507, upload-time = "2026-09-14T02:47:01.765655Z" }, + { url = "https://files.pythonhosted.org/packages/e7/47/cfa33cca1ba7c749fd2918cfc5c8ded788f378cc6424d23e4fead5a14125/lance_namespace-0.13.0-py3-none-any.whl", hash = "sha256:438c7b17aef421c21c138196e715f2510d62f07e865372047f87c1e75e618c7a", size = 13507, upload-time = "2026-09-14T02:47:01.765Z" }, ] [[package]] @@ -1869,9 +1869,9 @@ dependencies = [ { name = "typing-extensions" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/69/25/9aaa4a5e8999693fb0f227c2c0c4b97bd8f0539066408cdff0b89d41b2d5/lance_namespace_urllib3_client-0.13.0.tar.gz", hash = "sha256:1e8a79c6e4e6277033597fd76aa0e2f33d909ca1436c935936e9e569221f43ef", size = 238348, upload-time = "2026-09-14T02:47:04.521878Z" } +sdist = { url = "https://files.pythonhosted.org/packages/69/25/9aaa4a5e8999693fb0f227c2c0c4b97bd8f0539066408cdff0b89d41b2d5/lance_namespace_urllib3_client-0.13.0.tar.gz", hash = "sha256:1e8a79c6e4e6277033597fd76aa0e2f33d909ca1436c935936e9e569221f43ef", size = 238348, upload-time = "2026-09-14T02:47:04.521Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/60/4c/7b8f0712a7fe1b8655b711342bc4989696635a79e7027ee56ba3cae23e99/lance_namespace_urllib3_client-0.13.0-py3-none-any.whl", hash = "sha256:fb361eb4f6c7f2d1f9e92809609657b73e38241393e9c4516e12d6b6ee643a0a", size = 406848, upload-time = "2026-09-14T02:47:02.715954Z" }, + { url = "https://files.pythonhosted.org/packages/60/4c/7b8f0712a7fe1b8655b711342bc4989696635a79e7027ee56ba3cae23e99/lance_namespace_urllib3_client-0.13.0-py3-none-any.whl", hash = "sha256:fb361eb4f6c7f2d1f9e92809609657b73e38241393e9c4516e12d6b6ee643a0a", size = 406848, upload-time = "2026-09-14T02:47:02.715Z" }, ] [[package]] @@ -2006,8 +2006,8 @@ requires-dist = [ { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, - { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b1" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b1" }, + { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b2" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b2" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -2884,7 +2884,7 @@ name = "nvidia-cudnn-cu13" version = "9.19.0.56" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-cublas" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f1/84/26025437c1e6b61a707442184fa0c03d083b661adf3a3eecfd6d21677740/nvidia_cudnn_cu13-9.19.0.56-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:6ed29ffaee1176c612daf442e4dd6cfeb6a0caa43ddcbeb59da94953030b1be4", size = 433781201, upload-time = "2026-02-03T20:40:53.805Z" }, @@ -2896,7 +2896,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, @@ -2926,9 +2926,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, - { name = "nvidia-cusparse", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-cublas" }, + { name = "nvidia-cusparse" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, @@ -2940,7 +2940,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, @@ -3117,10 +3117,10 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "python-dateutil", marker = "python_full_version < '3.11'" }, - { name = "pytz", marker = "python_full_version < '3.11'" }, - { name = "tzdata", marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9c/d6/9f8431bacc2e19dca897724cd097b1bb224a6ad5433784a44b587c7c13af/pandas-2.2.3.tar.gz", hash = "sha256:4f18ba62b61d7e192368b84517265a99b4d7ee8912f8708660fb4a366cc82667", size = 4399213, upload-time = "2024-09-20T13:10:04.827Z" } wheels = [ @@ -3169,11 +3169,11 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12' or python_full_version >= '3.14'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and python_full_version < '3.14'" }, - { name = "python-dateutil", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, - { name = "pytz", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, - { name = "tzdata", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, ] sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } wheels = [ @@ -3236,9 +3236,9 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, - { name = "python-dateutil", marker = "python_full_version >= '3.14'" }, - { name = "tzdata", marker = "(python_full_version >= '3.14' and sys_platform == 'emscripten') or (python_full_version >= '3.14' and sys_platform == 'win32')" }, + { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f8/87/4341c6252d1c47b08768c3d25ac487362bf403f0313ddae4a2a26c9b1b4c/pandas-3.0.3.tar.gz", hash = "sha256:696a4a00a2a2a35d4e5deb3fc946641b96c944f02230e4f76137fe35d806c4fc", size = 4651414, upload-time = "2026-05-11T18:54:29.21Z" } wheels = [ @@ -3346,7 +3346,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "ptyprocess" }, ] sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } wheels = [ @@ -3938,7 +3938,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b1" +version = "15.0.0b2" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -3948,12 +3948,12 @@ dependencies = [ { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_23L1Nd/pylance-15.0.0b1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:19605d3daca1224cc0db079054be5d4eec403dcf286bf4617430bfc259ab0a52" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1Ho3RK/pylance-15.0.0b1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be22b0b6f1e1d250ffaa82b449e982c817db33103c483d1005020285310623cf" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1QmyF0/pylance-15.0.0b1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5b2761d60b1b9db112058213f1f7b2de82b08cbe65888fab08b0a56e702482e" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1in2Ph/pylance-15.0.0b1-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:294a0fedae312ed32d1b66cddbf7e69770ec9b4c82a873af60c619ed88450718" }, - { url = "https://pypi.fury.io/lance-format/-/ver_21xpLH/pylance-15.0.0b1-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ff20a16703d4d3f3bc675b25ce1871ba1d54137929dc46305bffdd07f7b35a6b" }, - { url = "https://pypi.fury.io/lance-format/-/ver_AAGzF/pylance-15.0.0b1-cp310-abi3-win_amd64.whl", hash = "sha256:3b134e24a5becfc940ca134cf78aa3bae8b80ec40f8927a1b856273ab76213f2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_5aLfR/pylance-15.0.0b2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:fd6b872e348d804c3188d014f2ff469f8cfaff5bbe846617e665c1e2a2965683" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1W21Yj/pylance-15.0.0b2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b0ed217ee71bea57ef97303bd1318ae212ee005c885c16390d7efbaf1f7398e3" }, + { url = "https://pypi.fury.io/lance-format/-/ver_12xJCp/pylance-15.0.0b2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72580d6359db4d471c578daab46a35fd87e74e57a1cb64e333188fea1e1c2f1b" }, + { url = "https://pypi.fury.io/lance-format/-/ver_m4ypB/pylance-15.0.0b2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c194f95e2d2b1c5a9e4f57ed2681a9295effe5aaa165bf924f2b2090094c4645" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1zYkf2/pylance-15.0.0b2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c14532517ed1452d9cb215f33dc4bc3166500e14145c8c6f2f3538b82ac5147b" }, + { url = "https://pypi.fury.io/lance-format/-/ver_xp2do/pylance-15.0.0b2-cp310-abi3-win_amd64.whl", hash = "sha256:ce13e573a1842eda18f9b74eec4c8d1dc60db0895581db3226c6a6b1a8e79a75" }, ] [[package]] @@ -4709,10 +4709,10 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "joblib", marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "threadpoolctl", marker = "python_full_version < '3.11'" }, + { name = "joblib" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" } }, + { name = "threadpoolctl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } wheels = [ @@ -4760,13 +4760,13 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "joblib", marker = "python_full_version >= '3.11'" }, - { name = "narwhals", marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "joblib" }, + { name = "narwhals" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "threadpoolctl", marker = "python_full_version >= '3.11'" }, + { name = "threadpoolctl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/fa/6f/37092bdb25f712817231799fc5674d8e704066a8a70c1d2d40517e18b4ab/scikit_learn-1.9.0.tar.gz", hash = "sha256:8833266989d3a5110178a9fae30783675460724d0e1efb13b14901d2c660c557", size = 7750767, upload-time = "2026-06-02T11:54:32.706Z" } wheels = [ @@ -4810,7 +4810,7 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" } wheels = [ @@ -4869,7 +4869,7 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } wheels = [ @@ -4946,7 +4946,7 @@ resolution-markers = [ "python_full_version >= '3.12' and python_full_version < '3.14'", ] dependencies = [ - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" } wheels = [ diff --git a/python/vendor/lance-arrow/Cargo.toml b/python/vendor/lance-arrow/Cargo.toml index 9cb156f2e..e9adc478c 100644 --- a/python/vendor/lance-arrow/Cargo.toml +++ b/python/vendor/lance-arrow/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-arrow" -version = "15.0.0-beta.1" +version = "15.0.0-beta.2" edition = "2024" authors = ["Lance Devs "] license = "Apache-2.0" @@ -10,9 +10,6 @@ description = "Arrow Extension for Lance" keywords = ["data-format", "data-science", "machine-learning", "apache-arrow", "data-analytics"] categories = ["database-implementations"] -[lib] -crate-type = ["cdylib", "rlib"] - [dependencies] arrow-array.workspace = true arrow-buffer.workspace = true diff --git a/python/vendor/lance-arrow/README.lancedb.md b/python/vendor/lance-arrow/README.lancedb.md index 5ed714e08..4a9f6176f 100644 --- a/python/vendor/lance-arrow/README.lancedb.md +++ b/python/vendor/lance-arrow/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-arrow` from Lance tag `v15.0.0-beta.1` -(commit `46a7cfe1fba5efa1f90deea4c7b14d414b991409`), licensed under Apache-2.0. +This directory contains `rust/lance-arrow` from Lance tag `v15.0.0-beta.2` +(commit `f50a157269d925ad5708c7b0f7ec6c87b0fd08dd`), licensed under Apache-2.0. LanceDB carries a local fix in `src/lib.rs` for sliced child validity bitmaps until a Lance release includes the fix. The patch is selected in the root diff --git a/python/vendor/lance-arrow/src/lib.rs b/python/vendor/lance-arrow/src/lib.rs index f26e1f3e3..6c31cf0c5 100644 --- a/python/vendor/lance-arrow/src/lib.rs +++ b/python/vendor/lance-arrow/src/lib.rs @@ -27,7 +27,7 @@ use arrow_array::{ use arrow_array::{ Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array, new_null_array, }; -use arrow_buffer::MutableBuffer; +use arrow_buffer::{BooleanBufferBuilder, MutableBuffer, NullBuffer}; use arrow_data::ArrayDataBuilder; use arrow_schema::{ArrowError, DataType, Field, Fields, IntervalUnit, Schema, SortOptions}; use arrow_select::{interleave::interleave, take::take}; @@ -670,7 +670,7 @@ impl RecordBatchExt for RecordBatch { } let left_struct_array: StructArray = self.clone().into(); let right_struct_array: StructArray = other.clone().into(); - self.try_new_from_struct_array(merge(&left_struct_array, &right_struct_array)) + self.try_new_from_struct_array(merge(&left_struct_array, &right_struct_array)?) } fn merge_with_schema(&self, other: &RecordBatch, schema: &Schema) -> Result { @@ -921,12 +921,44 @@ fn holds_struct(data_type: &DataType) -> bool { } } +/// The values of `list`, with the items of every entry that is null in `list` +/// but valid in `other` made null. Those entries become valid when the two +/// lists are merged, and their items here were never meant to be read. Merging +/// the items then pushes these nulls into their children. +fn hide_items_revealed_by( + list: &GenericListArray, + other: Option<&NullBuffer>, +) -> ArrayRef { + let Some(nulls) = list.nulls() else { + return list.values().clone(); + }; + let revealed = match other { + Some(other) => other.inner() & &!nulls.inner(), + None => !nulls.inner(), + }; + if revealed.count_set_bits() == 0 { + return list.values().clone(); + } + let offsets = list.value_offsets(); + let mut items_validity = BooleanBufferBuilder::new(list.values().len()); + items_validity.append_n(list.values().len(), true); + for row in revealed.set_indices() { + for item in offsets[row].as_usize()..offsets[row + 1].as_usize() { + items_validity.set_bit(item, false); + } + } + adjust_child_validity( + list.values(), + Some(&NullBuffer::new(items_validity.finish())), + ) +} + /// Merge the values of two lists: structs field by field, nested lists /// recursively, anything else keeps the left side. -fn merge_list_values(left: &ArrayRef, right: &ArrayRef) -> ArrayRef { - match (left.data_type(), right.data_type()) { +fn merge_list_values(left: &ArrayRef, right: &ArrayRef) -> Result { + Ok(match (left.data_type(), right.data_type()) { (DataType::Struct(_), DataType::Struct(_)) => { - Arc::new(merge(left.as_struct(), right.as_struct())) + Arc::new(merge(left.as_struct(), right.as_struct())?) } (DataType::List(_), DataType::List(_)) | (DataType::LargeList(_), DataType::LargeList(_)) @@ -934,27 +966,29 @@ fn merge_list_values(left: &ArrayRef, right: &ArrayRef) -> ArrayRef { && holds_struct(left.data_type()) && holds_struct(right.data_type()) => { - merge_list_struct(left, right) + merge_list_struct(left, right, None, None)? } _ => left.clone(), - } + }) } fn merge_list_struct_helper( left: &dyn Array, right: &dyn Array, -) -> Arc { + null_left: bool, + null_right: bool, +) -> Result { let left_list: &GenericListArray = left.as_list(); let right_list: &GenericListArray = right.as_list(); - let item_name = match left.data_type() { - DataType::List(item) | DataType::LargeList(item) => item.name().clone(), - _ => unreachable!(), + let ((DataType::List(left_item), DataType::List(right_item)) + | (DataType::LargeList(left_item), DataType::LargeList(right_item))) = + (left.data_type(), right.data_type()) + else { + unreachable!() }; - // One side all-null (a placeholder for columns this fragment lacks) has - // no values, so stand in nulls shaped like the other side's. - let null_left = left_list.null_count() == left_list.len(); - let null_right = !null_left && right_list.null_count() == right_list.len(); - let (merged_items, list, items_nullable) = if null_left || null_right { + let (merged_items, list, nulls, items_nullable) = if null_left || null_right { + // One side all-null (a placeholder for columns this fragment lacks) has + // no values, so stand in nulls shaped like the other side's. let not_null = if null_left { right_list } else { left_list }; let values_len = not_null.values().len(); let values = |list: &GenericListArray, is_null: bool| { @@ -967,39 +1001,68 @@ fn merge_list_struct_helper( let merged = merge_list_values( &values(left_list, null_left), &values(right_list, null_right), - ); - (merged, not_null, true) + )?; + ( + merged, + not_null, + not_null.nulls().cloned(), + left_item.is_nullable() || right_item.is_nullable(), + ) } else { if left_list.offsets().inner() != right_list.offsets().inner() { panic!("Attempt to merge list struct arrays which do not have same offsets"); } - let merged = merge_list_values(left_list.values(), right_list.values()); - let nullable = match left.data_type() { - DataType::List(item) | DataType::LargeList(item) => item.is_nullable(), - _ => unreachable!(), - }; - (merged, left_list, nullable) + // The lists share offsets, and an entry is valid if either side has it, + // as for struct rows. Each side's items under its own null entries are + // hidden first, so the other side's validity cannot expose them. + let left_items = hide_items_revealed_by(left_list, right_list.nulls()); + let right_items = hide_items_revealed_by(right_list, left_list.nulls()); + let merged = merge_list_values(&left_items, &right_items)?; + ( + merged, + left_list, + merge_struct_validity(left_list.nulls(), right_list.nulls()), + left_item.is_nullable() || right_item.is_nullable(), + ) }; let items_field = Arc::new(Field::new( - item_name, + left_item.name(), merged_items.data_type().clone(), items_nullable, )); - Arc::new(GenericListArray::::new( + Ok(Arc::new(GenericListArray::::new( items_field, list.offsets().clone(), merged_items, - list.nulls().cloned(), - )) + nulls, + ))) } /// Merge two lists whose items hold structs. Only succeeds if both lists have /// the same offsets or one of them is all-null; panics otherwise. -fn merge_list_struct(left: &dyn Array, right: &dyn Array) -> Arc { +/// +/// `left_parent` and `right_parent`, when given, null each side's entries under +/// its null parent rows before the merge. +fn merge_list_struct( + left: &ArrayRef, + right: &ArrayRef, + left_parent: Option<&NullBuffer>, + right_parent: Option<&NullBuffer>, +) -> Result { + // The parents are applied before the all-null side is picked, so a side + // whose rows all sit under null parents counts as the placeholder and the + // other side's offsets are kept. + let left = adjust_child_validity(left, left_parent); + let right = adjust_child_validity(right, right_parent); + let null_left = left.null_count() == left.len(); + let null_right = !null_left && right.null_count() == right.len(); + let (left, right) = (left.as_ref(), right.as_ref()); match (left.data_type(), right.data_type()) { - (DataType::List(_), DataType::List(_)) => merge_list_struct_helper::(left, right), + (DataType::List(_), DataType::List(_)) => { + merge_list_struct_helper::(left, right, null_left, null_right) + } (DataType::LargeList(_), DataType::LargeList(_)) => { - merge_list_struct_helper::(left, right) + merge_list_struct_helper::(left, right, null_left, null_right) } _ => unreachable!(), } @@ -1187,7 +1250,46 @@ fn adjust_child_validity( ) } -fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> StructArray { +/// Fails if `field`, a non-nullable child of one side's struct, sits under a +/// row that is null on that side but valid in `merged`. The merged row is valid +/// because the other side has it, and this side has no value to show there. +fn check_hideable( + field: &Field, + parent: Option<&NullBuffer>, + merged: Option<&NullBuffer>, +) -> Result<()> { + let Some(parent) = parent.filter(|_| !field.is_nullable()) else { + return Ok(()); + }; + let revealed = match merged { + Some(merged) => merged.inner() & &!parent.inner(), + None => !parent.inner(), + }; + match revealed.set_indices().next() { + None => Ok(()), + Some(row) => Err(ArrowError::InvalidArgumentError(format!( + "Cannot merge non-nullable field '{}': its parent is null on one side but valid \ + on the other at row {row}, where the field has no value", + field.name() + ))), + } +} + +/// `column`, a child of one side's struct, with that struct's null rows pushed +/// into it. The merged struct is valid where either side is, so the column +/// would otherwise show, at a row only the other side has, what its own null +/// parent hides. +fn hide_under_parent( + field: &Field, + column: &ArrayRef, + parent: Option<&NullBuffer>, + merged: Option<&NullBuffer>, +) -> Result { + check_hideable(field, parent, merged)?; + Ok(adjust_child_validity(column, parent)) +} + +fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> Result { let mut fields: Vec = vec![]; let mut columns: Vec = vec![]; let right_fields = right_struct_array.fields(); @@ -1199,6 +1301,7 @@ fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> S // Compute merged validity let merged_validity = merge_struct_validity(left_validity, right_validity); + let merged = merged_validity.as_ref(); // iterate through the fields on the left hand side for (left_field, left_column) in left_struct_array @@ -1217,9 +1320,13 @@ fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> S // if both fields are struct, merge them recursively match (left_field.data_type(), right_field.data_type()) { (DataType::Struct(_), DataType::Struct(_)) => { - let left_sub_array = left_column.as_struct(); - let right_sub_array = right_column.as_struct(); - let merged_sub_array = merge(left_sub_array, right_sub_array); + // Both sides feed this column, so a row one side's parent + // hides can still take its value from the other side, and + // the field's nullability is checked on the merged result. + let left_sub_array = adjust_child_validity(left_column, left_validity); + let right_sub_array = adjust_child_validity(right_column, right_validity); + let merged_sub_array = + merge(left_sub_array.as_struct(), right_sub_array.as_struct())?; fields.push(Field::new( left_field.name(), merged_sub_array.data_type().clone(), @@ -1235,12 +1342,22 @@ fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> S // Identical inner types: nothing to merge, keep the left column. if left_list.data_type() == right_list.data_type() { fields.push(left_field.as_ref().clone()); - columns.push(left_column.clone()); + columns.push(hide_under_parent( + left_field, + left_column, + left_validity, + merged, + )?); } else { // The struct fields differ, so merge them structurally. merge_list_struct // only succeeds when both lists share offsets or one side is all-null; // it panics otherwise. - let merged_sub_array = merge_list_struct(&left_column, &right_column); + let merged_sub_array = merge_list_struct( + left_column, + right_column, + left_validity, + right_validity, + )?; fields.push(Field::new( left_field.name(), @@ -1254,41 +1371,41 @@ fn merge(left_struct_array: &StructArray, right_struct_array: &StructArray) -> S _ => { // TODO handle list-of-struct and other types fields.push(left_field.as_ref().clone()); - // Adjust the column validity: if left struct was null, propagate to child - let adjusted_column = adjust_child_validity(left_column, left_validity); - columns.push(adjusted_column); + columns.push(hide_under_parent( + left_field, + left_column, + left_validity, + merged, + )?); } } } None => { fields.push(left_field.as_ref().clone()); - // Adjust the column validity: if left struct was null, propagate to child - let adjusted_column = adjust_child_validity(left_column, left_validity); - columns.push(adjusted_column); + columns.push(hide_under_parent( + left_field, + left_column, + left_validity, + merged, + )?); } } } // now iterate through the fields on the right hand side - right_fields - .iter() - .zip(right_columns.iter()) - .for_each(|(field, column)| { - // add new columns on the right - if !left_struct_array - .fields() - .iter() - .any(|f| f.name() == field.name()) - { - fields.push(field.as_ref().clone()); - // This field doesn't exist on the left - // We use the right's column but need to adjust for struct validity - let adjusted_column = adjust_child_validity(column, right_validity); - columns.push(adjusted_column); - } - }); + for (field, column) in right_fields.iter().zip(right_columns.iter()) { + // add new columns on the right + if !left_struct_array + .fields() + .iter() + .any(|f| f.name() == field.name()) + { + fields.push(field.as_ref().clone()); + columns.push(hide_under_parent(field, column, right_validity, merged)?); + } + } - StructArray::try_new(Fields::from(fields), columns, merged_validity).unwrap() + StructArray::try_new(Fields::from(fields), columns, merged_validity) } fn merge_with_schema( @@ -1563,6 +1680,7 @@ impl BufferExt for arrow_buffer::Buffer { #[cfg(test)] mod tests { use super::*; + use arrow_array::types::Int32Type; use arrow_array::{ BinaryArray, BinaryViewArray, BooleanArray, FixedSizeBinaryArray, Float32Array, Int32Array, LargeBinaryArray, ListArray, NullArray, StringArray, StructArray, new_empty_array, @@ -2083,6 +2201,493 @@ mod tests { assert_eq!(merged, left); } + /// A list of `items`, one item per entry. + fn one_item_per_entry(large: bool, items: ArrayRef) -> ArrayRef { + let item_field = Arc::new(Field::new("item", items.data_type().clone(), true)); + let lengths = vec![1; items.len()]; + if large { + Arc::new(LargeListArray::new( + item_field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } else { + Arc::new(ListArray::new( + item_field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } + } + + /// A batch with the single column `s`, valid per `parent_validity`. + fn batch_of_parent(parent: StructArray) -> RecordBatch { + RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "s", + parent.data_type().clone(), + true, + )])), + vec![Arc::new(parent)], + ) + .unwrap() + } + + /// `{s: struct>>}`, one row per value, each + /// list holding one item, and `s` valid per `parent_validity`. + fn list_struct_under_parent( + large: bool, + child: &str, + parent_validity: &[bool], + values: &[i32], + ) -> RecordBatch { + let items = Arc::new(StructArray::new( + vec![Field::new(child, DataType::Int32, true)].into(), + vec![Arc::new(Int32Array::from(values.to_vec()))], + None, + )); + let list = one_item_per_entry(large, items); + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(parent_validity.to_vec().into()), + )) + } + + /// The child `name` of the single item in row `row` of the merged `s.l`. + fn merged_item_child(merged: &RecordBatch, large: bool, row: usize, name: &str) -> ArrayRef { + let list = merged.column(0).as_struct().column(0); + let item = if large { + list.as_list::().value(row) + } else { + list.as_list::().value(row) + }; + item.as_struct().column_by_name(name).unwrap().clone() + } + + #[test] + fn test_merge_list_struct_identical_schema_hides_a_null_parent_row() { + for large in [false, true] { + let left = list_struct_under_parent(large, "x", &[false, true], &[11, 12]); + let right = list_struct_under_parent(large, "x", &[true, true], &[21, 22]); + let merged = left.merge(&right).unwrap(); + let parent = merged.column(0).as_struct(); + assert!(parent.is_valid(0), "large={large}"); + assert!( + parent.column(0).is_null(0), + "large={large}: the list under the null left parent became visible" + ); + assert!(parent.column(0).is_valid(1), "large={large}"); + } + } + + #[test] + fn test_merge_list_struct_hides_the_items_of_a_null_parent_row() { + for large in [false, true] { + // Null parent on the left: row 0 keeps the right item, not x = 11. + let left = list_struct_under_parent(large, "x", &[false, true], &[11, 12]); + let right = list_struct_under_parent(large, "y", &[true, true], &[21, 22]); + let merged = left.merge(&right).unwrap(); + assert!(merged.column(0).as_struct().column(0).is_valid(0)); + assert!( + merged_item_child(&merged, large, 0, "x").is_null(0), + "large={large}: x under the null left parent became visible" + ); + let y = merged_item_child(&merged, large, 0, "y"); + assert_eq!(y.as_primitive::().value(0), 21, "large={large}"); + + // Null parent on the right: row 0 keeps x = 11, not y = 21. + let left = list_struct_under_parent(large, "x", &[true, true], &[11, 12]); + let right = list_struct_under_parent(large, "y", &[false, true], &[21, 22]); + let merged = left.merge(&right).unwrap(); + let x = merged_item_child(&merged, large, 0, "x"); + assert_eq!(x.as_primitive::().value(0), 11, "large={large}"); + assert!( + merged_item_child(&merged, large, 0, "y").is_null(0), + "large={large}: y under the null right parent became visible" + ); + + // Row 1 is valid on both sides and keeps both items. + let x = merged_item_child(&merged, large, 1, "x"); + let y = merged_item_child(&merged, large, 1, "y"); + assert_eq!(x.as_primitive::().value(0), 12, "large={large}"); + assert_eq!(y.as_primitive::().value(0), 22, "large={large}"); + } + } + + #[test] + fn test_merge_list_struct_follows_a_sliced_parent() { + for large in [false, true] { + // After slicing, row 0 is the null parent row and row 1 is valid. + let left = list_struct_under_parent(large, "x", &[true, false, true], &[10, 11, 12]); + let left = left.slice(1, 2); + + let same = list_struct_under_parent(large, "x", &[true, true, true], &[20, 21, 22]); + let merged = left.merge(&same.slice(1, 2)).unwrap(); + let list = merged.column(0).as_struct().column(0); + assert!(list.is_null(0), "large={large}"); + assert!(list.is_valid(1), "large={large}"); + + let other = list_struct_under_parent(large, "y", &[true, true, true], &[20, 21, 22]); + let merged = left.merge(&other.slice(1, 2)).unwrap(); + assert!( + merged_item_child(&merged, large, 0, "x").is_null(0), + "large={large}" + ); + let x = merged_item_child(&merged, large, 1, "x"); + assert_eq!(x.as_primitive::().value(0), 12, "large={large}"); + } + } + + /// A non-nullable `l` or item child cannot be nulled under a parent row that + /// only the other side has, so the merge fails there rather than show the + /// hidden value. Where both sides agree on the parent, nothing is revealed + /// and the same fields merge. + #[test] + fn test_merge_list_struct_with_non_nullable_fields_under_a_null_parent() { + #[derive(Clone, Copy)] + struct Shape { + child: &'static str, + l_nullable: bool, + item_nullable: bool, + child_nullable: bool, + null_first_entry: bool, + null_first_item: bool, + } + let shape = |child| Shape { + child, + l_nullable: true, + item_nullable: true, + child_nullable: true, + null_first_entry: false, + null_first_item: false, + }; + let batch = |shape: Shape, parent_validity: [bool; 2]| { + let items = Arc::new(StructArray::new( + vec![Field::new( + shape.child, + DataType::Int32, + shape.child_nullable, + )] + .into(), + vec![Arc::new(Int32Array::from(vec![1, 2]))], + shape.null_first_item.then(|| vec![false, true].into()), + )); + let list: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new( + "item", + items.data_type().clone(), + shape.item_nullable, + )), + OffsetBuffer::::from_lengths([1, 1]), + items, + shape.null_first_entry.then(|| vec![false, true].into()), + )); + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), shape.l_nullable)].into(), + vec![list], + Some(parent_validity.to_vec().into()), + )) + }; + let null_first = [false, true]; + let all_valid = [true, true]; + let cases = [ + // Non-nullable `l`, identical item types. + ( + Shape { + l_nullable: false, + ..shape("x") + }, + Shape { + l_nullable: false, + ..shape("x") + }, + Some("Cannot merge non-nullable field 'l'"), + ), + // Non-nullable `l` on the left, a null entry on the right: neither + // side has an entry at the merged row. + ( + Shape { + l_nullable: false, + ..shape("x") + }, + Shape { + null_first_entry: true, + ..shape("y") + }, + Some("non-nullable StructArray field \"l\""), + ), + // A non-nullable child of the item struct. + ( + Shape { + child_nullable: false, + ..shape("x") + }, + shape("y"), + Some("Cannot merge non-nullable field 'x'"), + ), + // A non-nullable item can be hidden where the right item is null. + ( + Shape { + item_nullable: false, + ..shape("x") + }, + Shape { + null_first_item: true, + ..shape("y") + }, + None, + ), + ]; + for (case, (left, right, rejected)) in cases.into_iter().enumerate() { + let merged = batch(left, null_first).merge(&batch(right, all_valid)); + match rejected { + Some(expected) => { + let message = merged.unwrap_err().to_string(); + assert!(message.contains(expected), "case {case}: {message}"); + } + None => assert!(merged.is_ok(), "case {case}: {merged:?}"), + } + let agreed = batch(left, null_first).merge(&batch(right, null_first)); + assert!( + agreed.is_ok(), + "case {case} with agreeing parents: {agreed:?}" + ); + } + } + + /// The fragment reader merges a data batch with an all-null placeholder for + /// a nested child the file lacks. Only the placeholder's top-level field is + /// nullable, so a non-nullable field below it must still merge, in either + /// order, keeping the data and filling the new child with nulls. + #[test] + fn test_merge_with_a_placeholder_under_a_non_nullable_field() { + let inner = + |child: &str| -> Fields { vec![Field::new(child, DataType::Int32, true)].into() }; + for wrap in ["struct", "list", "large_list"] { + let wrapped = |fields: Fields| match wrap { + "struct" => DataType::Struct(fields), + "list" => { + DataType::List(Arc::new(Field::new("item", DataType::Struct(fields), true))) + } + _ => DataType::LargeList(Arc::new(Field::new( + "item", + DataType::Struct(fields), + true, + ))), + }; + let outer = |child: &str| { + DataType::Struct(vec![Field::new("inner", wrapped(inner(child)), false)].into()) + }; + let items: ArrayRef = Arc::new(StructArray::new( + inner("a"), + vec![Arc::new(Int32Array::from(vec![1, 2]))], + None, + )); + let data_inner = match wrap { + "struct" => items, + "list" => one_item_per_entry(false, items), + _ => one_item_per_entry(true, items), + }; + let data = batch_of_parent(StructArray::new( + vec![Field::new("inner", data_inner.data_type().clone(), false)].into(), + vec![data_inner], + None, + )); + let placeholder = batch_of_parent(new_null_array(&outer("b"), 2).as_struct().clone()); + + for (left, right) in [(&data, &placeholder), (&placeholder, &data)] { + let merged = left.merge(right).unwrap(); + let inner = merged + .column(0) + .as_struct() + .column_by_name("inner") + .unwrap(); + let items = match wrap { + "struct" => inner.clone(), + "list" => inner.as_list::().values().clone(), + _ => inner.as_list::().values().clone(), + }; + let items = items.as_struct(); + let a = items.column_by_name("a").unwrap(); + assert_eq!(a.as_primitive::().values(), &[1, 2], "{wrap}"); + assert_eq!(a.null_count(), 0, "{wrap}"); + assert_eq!(items.column_by_name("b").unwrap().null_count(), 2, "{wrap}"); + } + } + } + + /// The null parent row's values stay hidden below a struct nested in the + /// list item, and below a plain struct field. + #[test] + fn test_merge_hides_nested_structs_of_a_null_parent_row() { + let nested = |child: &str, values: Vec| { + let leaf = StructArray::new( + vec![Field::new(child, DataType::Int32, true)].into(), + vec![Arc::new(Int32Array::from(values))], + None, + ); + StructArray::new( + vec![Field::new("payload", leaf.data_type().clone(), true)].into(), + vec![Arc::new(leaf)], + None, + ) + }; + let x_of = |payload: &dyn Array, row: usize| { + let x = payload.as_struct().column_by_name("x").unwrap().clone(); + x.is_null(row) + }; + + for large in [false, true] { + let in_list = |child: &str, parent: [bool; 2]| { + let list = one_item_per_entry(large, Arc::new(nested(child, vec![11, 12]))); + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(parent.to_vec().into()), + )) + }; + let merged = in_list("x", [false, true]) + .merge(&in_list("y", [true, true])) + .unwrap(); + let list = merged.column(0).as_struct().column(0); + let item = if large { + list.as_list::().value(0) + } else { + list.as_list::().value(0) + }; + let payload = item.as_struct().column_by_name("payload").unwrap(); + assert!(x_of(payload.as_ref(), 0), "large={large}"); + } + + let in_struct = |child: &str, parent: [bool; 2]| { + let inner = nested(child, vec![11, 12]); + batch_of_parent(StructArray::new( + vec![Field::new("c", inner.data_type().clone(), true)].into(), + vec![Arc::new(inner)], + Some(parent.to_vec().into()), + )) + }; + let merged = in_struct("x", [false, true]) + .merge(&in_struct("y", [true, true])) + .unwrap(); + let c = merged.column(0).as_struct().column(0); + let payload = c.as_struct().column_by_name("payload").unwrap(); + assert!(x_of(payload.as_ref(), 0)); + assert!(!x_of(payload.as_ref(), 1)); + } + + /// A batch whose parent rows are all null merges with an all-null + /// placeholder whose item struct holds more fields. + #[test] + fn test_merge_list_struct_under_null_parents_with_a_placeholder() { + for large in [false, true] { + let a = Field::new("a", DataType::Int32, true); + let inner = StructArray::new( + vec![a.clone()].into(), + vec![Arc::new(Int32Array::from(vec![1, 2]))], + None, + ); + let items = Arc::new(StructArray::new( + vec![Field::new("x", inner.data_type().clone(), true)].into(), + vec![Arc::new(inner)], + None, + )); + let list = one_item_per_entry(large, items); + let left = batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(vec![false, false].into()), + )); + + let wider_x = + DataType::Struct(vec![a.clone(), Field::new("b", DataType::Int32, true)].into()); + let wider_items = new_null_array( + &DataType::Struct(vec![Field::new("x", wider_x, true)].into()), + 2, + ); + let wider_list = one_item_per_entry(large, wider_items); + let placeholder = new_null_array( + &DataType::Struct( + vec![Field::new("l", wider_list.data_type().clone(), true)].into(), + ), + 2, + ); + let right = batch_of_parent(placeholder.as_struct().clone()); + + let merged = left.merge(&right).unwrap(); + assert_eq!(merged.column(0).null_count(), 2, "large={large}"); + } + } + + /// A side whose list entries are all hidden by null parents merges like a + /// placeholder, so the other side's lists survive even with other offsets. + #[test] + fn test_merge_list_struct_hidden_side_keeps_the_other_offsets() { + for large in [false, true] { + let list_of = |child: &str, lengths: Vec, values: Vec| -> ArrayRef { + let items: ArrayRef = Arc::new(StructArray::new( + vec![Field::new(child, DataType::Int32, true)].into(), + vec![Arc::new(Int32Array::from(values))], + None, + )); + let field = Arc::new(Field::new("item", items.data_type().clone(), true)); + if large { + Arc::new(LargeListArray::new( + field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } else { + Arc::new(ListArray::new( + field, + OffsetBuffer::::from_lengths(lengths), + items, + None, + )) + } + }; + let parent = |list: ArrayRef, validity: Vec| { + batch_of_parent(StructArray::new( + vec![Field::new("l", list.data_type().clone(), true)].into(), + vec![list], + Some(validity.into()), + )) + }; + let left = parent(list_of("x", vec![1, 1], vec![1, 2]), vec![false, false]); + let right = parent(list_of("y", vec![2, 0], vec![7, 8]), vec![true, true]); + + let merged = left.merge(&right).unwrap(); + let list = merged.column(0).as_struct().column(0); + let (first, second) = if large { + let list = list.as_list::(); + (list.value(0), list.value(1)) + } else { + let list = list.as_list::(); + (list.value(0), list.value(1)) + }; + let first = first.as_struct(); + assert_eq!( + first + .column_by_name("y") + .unwrap() + .as_primitive::() + .values(), + &[7, 8], + "large={large}" + ); + assert_eq!( + first.column_by_name("x").unwrap().null_count(), + 2, + "large={large}" + ); + assert_eq!(second.len(), 0, "large={large}"); + } + } + #[test] fn test_byte_width_opt() { assert_eq!(DataType::Int32.byte_width_opt(), Some(4)); @@ -2315,7 +2920,7 @@ mod tests { ); // Merge the two structs - let merged = merge(&left_struct, &right_struct); + let merged = merge(&left_struct, &right_struct).unwrap(); // Expected: // Row 1: both non-null -> {width: 300, height: 500} @@ -2355,7 +2960,7 @@ mod tests { Some(vec![false, false].into()), ); - let merged = merge(&all_null_left, &all_null_right); + let merged = merge(&all_null_left, &all_null_right).unwrap(); assert_eq!(merged.null_count(), 2); // An all-null side is the identity of the merge, so the other side decides each row. @@ -2364,7 +2969,7 @@ mod tests { vec![Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef], Some(vec![true, false].into()), ); - let merged = merge(&partial_left, &all_null_right); + let merged = merge(&partial_left, &all_null_right).unwrap(); assert!(!merged.is_null(0)); assert!(merged.is_null(1)); @@ -2374,7 +2979,7 @@ mod tests { vec![Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef], None, ); - let merged = merge(&all_valid_left, &all_null_right); + let merged = merge(&all_valid_left, &all_null_right).unwrap(); assert_eq!(merged.null_count(), 0); // An explicit all-valid buffer has the same semantics as a missing buffer. @@ -2401,7 +3006,7 @@ mod tests { ); // Previously panicked: "Arrays of type Null cannot contain a null bitmask" - let merged = merge(&left_struct, &right_struct); + let merged = merge(&left_struct, &right_struct).unwrap(); assert_eq!(merged.len(), 2); let b_col = merged.column_by_name("b").unwrap(); // DataType::Null implies all-null by definition; no null bitmap is stored. diff --git a/python/vendor/lance-arrow/src/stream.rs b/python/vendor/lance-arrow/src/stream.rs index c5e55f093..5aee834fd 100644 --- a/python/vendor/lance-arrow/src/stream.rs +++ b/python/vendor/lance-arrow/src/stream.rs @@ -8,16 +8,21 @@ use arrow_array::RecordBatch; use arrow_schema::{ArrowError, SchemaRef}; use futures::stream::{self, Stream, StreamExt}; use std::pin::Pin; +use std::vec::IntoIter; use crate::deepcopy::deep_copy_batch_sliced; /// Rechunks a stream of [`RecordBatch`] so that each output batch has -/// approximately `target_bytes` of array data. +/// approximately `max_bytes` of array data. /// /// Small input batches are accumulated (by concatenation) until at least /// `min_bytes` of data has been collected. If the resulting batch exceeds /// `max_bytes`, it is sliced into roughly equal pieces of ~`max_bytes` /// (assuming uniform row sizes). +/// +/// Slices share the input's buffers, so their array memory sizes may still +/// report the full parent allocation. Once split, all slices are delivered +/// directly, including a final slice smaller than `min_bytes`. pub fn rechunk_stream_by_size( input: S, input_schema: SchemaRef, @@ -74,6 +79,7 @@ where RechunkState { input: Box::pin(input), accumulated: Vec::new(), + slices: Vec::new().into_iter(), acc_bytes: 0, done: false, input_schema, @@ -82,6 +88,12 @@ where deep_copy, }, |mut state| async move { + // These slices are already sized. Measuring their shared buffers + // again would repeatedly split the tail using the parent size. + if let Some(batch) = state.slices.next() { + return Ok(Some((batch, state))); + } + if state.done && state.accumulated.is_empty() { return Ok(None); } @@ -106,17 +118,6 @@ where return Ok(None); } - // Fast path: if the first accumulated batch already meets the - // byte threshold, deliver it directly instead of concatenating - // everything together (which would just get sliced back apart). - if state.accumulated.len() > 1 - && state.accumulated[0].get_array_memory_size() >= state.min_bytes - { - let b = state.accumulated.remove(0); - state.acc_bytes -= b.get_array_memory_size(); - return Ok(Some((b, state))); - } - let batch = if state.accumulated.len() == 1 { state.accumulated.pop().unwrap() } else { @@ -132,19 +133,9 @@ where let mut slices = slice_batch(batch, state.max_bytes, state.deep_copy).map_err(E::from)?; - if slices.len() == 1 { - Ok(Some((slices.pop().unwrap(), state))) - } else { - let first = slices.remove(0); - - // Stash leftover slices for subsequent iterations. - for a in &slices { - state.acc_bytes += a.get_array_memory_size(); - } - state.accumulated = slices; - - Ok(Some((first, state))) - } + let first = slices.remove(0); + state.slices = slices.into_iter(); + Ok(Some((first, state))) }, ) } @@ -206,12 +197,13 @@ fn slice_batch( Ok(result) } -/// Internal state for [`rechunk_stream`]. +/// Internal state for [`rechunk_stream_by_size`]. /// /// Kept as a named struct so the `try_unfold` closure stays readable. struct RechunkState { input: Pin>, accumulated: Vec, + slices: IntoIter, acc_bytes: usize, done: bool, input_schema: SchemaRef, @@ -339,9 +331,9 @@ mod tests { #[test] fn test_sliced_leftovers_are_not_recombined() { - // Key test for the fast-path optimisation. When a large batch is - // sliced, leftover slices should be delivered one-at-a-time without - // being concatenated back together. We verify this by checking that + // When a large batch is sliced, leftover slices should be delivered + // one at a time without being split again or concatenated back + // together. We verify zero-copy behavior by checking that // every output buffer pointer falls inside the original batch's // allocation (i.e. they are all zero-copy slices, not fresh copies). let batch = make_batch(1000); @@ -354,7 +346,11 @@ mod tests { let result = collect_rechunked(vec![batch], bytes / 8, bytes / 4); assert_eq!(total_rows(&result), 1000); - assert!(result.len() >= 4); + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![250, 250, 250, 250], + "leftover slices must not be split again using the parent buffer size" + ); for (i, b) in result.iter().enumerate() { let ptr = b.column(0).to_data().buffers()[0].as_ptr() as usize; @@ -381,6 +377,7 @@ mod tests { // After a large batch is fully drained, subsequent small batches // should be accumulated normally. let large = make_batch(1000); + let large_bytes = large.get_array_memory_size(); let small_bytes = make_batch(10).get_array_memory_size(); let batches = vec![ large, @@ -390,12 +387,12 @@ mod tests { make_batch(10), make_batch(10), ]; - let result = collect_rechunked(batches, small_bytes * 3, small_bytes * 100); + let result = collect_rechunked(batches, small_bytes * 3, large_bytes / 4); assert_eq!(total_rows(&result), 1050); - // The large batch should appear (possibly sliced) followed by - // concatenated small batches, so we should have fewer output batches - // than the 6 inputs. - assert!(result.len() < 6); + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![250, 250, 250, 250, 30, 20] + ); } #[test] @@ -441,10 +438,9 @@ mod tests { let bytes = batch.get_array_memory_size(); let result = collect_rechunked(vec![batch], 0, bytes / 4); assert_eq!(total_rows(&result), 1000); - assert!( - result.len() >= 4, - "expected at least 4 slices, got {}", - result.len() + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![250, 250, 250, 250] ); } @@ -475,6 +471,25 @@ mod tests { Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)])) } + #[test] + fn test_variable_length_tail_is_not_resliced() { + let batch = make_variable_batch(100, 256, usize::MAX, 256); + let bytes = batch.get_array_memory_size(); + let max_bytes = bytes - bytes / 4; + let input = stream::iter(vec![Ok::<_, ArrowError>(batch)]); + let rechunked = rechunk_stream_by_size(input, variable_schema(), max_bytes, max_bytes); + let result: Vec<_> = block_on(rechunked.collect::>()) + .into_iter() + .map(Result::unwrap) + .collect(); + + assert_eq!( + result.iter().map(RecordBatch::num_rows).collect::>(), + vec![75, 25] + ); + assert_eq!(total_rows(&result), 100); + } + fn collect_rechunked_variable( batches: Vec, min_bytes: usize, diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 62029bb92..7f3764b02 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -46,7 +46,7 @@ lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lind lance-table = { workspace = true } lance-linalg = { workspace = true } lance-encoding = { workspace = true } -lance-arrow = { version = "=15.0.0-beta.1", tag = "v15.0.0-beta.1", git = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } lance-namespace = { workspace = true } lance-namespace-impls = { workspace = true } metrics = { workspace = true, optional = true } diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 142b2264e..07808d56c 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -687,6 +687,8 @@ async fn map_blob_take_error( let message = err.to_string(); let missing_row_id = message.contains("must not target deleted rows") || message.contains("belongs to non-existent fragment") + || (message.contains("Unknown fragment id ") + && message.contains("in fragment filter; not part of the current dataset version")) || (message.contains("Invalid read params ") && message.contains("addressable rows")) || message.contains("Could not resolve all requested row IDs"); diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 91a0ed6ea..a066a4d6d 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -2137,7 +2137,7 @@ mod lsm_tests { } fn training_criteria(&self) -> lance_index::scalar::registry::TrainingCriteria { use lance_index::scalar::registry::{TrainingCriteria, TrainingOrdering}; - TrainingCriteria::new(TrainingOrdering::Values).with_row_id() + TrainingCriteria::new(TrainingOrdering::Values).with_row_addr() } fn validate( &self, @@ -2181,24 +2181,8 @@ mod lsm_tests { &self, ctx: &lance::dataset::mem_wal::index::FlushContext<'_>, ) -> lance_core::Result { - // BTree now trains on row addresses, while Bitmap still takes row IDs. - // These coincide in the flushed generation, which uses physical IDs. - assert!(!ctx.generation()?.dataset.manifest().uses_stable_row_ids()); - let batches = self - .0 - .to_training_batches(ctx.batch_size)? - .into_iter() - .map(|batch| { - assert_eq!(batch.schema().field(1).name(), lance_core::ROW_ADDR); - let schema = Arc::new(Schema::new(vec![ - batch.schema().field(0).clone(), - Field::new(lance_core::ROW_ID, DataType::UInt64, false), - ])); - RecordBatch::try_new(schema, batch.columns().to_vec()) - }) - .collect::, _>>()?; Ok(lance::dataset::mem_wal::index::FlushOutcome::from_batches( - batches, + self.0.to_training_batches(ctx.batch_size)?, )) } } From 83b727513744edd565d408a8b7a6043438bd12f3 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:51:06 +0800 Subject: [PATCH 124/180] fix(remote): make HTTP timeout errors actionable (#4650) Remote `create_table` reader uploads can exceed the read deadline while waiting for response headers, but reqwest's main error message only says "error sending request". Make HTTP and retry errors explicitly identify timeouts and name the relevant `client_config.timeout_config` settings and environment variables, preserving typed sources, request metadata, and retry classification. Document that the read timeout covers waiting for headers during upload. This implements the issue's diagnostic option: creation still uses one streaming request, so large or slow readers may require a longer `client_config.timeout_config.read_timeout`. Validation: - 48 focused Rust client, error, and retry tests passed. Regression coverage holds an upload open until its read timeout and also exercises TLS connection timeouts, with and without retries. - 8 Python create-table and HTTP/retry error tests passed in the uv-managed environment after rebuilding the extension, including reader creation with read and overall timeouts. - `cargo check --quiet --features remote --tests --examples` passed. - `cargo clippy --quiet --features remote --tests --examples` passed. - Rust formatting and Python package Ruff lint/format checks passed. - Repository-wide `ruff check .` reports 49 existing findings under `docs/web-tests`; those files are unchanged. Fixes #4646 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/src/js/interfaces/TimeoutConfig.md | 4 + nodejs/src/remote.rs | 4 + python/python/lancedb/remote/__init__.py | 5 +- python/python/tests/test_remote_db.py | 37 ++++++++ rust/lancedb/src/error.rs | 41 +++++++- rust/lancedb/src/remote/client.rs | 115 +++++++++++++++++++++++ 6 files changed, 203 insertions(+), 3 deletions(-) diff --git a/docs/src/js/interfaces/TimeoutConfig.md b/docs/src/js/interfaces/TimeoutConfig.md index c821afc4d..74e174522 100644 --- a/docs/src/js/interfaces/TimeoutConfig.md +++ b/docs/src/js/interfaces/TimeoutConfig.md @@ -45,6 +45,10 @@ The timeout for reading data from the server in seconds. Default is 300 seconds (5 minutes). This can also be set via the environment variable `LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds. +This also applies while waiting for response headers during an upload. +A large or slowly produced request body (for example, when creating a +table) may need a longer timeout even if data is still being uploaded. + *** ### timeout? diff --git a/nodejs/src/remote.rs b/nodejs/src/remote.rs index d7e2a21cd..c776ea597 100644 --- a/nodejs/src/remote.rs +++ b/nodejs/src/remote.rs @@ -25,6 +25,10 @@ pub struct TimeoutConfig { /// The timeout for reading data from the server in seconds. Default is 300 /// seconds (5 minutes). This can also be set via the environment variable /// `LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds. + /// + /// This also applies while waiting for response headers during an upload. + /// A large or slowly produced request body (for example, when creating a + /// table) may need a longer timeout even if data is still being uploaded. pub read_timeout: Option, /// The timeout for keeping idle connections in the connection pool in seconds. /// Default is 300 seconds (5 minutes). This can also be set via the diff --git a/python/python/lancedb/remote/__init__.py b/python/python/lancedb/remote/__init__.py index a1c8ebee5..bb9a32122 100644 --- a/python/python/lancedb/remote/__init__.py +++ b/python/python/lancedb/remote/__init__.py @@ -52,7 +52,10 @@ class TimeoutConfig: `LANCE_CLIENT_CONNECT_TIMEOUT`, as an integer number of seconds. read_timeout: Optional[timedelta] The timeout for reading data from the server. Default is 300 seconds - (5 minutes). This can also be set via the environment variable + (5 minutes). This also applies while waiting for response headers during + an upload. Increase it for large or slowly produced inputs to + `create_table`, even if data is still being uploaded. This can also be + set via the environment variable `LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds. pool_idle_timeout: Optional[timedelta] The timeout for keeping idle connections in the connection pool. Default diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 32f999d18..b2515cd26 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -811,6 +811,43 @@ def test_create_table_exist_ok_with_mode_overwrite(): assert table is not None +@pytest.mark.asyncio +@pytest.mark.parametrize( + "timeout_config", + [{"read_timeout": 0.5}, {"timeout": 0.5, "read_timeout": 5}], +) +async def test_create_table_timeout_is_actionable(timeout_config): + release_response = threading.Event() + received = {} + + def handler(request): + received["path"] = request.path + received["request_id"] = request.headers["x-request-id"] + release_response.wait(timeout=5) + request.close_connection = True + + async with mock_lancedb_connection_async( + handler, timeout_config=timeout_config + ) as db: + batch = pa.record_batch({"id": [1, 2]}) + reader = pa.RecordBatchReader.from_batches(batch.schema, [batch]) + try: + with pytest.raises(HttpError) as exc_info: + await db.create_table("test", reader) + finally: + release_response.set() + + error = exc_info.value + assert "timed out" in str(error) + assert "client_config.timeout_config.read_timeout" in str(error) + assert "client_config.timeout_config.timeout" in str(error) + assert "LANCE_CLIENT_READ_TIMEOUT" in str(error) + assert received["path"] == "/v1/table/test/create/?mode=create" + assert error.request_id == received["request_id"] + assert error.status_code is None + assert isinstance(error.__cause__, HttpError) + + @pytest.mark.asyncio async def test_http_error(): request_id_holder = {"request_id": None} diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 6052b67d8..1b1f5b0a5 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -10,6 +10,25 @@ use snafu::Snafu; pub(crate) type BoxError = Box; +// reqwest's Display omits the timeout cause. Add guidance at display time so +// callers still receive the original typed source and its full error chain. +#[cfg(feature = "remote")] +fn http_timeout_hint(source: &(dyn std::error::Error + 'static)) -> &'static str { + match source.downcast_ref::() { + Some(error) if error.is_timeout() && error.is_connect() => { + "; connection timed out. Check client_config.timeout_config.connect_timeout \ + (LANCE_CLIENT_CONNECT_TIMEOUT) and client_config.timeout_config.timeout \ + (LANCE_CLIENT_TIMEOUT) if configured" + } + Some(error) if error.is_timeout() => { + "; request timed out. For slow uploads or responses, check \ + client_config.timeout_config.read_timeout (LANCE_CLIENT_READ_TIMEOUT) \ + and client_config.timeout_config.timeout (LANCE_CLIENT_TIMEOUT) if configured" + } + _ => "", + } +} + /// Why a job failed, to whatever precision the backend provides. /// /// A job run in this process carries the error it failed with in [`Self::source`]. @@ -111,7 +130,10 @@ pub enum Error { #[snafu(display("lance error: {source}"))] Lance { source: lance::Error }, #[cfg(feature = "remote")] - #[snafu(display("Http error: (request_id={request_id}) {source}"))] + #[snafu(display( + "Http error: (request_id={request_id}) {source}{}", + http_timeout_hint(source.as_ref()) + ))] Http { #[snafu(source(from(reqwest::Error, Box::new)))] source: Box, @@ -127,7 +149,8 @@ pub enum Error { "Hit retry limit for request_id={request_id} (\ request_failures={request_failures}/{max_request_failures}, \ connect_failures={connect_failures}/{max_connect_failures}, \ - read_failures={read_failures}/{max_read_failures}): {source}" + read_failures={read_failures}/{max_read_failures}): {source}{}", + http_timeout_hint(source.as_ref()) ))] Retry { request_id: String, @@ -314,6 +337,20 @@ impl From for Error { mod tests { use super::*; + #[cfg(feature = "remote")] + #[test] + fn non_timeout_http_error_message_is_unchanged() { + let error = Error::Http { + source: "server error".into(), + request_id: "test".into(), + status_code: Some(reqwest::StatusCode::INTERNAL_SERVER_ERROR), + }; + assert_eq!( + error.to_string(), + "Http error: (request_id=test) server error" + ); + } + #[test] fn unsupported_filesystem_operations_have_actionable_error() { let object_store_error = object_store::Error::Generic { diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index f54e2fe3e..bf90b1e77 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -233,6 +233,10 @@ pub struct TimeoutConfig { pub connect_timeout: Option, /// The timeout for reading a response from the server. /// + /// This also applies while waiting for response headers during an upload. + /// A large or slowly produced request body (for example, when creating a + /// table) may need a longer timeout even if data is still being uploaded. + /// /// You can also set the `LANCE_CLIENT_READ_TIMEOUT` environment variable /// to set this value. Use an integer value in seconds. /// @@ -1205,6 +1209,117 @@ pub mod test_utils { #[cfg(test)] mod tests { + #[tokio::test] + async fn test_http_timeout_error_is_actionable() { + use super::*; + use futures::StreamExt; + + // Keep consuming the upload without sending response headers (HTTP) or + // completing the TLS handshake (HTTPS). The HTTP body never reaches EOF, + // so its read timeout fires while it is still uploading. + for (scheme, retry) in [ + ("http", false), + ("http", true), + ("https", false), + ("https", true), + ] { + let connect_timeout = scheme == "https"; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let _ = tokio::io::copy(&mut socket, &mut tokio::io::sink()).await; + }); + let client = RestfulLanceDbClient::try_new( + &parse_db_url("db://test").unwrap(), + "us-east-1", + Some(format!("{scheme}://{address}")), + HeaderMap::new(), + ClientConfig { + timeout_config: TimeoutConfig { + connect_timeout: Some(Duration::from_millis(200)), + read_timeout: Some(Duration::from_secs(2)), + ..Default::default() + }, + retry_config: RetryConfig { + connect_retries: Some(1), + read_retries: Some(1), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let make_body = || { + Ok(Body::wrap_stream( + futures::stream::once(async { + Ok::<_, std::io::Error>(bytes::Bytes::from_static(b"upload")) + }) + .chain(futures::stream::pending()), + )) + }; + let request = client + .post("/v1/table/test/create/") + .header(REQUEST_ID_HEADER, "upload-timeout"); + let error = if retry { + client + .send_with_retry(request, Some(Box::new(make_body)), true) + .await + } else { + client.send(request.body(make_body().unwrap())).await + } + .unwrap_err(); + server.abort(); + + let message = error.to_string(); + assert!(message.contains("timed out"), "{message}"); + let (config, env_var) = if connect_timeout { + ( + "client_config.timeout_config.connect_timeout", + "LANCE_CLIENT_CONNECT_TIMEOUT", + ) + } else { + ( + "client_config.timeout_config.read_timeout", + "LANCE_CLIENT_READ_TIMEOUT", + ) + }; + assert!(message.contains(config), "{message}"); + assert!( + message.contains("client_config.timeout_config.timeout"), + "{message}" + ); + assert!(message.contains(env_var), "{message}"); + let (request_id, status_code, source) = match &error { + Error::Http { + request_id, + status_code, + source, + } if !retry => (request_id, status_code, source), + Error::Retry { + request_id, + status_code, + source, + read_failures, + connect_failures, + .. + } if retry => { + assert_eq!(*read_failures, u8::from(!connect_timeout)); + assert_eq!(*connect_failures, u8::from(connect_timeout)); + (request_id, status_code, source) + } + other => panic!("unexpected error: {other:?}"), + }; + assert_eq!(request_id, "upload-timeout"); + assert_eq!(*status_code, None); + // Retain the typed source for retry classification and Python causes. + let source = source.downcast_ref::().unwrap(); + assert!(source.is_timeout()); + assert_eq!(source.is_connect(), connect_timeout); + } + } + /// A configuration naming any other delimiter is refused where it was /// written, rather than producing identifiers no service splits the way the /// caller meant. From c167b99fa075b10b97ebce976d509861b0974807 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:56:50 +0800 Subject: [PATCH 125/180] fix: read legacy blob columns through blob APIs (#4649) Legacy blob v1 columns were rejected by LanceDB's blob validation and omitted from `blob_columns()`, even though the pinned Lance reader already supports them. Accept both blob versions in read validation and discovery so `fetch_blobs`, `fetch_blob_files`, and `fetch_blob_ranges` can read legacy payloads through the existing native reader. Keep list-nested blobs excluded from row-based reads and document how to fetch legacy blobs using explicit row IDs. Regression coverage checks sync and async APIs, independently written Lance datasets, ordering and duplicates across fragments, null and empty blobs, lazy seeking, ranges, and deleted rows. Fixes #4644 Validation: - Both new Python regressions failed on the original implementation with the reported legacy-column rejection and empty discovery result, then passed with the fix. - Python blob suite: 202 passed, 1 skipped. - Remote blob tests: 29 passed. - Focused Rust blob unit tests with `remote`: 13 passed. - Rust blob integration suite with `remote`: 59 passed, including legacy storage 2.0 and 2.1. - Rust compile and Clippy checks with `remote`, tests, and examples passed. - Python package Ruff lint and format checks passed; Rust formatting passed. - Repository-wide `ruff check .` reports 49 existing errors in unchanged `docs/web-tests` examples; the Python package is clean. --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/src/python/python.md | 3 + python/python/lancedb/table.py | 7 +- python/python/tests/test_blob.py | 70 +++++++++++++++++- rust/lancedb/src/blob.rs | 98 ++++++++++++++++++++------ rust/lancedb/src/remote/table/blobs.rs | 2 +- rust/lancedb/src/table.rs | 13 ++-- rust/lancedb/tests/blob_integration.rs | 66 +++++++++++++++-- 7 files changed, 220 insertions(+), 39 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5f87302ad..d42d70c4a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -581,6 +581,9 @@ pylance, LanceDB uses a matching `lance.blob.v2` extension type so blob columns still work. Native table queries return descriptors. Call [`fetch_blob_files`][lancedb.table.Table.fetch_blob_files] for lazy reads or [`fetch_blobs`][lancedb.table.Table.fetch_blobs] for eager bytes. +Local tables support these fetch APIs for both legacy blob v1 columns +(`lance-encoding:blob`) and blob v2 columns. For legacy columns, obtain row IDs +with `search().with_row_id(True).to_arrow()` and pass the result to the fetch API. One missing or deleted row ID rejects the entire blob-read batch; the APIs do not return partial results. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 6df109d6c..7bef43c0d 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2516,7 +2516,7 @@ class Table(ABC): @abstractmethod def blob_columns(self) -> list[str]: - """Names of blob v2 columns that can be fetched by row id. + """Names of blob v1 and v2 columns that can be fetched by row id. Struct-nested blobs use dotted paths. Blobs inside lists are omitted because a row id does not identify an individual list element. @@ -2530,6 +2530,7 @@ class Table(ABC): ) -> pa.LargeBinaryArray: """Materialize full blob bytes for ``column`` at the given rows. + Local tables support both legacy blob v1 and blob v2 columns. The result has the same length and order as ``row_ids``. Null blobs produce null slots; valid empty blobs produce ``b""``. @@ -2553,8 +2554,9 @@ class Table(ABC): column: str, requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: - """Materialize row-specific byte ranges from a blob v2 column. + """Materialize row-specific byte ranges from a blob column. + Local tables support both legacy blob v1 and blob v2 columns. Each request is a three-item ``(row_id, offset, length)`` sequence. Requests may be repeated or reordered, including multiple ranges for the same blob. @@ -2579,6 +2581,7 @@ class Table(ABC): ) -> "list[Optional[BlobFile]]": """Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles. + Local tables support both legacy blob v1 and blob v2 columns. Prefer this over :meth:`fetch_blobs` for large payloads. ``row_ids`` is a ``list[int]``, an integer Arrow array or chunked array, or a query ``pyarrow.Table`` carrying row identity via ``_rowid`` or a diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index da362f053..f4c6a9e24 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1903,10 +1903,74 @@ def test_legacy_v1_query_omits_auto_row_id(): assert "_rowid" not in hits.column_names -def test_fetch_blobs_rejects_legacy_v1_column(): +def test_fetch_legacy_v1_blobs(): table = _legacy_v1_table("legacy_fetch") - with pytest.raises(ValueError, match="legacy blob column.*blob v2"): - table.fetch_blobs("legacy", [0]) + table.add( + [ + {"id": 2, "legacy": None}, + {"id": 3, "legacy": b""}, + {"id": 4, "legacy": b"another fragment"}, + ] + ) + hits = table.search().select(["id", "legacy"]).with_row_id(True).to_arrow() + assert pa.types.is_struct(hits["legacy"].type) + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + row_ids = [by_id[i] for i in [4, 2, 1, 3, 4]] + expected = [b"another fragment", None, b"old", b"", b"another fragment"] + assert table.fetch_blobs("legacy", row_ids).to_pylist() == expected + assert table.blob_columns() == ["legacy"] + assert table.fetch_blobs("legacy", hits).to_pylist() == [ + b"old", + None, + b"", + b"another fragment", + ] + assert table.fetch_blobs("legacy", []).to_pylist() == [] + assert table.fetch_blob_files("legacy", []) == [] + + handles = table.fetch_blob_files("legacy", row_ids) + assert len(handles) == len(expected) + for handle, payload in zip(handles, expected): + if payload is None: + assert handle is None + else: + with handle: + assert handle.size() == len(payload) + assert handle.read(2) == payload[:2] + assert handle.seek(0) == 0 + assert handle.read() == payload + + assert table.fetch_blob_ranges( + "legacy", [(by_id[4], 8, 8), (by_id[2], 0, 1), (by_id[3], 0, 0)] + ).to_pylist() == [b"fragment", None, b""] + + table.delete("id = 2") + for fetch in [table.fetch_blobs, table.fetch_blob_files]: + with pytest.raises(ValueError, match="row ids but some do not exist"): + fetch("legacy", [by_id[1], by_id[2]]) + + +@pytest.mark.asyncio +async def test_async_fetch_legacy_v1_blobs(tmp_path): + table = _legacy_v1_table("legacy_async_source") + # Open a dataset written by Lance independently of the LanceDB connection. + lance.write_dataset( + pa.Table.from_pylist( + [{"id": 1, "legacy": b"old"}, {"id": 2, "legacy": None}], + schema=table.schema, + ), + tmp_path / "legacy.lance", + data_storage_version="2.0", + ) + db = await lancedb.connect_async(tmp_path) + table = await db.open_table("legacy") + assert await table.blob_columns() == ["legacy"] + hits = await table.query().with_row_id().to_arrow() + assert (await table.fetch_blobs("legacy", hits)).to_pylist() == [b"old", None] + handles = await table.fetch_blob_files("legacy", hits) + assert handles[0].read() == b"old" + handles[0].close() + assert handles[1] is None @pytest.mark.asyncio diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 07808d56c..ce124e891 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -1,13 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Lance blob v2 columns store large binary payloads out of line. +//! Lance blob columns store large binary payloads out of line. //! -//! Declare a column with [`blob`]. On write, [`crate::table::Table::add`] coerces +//! The read APIs support both legacy blob v1 and blob v2 columns. +//! +//! Declare a blob v2 column with [`blob`]. On write, [`crate::table::Table::add`] coerces //! raw `Binary` / `LargeBinary` into the blob struct layout. Queries return //! small descriptors, not bytes. //! -//! Blob tables require Lance file format >= 2.2. `_rowid` values stay valid +//! Blob v2 tables require Lance file format >= 2.2. `_rowid` values stay valid //! after compaction when the table has stable row ids. Overwrite is a new //! create and does not keep the previous table's stable row id setting. @@ -467,14 +469,27 @@ pub(crate) fn field_tree_has_blob_v2(field: &Field) -> bool { } } -/// Collects the dotted paths of row-addressable blob v2 columns under `field`. +fn field_tree_has_blob(field: &Field) -> bool { + if field.is_blob() { + return true; + } + match field.data_type() { + DataType::Struct(children) => children.iter().any(|c| field_tree_has_blob(c)), + DataType::List(child) | DataType::LargeList(child) | DataType::FixedSizeList(child, _) => { + field_tree_has_blob(child) + } + _ => false, + } +} + +/// Collects the dotted paths of row-addressable blob columns under `field`. fn collect_blob_paths(field: &Field, prefix: &str, paths: &mut Vec) { let path = if prefix.is_empty() { field.name().clone() } else { format!("{prefix}.{}", field.name()) }; - if field.is_blob_v2() { + if field.is_blob() { paths.push(path); return; } @@ -491,7 +506,7 @@ fn is_list_blob_path(field: &Field, prefix: &str, column: &str, inside_list: boo } else { format!("{prefix}.{}", field.name()) }; - if field.is_blob_v2() { + if field.is_blob() { return inside_list && column == path; } match field.data_type() { @@ -499,7 +514,7 @@ fn is_list_blob_path(field: &Field, prefix: &str, column: &str, inside_list: boo .iter() .any(|child| is_list_blob_path(child, &path, column, inside_list)), DataType::List(child) | DataType::LargeList(child) | DataType::FixedSizeList(child, _) => { - (column == path && field_tree_has_blob_v2(child)) + (column == path && field_tree_has_blob(child)) || is_list_blob_path(child, &path, column, true) } _ => false, @@ -527,7 +542,7 @@ pub(crate) fn has_blob_columns(schema: &Schema) -> bool { schema.fields().iter().any(|f| field_tree_has_blob_v2(f)) } -/// Row-addressable blob v2 column paths in `schema`, in declaration order. +/// Row-addressable blob v1 and v2 column paths in `schema`, in declaration order. /// Struct-nested blobs use dotted paths (e.g. `info.blob`); list-nested blobs /// are omitted because a row id cannot identify an individual list element. pub(crate) fn blob_column_names(schema: &Schema) -> Vec { @@ -557,15 +572,37 @@ pub(crate) fn ensure_blob_storage_version(schema: &Schema, params: &mut WritePar } } -/// Validate that `column` exists and is a blob v2 column. -/// -/// Legacy v1 columns (`lance-encoding:blob`) error with a migration hint. -pub(crate) fn ensure_blob_v2_column( +/// Validate that `column` exists and is a row-addressable blob v1 or v2 column. +pub(crate) fn ensure_blob_column( schema: &lance_core::datatypes::Schema, column: &str, ) -> Result<()> { // A top-level blob cannot have a list ancestor. Keep the common read path // from converting the entire schema just to validate that condition. + if column.contains('.') + || schema + .field(column) + .is_none_or(|field| !field.is_blob() && !field.is_blob_v2()) + { + reject_list_blob_column(&Schema::from(schema), column)?; + } + match schema.field(column) { + Some(field) if field.is_blob() || field.is_blob_v2() => Ok(()), + Some(_) => Err(Error::InvalidInput { + message: format!("column '{column}' is not a blob column"), + }), + None => Err(Error::InvalidInput { + message: format!("no column named '{column}' in this table"), + }), + } +} + +/// Validate a blob v2 descriptor source column. +/// +/// Stored SQL descriptors only describe blob v2 layouts. Keep legacy v1 +/// support on the row-id fetch APIs instead of broadening descriptor +/// reopening to a storage format it cannot encode. +fn ensure_blob_v2_column(schema: &lance_core::datatypes::Schema, column: &str) -> Result<()> { if column.contains('.') || schema.field(column).is_none_or(|field| !field.is_blob_v2()) { reject_list_blob_column(&Schema::from(schema), column)?; } @@ -708,7 +745,7 @@ pub(crate) async fn take_blob_ranges_aligned( column: &str, requests: &[BlobRangeRequest], ) -> Result { - ensure_blob_v2_column(dataset.schema(), column)?; + ensure_blob_column(dataset.schema(), column)?; if requests.is_empty() { return Ok(LargeBinaryBuilder::new().finish()); } @@ -749,7 +786,7 @@ pub(crate) async fn take_blobs_aligned( column: &str, row_ids: &[u64], ) -> Result { - ensure_blob_v2_column(dataset.schema(), column)?; + ensure_blob_column(dataset.schema(), column)?; if row_ids.is_empty() { return Ok(LargeBinaryBuilder::new().finish()); } @@ -782,7 +819,7 @@ pub(crate) async fn take_blob_files_aligned( column: &str, row_ids: &[u64], ) -> Result>> { - ensure_blob_v2_column(dataset.schema(), column)?; + ensure_blob_column(dataset.schema(), column)?; if row_ids.is_empty() { return Ok(Vec::new()); } @@ -930,20 +967,35 @@ mod tests { } #[test] - fn legacy_v1_blob_column_is_rejected_with_migration_hint() { + fn legacy_v1_blob_columns_are_row_addressable() { let legacy = Field::new("image", DataType::LargeBinary, true).with_metadata( std::collections::HashMap::from([( "lance-encoding:blob".to_string(), "true".to_string(), )]), ); - let arrow_schema = Schema::new(vec![legacy]); + let arrow_schema = Schema::new(vec![ + legacy.clone(), + Field::new("info", DataType::Struct(vec![legacy.clone()].into()), true), + Field::new("images", DataType::List(Arc::new(legacy)), true), + ]); let lance_schema = lance_core::datatypes::Schema::try_from(&arrow_schema).unwrap(); - let err = ensure_blob_v2_column(&lance_schema, "image").unwrap_err(); - assert!(matches!(err, Error::InvalidInput { .. })); - assert!(err.to_string().contains("legacy blob column")); - assert!(err.to_string().contains("lance.blob.v2")); + ensure_blob_column(&lance_schema, "image").unwrap(); + ensure_blob_column(&lance_schema, "info.image").unwrap(); + assert_eq!( + blob_column_names(&arrow_schema), + vec!["image", "info.image"] + ); + for path in ["images", "images.image"] { + let err = ensure_blob_column(&lance_schema, path).unwrap_err(); + assert!( + err.to_string() + .contains("blobs inside lists cannot be fetched") + ); + } + // Legacy columns do not require the blob v2 write format. + assert!(!has_blob_columns(&arrow_schema)); } #[test] @@ -951,10 +1003,10 @@ mod tests { let arrow_schema = Schema::new(vec![Field::new("id", DataType::Int64, false)]); let lance_schema = lance_core::datatypes::Schema::try_from(&arrow_schema).unwrap(); - let err = ensure_blob_v2_column(&lance_schema, "id").unwrap_err(); + let err = ensure_blob_column(&lance_schema, "id").unwrap_err(); assert!(err.to_string().contains("'id' is not a blob column")); - let err = ensure_blob_v2_column(&lance_schema, "missing").unwrap_err(); + let err = ensure_blob_column(&lance_schema, "missing").unwrap_err(); assert!(err.to_string().contains("no column named 'missing'")); } diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index e3cdfc6a6..65ab13935 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -405,7 +405,7 @@ impl RemoteTable { error } - /// Blob v2 columns are marked in field metadata, which `describe` returns. Reading + /// Blob columns are marked in field metadata, which `describe` returns. Reading /// them from the cached schema needs no route of its own and no version gate. pub(super) async fn blob_columns_impl(&self) -> Result> { let schema = self.schema().await?; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index d6575b959..7097644e4 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -766,7 +766,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn close_rte_writers(&self) -> Result<()> { Ok(()) } - /// Names of the blob v2 columns in this table, in declaration order. + /// Names of the blob v1 and v2 columns in this table, in declaration order. async fn blob_columns(&self) -> Result> { Err(Error::NotSupported { message: "blob_columns is not supported on this table type".into(), @@ -1251,7 +1251,7 @@ impl Table { self.inner.count_rows(filter).await } - /// Names of the row-addressable blob v2 columns, in declaration order. + /// Names of the row-addressable blob v1 and v2 columns, in declaration order. /// /// Blobs nested in structs use dotted paths (e.g. `info.blob`). Blobs /// inside lists are omitted because row ids cannot identify their elements. @@ -1262,6 +1262,7 @@ impl Table { /// Materialize blob bytes for the given row ids. /// + /// Native tables support both legacy blob v1 and blob v2 columns. /// Output matches `row_ids` in length and order. Null blobs are null; /// valid empty blobs contain empty byte strings. Cloud limits individual /// requests to 1024 row ids and 64 MiB of blob bytes; the remote client @@ -1297,7 +1298,7 @@ impl Table { /// /// Blobs inside lists cannot be fetched by row id. Returns /// [`Error::InvalidInput`] for those paths, when the column does not exist, - /// or when it is not a blob v2 column. Returns [`Error::NotSupported`] on + /// or when it is not a blob column. Returns [`Error::NotSupported`] on /// table types without blob support. pub async fn fetch_blobs( &self, @@ -1307,8 +1308,9 @@ impl Table { self.inner.fetch_blobs(column.as_ref(), row_ids).await } - /// Materialize row-specific ranges from a blob v2 column. + /// Materialize row-specific ranges from a blob column. /// + /// Native tables support both legacy blob v1 and blob v2 columns. /// Each request contains a row id and a blob-local offset and length. /// Requests may be duplicated or reordered, including multiple /// ranges for the same blob. The output has the same length and order as @@ -1341,7 +1343,7 @@ impl Table { /// ``` /// /// Returns an error when a range is invalid, a requested row id does not - /// exist, or the column is not a blob v2 column. Returns + /// exist, or the column is not a blob column. Returns /// [`Error::NotSupported`] on table types without blob support. pub async fn fetch_blob_ranges( &self, @@ -1356,6 +1358,7 @@ impl Table { /// Open lazy [`BlobFile`] handles for the given row ids. /// + /// Native tables support both legacy blob v1 and blob v2 columns. /// Same length and order as `row_ids`. Null rows are `None`. Bytes are not /// read from disk until a call to [`BlobFile::read`]. /// Remote blob requests share a connection-wide concurrency limit. Set diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index 8559a0e43..0a4240038 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -947,12 +947,15 @@ async fn fetch_blobs_rejects_unknown_column() -> Result<()> { Ok(()) } +#[rstest::rstest] +#[case("2.0")] +#[case("2.1")] #[tokio::test] -async fn fetch_blobs_rejects_legacy_v1_blob_column() -> Result<()> { +async fn fetch_blob_apis_read_legacy_v1_blob_column(#[case] storage_version: &str) -> Result<()> { let tmp = tempdir().unwrap(); // Legacy v1 blob columns are only writable at file version <= 2.1. let db = connect(tmp.path().to_str().unwrap()) - .storage_options([(OPT_NEW_TABLE_STORAGE_VERSION, "2.1")]) + .storage_options([(OPT_NEW_TABLE_STORAGE_VERSION, storage_version)]) .execute() .await?; let legacy = Field::new("image", DataType::LargeBinary, true).with_metadata( @@ -963,9 +966,62 @@ async fn fetch_blobs_rejects_legacy_v1_blob_column() -> Result<()> { legacy, ])); let table = db.create_empty_table("t", schema).execute().await?; + table + .add(binary_input_batch( + &[1, 2, 3, 4], + &[Some(b"abcdef"), None, Some(b""), Some(b"uvwxyz")], + )) + .execute() + .await?; - let err = table.fetch_blobs("image", &[0]).await.unwrap_err(); - assert!(err.to_string().contains("legacy blob column")); + assert!(!supports_blob_v2(storage_format_version(&table).await)); + assert_eq!(table.blob_columns().await?, vec!["image"]); + + let pairs = collect_id_rowid(&table).await?; + let by_id = |want: i64| pairs.iter().find(|(id, _)| *id == want).unwrap().1; + let row_ids = [by_id(4), by_id(2), by_id(1), by_id(3), by_id(4)]; + let expected: [Option<&[u8]>; 5] = [ + Some(b"uvwxyz"), + None, + Some(b"abcdef"), + Some(b""), + Some(b"uvwxyz"), + ]; + let bytes = table.fetch_blobs("image", &row_ids).await?; + assert_eq!(bytes.iter().collect::>(), expected); + + let files = table.fetch_blob_files("image", &row_ids).await?; + assert_eq!(files.len(), expected.len()); + for (file, payload) in files.iter().zip(expected) { + match payload { + Some(payload) => { + let file = file.as_ref().unwrap(); + assert_eq!(file.size(), payload.len() as u64); + assert_eq!(file.read().await?.as_ref(), payload); + } + None => assert!(file.is_none()), + } + } + assert_eq!( + files[2].as_ref().unwrap().read_range(1..4).await?.as_ref(), + b"bcd" + ); + + let ranges = table + .fetch_blob_ranges( + "image", + [ + BlobRangeRequest::new(by_id(4), 1, 3), + BlobRangeRequest::new(by_id(2), 0, 0), + BlobRangeRequest::new(by_id(1), 2, 3), + BlobRangeRequest::new(by_id(3), 0, 0), + BlobRangeRequest::new(by_id(4), 0, 2), + ], + ) + .await?; + let expected_ranges: [Option<&[u8]>; 5] = + [Some(b"vwx"), None, Some(b"cde"), Some(b""), Some(b"uv")]; + assert_eq!(ranges.iter().collect::>(), expected_ranges); Ok(()) } @@ -1406,7 +1462,7 @@ async fn v1_blob_descriptors(table: &Table) -> Result Result>)>> { let pairs = sorted_id_rowid(table).await?; let row_ids: Vec = pairs.iter().map(|(_, row_id)| *row_id).collect(); From 2cd635d41ca215985aa1df9c903b019b782f6b25 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:34:01 +0800 Subject: [PATCH 126/180] fix: correct remote materialized view refresh results and options (#4672) Remote materialized-view refreshes drained the SQL result and then fabricated `mode=rebuild`, `rows_written=`, and `source_version=0`. This made incremental refreshes report incorrect statistics. Make these three result fields optional across Rust, Python, and TypeScript, and leave them unset for remote SQL refreshes. Remove the post-refresh row count request. Local refreshes continue to populate all metrics, and `version` remains the view version observed after completion. Remote per-operation statistics remain unavailable until the SQL job adapter can retrieve them. Expose the forced-rebuild option through the Rust builder, synchronous/asynchronous Python refresh and job methods, and TypeScript refresh. Remote `full=true` sends `WITH (full = true)`; the default lets the server choose its refresh mode. Local source-version pinning and remote job cancellation are preserved. Local refresh regression tests respect the `experimental-functions` build gate, while remote refresh coverage also runs in default builds. Validation: - Rust: 20 materialized-view tests and 21 remote SQL tests passed with `remote,experimental-functions`; `cargo fmt --all` passed. - Python: rebuilt the extension in the uv-managed environment. The default build passed 23 tests with 27 feature-dependent skips. The opt-in build passed 61 tests with 3 expected default-build-only skips, covering the materialized-view suite and 14 async query-serialization cases from current main. Python Ruff lint and formatting checks passed. - TypeScript: default and opt-in native builds and TypeScript compilation passed. The default build passed 5 tests with 10 expected feature-dependent skips; the opt-in build passed all 14 materialized-view tests with the default-build-only test skipped. Lint/format checks and documentation generation passed. - Repository-wide `ruff check .` reports 48 pre-existing violations in unchanged `docs/web-tests` files; `ruff check python` passes. Fixes #4670 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/src/js/classes/MaterializedView.md | 10 +- .../RefreshMaterializedViewResult.md | 18 +-- nodejs/__test__/materialized_view.test.ts | 38 ++++-- nodejs/lancedb/materialized_view.ts | 14 ++- nodejs/lancedb/table.ts | 4 +- nodejs/src/table.rs | 23 ++-- python/python/lancedb/_lancedb.pyi | 10 +- python/python/lancedb/materialized_view.py | 33 +++-- .../python/tests/test_materialized_views.py | 114 +++++++++++++++++- python/src/table.rs | 29 +++-- rust/lancedb/src/materialized_view.rs | 62 +++++++--- rust/lancedb/src/materialized_view/refresh.rs | 23 ++-- rust/lancedb/src/remote/sql_test.rs | 65 +++++++--- rust/lancedb/src/remote/table.rs | 18 +-- rust/lancedb/src/table.rs | 1 + 15 files changed, 347 insertions(+), 115 deletions(-) diff --git a/docs/src/js/classes/MaterializedView.md b/docs/src/js/classes/MaterializedView.md index bb02f5dc2..3ba4d56b3 100644 --- a/docs/src/js/classes/MaterializedView.md +++ b/docs/src/js/classes/MaterializedView.md @@ -66,14 +66,18 @@ refresh(options?): Promise Recompute the view from its source. Local refresh requires a source build with `experimental-functions`. -Every refresh rebuilds the complete view. For local views, -`sourceVersion` refreshes to that source version instead of the latest; -remote SQL refreshes do not support source-version pinning. +`full: true` forces a remote rebuild; otherwise the server chooses the +refresh mode. Local views always rebuild, and `sourceVersion` selects a +source version instead of the latest. Remote SQL refreshes do not support +source-version pinning. Their results leave `mode`, `rowsWritten`, and +`sourceVersion` absent because the SQL job adapter does not expose these metrics. #### Parameters * **options?** +* **options.full?**: `boolean` + * **options.sourceVersion?**: `number` #### Returns diff --git a/docs/src/js/interfaces/RefreshMaterializedViewResult.md b/docs/src/js/interfaces/RefreshMaterializedViewResult.md index 1c8b8bc21..05321683e 100644 --- a/docs/src/js/interfaces/RefreshMaterializedViewResult.md +++ b/docs/src/js/interfaces/RefreshMaterializedViewResult.md @@ -8,30 +8,34 @@ ## Properties -### mode +### mode? ```ts -mode: string; +optional mode: string; ``` -How the view was brought up to date: "rebuild". +How the view was brought up to date: "rebuild", or absent for remote SQL refreshes. *** -### rowsWritten +### rowsWritten? ```ts -rowsWritten: number; +optional rowsWritten: number; ``` +Rows written by this refresh, or absent for remote SQL refreshes. + *** -### sourceVersion +### sourceVersion? ```ts -sourceVersion: number; +optional sourceVersion: number; ``` +Source version refreshed to, or absent for remote SQL refreshes. + *** ### version diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index 2324e1fcf..0840395fe 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -6,6 +6,7 @@ import * as tmp from "tmp"; import { Connection, connect } from "../lancedb"; import { DEFINITION_META_KEY, + MaterializedView, definitionFromMetadata, } from "../lancedb/materialized_view"; import { experimentalFunctionsEnabled } from "../lancedb/native"; @@ -94,20 +95,33 @@ describe("materialized views", () => { ); }); - experimentalTest("fully refreshes after an append", async () => { - const view = await db.createMaterializedView("copy", "people", { - withNoData: true, - }); - await view.refresh(); + experimentalTest.each([false, true])( + "fully refreshes after an append (full=%s)", + async (full) => { + const view = await db.createMaterializedView("copy", "people", { + withNoData: true, + }); + await view.refresh(); - const people = await db.openTable("people"); - await people.add([{ name: "alan", age: 41 }]); - const result = await view.refresh(); - expect(result.mode).toBe("rebuild"); - expect(Number(result.rowsWritten)).toBe(4); - expect(await view.table().countRows()).toBe(4); + const people = await db.openTable("people"); + await people.add([{ name: "alan", age: 41 }]); + const result = await view.refresh({ full }); + expect(result.mode).toBe("rebuild"); + expect(Number(result.rowsWritten)).toBe(4); + expect(await view.table().countRows()).toBe(4); - expect((await view.refresh()).mode).toBe("rebuild"); + expect((await view.refresh()).mode).toBe("rebuild"); + }, + ); + + it("forwards a forced refresh and preserves absent remote metrics", async () => { + const view = new MaterializedView(await db.openTable("people")); + const remoteResult = { version: 42 }; + const refresh = jest + .spyOn(view.table(), "refreshMaterializedView") + .mockResolvedValue(remoteResult); + expect(await view.refresh({ full: true })).toEqual(remoteResult); + expect(refresh).toHaveBeenCalledWith(undefined, true); }); experimentalTest("lists views and rejects non-views", async () => { diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts index cc209b14d..afb61b9ab 100644 --- a/nodejs/lancedb/materialized_view.ts +++ b/nodejs/lancedb/materialized_view.ts @@ -188,14 +188,20 @@ export class MaterializedView { * Recompute the view from its source. * Local refresh requires a source build with `experimental-functions`. * - * Every refresh rebuilds the complete view. For local views, - * `sourceVersion` refreshes to that source version instead of the latest; - * remote SQL refreshes do not support source-version pinning. + * `full: true` forces a remote rebuild; otherwise the server chooses the + * refresh mode. Local views always rebuild, and `sourceVersion` selects a + * source version instead of the latest. Remote SQL refreshes do not support + * source-version pinning. Their results leave `mode`, `rowsWritten`, and + * `sourceVersion` absent because the SQL job adapter does not expose these metrics. */ async refresh(options?: { + full?: boolean; sourceVersion?: number; }): Promise { validateNonNegativeInteger(options?.sourceVersion, "sourceVersion"); - return await this.inner.refreshMaterializedView(options?.sourceVersion); + return await this.inner.refreshMaterializedView( + options?.sourceVersion, + options?.full, + ); } } diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 4738b6140..b88603fb7 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -699,6 +699,7 @@ export abstract class Table { */ abstract refreshMaterializedView( sourceVersion?: number, + full?: boolean, ): Promise; /** @ignore */ @@ -1442,8 +1443,9 @@ export class LocalTable extends Table { async refreshMaterializedView( sourceVersion?: number, + full?: boolean, ): Promise { - return await this.inner.refreshMaterializedView(sourceVersion); + return await this.inner.refreshMaterializedView(sourceVersion, full); } async materializedViewDefinition(): Promise { diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 0a40e0a13..a1410ad85 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -470,11 +470,12 @@ impl Table { pub async fn refresh_materialized_view( &self, source_version: Option, + full: Option, ) -> napi::Result { let view = lancedb::MaterializedView::from_table(self.inner_ref()?.clone()) .await .default_error()?; - let mut builder = view.refresh(); + let mut builder = view.refresh().full(full.unwrap_or(false)); if let Some(version) = source_version { let version = u64::try_from(version).map_err(|_| { napi::Error::from_reason("sourceVersion must be a non-negative integer") @@ -1615,22 +1616,24 @@ impl From for FunctionErrors { #[napi(object)] pub struct RefreshMaterializedViewResult { - /// How the view was brought up to date: "rebuild". - pub mode: String, - pub rows_written: i64, - pub source_version: i64, + /// How the view was brought up to date: "rebuild", or absent for remote SQL refreshes. + pub mode: Option, + /// Rows written by this refresh, or absent for remote SQL refreshes. + pub rows_written: Option, + /// Source version refreshed to, or absent for remote SQL refreshes. + pub source_version: Option, pub version: i64, } impl From for RefreshMaterializedViewResult { fn from(value: lancedb::RefreshMaterializedViewResult) -> Self { - let mode = match value.mode { + let mode = value.mode.map(|mode| match mode { lancedb::RefreshMode::Rebuild => "rebuild", - }; + }); Self { - mode: mode.to_string(), - rows_written: value.rows_written as i64, - source_version: value.source_version as i64, + mode: mode.map(str::to_string), + rows_written: value.rows_written.map(|rows| rows as i64), + source_version: value.source_version.map(|version| version as i64), version: value.version as i64, } } diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 333fca92e..7e1307a4a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -528,10 +528,10 @@ class Table: limit: Optional[int] = None, ) -> FunctionErrors: ... async def refresh_materialized_view( - self, source_version: Optional[int] = None + self, source_version: Optional[int] = None, *, full: bool = False ) -> RefreshMaterializedViewResult: ... async def refresh_materialized_view_async( - self, source_version: Optional[int] = None + self, source_version: Optional[int] = None, *, full: bool = False ) -> Job: ... async def materialized_view_definition(self) -> str: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... @@ -921,9 +921,9 @@ class FunctionErrors: class RefreshMaterializedViewResult: @staticmethod def from_json(value: str) -> RefreshMaterializedViewResult: ... - mode: str - rows_written: int - source_version: int + mode: Optional[str] + rows_written: Optional[int] + source_version: Optional[int] version: int class AlterColumnsResult: diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 8efe31f05..7fc110dcc 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -184,31 +184,36 @@ class AsyncMaterializedView: return _definition_from_json(raw) async def refresh( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. - Every refresh rebuilds the complete view. For local views, - ``source_version`` refreshes to that source version instead of the - latest; remote SQL refreshes do not support source-version pinning. + ``full=True`` forces a remote rebuild; otherwise the server chooses + the refresh mode. Local views always rebuild, and ``source_version`` + selects a source version instead of the latest. Remote SQL refreshes + do not support source-version pinning. + + Remote results leave ``mode``, ``rows_written``, and ``source_version`` + as ``None`` because the SQL job adapter does not expose these metrics. """ return await self._table._inner.refresh_materialized_view( - source_version=source_version + source_version=source_version, full=full ) async def refresh_async( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "AsyncJob[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. The job may already be complete for a local view. Remote refreshes are - submitted through the SQL service. + submitted through the SQL service. Options and result metrics follow + [refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]. """ from ._lancedb import RefreshMaterializedViewResult return _typed_job( await self._table._inner.refresh_materialized_view_async( - source_version=source_version + source_version=source_version, full=full ), RefreshMaterializedViewResult.from_json, ) @@ -240,18 +245,22 @@ class MaterializedView: return LOOP.run(self._async.definition()) def refresh( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. See [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].""" - return LOOP.run(self._async.refresh(source_version=source_version)) + return LOOP.run(self._async.refresh(full=full, source_version=source_version)) def refresh_async( - self, *, source_version: Optional[int] = None + self, *, full: bool = False, source_version: Optional[int] = None ) -> "Job[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. See [AsyncMaterializedView.refresh_async][lancedb.materialized_view.AsyncMaterializedView.refresh_async]. """ - return Job(LOOP.run(self._async.refresh_async(source_version=source_version))) + return Job( + LOOP.run( + self._async.refresh_async(full=full, source_version=source_version) + ) + ) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 337fcad78..04dbe2fec 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -8,6 +8,7 @@ import threading import lancedb import pytest +import pyarrow as pa from lancedb.db import AsyncConnection from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection @@ -112,6 +113,98 @@ def test_remote_drop_async_returns_server_job(): assert requests == [("/v1/materialized_view/adults/drop", {})] +@contextlib.contextmanager +def mock_remote_materialized_view_refresh(): + requests = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + requests.append(self.path) + if self.path == "/v1/materialized_view/view/describe": + response = {"query": "SELECT * FROM source"} + else: + assert self.path == "/v1/table/view/describe/" + response = {"version": 42, "schema": {"fields": []}} + encoded = json.dumps(response).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + with http.server.HTTPServer(("localhost", 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"http://localhost:{server.server_address[1]}", requests + finally: + server.shutdown() + thread.join() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("full", [False, True]) +async def test_remote_refresh_reports_unknown_metrics(sync, background, full): + flight = pytest.importorskip("pyarrow.flight") + + class RefreshServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.commands = [] + + def do_get(self, context, ticket): + self.commands.append(ticket.ticket) + # SQL completion carries no refresh statistics. + return flight.RecordBatchStream(pa.table({"status": ["ok"]})) + + with ( + mock_remote_materialized_view_refresh() as (host, requests), + RefreshServer() as server, + ): + options = {"full": True} if full else {} + connect = lancedb.connect if sync else lancedb.connect_async + db = connect( + "db://dev", + api_key="fake", + host_override=host, + sql_host_override=f"grpc://127.0.0.1:{server.port}", + client_config={"retry_config": {"retries": 0}}, + ) + if sync: + view = db.open_materialized_view("view") + result = ( + view.refresh_async(**options).wait() + if background + else view.refresh(**options) + ) + else: + db = await db + view = await db.open_materialized_view("view") + if background: + job = await view.refresh_async(**options) + result = await job.wait() + else: + result = await view.refresh(**options) + + assert result.mode is None + assert result.rows_written is None + assert result.source_version is None + assert result.version == 42 + assert repr(result) == ( + "RefreshMaterializedViewResult(mode=None, rows_written=None, " + "source_version=None, version=42)" + ) + (command,) = server.commands + assert b'REFRESH MATERIALIZED VIEW "view"' in command + assert (b"WITH (full = true)" in command) is full + assert not any("count_rows" in path for path in requests) + + def test_sync_remote_create_uses_public_async_connection(): calls = [] @@ -226,20 +319,37 @@ def test_definition_round_trips(tmp_path): @pytest.mark.experimental_functions -def test_full_refresh_after_append(tmp_path): +@pytest.mark.parametrize("full", [False, True]) +def test_full_refresh_after_append(tmp_path, full): db = make_db(tmp_path) view = db.create_materialized_view("copy", "people", with_no_data=True) view.refresh() db.open_table("people").add([{"name": "alan", "age": 41}]) - result = view.refresh() + result = view.refresh(full=full) assert result.mode == "rebuild" assert result.rows_written == 4 + assert result.source_version == db.open_table("people").version assert view.table.count_rows() == 4 assert view.refresh().mode == "rebuild" +@pytest.mark.experimental_functions +def test_full_refresh_can_pin_local_source_version(tmp_path): + db = make_db(tmp_path) + source = db.open_table("people") + version = source.version + view = db.create_materialized_view("copy", "people", with_no_data=True) + source.add([{"name": "alan", "age": 41}]) + + result = view.refresh(full=True, source_version=version) + assert result.mode == "rebuild" + assert result.rows_written == 3 + assert result.source_version == version + assert view.table.count_rows() == 3 + + @pytest.mark.experimental_functions def test_full_refresh_after_update(tmp_path): db = make_db(tmp_path) diff --git a/python/src/table.rs b/python/src/table.rs index 62fc9e611..d77fd14b8 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -694,9 +694,9 @@ impl From for FunctionErrors { #[pyclass(get_all, from_py_object)] #[derive(Clone, Debug)] pub struct RefreshMaterializedViewResult { - pub mode: String, - pub rows_written: u64, - pub source_version: u64, + pub mode: Option, + pub rows_written: Option, + pub source_version: Option, pub version: u64, } @@ -716,18 +716,23 @@ impl RefreshMaterializedViewResult { pub fn __repr__(&self) -> String { format!( "RefreshMaterializedViewResult(mode={}, rows_written={}, source_version={}, version={})", - self.mode, self.rows_written, self.source_version, self.version + self.mode.as_deref().unwrap_or("None"), + self.rows_written + .map_or_else(|| "None".into(), |value| value.to_string()), + self.source_version + .map_or_else(|| "None".into(), |value| value.to_string()), + self.version ) } } impl From for RefreshMaterializedViewResult { fn from(result: lancedb::RefreshMaterializedViewResult) -> Self { - let mode = match result.mode { + let mode = result.mode.map(|mode| match mode { lancedb::RefreshMode::Rebuild => "rebuild", - }; + }); Self { - mode: mode.to_string(), + mode: mode.map(str::to_string), rows_written: result.rows_written, source_version: result.source_version, version: result.version, @@ -2054,17 +2059,18 @@ impl Table { }) } - #[pyo3(signature = (source_version=None))] + #[pyo3(signature = (source_version=None, *, full=false))] pub fn refresh_materialized_view( self_: PyRef<'_, Self>, source_version: Option, + full: bool, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let view = lancedb::MaterializedView::from_table(inner) .await .infer_error()?; - let mut builder = view.refresh(); + let mut builder = view.refresh().full(full); if let Some(version) = source_version { builder = builder.source_version(version); } @@ -2073,17 +2079,18 @@ impl Table { }) } - #[pyo3(signature = (source_version=None))] + #[pyo3(signature = (source_version=None, *, full=false))] pub fn refresh_materialized_view_async( self_: PyRef<'_, Self>, source_version: Option, + full: bool, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let view = lancedb::MaterializedView::from_table(inner) .await .infer_error()?; - let mut builder = view.refresh(); + let mut builder = view.refresh().full(full); if let Some(version) = source_version { builder = builder.source_version(version); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index b7124d930..5a7169b7c 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1844,14 +1844,17 @@ impl MaterializedView { /// Recompute the view from its source. /// - /// Every refresh rebuilds the view from the selected source version. + /// Local refreshes rebuild the view from the selected source version. + /// Remote refreshes let the server select a mode unless + /// [`RefreshMaterializedViewBuilder::full`] requests a rebuild. Their + /// result leaves unavailable refresh metrics as `None`. /// /// ```no_run /// # #![recursion_limit = "256"] /// # use lancedb::materialized_view::MaterializedView; /// # async fn refresh(view: &MaterializedView) -> Result<(), Box> { /// let result = view.refresh().execute().await?; - /// println!("{:?}: {} rows", result.mode, result.rows_written); + /// println!("{:?}: {:?} rows", result.mode, result.rows_written); /// # Ok(()) /// # } /// ``` @@ -1859,6 +1862,7 @@ impl MaterializedView { RefreshMaterializedViewBuilder { view: self.clone(), source_version: None, + full: false, } } } @@ -1867,9 +1871,26 @@ impl MaterializedView { pub struct RefreshMaterializedViewBuilder { view: MaterializedView, source_version: Option, + full: bool, } impl RefreshMaterializedViewBuilder { + /// Force a complete rebuild instead of letting the remote server choose + /// the refresh mode. Defaults to `false`. Local views always rebuild. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # use lancedb::materialized_view::MaterializedView; + /// # async fn refresh(view: &MaterializedView) -> lancedb::Result<()> { + /// view.refresh().full(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn full(mut self, full: bool) -> Self { + self.full = full; + self + } + /// Refresh a local view to this source table version instead of the latest. /// Remote SQL refreshes do not support source-version pinning. pub fn source_version(mut self, version: u64) -> Self { @@ -1884,7 +1905,7 @@ impl RefreshMaterializedViewBuilder { .view .table .base_table() - .refresh_materialized_view_async(self.source_version) + .refresh_materialized_view_async(self.source_version, self.full) .await; } crate::require_experimental_functions()?; @@ -2102,19 +2123,23 @@ mod tests { .execute() .await .unwrap(); - let refreshed = view.refresh().execute().await.unwrap(); - assert_eq!(refreshed.mode, RefreshMode::Rebuild); - assert_eq!(refreshed.rows_written, 3); + let refreshed = view.refresh().full(true).execute().await.unwrap(); + assert_eq!(refreshed.mode, Some(RefreshMode::Rebuild)); + assert_eq!(refreshed.rows_written, Some(3)); + assert_eq!( + refreshed.source_version, + Some(source.version().await.unwrap()) + ); assert_eq!(view.table().count_rows(None).await.unwrap(), 3); let unchanged = view.refresh().execute().await.unwrap(); - assert_eq!(unchanged.mode, RefreshMode::Rebuild); - assert_eq!(unchanged.rows_written, 3); + assert_eq!(unchanged.mode, Some(RefreshMode::Rebuild)); + assert_eq!(unchanged.rows_written, Some(3)); source.delete("true").await.unwrap(); let emptied = view.refresh().execute().await.unwrap(); - assert_eq!(emptied.mode, RefreshMode::Rebuild); - assert_eq!(emptied.rows_written, 0); + assert_eq!(emptied.mode, Some(RefreshMode::Rebuild)); + assert_eq!(emptied.rows_written, Some(0)); assert_eq!(view.table().count_rows(None).await.unwrap(), 0); } @@ -2274,10 +2299,13 @@ mod tests { // Refresh, chained, is the writer. source.add(row()).execute().await.unwrap(); - assert_eq!(view.refresh().execute().await.unwrap().rows_written, 3); + assert_eq!( + view.refresh().execute().await.unwrap().rows_written, + Some(3) + ); assert_eq!( downstream.refresh().execute().await.unwrap().rows_written, - 3 + Some(3) ); assert_eq!( downstream @@ -2312,7 +2340,10 @@ mod tests { .await .unwrap(); source.drop_columns(&["y"]).await.unwrap(); - assert_eq!(view.refresh().execute().await.unwrap().rows_written, 3); + assert_eq!( + view.refresh().execute().await.unwrap().rows_written, + Some(3) + ); } #[tokio::test] @@ -2355,7 +2386,10 @@ mod tests { .execute() .await .unwrap(); - assert_eq!(view.refresh().execute().await.unwrap().rows_written, 4); + assert_eq!( + view.refresh().execute().await.unwrap().rows_written, + Some(4) + ); view.table().optimize(OptimizeAction::All).await.unwrap(); assert_eq!( view.table().count_rows(Some("x > 2".into())).await.unwrap(), diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 1186ac576..70a795eb3 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -45,13 +45,16 @@ pub enum RefreshMode { /// The result of refreshing a materialized view. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshMaterializedViewResult { - /// How the view was brought up to date. - pub mode: RefreshMode, - /// Rows written to the replacement view. - pub rows_written: u64, - /// The source table version the view reflects. - pub source_version: u64, - /// The view table version after the refresh. + /// How the view was brought up to date, or `None` when unavailable. + /// Remote SQL refreshes currently do not expose this metric. + pub mode: Option, + /// Rows written by this refresh, or `None` when unavailable. + /// Remote SQL refreshes currently do not expose this metric. + pub rows_written: Option, + /// The source table version the view reflects, or `None` when unavailable. + /// Remote SQL refreshes currently do not expose this metric. + pub source_version: Option, + /// The view table version observed after the refresh. pub version: u64, } @@ -182,9 +185,9 @@ pub(crate) async fn execute_refresh( let version = committed.version().version; native.dataset.update(committed); Ok(RefreshMaterializedViewResult { - mode: RefreshMode::Rebuild, - rows_written: rows_written.load(Ordering::Relaxed), - source_version, + mode: Some(RefreshMode::Rebuild), + rows_written: Some(rows_written.load(Ordering::Relaxed)), + source_version: Some(source_version), version, }) } diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 1368dd753..260471612 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1021,7 +1021,7 @@ async fn rejected_job_cancellation_does_not_abort_sql_completion() { } #[tokio::test] -async fn remote_refresh_twice_keeps_latest_selector() { +async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let incoming = futures::stream::try_unfold(listener, |listener| async { @@ -1029,6 +1029,8 @@ async fn remote_refresh_twice_keeps_latest_selector() { Ok::<_, std::io::Error>(Some((socket, listener))) }); let service = TestSqlService::default(); + let statements = service.statements.clone(); + let headers = service.headers.clone(); let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); let server = tokio::spawn( tonic::transport::Server::builder() @@ -1052,11 +1054,11 @@ async fn remote_refresh_twice_keeps_latest_selector() { .body() .and_then(reqwest::Body::as_bytes) .and_then(|bytes| serde_json::from_slice::(bytes).ok()) - .unwrap(); + .unwrap_or_default(); captured.lock().unwrap().push(body["version"].clone()); let text = match request.url().path() { + "/v1/materialized_view/ns$view/describe" => r#"{"query": "SELECT * FROM source"}"#, "/v1/table/ns$view/describe/" => r#"{"version": 42, "schema": {"fields": []}}"#, - "/v1/table/ns$view/count_rows/" => "2", other => panic!("unexpected REST request: {other}"), }; http::Response::builder() @@ -1072,24 +1074,54 @@ async fn remote_refresh_twice_keeps_latest_selector() { Default::default(), Some(sql_client), ); + let database = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected database request: {}", request.url()); + }); + let view = + crate::MaterializedView::from_table(crate::Table::new(Arc::new(table), Arc::new(database))) + .await + .unwrap(); - let first = table - .refresh_materialized_view_async(None) - .await - .unwrap() - .wait() - .await - .unwrap(); - let second = table - .refresh_materialized_view_async(None) + let first = view.refresh().execute().await.unwrap(); + let second = view + .refresh() + .full(true) + .execute_async() .await .unwrap() .wait() .await .unwrap(); - assert_eq!(first.version, 42); - assert_eq!(second.version, 42); + for result in [first, second] { + assert_eq!(result.mode, None); + assert_eq!(result.rows_written, None); + assert_eq!(result.source_version, None); + assert_eq!(result.version, 42); + // Query-backed jobs serialize their typed result before returning it. + let json = serde_json::to_value(result).unwrap(); + assert!(json["mode"].is_null()); + assert!(json["rows_written"].is_null()); + assert!(json["source_version"].is_null()); + } + assert!(matches!( + view.refresh().source_version(7).execute_async().await, + Err(Error::NotSupported { .. }) + )); + assert_eq!( + *statements.lock().unwrap(), + [ + "REFRESH MATERIALIZED VIEW \"view\"", + "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", + ] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "ns") + ); assert!( selectors .lock() @@ -1147,7 +1179,10 @@ async fn cancelling_remote_refresh_cancels_sql_query() { Default::default(), Some(sql_client), ); - let job = table.refresh_materialized_view_async(None).await.unwrap(); + let job = table + .refresh_materialized_view_async(None, false) + .await + .unwrap(); tokio::time::timeout(Duration::from_secs(10), async { while do_get_count.load(Ordering::SeqCst) == 0 { tokio::task::yield_now().await; diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 29cf774fc..061ae8bf2 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2224,6 +2224,7 @@ impl BaseTable for RemoteTable { async fn refresh_materialized_view_async( &self, source_version: Option, + full: bool, ) -> Result> { self.check_mutable().await?; if source_version.is_some() { @@ -2236,8 +2237,9 @@ impl BaseTable for RemoteTable { message: "SQL is unavailable for this remote table client".to_string(), })?; let statement = format!( - "REFRESH MATERIALIZED VIEW {}", - quote_sql_identifier(&self.name) + "REFRESH MATERIALIZED VIEW {}{}", + quote_sql_identifier(&self.name), + if full { " WITH (full = true)" } else { "" }, ); let namespace = self.namespace.clone(); let client = self.client.clone(); @@ -2259,15 +2261,13 @@ impl BaseTable for RemoteTable { ); table.checkout_latest().await?; let version = table.version().await?; - let rows_written = - u64::try_from(table.count_rows(None).await?).map_err(|_| Error::Runtime { - message: "materialized-view row count exceeds u64".to_string(), - })?; freshness_request.observe_version(&freshness, version); Ok(RefreshMaterializedViewResult { - mode: crate::materialized_view::RefreshMode::Rebuild, - rows_written, - source_version: 0, + // The SQL job adapter does not expose refresh metrics. Table + // metadata cannot tell us what this refresh actually did. + mode: None, + rows_written: None, + source_version: None, version, }) }) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 7097644e4..a7db1ae5e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -585,6 +585,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn refresh_materialized_view_async( &self, _source_version: Option, + _full: bool, ) -> Result> { Err(Error::NotSupported { message: "remote materialized-view refresh is not supported on this table type".into(), From 3575f972ac4ca599ba92fe5ea8081a1f3f4f8953 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=BF=97=E8=B0=A6?= <89645338+simpleqt@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:49:31 +0800 Subject: [PATCH 127/180] fix(python): accept tuples and pyarrow arrays as hybrid search vectors (#4662) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The synchronous hybrid query builder rejected vector containers that the rest of the Python API accepts: ```python table.search(query_type="hybrid").vector((1.0, 2.0)).text("hello").to_pandas() # ValueError table.search(query_type="hybrid").vector(pa.array([1.0, 2.0], pa.float32()))... # ValueError: Vector query must be either a string or a vector ``` `lancedb.common.VEC` documents `list[float] | tuple[float, ...] | np.ndarray | pa.Array`, and the same two containers work for `table.search(vector)` and for the async hybrid API (`AsyncQuery.nearest_to(...).nearest_to_text(...)`). `LanceHybridQueryBuilder._validate_query` only listed `str | list | np.ndarray`, so a tuple or a pyarrow array was refused before reaching the query planner. This normalises the vector exactly the way `LanceQueryBuilder.create` already does — list/tuple to a `np.float32` array, `np.ndarray` through `astype(float32)`, `pa.Array`/`pa.ChunkedArray` through `np.array(..., dtype=float32)`, strings passed through — and keeps the existing `ValueError` for anything else. `python/python/tests/test_hybrid_query.py::test_hybrid_query_accepts_every_vector_container` is parametrised over tuple, pyarrow array and pyarrow chunked array, and asserts the returned `_rowid`s match the `list` form: 3 failed on `main` (`ValueError` from `query.py:2452`), 3 passed with the change. Neighbouring suites (`test_hybrid_query.py`, `test_query.py`, `test_rerankers.py`) are 220 passed / 9 skipped, and `test_table.py`, `test_remote_db.py`, `test_fts.py`, `test_index.py`, `test_permutation.py` are 724 passed / 5 skipped. `ruff` at the version pinned in the repository's pre-commit config (0.9.9) reports no findings and `ruff format --check` is clean. One source file (`python/python/lancedb/query.py`), no behaviour change for containers that already worked. Prepared with AI assistance; every line was verified by running the cases above. --------- Co-authored-by: Xuanwo --- python/python/lancedb/query.py | 28 ++++++++++++--- python/python/tests/test_hybrid_query.py | 44 ++++++++++++++++++++++-- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 644b6571f..b2093712e 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1655,12 +1655,12 @@ class LanceQueryBuilder(ABC): self.to_query_object(), distributed_metrics=distributed_metrics ) - def vector(self, vector: Union[np.ndarray, list]) -> Self: + def vector(self, vector: Union[VEC, Tuple]) -> Self: """Set the vector to search for. Parameters ---------- - vector: np.ndarray or list + vector: list, tuple, np.ndarray, pa.Array, or pa.ChunkedArray The vector to search for. Returns @@ -2450,7 +2450,15 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): ) vector_query = vector if vector is not None else query - if not isinstance(vector_query, (str, list, np.ndarray)): + # Accept the same containers as the vector search path, which + # normalizes them in `LanceQueryBuilder.create`. + if isinstance(vector_query, (list, tuple)): + vector_query = np.array(vector_query, dtype=np.float32) + elif isinstance(vector_query, np.ndarray): + vector_query = vector_query.astype(np.float32) + elif isinstance(vector_query, (pa.Array, pa.ChunkedArray)): + vector_query = np.array(vector_query.to_pylist(), dtype=np.float32) + elif not isinstance(vector_query, str): raise ValueError("Vector query must be either a string or a vector") text_query = text or query @@ -2923,7 +2931,19 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): self._refine_factor = refine_factor return self - def vector(self, vector: Union[np.ndarray, list]) -> LanceHybridQueryBuilder: + def vector(self, vector: Union[VEC, Tuple]) -> LanceHybridQueryBuilder: + """Set the vector to search for. + + Parameters + ---------- + vector: list, tuple, np.ndarray, pa.Array, or pa.ChunkedArray + The vector to search for. + + Returns + ------- + LanceHybridQueryBuilder + The LanceHybridQueryBuilder object. + """ self._vector = vector return self diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 19050093c..c432bac59 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -315,13 +315,53 @@ def test_hybrid_query_offset(sync_table: Table): assert offset_result["_rowid"].to_pylist() == full["_rowid"].to_pylist()[2:] +@pytest.mark.parametrize( + "query_vector", + [ + pytest.param((0.0, 0.4), id="tuple"), + pytest.param(pa.array([0.0, 0.4], type=pa.float32()), id="pa-array"), + pytest.param( + pa.chunked_array([[0.0], [0.4]], type=pa.float32()), id="pa-chunked-array" + ), + ], +) +def test_hybrid_query_accepts_every_vector_container(sync_table: Table, query_vector): + # Vector search and the async hybrid API both accept tuples and pyarrow + # arrays for the query vector (``VEC`` in ``lancedb/common.py``), so the + # sync hybrid builder must accept them too. + expected = ( + sync_table.search(query_type="hybrid") + .vector([0.0, 0.4]) + .text("dog") + .limit(2) + .with_row_id(True) + .to_arrow() + ) + + result = ( + sync_table.search(query_type="hybrid") + .vector(query_vector) + .text("dog") + .limit(2) + .with_row_id(True) + .to_arrow() + ) + + assert result["_rowid"].to_pylist() == expected["_rowid"].to_pylist() + + def test_hybrid_query_default_limit(sync_table: Table): # The vector and FTS legs match disjoint rows, so fusing their results # yields more rows than the default limit. new_rows = [] + # Distinct distances and document lengths avoid ties in either leg, + # so comparing offset windows does not depend on tie ordering. for i in range(20): - new_rows.append({"text": "close_vec", "vector": [0.1, 0.1]}) - new_rows.append({"text": "dog", "vector": [50.0 + i, 50.0 + i]}) + coordinate = 0.11 + i * 0.001 + new_rows.append({"text": "close_vec", "vector": [coordinate, coordinate]}) + new_rows.append( + {"text": "dog " + "padding " * (i + 1), "vector": [50.0 + i, 50.0 + i]} + ) sync_table.add(new_rows) def query(): From dcac834233ded0d992affd67745d1a824a52dcdf Mon Sep 17 00:00:00 2001 From: Jay Pokale Date: Tue, 27 Oct 2026 21:05:04 +0530 Subject: [PATCH 128/180] fix(python)!: reject tuple fields with mixed element types in pydantic models (#4679) `pydantic_to_schema` maps a `Tuple[...]` field to an Arrow list of its **first** element type. A tuple with different element types gets the wrong schema, and the error only surfaces when a row is written: ```python class Pair(LanceModel): pair: Tuple[int, str] pydantic_to_schema(Pair) # pair: list db.create_table("t", schema=Pair).add([Pair(pair=(1, "a"))]) # pyarrow.lib.ArrowInvalid: Could not convert 'a' with type str: tried to convert to int64 ``` An Arrow list has a single element type, so such a tuple cannot be stored as one. This raises a `TypeError` when the schema is built, saying the tuple elements must share one type and pointing to a nested `LanceModel` for a fixed set of differently typed fields. Homogeneous tuples are unchanged: `Tuple[int, int]` and `Tuple[float, ...]` still map to lists. **Breaking change:** a model with a mixed-type tuple field, which used to get a (wrong) `list<...>` schema from `pydantic_to_schema`, now raises `TypeError` when the schema is built. Such a schema could not hold the model's values: writing a row failed with `ArrowInvalid`. The requirement and the nested-`LanceModel` alternative are documented in the `pydantic_to_schema` docstring. Tests (in `test_pydantic.py`): `TypeError` for `Tuple[int, str]` (fails on `main`), and the list mapping for `Tuple[int, int]` and `Tuple[float, ...]`. The whole file passes; `ruff format` and `ruff check` are clean. I used an AI assistant (Claude) while working on this; I reviewed and tested the change. --------- Co-authored-by: Xuanwo --- python/python/lancedb/pydantic.py | 18 ++++++++++++++++++ python/python/tests/test_pydantic.py | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index db8723a99..d2b5cb22d 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -259,6 +259,15 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType: f"{py_type}. Specify the element type, e.g. List[int] instead " "of a bare List." ) + # An Arrow list has a single element type, so a tuple such as + # Tuple[int, str] cannot be stored as one. Tuple[int, ...] is homogeneous. + element_types = {arg for arg in args if arg is not Ellipsis} + if len(element_types) > 1: + raise TypeError( + "Converting Pydantic type to Arrow Type: unsupported type " + f"{py_type}. All tuple elements must have the same type; use a " + "nested LanceModel for a fixed set of fields with different types." + ) child = args[0] return _pydantic_list_child_to_arrow(child, field) raise TypeError( @@ -419,6 +428,15 @@ def pydantic_to_schema(model: Type[pydantic.BaseModel]) -> pa.Schema: pyarrow.Schema The Arrow Schema + Raises + ------ + TypeError + If a field has a type with no Arrow equivalent. A ``Tuple`` field becomes + an Arrow list, so all its elements must have the same type, as in + ``Tuple[int, int]`` or ``Tuple[float, ...]``; for a fixed set of fields + with different types, such as ``Tuple[int, str]``, use a nested + ``LanceModel`` (an Arrow struct) instead. + Examples -------- diff --git a/python/python/tests/test_pydantic.py b/python/python/tests/test_pydantic.py index 6717bbc32..09af2f081 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -200,6 +200,27 @@ def test_bare_generic_raises_type_error(): pydantic_to_schema(TestModel) +def test_tuple_with_mixed_element_types_raises_type_error(): + # An Arrow list has one element type, so Tuple[int, str] has no Arrow + # equivalent. It used to map to list and fail later, on write. + class TestModel(pydantic.BaseModel): + pair: Tuple[int, str] + + with pytest.raises(TypeError, match="same type"): + pydantic_to_schema(TestModel) + + +def test_homogeneous_tuples_map_to_lists(): + class TestModel(pydantic.BaseModel): + pair: Tuple[int, int] + many: Tuple[float, ...] + + schema = pydantic_to_schema(TestModel) + + assert schema.field("pair").type == pa.list_(pa.int64()) + assert schema.field("many").type == pa.list_(pa.float64()) + + def test_nested_struct_list_optional(): class SplitInfo(pydantic.BaseModel): start_frame: int From 4b373b20709eb5314510aca3ae9e4e62b999a64d Mon Sep 17 00:00:00 2001 From: Ozawa Song <139314449+dawid0309@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:29:22 +0800 Subject: [PATCH 129/180] fix(python)!: support compat-only imports (#3973) Read `__version__` from the native `_lancedb` module so `import lancedb` works when only `lancedb-compat` is installed. Add the type declaration and a subprocess regression test. Ruff and Linux-targeted Pyright pass. Import tests: 1 passed and 1 Linux-only test skipped on Windows. Runtime tests used the official same-version Windows native module; a fresh source build still needs CI. BREAKING CHANGE: `lancedb.__version__` now uses the native version string. Prereleases may report `0.41.0-beta.13` instead of `0.41.0b13`. Fixes #3950 --------- Co-authored-by: Xuanwo --- python/python/lancedb/__init__.py | 4 +--- python/python/lancedb/_lancedb.pyi | 1 + python/python/tests/test_import.py | 34 ++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 6c71c6261..fa1c105e9 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -2,14 +2,12 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors -import importlib.metadata import os from concurrent.futures import ThreadPoolExecutor from datetime import timedelta from typing import Dict, Optional, Union, Any, List, Iterable, TYPE_CHECKING -__version__ = importlib.metadata.version("lancedb") - +from ._lancedb import __version__ as __version__ from ._lancedb import connect as lancedb_connect from ._lancedb import FtsToken from ._lancedb import FunctionErrorFragment as FunctionErrorFragment diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 7e1307a4a..d5fcac30f 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -32,6 +32,7 @@ IvfHnswPq: type[HnswPq] = HnswPq IvfHnswSq: type[HnswSq] = HnswSq IvfHnswFlat: type[HnswFlat] = HnswFlat AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"] +__version__: str class MetricPoint: name: str diff --git a/python/python/tests/test_import.py b/python/python/tests/test_import.py index 4b87a0ce8..e8373b03b 100644 --- a/python/python/tests/test_import.py +++ b/python/python/tests/test_import.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import os import re import shutil import subprocess @@ -31,3 +32,36 @@ def test_native_extension_does_not_link_openssl(): "the LanceDB native extension must use rustls instead of linking OpenSSL: " f"{openssl_libraries}" ) + + +def test_top_level_version_comes_from_native_module(): + child_code = """ +import importlib.metadata + +orig_version = importlib.metadata.version + +def fail_version_lookup(_: str) -> str: + if _ in {"lancedb", "lancedb-compat"}: + raise AssertionError("lancedb import should not query distribution metadata") + return orig_version(_) + +importlib.metadata.version = fail_version_lookup + +import lancedb +import lancedb._lancedb as native_module +import lancedb.db + +assert lancedb.__version__ == native_module.__version__ +""" + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) + + result = subprocess.run( + [sys.executable, "-c", child_code], + check=False, + capture_output=True, + text=True, + env=env, + ) + + assert result.returncode == 0, result.stderr or result.stdout From fe079eb42153a2459c218573859dafe720a3afdb Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:31:23 -0700 Subject: [PATCH 130/180] fix!: restore blob SQL inserts with explicit adapter schemas (#4687) --- rust/lancedb/CHANGELOG.md | 15 + rust/lancedb/src/remote/table.rs | 221 ++++++ rust/lancedb/src/table/datafusion.rs | 217 +++++- .../src/table/datafusion/blob_nulls.rs | 2 +- rust/lancedb/tests/datafusion_blob_schema.rs | 636 ++++++++++++++++++ 5 files changed, 1083 insertions(+), 8 deletions(-) create mode 100644 rust/lancedb/CHANGELOG.md create mode 100644 rust/lancedb/tests/datafusion_blob_schema.rs diff --git a/rust/lancedb/CHANGELOG.md b/rust/lancedb/CHANGELOG.md new file mode 100644 index 000000000..028f67128 --- /dev/null +++ b/rust/lancedb/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +## Unreleased + +- `BaseTableAdapter` now defaults to `BlobSchema::Read`, exposing the Blob v2 + descriptors returned by scans. SQL INSERT into Blob v2 tables requires opting + into `BlobSchema::Write` with `with_blob_schema`. Write-mode queries support + scalar projections that exclude blobs, scalar filters, and `COUNT(*)`. + Scans must exactly match the projected provider schema, including metadata + and nullability. Blob v2 descriptor scans fail during planning; legacy v1 + blobs expose `LargeBinary` write inputs and reject descriptor scans with a + schema mismatch. A scalar sibling inside a blob-containing struct also needs + a separate read adapter because DataFusion projects the whole parent struct. + Tables without blob columns behave the same in both modes. Generated `_rowid`, + `_rowaddr`, and `_score` columns are exposed only in read mode. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 061ae8bf2..214e06d4e 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5712,6 +5712,227 @@ mod tests { assert!(fields.find("data").is_none()); } + #[tokio::test] + async fn test_adapter_blob_read_schema_matches_remote_scan() { + use datafusion::prelude::SessionContext; + use datafusion_catalog::TableProvider; + use lance_core::datatypes::Projection; + + let write_schema = Schema::new(vec![ + Field::new("id", DataType::Int64, false), + crate::blob("image", true), + ]); + let read_schema = Arc::new( + Projection::full(Arc::new(LanceSchema::try_from(&write_schema).unwrap())) + .to_arrow_schema(), + ); + let descriptor = arrow_array::new_null_array(read_schema.field(1).data_type(), 2); + let response = RecordBatch::try_new( + read_schema, + vec![Arc::new(Int64Array::from(vec![1, 2])), descriptor], + ) + .unwrap(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + schema_describe_response(&write_schema).map(String::into_bytes) + } + "/v1/table/my_table/query/" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let columns = body["columns"] + .as_array() + .unwrap() + .iter() + .map(|column| { + response + .schema() + .index_of(column.as_str().unwrap()) + .unwrap() + }) + .collect::>(); + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(write_ipc_file(&response.project(&columns).unwrap())) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + let adapter = + crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + let ctx = SessionContext::new(); + let plan = adapter.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert!( + batches + .iter() + .all(|batch| batch.schema() == adapter.schema()) + ); + let adapter = adapter.with_blob_schema(crate::table::datafusion::BlobSchema::Write); + let plan = adapter + .scan(&ctx.state(), Some(&vec![0]), &[], None) + .await + .unwrap(); + let expected = Arc::new(adapter.schema().project(&[0]).unwrap()); + assert_eq!(plan.schema(), expected); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert!(batches.iter().all(|batch| batch.schema() == expected)); + } + + #[tokio::test] + async fn test_adapter_write_scan_checks_metadata_and_nullability() { + use crate::table::datafusion::{BaseTableAdapter, BlobSchema}; + use datafusion::prelude::SessionContext; + use datafusion_catalog::TableProvider; + + let declared = Field::new("id", DataType::Int64, false) + .with_metadata(HashMap::from([("meaning".into(), "identifier".into())])); + for returned in [ + declared.clone(), + declared.clone().with_nullable(true), + declared.clone().with_metadata(HashMap::new()), + ] { + let matches = returned == declared; + let write_schema = Schema::new(vec![declared.clone()]); + let response = RecordBatch::try_new( + Arc::new(Schema::new(vec![returned])), + vec![Arc::new(Int64Array::from(vec![1]))], + ) + .unwrap(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + schema_describe_response(&write_schema).map(String::into_bytes) + } + "/v1/table/my_table/query/" => http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(write_ipc_file(&response)) + .unwrap(), + path => panic!("unexpected request: {path}"), + }); + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write); + let ctx = SessionContext::new(); + let result = adapter.scan(&ctx.state(), None, &[], None).await; + if matches { + let plan = result.unwrap(); + assert_eq!(plan.schema(), adapter.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(batches[0].schema(), adapter.schema()); + } else { + let error = result.unwrap_err(); + assert!( + error.to_string().contains("Scan schema mismatch"), + "{error}" + ); + } + } + } + + #[tokio::test] + async fn test_adapter_blob_write_sql_remote_payload_round_trip() { + use crate::table::datafusion::{BaseTableAdapter, BlobSchema}; + use datafusion::prelude::SessionContext; + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + crate::blob("image", true), + ])); + let described_schema = schema.clone(); + let (sender, receiver) = std::sync::mpsc::channel(); + let table = + Table::new_with_handler("my_table", move |mut request| match request.url().path() { + "/v1/table/my_table/describe/" => schema_describe_response(&described_schema), + "/v1/table/my_table/insert/" => { + let body = request.body_mut().take().unwrap(); + sender.send(body).unwrap(); + http::Response::builder() + .status(200) + .body(r#"{"version": 2}"#.to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write); + let ctx = SessionContext::new(); + ctx.register_table("docs", Arc::new(adapter)).unwrap(); + + // Persist the exact Arrow stream sent to the mocked remote endpoint to + // a real native sink, then check storage bytes independently of schemas. + let tmp = tempfile::tempdir().unwrap(); + let db = crate::connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let sink = db + .create_empty_table("sink", schema) + .execute() + .await + .unwrap(); + for query in [ + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + "INSERT INTO docs VALUES (2, NULL)", + "INSERT INTO docs (id) VALUES (3)", + "INSERT INTO docs SELECT 4, named_struct('data', X'', 'uri', NULL)", + ] { + ctx.sql(query).await.unwrap().collect().await.unwrap(); + let body = collect_body(receiver.recv().unwrap()).await; + let reader = StreamReader::try_new(Cursor::new(body), None).unwrap(); + for batch in reader { + sink.add(batch.unwrap()).execute().await.unwrap(); + } + } + let batches = sink + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_ids = batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("_rowid") + .unwrap() + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect::>(); + let actual = sink.fetch_blobs("image", &row_ids).await.unwrap(); + assert_eq!( + actual, + LargeBinaryArray::from(vec![ + Some(b"hi".as_slice()), + None, + None, + Some(b"".as_slice()) + ]) + ); + } + #[rstest] #[case(semver::Version::new(0, 1, 0))] #[case(semver::Version::new(0, 5, 0))] diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 973ab0123..8f187d465 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -166,10 +166,40 @@ impl ExecutionPlan for MetadataEraserExec { } } +/// The blob schema exposed by a [`BaseTableAdapter`]. +/// +/// DataFusion uses one provider schema for both scans and INSERT coercion. +/// Blob descriptors and blob write inputs have different types, so applications +/// that need both can register separate read and write adapters for one table. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum BlobSchema { + /// Expose Blob v2 descriptors (`kind`, `position`, `size`, `blob_id`, `blob_uri`) + /// and legacy v1 descriptors (`position`, `size`). Scans support all blob fields; + /// SQL INSERT into Blob v2 tables is unsupported. + #[default] + Read, + /// Expose Blob v2 write inputs (`data`, `uri`, `position`, `size`) and legacy + /// v1 `LargeBinary` inputs for SQL INSERT. Scans must match the projected + /// provider schema exactly; use [`Self::Read`] to scan blob descriptors or + /// scalar siblings whose projected parent contains a blob. + Write, +} + +/// A DataFusion provider for a LanceDB table. +/// +/// Defaults to [`BlobSchema::Read`], matching the descriptor schema produced by +/// scans without fetching blob bytes. Use [`Self::with_blob_schema`] to enable +/// SQL INSERT into blob columns. Legacy v1 blobs expose descriptors in read mode +/// and `LargeBinary` inputs in write mode; write-mode descriptor scans fail with +/// a schema mismatch. Tables without blob columns behave the same in both modes. #[derive(Debug)] pub struct BaseTableAdapter { table: Arc, + // Only the read schema includes opted-in system/FTS columns. schema: Arc, + write_schema: Arc, + blob_schema: BlobSchema, fts_query: Option, use_rte: Option, } @@ -183,15 +213,59 @@ impl BaseTableAdapter { let schema = Projection::full(Arc::new(LanceSchema::try_from(write_schema.as_ref())?)) .to_arrow_schema(); let schema = blob_nulls::read_schema(&schema).with_metadata(HashMap::default()); + let write_schema = Arc::new( + write_schema + .as_ref() + .clone() + .with_metadata(HashMap::default()), + ); Ok(Self { table, schema: Arc::new(schema), + write_schema, + blob_schema: BlobSchema::Read, fts_query: None, use_rte: None, }) } + /// Choose the schema used by DataFusion for blob columns. + /// + /// [`BlobSchema::Write`] enables INSERT with blob write structs, NULLs, and + /// omitted nullable blobs. Scans requiring blobs fail with + /// "Blob v2 scans require BlobSchema::Read" before execution. Legacy v1 blobs + /// expose `LargeBinary` write inputs, so their descriptor scans fail with a + /// schema mismatch. Write-mode scans are accepted only when the actual schema + /// exactly matches the projected provider schema, including metadata and + /// nullability. No blob payloads are fetched to emulate reads. + /// + /// Scalar projections that exclude blob fields, `COUNT(*)`, and scalar filters + /// remain supported. DataFusion projects whole top-level fields, so selecting + /// `extra.note` also requests its parent `extra`. If that struct contains a blob, + /// even this scalar projection requires [`BlobSchema::Read`], as do computed + /// scalar and window queries that project the same parent. + /// + /// Register a separate read adapter for blob descriptor queries and scalar + /// queries rejected in write mode. A self-insert whose SELECT accesses blobs + /// also fails before writing any rows. + /// Other adapter builders preserve the selected mode. Generated `_rowid`, + /// `_rowaddr`, and `_score` columns are exposed only in read mode. + /// + /// ``` + /// use lancedb::table::datafusion::{BaseTableAdapter, BlobSchema}; + /// + /// # async fn adapter(table: &lancedb::Table) -> lancedb::Result { + /// Ok(BaseTableAdapter::try_new(table.base_table().clone()) + /// .await? + /// .with_blob_schema(BlobSchema::Write)) + /// # } + /// ``` + pub fn with_blob_schema(mut self, blob_schema: BlobSchema) -> Self { + self.blob_schema = blob_schema; + self + } + /// Expose the requested Lance system columns to DataFusion. /// /// Supports [`ROW_ID`] (`_rowid`) and [`ROW_ADDR`] (`_rowaddr`), both nullable @@ -199,7 +273,8 @@ impl BaseTableAdapter { /// already exposed by this adapter. Other names return [`Error::InvalidInput`]. /// /// System columns are hidden by default so existing `SELECT *` queries keep - /// their data-only schema. After opting in, `SELECT *` includes these columns. + /// their data-only schema. After opting in, `SELECT *` includes these columns + /// in [`BlobSchema::Read`] mode. The write schema remains data-only for INSERT. /// /// ``` /// use lance_core::{ROW_ADDR, ROW_ID}; @@ -239,6 +314,8 @@ impl BaseTableAdapter { } /// Create a new adapter with an FTS query applied. + /// + /// The generated `_score` column is exposed only in [`BlobSchema::Read`] mode. pub fn with_fts_query(&self, fts_query: FullTextSearchQuery) -> Self { // Add _score column to the schema let score_field = Field::new("_score", DataType::Float32, true); @@ -249,16 +326,28 @@ impl BaseTableAdapter { Self { table: self.table.clone(), schema, + write_schema: self.write_schema.clone(), + blob_schema: self.blob_schema, fts_query: Some(fts_query), use_rte: self.use_rte, } } } +fn blob_scan_error() -> DataFusionError { + DataFusionError::Plan( + "Blob v2 scans require BlobSchema::Read; use a separate read adapter for blob fields" + .into(), + ) +} + #[async_trait] impl TableProvider for BaseTableAdapter { fn schema(&self) -> Arc { - self.schema.clone() + match self.blob_schema { + BlobSchema::Read => self.schema.clone(), + BlobSchema::Write => self.write_schema.clone(), + } } fn table_type(&self) -> TableType { @@ -272,8 +361,18 @@ impl TableProvider for BaseTableAdapter { filters: &[Expr], limit: Option, ) -> DataFusionResult> { - // For FTS queries, disable auto-projection of _score to match DataFusion expectations - let disable_scoring = self.fts_query.is_some() && projection.is_some(); + // Check directly supplied filters too, not just optimizer pushdown calls. + if self.blob_schema == BlobSchema::Write { + for filter in filters { + if blob_nulls::references_descriptor(filter, &self.schema)? { + return Err(blob_scan_error()); + } + } + } + // The writer never advertises _score. For readers, an explicit projection + // controls whether it is included, rather than FTS auto-projection. + let disable_scoring = self.fts_query.is_some() + && (projection.is_some() || self.blob_schema == BlobSchema::Write); let mut query = QueryRequest { full_text_search: self.fts_query.clone(), @@ -282,16 +381,17 @@ impl TableProvider for BaseTableAdapter { ..Default::default() }; + let provider_schema = self.schema(); if let Some(projection) = projection { let field_names = projection .iter() - .map(|i| self.schema.field(*i).name().clone()) + .map(|i| provider_schema.field(*i).name().clone()) .collect(); query.select = Select::Columns(field_names); } else { // Select::All excludes system columns, which may be part of our schema. query.select = Select::Columns( - self.schema + provider_schema .fields() .iter() .map(|field| field.name().clone()) @@ -323,7 +423,32 @@ impl TableProvider for BaseTableAdapter { .map_err(|err| DataFusionError::External(err.into())) .await?; let plan = blob_nulls::mask_plan(plan)?; - Ok(Arc::new(MetadataEraserExec::new(plan))) + let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + if self.blob_schema == BlobSchema::Write { + let schema = match projection { + Some(projection) => Arc::new(provider_schema.project(projection)?), + None => provider_schema, + }; + // Compare the full schemas, including field metadata and nullability. + // A scan must satisfy its advertised contract before it is returned + // to DataFusion; later projections cannot repair a mismatched scan. + if plan.schema() != schema { + if plan + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + return Err(blob_scan_error()); + } + return Err(arrow_schema::ArrowError::SchemaError(format!( + "Scan schema mismatch: expected {schema:?}, got {:?}", + plan.schema() + )) + .into()); + } + } + Ok(plan) } fn supports_filters_pushdown( @@ -338,6 +463,9 @@ impl TableProvider for BaseTableAdapter { .map(|filter| { Ok( if blob_nulls::references_descriptor(filter, &self.schema)? { + if self.blob_schema == BlobSchema::Write { + return Err(blob_scan_error()); + } TableProviderFilterPushDown::Unsupported } else { TableProviderFilterPushDown::Exact @@ -358,6 +486,17 @@ impl TableProvider for BaseTableAdapter { input: Arc, insert_op: InsertOp, ) -> DataFusionResult> { + if self.blob_schema == BlobSchema::Read + && self + .schema + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + return Err(DataFusionError::NotImplemented( + "SQL INSERT into Blob v2 tables requires BlobSchema::Write".into(), + )); + } let mode = match insert_op { InsertOp::Append => WriteMode::Append, InsertOp::Overwrite => WriteMode::Overwrite, @@ -603,6 +742,70 @@ pub mod tests { )) } + #[tokio::test] + async fn test_blob_schema_builders_preserve_modes_and_system_columns() { + use super::BlobSchema; + + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table( + "docs", + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + crate::blob("payload", true), + ])), + ) + .execute() + .await + .unwrap(); + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write) + .with_system_columns(&[ROW_ID]) + .unwrap() + .with_use_rte(Some(false)) + .with_fts_query(lance_index::scalar::FullTextSearchQuery::new( + "hello".into(), + )) + .with_system_columns(&[ROW_ADDR]) + .unwrap(); + assert_eq!(adapter.blob_schema, BlobSchema::Write); + assert_eq!(adapter.use_rte, Some(false)); + assert!(adapter.fts_query.is_some()); + let names = adapter + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>() + .join(","); + assert_eq!(names, "id,payload"); + let DataType::Struct(fields) = adapter.schema().field(1).data_type().clone() else { + unreachable!() + }; + assert!(fields.find("data").is_some()); + let adapter = adapter.with_blob_schema(BlobSchema::Read); + assert_eq!( + adapter + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + ["id", "payload", "_rowid", "_score", "_rowaddr"] + ); + let DataType::Struct(fields) = adapter.schema().field(1).data_type().clone() else { + unreachable!() + }; + assert!(fields.find("kind").is_some()); + assert_eq!(adapter.schema().fields().len(), 5); + } + #[tokio::test] async fn test_sql_blob_descriptor_nulls() { use arrow_array::{UInt8Array, UInt64Array}; diff --git a/rust/lancedb/src/table/datafusion/blob_nulls.rs b/rust/lancedb/src/table/datafusion/blob_nulls.rs index 7c0cbda42..5befee5c3 100644 --- a/rust/lancedb/src/table/datafusion/blob_nulls.rs +++ b/rust/lancedb/src/table/datafusion/blob_nulls.rs @@ -24,7 +24,7 @@ use datafusion_physical_plan::{ExecutionPlan, projection::ProjectionExec}; use lance_arrow::FieldExt; use lance_core::datatypes::BlobV2Layout; -fn is_descriptor(field: &Field) -> bool { +pub(super) fn is_descriptor(field: &Field) -> bool { field.is_blob() && matches!(field.data_type(), DataType::Struct(fields) if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)) diff --git a/rust/lancedb/tests/datafusion_blob_schema.rs b/rust/lancedb/tests/datafusion_blob_schema.rs new file mode 100644 index 000000000..d51c182f6 --- /dev/null +++ b/rust/lancedb/tests/datafusion_blob_schema.rs @@ -0,0 +1,636 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use arrow_array::{ + Array, ArrayRef, Int64Array, LargeBinaryArray, ListArray, RecordBatch, StringArray, + StructArray, UInt64Array, cast::AsArray, +}; +use arrow_buffer::{NullBuffer, OffsetBuffer}; +use arrow_schema::{DataType, Field, Schema}; +use arrow_select::concat::concat_batches; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_catalog::TableProvider; +use lance_core::{ROW_ADDR, ROW_ID}; +use lance_index::scalar::FullTextSearchQuery; +use lancedb::{ + Table, blob, connect, + database::listing::OPT_NEW_TABLE_STORAGE_VERSION, + table::datafusion::{BaseTableAdapter, BlobSchema}, +}; +use tempfile::{TempDir, tempdir}; + +async fn empty_table(fields: Vec) -> (TempDir, Table) { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table("docs", Arc::new(Schema::new(fields))) + .execute() + .await + .unwrap(); + (tmp, table) +} + +async fn register(ctx: &SessionContext, table: &Table, mode: BlobSchema) { + let adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode); + ctx.deregister_table("docs").unwrap(); + ctx.register_table("docs", Arc::new(adapter)).unwrap(); +} + +async fn sql(ctx: &SessionContext, query: &str) -> RecordBatch { + let batches = ctx.sql(query).await.unwrap().collect().await.unwrap(); + concat_batches(&batches[0].schema(), &batches).unwrap() +} + +async fn planning_error(ctx: &SessionContext, query: &str) -> String { + let error = match ctx.sql(query).await { + Ok(df) => df.create_physical_plan().await.unwrap_err(), + Err(error) => error, + }; + error.to_string() +} + +async fn row_ids(ctx: &SessionContext, table: &Table) -> Vec { + let reader = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID]) + .unwrap(); + ctx.register_table("read_docs", Arc::new(reader)).unwrap(); + sql(ctx, "SELECT _rowid FROM read_docs ORDER BY id") + .await + .column(0) + .as_primitive::() + .values() + .to_vec() +} + +#[tokio::test] +async fn write_mode_inserts_blobs_nulls_omitted_and_reordered_columns() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + for query in [ + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + "INSERT INTO docs VALUES (2, NULL)", + "INSERT INTO docs (id) VALUES (3)", + "INSERT INTO docs SELECT 4, named_struct('data', X'', 'uri', NULL)", + "INSERT INTO docs (payload, id) SELECT named_struct('data', X'627965', 'uri', NULL), 5", + ] { + sql(&ctx, query).await; + } + let ids = row_ids(&ctx, &table).await; + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![ + Some(b"hi".as_slice()), + None, + None, + Some(b"".as_slice()), + Some(b"bye".as_slice()) + ]) + ); + let batch = sql(&ctx, "SELECT id, payload.size FROM read_docs ORDER BY id").await; + assert_eq!( + batch + .column(1) + .as_primitive::(), + &UInt64Array::from(vec![Some(2), None, None, Some(0), Some(3)]) + ); + assert_eq!( + sql(&ctx, "SELECT count(payload) FROM read_docs") + .await + .column(0) + .as_primitive::() + .value(0), + 3 + ); +} + +#[tokio::test] +async fn write_mode_inserts_two_blobs_in_explicit_column_order() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + blob("thumbnail", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + for query in [ + "INSERT INTO docs (thumbnail, id, payload) SELECT named_struct('data', X'', 'uri', NULL), 1, named_struct('data', X'6869', 'uri', NULL)", + "INSERT INTO docs (id) VALUES (2)", + "INSERT INTO docs VALUES (3, NULL, NULL)", + ] { + sql(&ctx, query).await; + } + let ids = row_ids(&ctx, &table).await; + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, None]) + ); + assert_eq!( + table.fetch_blobs("thumbnail", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"".as_slice()), None, None]) + ); +} + +#[tokio::test] +async fn write_mode_rejects_blob_reads_before_execution_and_supports_scalar_self_insert() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + sql( + &ctx, + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + ) + .await; + sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; + let system_adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID, lance_core::ROW_ADDR]) + .unwrap() + .with_blob_schema(BlobSchema::Read); + ctx.register_table("system_docs", Arc::new(system_adapter)) + .unwrap(); + assert_eq!( + sql( + &ctx, + "SELECT id, _rowid, _rowaddr FROM system_docs WHERE id > 0" + ) + .await + .num_rows(), + 2 + ); + for query in [ + "SELECT * FROM docs", + "SELECT payload FROM docs", + "SELECT payload.size FROM docs", + "SELECT payload.data FROM docs", + "SELECT count(payload) FROM docs", + "SELECT id FROM docs WHERE payload IS NULL", + "SELECT id FROM docs WHERE payload.size = 0", + "INSERT INTO docs SELECT id, payload FROM docs", + ] { + let error = planning_error(&ctx, query).await; + assert!( + error.contains("Blob v2 scans require BlobSchema::Read"), + "{query}: {error}" + ); + assert_eq!(table.count_rows(None).await.unwrap(), 2); + } + assert_eq!( + sql(&ctx, "SELECT count(*) FROM docs WHERE id > 0") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + assert_eq!( + sql(&ctx, "SELECT id FROM docs WHERE id = 1") + .await + .num_rows(), + 1 + ); + sql(&ctx, "INSERT INTO docs (id) SELECT id + 100 FROM docs").await; + let ids = row_ids(&ctx, &table).await; + assert_eq!(ids.len(), 4); + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, None, None]) + ); +} + +fn blob_inputs(values: Vec>) -> ArrayRef { + let data = LargeBinaryArray::from(values); + let DataType::Struct(fields) = blob("clip", true).data_type().clone() else { + unreachable!() + }; + let len = data.len(); + let nulls = data.nulls().cloned(); + Arc::new(StructArray::new( + fields, + vec![ + Arc::new(data), + Arc::new(StringArray::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + Arc::new(UInt64Array::new_null(len)), + ], + nulls, + )) +} + +#[tokio::test] +async fn nested_blob_projections_require_a_read_adapter() { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let fields = vec![ + Arc::new(Field::new("note", DataType::Utf8, true)), + Arc::new(blob("clip", true)), + ]; + let extra = StructArray::new( + fields.clone().into(), + vec![ + Arc::new(StringArray::from(vec![Some("a"), Some("b"), None])), + blob_inputs(vec![Some(b"hi"), None, Some(b"")]), + ], + Some(NullBuffer::from(vec![true, true, false])), + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("extra", DataType::Struct(fields.into()), true), + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + // DataFusion requests the same whole parent struct for extra.note and + // extra.clip. Neither can satisfy the writer's advertised scan schema. + for query in [ + "SELECT extra.note FROM docs ORDER BY id", + "SELECT count(extra.note) FROM docs", + "SELECT extra.note || 'x' FROM docs", + "SELECT row_number() OVER (ORDER BY extra.note) FROM docs", + "SELECT extra FROM docs", + "SELECT extra.clip FROM docs", + "SELECT extra.clip.size FROM docs", + "SELECT count(extra.clip) FROM docs", + ] { + let error = planning_error(&ctx, query).await; + assert!( + error.contains("Blob v2 scans require BlobSchema::Read"), + "{query}: {error}" + ); + } + let explain = sql(&ctx, "EXPLAIN SELECT id FROM docs WHERE extra.note = 'a'").await; + let explain = explain + .column(1) + .as_string::() + .iter() + .flatten() + .collect::>() + .join("\n"); + assert!(explain.contains("full_filters=["), "{explain}"); + assert!(!explain.contains("FilterExec"), "{explain}"); + assert_eq!( + sql(&ctx, "SELECT id FROM docs WHERE extra.note = 'a'") + .await + .num_rows(), + 1 + ); + register(&ctx, &table, BlobSchema::Read).await; + let batch = sql(&ctx, "SELECT extra.note FROM docs ORDER BY id").await; + assert_eq!( + batch.column(0).as_string::(), + &StringArray::from(vec![Some("a"), Some("b"), None]) + ); + assert_eq!( + sql(&ctx, "SELECT count(extra.note) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + assert_eq!( + sql(&ctx, "SELECT extra.note FROM docs WHERE extra.note = 'a'") + .await + .num_rows(), + 1 + ); + let reader = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let plan = reader.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), reader.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert!( + batches + .iter() + .all(|batch| batch.schema() == reader.schema()) + ); + let schema = reader.schema(); + ctx.register_table("read_docs", reader).unwrap(); + assert_eq!(sql(&ctx, "SELECT * FROM read_docs").await.schema(), schema); + assert_eq!( + sql(&ctx, "SELECT extra.clip.size FROM read_docs ORDER BY id") + .await + .column(0) + .as_primitive::(), + &UInt64Array::from(vec![Some(2), None, None]) + ); +} + +#[tokio::test] +async fn list_descriptors_match_declared_schema_and_cannot_be_scanned_in_write_mode() { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let list = ListArray::new( + Arc::new(blob("item", true)), + OffsetBuffer::from_lengths([1, 2]), + blob_inputs(vec![Some(b"hi"), None, Some(b"")]), + None, + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payloads", + list.data_type().clone(), + true, + )])), + vec![Arc::new(list)], + ) + .unwrap(); + let table = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + let reader = Arc::new( + BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(), + ); + let plan = reader.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), reader.schema()); + let batches = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert!( + batches + .iter() + .all(|batch| batch.schema() == reader.schema()) + ); + ctx.register_table("docs", reader).unwrap(); + assert_eq!( + sql(&ctx, "SELECT count(payloads) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + register(&ctx, &table, BlobSchema::Write).await; + assert!( + planning_error(&ctx, "SELECT payloads FROM docs") + .await + .contains("Blob v2 scans require BlobSchema::Read") + ); + assert_eq!( + sql(&ctx, "SELECT count(*) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); +} + +#[tokio::test] +async fn tables_without_blobs_support_inserts_and_full_scans_in_both_modes() { + let (_tmp, table) = empty_table(vec![Field::new("id", DataType::Int64, false)]).await; + let ctx = SessionContext::new(); + for (mode, id) in [(BlobSchema::Read, 1), (BlobSchema::Write, 2)] { + register(&ctx, &table, mode).await; + sql(&ctx, &format!("INSERT INTO docs VALUES ({id})")).await; + let provider = ctx.table_provider("docs").await.unwrap(); + let plan = provider.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), provider.schema()); + assert_eq!( + sql(&ctx, "SELECT * FROM docs").await.num_rows(), + id as usize + ); + } +} + +#[tokio::test] +async fn read_mode_rejects_null_and_omitted_blob_inserts_without_writing() { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Read).await; + for query in [ + "INSERT INTO docs VALUES (2, NULL)", + "INSERT INTO docs (id) VALUES (3)", + ] { + let error = planning_error(&ctx, query).await; + assert!( + error.contains("SQL INSERT into Blob v2 tables requires BlobSchema::Write"), + "{query}: {error}" + ); + assert_eq!(table.count_rows(None).await.unwrap(), 0); + } +} + +#[tokio::test] +async fn write_mode_inserts_exclude_read_only_builder_columns() { + for mode_first in [false, true] { + for system_first in [false, true] { + let (_tmp, table) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + Field::new("text", DataType::Utf8, true), + blob("payload", true), + ]) + .await; + let mut adapter = BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + if mode_first { + adapter = adapter.with_blob_schema(BlobSchema::Write); + } + let fts = FullTextSearchQuery::new("hello".into()); + adapter = if system_first { + adapter + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap() + .with_fts_query(fts) + } else { + adapter + .with_fts_query(fts) + .with_system_columns(&[ROW_ID, ROW_ADDR]) + .unwrap() + }; + let writer = adapter.with_blob_schema(BlobSchema::Write); + let ctx = SessionContext::new(); + ctx.register_table("docs", Arc::new(writer)).unwrap(); + sql( + &ctx, + "INSERT INTO docs SELECT 1, 'hello', named_struct('data', X'6869', 'uri', NULL)", + ) + .await; + sql(&ctx, "INSERT INTO docs (text, id) VALUES ('hello', 2)").await; + let ids = row_ids(&ctx, &table).await; + assert_eq!( + table.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None]) + ); + } + } +} + +#[tokio::test] +async fn legacy_blob_write_mode_rejects_descriptor_scans_and_keeps_scalar_scans() { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()) + .storage_options([(OPT_NEW_TABLE_STORAGE_VERSION, "2.1")]) + .execute() + .await + .unwrap(); + let legacy = Field::new("payload", DataType::LargeBinary, true).with_metadata( + std::collections::HashMap::from([("lance-encoding:blob".into(), "true".into())]), + ); + let table = db + .create_empty_table( + "docs", + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + legacy, + ])), + ) + .execute() + .await + .unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &table, BlobSchema::Write).await; + sql(&ctx, "INSERT INTO docs VALUES (1, X'6869')").await; + let writer = ctx.table_provider("docs").await.unwrap(); + assert_eq!(writer.schema().field(1).data_type(), &DataType::LargeBinary); + let error = writer + .scan(&ctx.state(), None, &[], None) + .await + .unwrap_err(); + assert!( + error.to_string().contains("Scan schema mismatch"), + "{error}" + ); + assert!(!error.to_string().contains("Blob v2"), "{error}"); + let plan = writer + .scan(&ctx.state(), Some(&vec![0]), &[], None) + .await + .unwrap(); + assert_eq!( + plan.schema(), + Arc::new(writer.schema().project(&[0]).unwrap()) + ); + assert_eq!( + sql(&ctx, "SELECT id + 1 FROM docs WHERE id = 1") + .await + .column(0) + .as_primitive::() + .value(0), + 2 + ); + assert_eq!( + sql(&ctx, "SELECT count(*) FROM docs") + .await + .column(0) + .as_primitive::() + .value(0), + 1 + ); + register(&ctx, &table, BlobSchema::Read).await; + let reader = ctx.table_provider("docs").await.unwrap(); + let plan = reader.scan(&ctx.state(), None, &[], None).await.unwrap(); + assert_eq!(plan.schema(), reader.schema()); + let DataType::Struct(fields) = reader.schema().field(1).data_type().clone() else { + panic!("expected a legacy descriptor"); + }; + assert_eq!(fields.len(), 2); + assert!(fields.find("position").is_some()); + assert!(fields.find("size").is_some()); + assert_eq!(sql(&ctx, "SELECT * FROM docs").await.num_rows(), 1); +} + +#[tokio::test] +async fn copying_non_null_descriptors_between_tables_commits_no_rows() { + let (_tmp, source) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_batch_size(1) + .with_target_partitions(1), + ); + register(&ctx, &source, BlobSchema::Write).await; + sql( + &ctx, + "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", + ) + .await; + sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; + register(&ctx, &source, BlobSchema::Read).await; + let (_dest_tmp, destination) = empty_table( + source + .schema() + .await + .unwrap() + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(), + ) + .await; + let writer = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write); + ctx.register_table("destination", Arc::new(writer)).unwrap(); + let version = destination.version().await.unwrap(); + // The null row is valid and reaches the writer before the non-null + // descriptor. Even if it is written to a fragment, it must not be committed. + let plan = ctx + .sql("INSERT INTO destination SELECT id, payload FROM docs ORDER BY id DESC") + .await + .unwrap() + .create_physical_plan() + .await + .unwrap(); + let error = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap_err(); + assert!(error.to_string().contains("blob"), "{error}"); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + assert_eq!(destination.version().await.unwrap(), version); + sql( + &ctx, + "INSERT INTO destination SELECT id, payload FROM docs WHERE payload IS NULL", + ) + .await; + let ids = row_ids(&ctx, &destination).await; + assert_eq!(ids.len(), 1); + assert_eq!( + destination.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![None::<&[u8]>]) + ); +} From 0cccc9c99101e0fdeb863ef216e9f18cce5d052b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:28:07 -0700 Subject: [PATCH 131/180] chore(deps): bump rust-minor-patch group and napi 3.15 (#4669) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the rust-minor-patch group: serde_json 1.0.154, tokio 1.54.1, uuid 1.28.0, reqwest 0.13.5, webbrowser 1.2.5, napi-derive 3.6.13, napi-build 2.6.0, arc-swap 1.9.3, libc 0.2.191. On top of the Dependabot update: * napi is bumped to 3.15.0 instead of 3.13.0. napi-derive 3.6.13 generates code that references `bindgen_prelude::NativeBorrowScopeRelease`, which napi 3.13.0 doesn't have, so the nodejs crate failed to compile. The napi and napi-derive floors in `nodejs/Cargo.toml` are raised so they can't drift apart again. * The RUSTSEC-2026-0410 ignore from #4683 is removed from `deny.toml`. #4690 already moved the lockfile to zstd-sys 2.1.2, which fixes it. The other three zstd ignores stay until we can move to Arrow 59+. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Will Jones Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 95 ++++++++++++++++++++++++----------------------- deny.toml | 11 ++---- nodejs/Cargo.toml | 4 +- 3 files changed, 54 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f189ba871..2881e765a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -141,7 +141,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -152,7 +152,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -181,9 +181,9 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" dependencies = [ "rustversion", ] @@ -3083,7 +3083,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -5617,7 +5617,7 @@ dependencies = [ "object_store 0.14.2", "quick-xml 0.40.1", "rand 0.9.5", - "reqwest 0.13.4", + "reqwest 0.13.5", "roaring", "serde", "serde_json", @@ -5802,7 +5802,7 @@ dependencies = [ "rand 0.9.5", "random_word", "regex", - "reqwest 0.13.4", + "reqwest 0.13.5", "roaring", "rstest", "semver", @@ -5968,9 +5968,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -6472,9 +6472,9 @@ dependencies = [ [[package]] name = "napi" -version = "3.12.5" +version = "3.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0c007d4a8ead952a81887661d41fd56b7e7a70d3d4d921f445fb37a8f6efa1e" +checksum = "6a746ad50efbfb632ade1de4025519a477decbbd798cea1a6ac41d7c44f80083" dependencies = [ "bitflags 2.11.1", "chrono", @@ -6492,42 +6492,42 @@ dependencies = [ [[package]] name = "napi-build" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0941983559cd62bfa7f04646a16428967a847365adeef27711e4e3927046bbed" +checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" [[package]] name = "napi-derive" -version = "3.6.9" +version = "3.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1d232c24dc6754979b27efdf2047a5849efc7c92c1245de87e6bedbb9f5c3c" +checksum = "3ff48271a0f61abb83f3e2d1989fa71169143db95f6f948c3a8903961f2855dc" dependencies = [ "convert_case", "ctor", "napi-derive-backend", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] name = "napi-derive-backend" -version = "6.1.4" +version = "6.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd6856fe1686867da90ed0dc292d7c0c87a695eb7c578b913360f33619ee01e3" +checksum = "f2639052c5aff9956a21d7b6202fc61d5e89c5f19c72d289b7a0641ea94e8159" dependencies = [ "convert_case", "proc-macro2", "quote", "semver", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] name = "napi-sys" -version = "3.4.0" +version = "3.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22a4f25c16a5c5411d987cd6fbd48313522ae1789ade2d6dd3efdc6d40a0fc8" +checksum = "d153beb7d5c973f4b9395be8a83054a28968b61188f1dd1a2cc2321af22daea2" dependencies = [ "libloading", ] @@ -6634,7 +6634,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -6774,7 +6774,7 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http 1.5.0", @@ -6916,7 +6916,7 @@ dependencies = [ "percent-encoding", "quick-xml 0.41.0", "rand 0.10.1", - "reqwest 0.13.4", + "reqwest 0.13.5", "rustls-pki-types", "serde", "serde_json", @@ -7054,7 +7054,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "opendal-core", - "reqwest 0.13.4", + "reqwest 0.13.5", ] [[package]] @@ -8147,8 +8147,8 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.4.1", - "itertools 0.12.1", + "heck 0.5.0", + "itertools 0.14.0", "log", "multimap", "petgraph", @@ -8167,7 +8167,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.14.0", "proc-macro2", "quote", "syn 2.0.117", @@ -8430,7 +8430,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -8985,11 +8985,11 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.13.4" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", "encoding_rs", "futures-core", @@ -9052,7 +9052,7 @@ dependencies = [ "anyhow", "async-trait", "http 1.5.0", - "reqwest 0.13.4", + "reqwest 0.13.5", "thiserror 2.0.18", "tower-service", ] @@ -9523,10 +9523,11 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash 0.2.0", "indexmap 2.14.0", "itoa", "memchr", @@ -9849,7 +9850,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.117", @@ -9861,7 +9862,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54254b8531cafa275c5e096f62d48c81435d1015405a91198ddb11e967301d40" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.117", @@ -9874,7 +9875,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -9993,7 +9994,7 @@ dependencies = [ "cfg-if 1.0.4", "libc", "psm", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -10488,9 +10489,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.53.3" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -10993,9 +10994,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.26.1" +version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ "getrandom 0.4.2", "js-sys", @@ -11220,9 +11221,9 @@ dependencies = [ [[package]] name = "webbrowser" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" +checksum = "d2c8ddfbbf66e501434657400268cefe51b95140a0266236415cda7627732df7" dependencies = [ "jni", "log", @@ -11780,7 +11781,7 @@ dependencies = [ "more-asserts", "rand 0.10.1", "redb", - "reqwest 0.13.4", + "reqwest 0.13.5", "reqwest-middleware", "serde", "serde_json", @@ -11887,7 +11888,7 @@ dependencies = [ "oneshot", "pin-project", "rand 0.10.1", - "reqwest 0.13.4", + "reqwest 0.13.5", "serde", "serde_json", "shellexpand", diff --git a/deny.toml b/deny.toml index c7a79f469..602cc2820 100644 --- a/deny.toml +++ b/deny.toml @@ -121,19 +121,16 @@ ignore = [ { id = "RUSTSEC-2026-0387", reason = "crypto-bigint via aws-sigv4 (sigv4a); no fixed upstream aws-sigv4 release yet" }, # zstd: arrow-ipc 58.x pins zstd ^0.13, while the patches require zstd - # >=0.14.3, zstd-safe >=8.2.0, and zstd-sys >=2.1.2. Arrow 59+ updates the - # dependency, but it cannot be used until DataFusion and Lance move to the - # matching Arrow line. LanceDB uses zstd::bulk through arrow-ipc and does - # not use the affected with_context, seekable, or decompress_stream APIs. - # The zstd-sys advisory is wasm32-only, and wasm32 is not a shipped target. + # >=0.14.3 and zstd-safe >=8.2.0. Arrow 59+ updates the dependency, but it + # cannot be used until DataFusion and Lance move to the matching Arrow line. + # LanceDB uses zstd::bulk through arrow-ipc and does not use the affected + # with_context, seekable, or decompress_stream APIs. # https://rustsec.org/advisories/RUSTSEC-2026-0391 # https://rustsec.org/advisories/RUSTSEC-2026-0398 # https://rustsec.org/advisories/RUSTSEC-2026-0403 - # https://rustsec.org/advisories/RUSTSEC-2026-0410 { id = "RUSTSEC-2026-0391", reason = "zstd 0.13 via arrow-ipc 58; affected with_context API is unused" }, { id = "RUSTSEC-2026-0398", reason = "zstd-safe 7 via arrow-ipc 58; affected seekable API is not enabled" }, { id = "RUSTSEC-2026-0403", reason = "zstd-safe 7 via arrow-ipc 58; affected streaming decoder API is unused" }, - { id = "RUSTSEC-2026-0410", reason = "zstd-sys via arrow-ipc 58; advisory is wasm32-only and wasm32 is not a shipped target" }, ] diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 4c86916eb..f41ed6cf3 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -23,7 +23,7 @@ env_logger.workspace = true futures.workspace = true lancedb.workspace = true lance-namespace.workspace = true -napi = { version = "3.8.3", default-features = false, features = [ +napi = { version = "3.15.0", default-features = false, features = [ "napi9", "async", "chrono_date", @@ -31,7 +31,7 @@ napi = { version = "3.8.3", default-features = false, features = [ ] } chrono.workspace = true serde_json.workspace = true -napi-derive = "3.5.2" +napi-derive = "3.6.13" # Prevent dynamic linking of lzma, which comes from datafusion lzma-sys = { version = "0.1", features = ["static"] } log.workspace = true From d44609b6f251e75e6e9ecc217138b59d90a2b5d7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:28:51 -0700 Subject: [PATCH 132/180] chore(deps): bump the nodejs-deps group across 1 directory with 3 updates (#4661) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the nodejs-deps group with 3 updates in the /nodejs directory: [@opentelemetry/api](https://github.com/open-telemetry/opentelemetry-js), [@opentelemetry/sdk-metrics](https://github.com/open-telemetry/opentelemetry-js) and [ts-jest](https://github.com/kulshekhar/ts-jest). Updates `@opentelemetry/api` from 1.9.1 to 1.10.0
Release notes

Sourced from @​opentelemetry/api's releases.

api/v1.10.0

1.10.0

:rocket: Features

  • feat(api): integrate the Logs API into @opentelemetry/api #4862 @​hectorhdzg
  • feat(api): add imperative context.attach() for setting context across callback boundaries that with() cannot wrap. #6845 @​pichlermarc
    • attach() returns a Token whose dispose() method restores the previous context. Use token.dispose() to detach.
    • attach is an optional method on the ContextManager interface; when the active context manager does not implement it, context.attach() logs a warning and returns a no-op token.
  • feat(api): add AnyValue type (of type unknown) and extend Attributes type values to use AnyValue #6780 @​trentm
    • This is part of supporting OTEP 4485.
    • This is a breaking change for SDK implementations, in that they may need to support more attribute types for any APIs that accept Attributes or AnyValue. Implementors should refer to the OTEP 4485 link above for "MUST / SHOULD" requirements for complex attributes handling. See also the attributes-handling utilities provided by @opentelemetry/core to help. For example, cleanSimpleAttributes() can be used to limit user-provided attributes to the set of value types supported in earlier @opentelemetry/api versions.
    • This change is typically not a breaking change for users of @opentelemetry/api. There is one possible breaking case: If a TypeScript user was using the Attributes type in their own code and using TypeScript Narrowing to reduce an attribute value to an expected type (example here). It is expected that this usage should be rare and, likely, limited to SDK implementations, if at all. (If this impacted your code, please let us know.)
    • Note for users of attributes: Simple attributes SHOULD be used whenever possible. Instrumentations SHOULD assume that backends do not index individual properties of complex attributes, that querying or aggregating on such properties is inefficient and complicated, and that reporting complex attributes carries higher performance overhead.

:bug: Bug Fixes

  • fix(api): cap tracestate list-members and total length in the deprecated TraceState.set() so it stays in step with TraceState from @opentelemetry/core #6964 @​Zuhef
  • fix: resolve the ESM build through the default export condition instead of import, so a resolver that activates neither import nor require still finds an entry point #7132 @​overbalance

:books: Documentation

  • docs(api): complete @since annotations for the public API #7023 @​nabeelamjadsheikh
    • Adds the three missing exported-type annotations and the member-level annotations for methods and properties introduced after their enclosing type.
    • Corrects Attributes, AttributeValue and TracerOptions from 1.3.0 to 1.1.0; all three were already importable in 1.1.0 via wildcard re-export.

:house: Internal

  • build: migrate the package build from tsc to tsdown, emitting dual CJS/ESM output from a single dist/ directory #6293 @​overbalance
    • The public entry points are unchanged: @opentelemetry/api and @opentelemetry/api/experimental. This package already declared an exports map, so deep imports such as @opentelemetry/api/build/src/... were rejected before this change and continue to be.
    • The emitted files moved out of build/src (CJS), build/esm and build/esnext (ESM) into dist/, using .cjs/.mjs extensions with matching .d.cts/.d.mts declarations. The non-standard esnext condition has been dropped in favour of the standard import/require conditions.
  • perf(api): add getGlobal fast-path #6956 @​legendecas
  • chore: remove the redundant module field from package.json; bundlers resolve the ESM build through the exports map #7130 @​overbalance
Changelog

Sourced from @​opentelemetry/api's changelog.

1.10.0

:rocket: (Enhancement)

:bug: (Bug Fix)

  • fix(core): added falsy check to make otel core work with browser where webpack config had process as false or null #3613 @​ravindra-dyte
  • fix(instrumentation-http): include query params in http.target #3646 @​kobi-co

:books: (Refine Doc)

:house: (Internal)

Commits
  • 56e6b1b chore: Release API 1.4.1, SDK 1.10.0, Experimental 0.36.0 (#3654)
  • ecb5ebe fix: Minor typing issues for web sandbox (#3660)
  • 48ecf22 feat(sdk-trace-base): add dropped attributes and events count on span (#3576)
  • 95bf6fc fix(build): add example/http to ignore list in update-ts-configs (#3657)
  • 3a2ca58 feat: add unit to view instrument selection criteria (#3647)
  • ebc8575 chore(jeager-exporter): deprecate jaeger exporter (#3585)
  • 2f715bd feat: allow to add attributes from grpc metadata in the patched server (#3589)
  • cbbdfd3 fix(sdk-node): update instrumentations once MeterProvider is initialized (#3624)
  • 4a4484a chore: update http example (#3651)
  • 494efff fix(otlp-exporter-base): fix changelog for merged retry pr (#3650)
  • Additional commits viewable in compare view

Updates `@opentelemetry/sdk-metrics` from 2.11.0 to 2.12.0
Release notes

Sourced from @​opentelemetry/sdk-metrics's releases.

v2.12.0

2.12.0

:rocket: Features

  • chore(sdk-trace): add StackContextManager in @opentelemetry/sdk-trace package #7086

:house: Internal

  • feat(ci): support releasing from maintenance branches #6767 @​pichlermarc
    • The API documentation site is only redeployed for releases whose commit is reachable from main, so a maintenance release no longer overwrites it.
Changelog

Sourced from @​opentelemetry/sdk-metrics's changelog.

CHANGELOG

All notable changes to this project will be documented in this file.

For API changes, see the API CHANGELOG. For experimental package changes, see the experimental CHANGELOG. For semantic convention package changes, see the semconv CHANGELOG. For notes on migrating to 2.x / 0.200.x see the upgrade guide. For notes on migrating to 3.x see the 3.x migration guide.

Unreleased

:boom: Breaking Changes

:rocket: Features

:bug: Bug Fixes

:books: Documentation

:house: Internal

3.0.0

:boom: Breaking Changes

  • chore(sdk-trace-node)!: remove the @opentelemetry/sdk-trace-node package #7054
    • The sdk-trace-node package has been replaced by the @opentelemetry/sdk-trace package. See the 3.x migration guide for full migration instructions.
  • chore(shim-opentracing)!: remove the @opentelemetry/shim-opentracing package
  • chore(context-async-hooks)!: remove the unused class AsyncHooksContextManager #7078
  • feat!: migrate package builds from tsc to tsdown, emitting dual CJS/ESM output from a single dist/ directory and declaring an exports map on every package #6293 @​overbalance
    • Importing a package by its name is unaffected in both CommonJS and ESM, as is every subpath listed in its exports map.
    • Deep imports into the build output no longer resolve. An exports map is an allowlist that Node.js and bundlers enforce, so specifiers such as @opentelemetry/core/build/src/... or @opentelemetry/core/build/esm/... now fail with ERR_PACKAGE_PATH_NOT_EXPORTED. Rewriting them to the new file layout does not help — unlisted subpaths are rejected whether or not the file exists.
    • The emitted files moved out of build/src (CJS), build/esm and build/esnext (ESM) into dist/, using .cjs/.mjs extensions with matching .d.cts/.d.mts declarations.
    • <package>/package.json is no longer importable for the same reason. Read a package's version from your own dependency metadata, or use SDK_INFO from @opentelemetry/core for the SDK version.
    • The non-standard esnext entry point has been removed; tools that preferred it fall back to module (ESM) or main (CJS).
    • If you depend on something that is only reachable through a deep import, please open an issue so it can be considered for the public API.
  • feat(core)!: remove deprecated getTimeOrigin, otperformance, _globalThis, and unrefTimer from @opentelemetry/core #7053
    • getTimeOrigin() — use performance.timeOrigin directly.
    • otperformance — use the global performance object directly.
    • _globalThis — use globalThis directly.
    • unrefTimer(timer) — call timer.unref() directly in your own code.
  • feat(sdk-trace)!: remove deprecated TracerProviderOptions.forceFlushTimeoutMillis #7057
    • Pass timeoutMillis to provider.forceFlush({ timeoutMillis }) instead. The default timeout is 30000ms.
  • feat(propagator-jaeger)!: remove @opentelemetry/propagator-jaeger package #7077
    • The Jaeger propagator is deprecated by the OpenTelemetry specification in favour of W3CTraceContextPropagator. Use W3CTraceContextPropagator from @opentelemetry/core instead.
    • See the 3.x migration guide for full instructions.

... (truncated)

Commits
  • 92b844e chore: prepare next v2.x release (#7151)
  • a859aff fix(web-common): export getElementXPath utility (#7124)
  • 2bd5a73 chore(web-common)!: deprecate addSpanNetworkEvents() et al instrumentation-...
  • d60f05e doc(sdk-trace): add description for StackContextManager (#7089)
  • 5bd476e chore: move context manager to sdk-trace (#7086)
  • 554c0c6 chore: move sdk-trace-web utils to web-common (#7058)
  • 788922c ci: support maintenance branch releases (#7036)
  • See full diff in compare view

Updates `ts-jest` from 29.4.12 to 29.4.15
Release notes

Sourced from ts-jest's releases.

v29.4.15

Please refer to CHANGELOG.md for details.

v29.4.14

Please refer to CHANGELOG.md for details.

v29.4.13

Please refer to CHANGELOG.md for details.

Changelog

Sourced from ts-jest's changelog.

29.4.15 (2026-10-15)

Bug Fixes

  • compiler: resolve modules with tsconfig options regardless of cache state (268746c), closes #5216
  • support .cjs config files in config:migrate (4001b4e), closes #4485

29.4.14 (2026-09-25)

Reverts

29.4.13 (2026-09-22)

Features

Performance Improvements

Commits
  • 197d4de chore(release): 29.4.15
  • ebad800 build(deps): update dependency node to v24.22.0
  • e5f6e98 test(compiler): clean up temp dirs from module resolution tests
  • 77dbb18 test(compiler): make module resolution tests path-independent on Windows
  • 268746c fix(compiler): resolve modules with tsconfig options regardless of cache state
  • 1536201 build(deps): update dependency vite to ^8.3.4
  • 141e39c build(deps): update dependency @​babel/core to ^8.0.7
  • 6a6686e build(deps-dev): bump shell-quote from 1.10.0 to 1.12.0 in /examples
  • 98e6e50 build(deps): bump proxy-addr from 2.0.7 to 2.0.8 in /website
  • d2439ff build(deps): bump compression from 1.8.1 to 1.8.2 in /website
  • Additional commits viewable in compare view

Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- nodejs/pnpm-lock.yaml | 58 +++++++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index 4c19305c8..faf0ad428 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -13,7 +13,7 @@ importers: dependencies: '@opentelemetry/api': specifier: ^1.9.0 - version: 1.9.1 + version: 1.10.0 reflect-metadata: specifier: ^0.2.2 version: 0.2.2 @@ -38,7 +38,7 @@ importers: version: 3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)(@types/node@22.7.4) '@opentelemetry/sdk-metrics': specifier: ^2.10.0 - version: 2.11.0(@opentelemetry/api@1.9.1) + version: 2.12.0(@opentelemetry/api@1.10.0) '@types/axios': specifier: ^0.14.0 version: 0.14.4 @@ -89,7 +89,7 @@ importers: version: 0.2.7 ts-jest: specifier: ^29.1.2 - version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) + version: 29.4.15(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) typedoc: specifier: 0.26.4 version: 0.26.4(typescript@5.5.4) @@ -1399,24 +1399,24 @@ packages: '@octokit/types@16.0.0': resolution: {integrity: sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==} - '@opentelemetry/api@1.9.1': - resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} + '@opentelemetry/api@1.10.0': + resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} engines: {node: '>=8.0.0'} - '@opentelemetry/core@2.11.0': - resolution: {integrity: sha512-7YP44XH0tV6+Mb54x2YGf84i7yi+31MBZlE8JwvozkxyTvXbSp10X7cI7YE49ChJ3shMJoBmCJF3+1QFBJctGA==} + '@opentelemetry/core@2.12.0': + resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/resources@2.11.0': - resolution: {integrity: sha512-Ie7+8q8MDF4FAEQCKVMTx3ReUvxiIAgIiiW3c9JdmP8+HMcDy20puT+AHjexnExgnbvBxjQ9fjkFDWrikJ2jQA==} + '@opentelemetry/resources@2.12.0': + resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.11.0': - resolution: {integrity: sha512-7GXXcObyHyDUUSG+L+kJoquty01bzm7ivE7+SSgXXJcHuPzGviptxwARmI2c+bnnxjexGQbJnyNlN8HxBP/Y7A==} + '@opentelemetry/sdk-metrics@2.12.0': + resolution: {integrity: sha512-mVMaEHwCUJuY3S4Esn+nT0yQA3qCEGh+SOPJsXygU0Gl453WcsDNjtEa8EfdewMwoLyr1tlofB4fXytVpiXuow==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.9.0 <1.10.0' @@ -2434,8 +2434,8 @@ packages: guid-typescript@1.0.9: resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -3280,12 +3280,12 @@ packages: peerDependencies: typescript: '>=4.2.0' - ts-jest@29.4.12: - resolution: {integrity: sha512-Ov6ClY53Fflh6BGAnY2DlTq1hYDrTycz2PVTXBWFW2CU+9zrEqAp9fWdGXl42EXO5RLSFAcAZ2JFKbP+zBTFfw==} + ts-jest@29.4.15: + resolution: {integrity: sha512-s2qmEUYFRqbjz1wv0EmccNPVOb45HOFpFuhzQJLKShYVisuTbCFPIIAIV2EuK5rIxb4BejLDbH7dnBZfYjybUQ==} engines: {node: ^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0} hasBin: true peerDependencies: - '@babel/core': '>=7.0.0-beta.0 <8' + '@babel/core': '>=7.0.0-beta.0 <9' '@jest/transform': ^29.0.0 || ^30.0.0 '@jest/types': ^29.0.0 || ^30.0.0 babel-jest: ^29.0.0 || ^30.0.0 @@ -5153,24 +5153,24 @@ snapshots: dependencies: '@octokit/openapi-types': 27.0.0 - '@opentelemetry/api@1.9.1': {} + '@opentelemetry/api@1.10.0': {} - '@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/core@2.12.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resources@2.11.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-metrics@2.11.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions@1.43.0': {} @@ -6376,7 +6376,7 @@ snapshots: guid-typescript@1.0.9: optional: true - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -7409,11 +7409,11 @@ snapshots: dependencies: typescript: 5.5.4 - ts-jest@29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): + ts-jest@29.4.15(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 jest: 29.7.0(@types/node@22.7.4) json5: 2.2.3 lodash.memoize: 4.1.2 From b44a0d2362bc25fa4fe884d740c2b7635588a3e9 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 28 Oct 2026 01:49:32 +0800 Subject: [PATCH 133/180] chore: update Lance to v15.0.0-beta.3 (#4692) Upgrade Lance to 15.0.0-beta.3 so `Dataset::concat_data_file_parts` returns a `Send` future and downstream workers can run it on Tokio. The upstream fix is https://github.com/lance-format/lance/pull/10370. Keep the vendored Arrow validity fix; upstream Arrow sources are unchanged between beta.2 and beta.3. --- Cargo.lock | 94 ++++++++++----------- Cargo.toml | 30 +++---- java/pom.xml | 2 +- python/pyproject.toml | 4 +- python/uv.lock | 18 ++-- python/vendor/lance-arrow/Cargo.toml | 2 +- python/vendor/lance-arrow/README.lancedb.md | 4 +- rust/lancedb/Cargo.toml | 2 +- 8 files changed, 78 insertions(+), 78 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2881e765a..6197bf30d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3584,8 +3584,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5059,8 +5059,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arc-swap", "arrow", @@ -5135,7 +5135,7 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.2" +version = "15.0.0-beta.3" dependencies = [ "arrow-array", "arrow-buffer", @@ -5157,7 +5157,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "arrow-buffer", @@ -5171,7 +5171,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "arrow-schema", @@ -5180,8 +5180,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrayref", "crunchy", @@ -5191,8 +5191,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "arrow-buffer", @@ -5229,8 +5229,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow", "arrow-array", @@ -5262,8 +5262,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow", "arrow-array", @@ -5288,8 +5288,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow", "arrow-array", @@ -5306,8 +5306,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "proc-macro2", "quote", @@ -5316,8 +5316,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-arith", "arrow-array", @@ -5351,8 +5351,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-arith", "arrow-array", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "geo-traits", "geo-types", @@ -5397,8 +5397,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arc-swap", "arrow", @@ -5474,8 +5474,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "arrow-schema", @@ -5498,8 +5498,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow", "arrow-array", @@ -5542,8 +5542,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "byteorder", "ethnum", @@ -5560,8 +5560,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "arrow-schema", @@ -5575,8 +5575,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow", "async-trait", @@ -5590,8 +5590,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arc-swap", "arrow", @@ -5645,8 +5645,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "arrow-buffer", @@ -5660,8 +5660,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow", "arrow-array", @@ -5701,8 +5701,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "arrow-array", "arrow-schema", @@ -5715,8 +5715,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.2#f50a157269d925ad5708c7b0f7ec6c87b0fd08dd" +version = "15.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 40040c329..546613ce2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,21 +18,21 @@ categories = ["database-implementations"] rust-version = "1.94.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.2", default-features = false, "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.2", default-features = false, "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.2", default-features = false, "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { version = "=15.0.0-beta.2", path = "python/vendor/lance-arrow" } +lance = { "version" = "=15.0.0-beta.3", default-features = false, "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.3", default-features = false, "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.3", default-features = false, "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { version = "=15.0.0-beta.3", path = "python/vendor/lance-arrow" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 96262a8e9..2340c084c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.2 + 15.0.0-beta.3 2.18.11 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index ac9281248..f71eac182 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -46,7 +46,7 @@ repository = "https://github.com/lancedb/lancedb" [project.optional-dependencies] pylance = [ # Keep the minimum in the bundled Lance major and compatible with tests below. - "pylance>=15.0.0b2", + "pylance>=15.0.0b3", ] # A library only needs the OpenTelemetry API; the application supplies and # configures the SDK (the actual exporter/reader). See @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow<25", "pyarrow-stubs>=16.0", - "pylance==15.0.0b2", + "pylance==15.0.0b3", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 329a9ef24..3158220dd 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2006,8 +2006,8 @@ requires-dist = [ { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, - { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b2" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b2" }, + { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b3" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -3938,7 +3938,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b2" +version = "15.0.0b3" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -3948,12 +3948,12 @@ dependencies = [ { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_5aLfR/pylance-15.0.0b2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:fd6b872e348d804c3188d014f2ff469f8cfaff5bbe846617e665c1e2a2965683" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1W21Yj/pylance-15.0.0b2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b0ed217ee71bea57ef97303bd1318ae212ee005c885c16390d7efbaf1f7398e3" }, - { url = "https://pypi.fury.io/lance-format/-/ver_12xJCp/pylance-15.0.0b2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72580d6359db4d471c578daab46a35fd87e74e57a1cb64e333188fea1e1c2f1b" }, - { url = "https://pypi.fury.io/lance-format/-/ver_m4ypB/pylance-15.0.0b2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c194f95e2d2b1c5a9e4f57ed2681a9295effe5aaa165bf924f2b2090094c4645" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1zYkf2/pylance-15.0.0b2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c14532517ed1452d9cb215f33dc4bc3166500e14145c8c6f2f3538b82ac5147b" }, - { url = "https://pypi.fury.io/lance-format/-/ver_xp2do/pylance-15.0.0b2-cp310-abi3-win_amd64.whl", hash = "sha256:ce13e573a1842eda18f9b74eec4c8d1dc60db0895581db3226c6a6b1a8e79a75" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1ttHFr/pylance-15.0.0b3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:aaca475121cef79ada6fc19e2e2b54860e411cc8291f9ffa5643500264513086" }, + { url = "https://pypi.fury.io/lance-format/-/ver_19DzNz/pylance-15.0.0b3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5632f269b9e138b9ed3e5c7b788dfe27e04debab9d0f4c72be468f56d4a0d45a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_20XdL/pylance-15.0.0b3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bdc92d7dc4d38323452543f71e61b493c3cfb5129dade33175f478e394b1959" }, + { url = "https://pypi.fury.io/lance-format/-/ver_YBklr/pylance-15.0.0b3-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:6fcaced6f675f027979e1928284e104ae45eb8282d7c1eb0e51e4a5b92b93392" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1HLHhZ/pylance-15.0.0b3-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f19240f3ccd621b746062fd2825e9340b99131c2cbda7ed5b226b6f7871b73f4" }, + { url = "https://pypi.fury.io/lance-format/-/ver_24P9Ax/pylance-15.0.0b3-cp310-abi3-win_amd64.whl", hash = "sha256:3f964e4ed093b6f170601d40772fcd3525fd73d15fd56eb30d884a446668d602" }, ] [[package]] diff --git a/python/vendor/lance-arrow/Cargo.toml b/python/vendor/lance-arrow/Cargo.toml index e9adc478c..f5852a2c0 100644 --- a/python/vendor/lance-arrow/Cargo.toml +++ b/python/vendor/lance-arrow/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-arrow" -version = "15.0.0-beta.2" +version = "15.0.0-beta.3" edition = "2024" authors = ["Lance Devs "] license = "Apache-2.0" diff --git a/python/vendor/lance-arrow/README.lancedb.md b/python/vendor/lance-arrow/README.lancedb.md index 4a9f6176f..b0d6419fd 100644 --- a/python/vendor/lance-arrow/README.lancedb.md +++ b/python/vendor/lance-arrow/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-arrow` from Lance tag `v15.0.0-beta.2` -(commit `f50a157269d925ad5708c7b0f7ec6c87b0fd08dd`), licensed under Apache-2.0. +This directory contains `rust/lance-arrow` from Lance tag `v15.0.0-beta.3` +(commit `2e22bb984d6cc6f5990f188cabb0b586b7bb51bc`), licensed under Apache-2.0. LanceDB carries a local fix in `src/lib.rs` for sliced child validity bitmaps until a Lance release includes the fix. The patch is selected in the root diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 7f3764b02..9da1023da 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -46,7 +46,7 @@ lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lind lance-table = { workspace = true } lance-linalg = { workspace = true } lance-encoding = { workspace = true } -lance-arrow = { "version" = "=15.0.0-beta.2", "tag" = "v15.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } lance-namespace = { workspace = true } lance-namespace-impls = { workspace = true } metrics = { workspace = true, optional = true } From 6e4f523e149e20d1aa836530bf4353bfc603cd02 Mon Sep 17 00:00:00 2001 From: Dan Tasse <105866+dantasse@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:59:51 -0400 Subject: [PATCH 134/180] docs: remove logical-column from docs (#4693) We've removed this feature from LanceDB Enterprise and no longer privilege the "lancedb:logical-column" key. So, removing that from these docs. --- docs/src/js/classes/Table.md | 2 -- docs/web/management/table.mdx | 1 - nodejs/lancedb/table.ts | 2 -- python/python/lancedb/table.py | 2 -- rust/lancedb/src/table.rs | 2 -- 5 files changed, 9 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 80bba02a0..ded04d4c8 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1434,8 +1434,6 @@ used when appropriate: - `lancedb:description`: for a human-readable description of a field. - `lancedb:tag:`: for a user-defined key-value tag, where the suffix names the tag category; e.g. `lancedb:tag:model: "clip"`. -- `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and - `feature_v2` might be in the same logical column. - `lancedb:status`: for status options (`production`, `candidate`, `deprecated`, `archived`) to designate the current life cycle state of this column. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index d817d4fa0..4e87bcbb1 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1180,7 +1180,6 @@ on finding this information in a consistent place. Use them when they fit your u | --- | --- | --- | | `lancedb:description` | Human-readable description of the field. | `"CLIP embedding of the product image"` | | `lancedb:tag:` | User-defined key/value tag, where the suffix names the tag category. | `"lancedb:tag:model": "clip"` | -| `lancedb:logical-column` | Groups related columns into one logical column. For example, `feature_v1` and `feature_v2` might belong to the same logical column. | `"lancedb:logical-column": "feature"` | | `lancedb:status` | Life cycle state of the column: `production`, `candidate`, `deprecated`, or `archived`. | `"lancedb:status": "production"` | diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index b88603fb7..71408803d 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -725,8 +725,6 @@ export abstract class Table { * - `lancedb:description`: for a human-readable description of a field. * - `lancedb:tag:`: for a user-defined key-value tag, where the suffix * names the tag category; e.g. `lancedb:tag:model: "clip"`. - * - `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and - * `feature_v2` might be in the same logical column. * - `lancedb:status`: for status options (`production`, `candidate`, * `deprecated`, `archived`) to designate the current life cycle state of * this column. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 7bef43c0d..ac82106cc 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3209,8 +3209,6 @@ class Table(ABC): - "lancedb:description": for a human-readable description of a field. - ``"lancedb:tag:"`` for a user-defined key-value tag, where the suffix names the tag category; e.g. "lancedb:tag:model": "clip". - - "lancedb:logical-column" for a column grouping; e.g. "feature_v1" - and "feature_v2" might be in the same logical column. - "lancedb:status" for status options ("production", "candidate", "deprecated", "archived") to designate the current life cycle state of this column. diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index a7db1ae5e..37edd9161 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2003,8 +2003,6 @@ impl Table { /// - `lancedb:description`: for a human-readable description of a field. /// - `lancedb:tag:`: for a user-defined key-value tag, where the suffix /// names the tag category; e.g. `lancedb:tag:model: "clip"`. - /// - `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and - /// `feature_v2` might be in the same logical column. /// - `lancedb:status`: for status options (`production`, `candidate`, /// `deprecated`, `archived`) to designate the current life cycle state of /// this column. From ac99ab173badecbd8349fbd155313b7dbc95a7cf Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 02:59:02 +0800 Subject: [PATCH 135/180] fix(python): support native blob conversion in pandas and batches (#4647) Plain local blob v2 scans tried to open a pylance dataset before reaching LanceDB's byte-fetch path, so `to_pandas(blob_mode="bytes")` failed when the optional dependency was absent. Batch readers also had no `blob_mode` option. Route supported blob v2 pandas conversions through the native Arrow path. Add `blob_mode` to sync and async batch readers, convert payloads during iteration, and expose the converted schema without fetching the first batch. Apply conversion after reranking and retain the default descriptor behavior. Clean up scanner error punctuation and remove the misleading plain-scan suggestion. Bytes mode retains the existing `to_arrow` restrictions for legacy/list blobs, remote tables, and namespace query pushdown. Lazy pandas handles and legacy pandas scans still require pylance; sync FTS/hybrid batching remains unsupported. Validation: - UV-managed editable Python development build completed successfully. - The absent-pylance regression tests fail against the original query implementation and pass with this change. - Blob and query suites: 403 passed, 1 skipped, 1 deselected. - Remote query suite: 190 passed. - Python-tree Ruff lint/format checks and the async reader Pyright check pass. Repository-wide Ruff reports existing errors outside the Python tree. Fixes #4645 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/web/management/table.mdx | 40 +++- python/python/lancedb/_blob.py | 14 +- python/python/lancedb/arrow.py | 13 +- python/python/lancedb/query.py | 182 +++++++++++++++--- python/python/tests/test_blob.py | 113 ++++++++++- .../tests/test_blob_query_without_pylance.py | 94 +++++++++ python/python/tests/test_query.py | 6 +- 7 files changed, 419 insertions(+), 43 deletions(-) create mode 100644 python/python/tests/test_blob_query_without_pylance.py diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 4e87bcbb1..182a80ec3 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -447,8 +447,8 @@ above:
In the Python SDK, `Table.to_pandas()`, `Table.to_arrow()`, and the query builder -methods `to_pandas()`, `to_arrow()`, and `to_list()` accept a `blob_mode` -argument: +methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a +`blob_mode` argument. Sync and async query builders support the same modes: | `blob_mode` | `to_pandas()` | `to_arrow()` and `to_list()` | | --- | --- | --- | @@ -456,10 +456,11 @@ argument: | `"descriptions"` | Returns descriptor dicts with `kind`, `position`, `size`, `blob_id`, and `blob_uri`. | Returns the 5-field descriptor without `_lance_row_id`. | | `"bytes"` | Materializes each blob as `bytes` in the DataFrame. | Materializes each blob as `large_binary` in Arrow or `bytes` in Python dicts. | -`to_pandas(blob_mode="lazy")` and `to_pandas(blob_mode="bytes")` require -pylance. Without it they raise `ImportError`. `to_arrow()`, -`to_list(blob_mode="bytes")`, `to_pandas(blob_mode="descriptions")`, and the -fetch methods do not. +For supported local v2 blob projections, `to_pandas(blob_mode="bytes")` and +`to_pandas(blob_mode="descriptions")` use native Arrow conversion without +pylance. Pandas conversions that need the Lance scanner, including plain-scan +`"lazy"` handles and legacy blobs, still require pylance. `to_arrow()`, +`to_list()`, `to_batches()`, and the fetch methods do not require pylance. `blob_mode="bytes"` requires a local table snapshot, so remote and in-memory tables raise `NotImplementedError`. On a remote table, `Table.to_pandas()` and @@ -475,9 +476,34 @@ them out of the projection. Extra keyword arguments on `to_pandas()`, such as `split_blocks` and `self_destruct`, are forwarded to PyArrow. +###### Stream blob results {#multimodal-blob-batches} + +`to_batches(blob_mode="bytes")` fetches blob v2 payloads one batch at a time +and returns them as Arrow `large_binary` values. Iterate over the reader and +call `batch.to_pandas()` to convert each batch to a DataFrame without collecting +all payloads at once. + +For sync queries, call `query.to_batches(batch_size=64, blob_mode="bytes")` +and iterate with `for`. For async queries, call +`await query.to_batches(max_batch_length=64, blob_mode="bytes")` and iterate +with `async for`. Sync full-text and hybrid queries do not support +`to_batches()`. + +The default `"lazy"` mode returns descriptors and keeps automatic `_rowid` +columns visible for manual fetches. `"descriptions"` returns the five-field +descriptors. Both `"bytes"` and `"descriptions"` hide automatic row IDs; +explicitly requested row IDs remain visible. + +Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, +including no legacy blobs, blobs inside lists, remote tables, or namespace +`QueryTable` pushdown. If concurrent writers can overwrite the table, use a +separate reader checked out to a fixed version before querying. Otherwise, +an overwrite can invalidate the row IDs used to fetch bytes and raise +`ValueError`. + ###### Optional pandas examples {#multimodal-blob-pandas} -These examples require pylance. The query example expects `tbl_async`, +The lazy-handle calls below require pylance. The query example expects `tbl_async`, `query_vector`, and a `video` column, which the `photos` table does not define. diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 46462553c..010c92009 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -280,7 +280,11 @@ async def replace_v2_blob_columns_with_bytes( row_ids = _hit_row_ids(tbl, present) for output_name, source_name in present.items(): tbl = _set_blob_column( - tbl, output_name, await fetch_blobs(source_name, row_ids) + tbl, + output_name, + await fetch_blobs(source_name, row_ids) + if row_ids + else pa.array([], type=pa.large_binary()), ) return tbl @@ -295,7 +299,13 @@ def replace_v2_blob_columns_with_bytes_sync( return tbl row_ids = _hit_row_ids(tbl, present) for output_name, source_name in present.items(): - tbl = _set_blob_column(tbl, output_name, fetch_blobs(source_name, row_ids)) + tbl = _set_blob_column( + tbl, + output_name, + fetch_blobs(source_name, row_ids) + if row_ids + else pa.array([], type=pa.large_binary()), + ) return tbl diff --git a/python/python/lancedb/arrow.py b/python/python/lancedb/arrow.py index 404efafea..c5a278ead 100644 --- a/python/python/lancedb/arrow.py +++ b/python/python/lancedb/arrow.py @@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from functools import singledispatch -from typing import List, Optional, Tuple, Union +from typing import AsyncIterator, List, Optional, Tuple, Union from lancedb.pydantic import LanceModel, model_to_dict import pyarrow as pa @@ -30,6 +30,7 @@ class AsyncRecordBatchReader: The schema of the batches produced by the stream. Accessing the schema does not consume any data from the stream """ + self._inner: AsyncIterator[pa.RecordBatch] if isinstance(inner, pa.Table): self._inner = self._async_iter_from_table(inner, max_batch_length) self.schema: pa.Schema = inner.schema @@ -39,6 +40,16 @@ class AsyncRecordBatchReader: else: raise TypeError("inner must be a RecordBatchStream or a Table") + @classmethod + def _from_batches( + cls, schema: pa.Schema, batches: AsyncIterator[pa.RecordBatch] + ) -> "AsyncRecordBatchReader": + """Wrap a transformed stream without consuming its first batch.""" + reader = cls.__new__(cls) + reader.schema = schema + reader._inner = batches + return reader + async def read_all(self) -> List[pa.RecordBatch]: """ Read all the record batches from the stream diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index b2093712e..03560ec31 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -104,11 +104,13 @@ class _LanceScanner(Protocol): def _unsupported_blob_pandas_error(reason: str) -> RuntimeError: + reason = reason.rstrip(".") + reason = reason[0].upper() + reason[1:] return RuntimeError( - "blob columns require Lance native scanner conversion for query " - f"to_pandas(), but {reason}. Use a plain scan query, pass " - "blob_mode='bytes' or blob_mode='descriptions', or remove blob columns " - "from the projection." + "Blob columns require Lance native scanner conversion for this query's " + f"to_pandas(). {reason}. For supported blob v2 queries, pass " + "blob_mode='bytes' or blob_mode='descriptions'. Otherwise, install " + "pylance for scanner conversion or remove blob columns from the projection." ) @@ -1139,9 +1141,10 @@ class LanceQueryBuilder(ABC): The maximum time to wait for the query to complete. If None, wait indefinitely. blob_mode: str, default "lazy" - Controls how blob columns are returned. Eligible local plain scans - use Lance's scanner, which returns lazy blob handles in ``"lazy"`` - mode and also supports legacy blob columns. Other local blob v2 + Controls how blob columns are returned. Local blob v2 queries support + ``"bytes"`` and ``"descriptions"`` without pylance. Eligible local + plain scans use pylance's scanner for lazy blob handles in ``"lazy"`` + mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. Remote blob queries support only ``"descriptions"`` until a stable @@ -1219,15 +1222,16 @@ class LanceQueryBuilder(ABC): batch_size: Optional[int] = None, *, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: """ Execute the query and return the results as a pyarrow [RecordBatchReader](https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatchReader.html) - For v2 blob projections, ``to_batches`` keeps the auto ``_rowid`` - column visible so batch consumers can call ``fetch_blobs``. Use - ``to_arrow``, ``to_list``, or ``to_pandas`` if you want LanceDB to hide - auto row ids in the final collected result. + For v2 blob projections, the default ``blob_mode="lazy"`` keeps the + auto ``_rowid`` column visible so batch consumers can call + ``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide + automatic row ids. Parameters ---------- @@ -1236,6 +1240,16 @@ class LanceQueryBuilder(ABC): timeout: Optional[timedelta] The maximum time to wait for the query to complete. If None, wait indefinitely. + blob_mode: str, default "lazy" + ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. + ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 + payloads one batch at a time, without requiring pylance. Bytes mode + has the same restrictions as :meth:`to_arrow`. + + Examples + -------- + Stream blob payloads with ``query.to_batches(blob_mode="bytes")`` and + convert each batch separately with ``batch.to_pandas()``. """ raise NotImplementedError @@ -1499,6 +1513,28 @@ class LanceQueryBuilder(ABC): finalized = finalized.drop_columns(["_rowid"]) return finalized + def _batches_in_mode( + self, + reader: pa.RecordBatchReader, + blob_mode: BlobMode, + blob_sources: dict[str, str], + ) -> pa.RecordBatchReader: + if blob_mode == "lazy": + return reader + + def convert(tbl: pa.Table) -> pa.Table: + return self._finalize_blob_query_table( + tbl, blob_mode=blob_mode, blob_sources=blob_sources + ) + + schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema + + def batches(): + for batch in reader: + yield from convert(pa.Table.from_batches([batch])).to_batches() + + return pa.RecordBatchReader.from_batches(schema, batches()) + def with_row_address(self, with_row_address: bool = True) -> Self: """Set whether to return row addresses. @@ -1717,7 +1753,18 @@ class LanceQueryBuilder(ABC): get_uri_scheme(self._table._dataset_path) == "memory" ): return None - dataset = self._table.to_lance() + # Blob v2 payloads and descriptions use LanceDB's native fetch path. + # Only lazy handles, legacy blobs, and scanner-only options need pylance. + if ( + blob_mode != "lazy" + and not _query_needs_lance_scanner(self) + and blob_v2_projection_sources(self._table.schema, query.columns) + ): + return None + try: + dataset = self._table.to_lance() + except ImportError as err: + raise _unsupported_blob_pandas_error(str(err)) from err blob_auto_row_id = self._blob_auto_row_id_enabled() blob_sources = ( blob_v2_projection_sources(self._table.schema, query.columns) @@ -2076,6 +2123,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): batch_size: Optional[int] = None, *, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: """ Execute the query and return the result as a RecordBatchReader object. @@ -2087,11 +2135,15 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): timeout: timedelta, default None The maximum time to wait for the query to complete. If None, wait indefinitely. + blob_mode: str, default "lazy" + Controls blob conversion as described in + :meth:`LanceQueryBuilder.to_batches`. Returns ------- pa.RecordBatchReader """ + blob_sources = self._validated_blob_sources(blob_mode) vector = self._query if isinstance(self._query, list) else self._query.tolist() if isinstance(vector[0], np.ndarray): vector = [v.tolist() for v in vector] @@ -2108,7 +2160,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): result_set.schema, result_set.to_batches() ) - return result_set + return self._batches_in_mode(result_set, blob_mode, blob_sources) def where( self, where: Union[str, Expr], prefilter: bool = None @@ -2323,7 +2375,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): ) def to_batches( - self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None + self, + /, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + *, + blob_mode: BlobMode = "lazy", ): raise NotImplementedError("to_batches on an FTS query") @@ -2379,10 +2436,19 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): return self._table._output_schema(query) def to_batches( - self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None + self, + /, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + *, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: + blob_sources = self._validated_blob_sources(blob_mode) query = self._query_for_scan() - return self._table._execute_query(query, batch_size=batch_size, timeout=timeout) + reader = self._table._execute_query( + query, batch_size=batch_size, timeout=timeout + ) + return self._batches_in_mode(reader, blob_mode, blob_sources) def rerank(self, reranker: Reranker) -> LanceEmptyQueryBuilder: """Rerank the results using the specified reranker. @@ -2676,7 +2742,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): return results def to_batches( - self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None + self, + /, + batch_size: Optional[int] = None, + timeout: Optional[timedelta] = None, + *, + blob_mode: BlobMode = "lazy", ): raise NotImplementedError("to_batches not yet supported on a hybrid query") @@ -3279,6 +3350,7 @@ class AsyncQueryBase(object): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> AsyncRecordBatchReader: """ Execute the query and return the results as an Apache Arrow RecordBatchReader. @@ -3295,7 +3367,47 @@ class AsyncQueryBase(object): The maximum time to wait for the query to complete. If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. + blob_mode: str, default "lazy" + ``"lazy"`` keeps blob descriptors and auto row ids for manual fetches. + ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2 + payloads one batch at a time, without requiring pylance. Bytes mode + has the same restrictions as :meth:`to_arrow`. + + Examples + -------- + Use ``async for batch in await query.to_batches(blob_mode="bytes")`` + to stream blob payloads and convert each batch with ``batch.to_pandas()``. """ + blob_sources = await self._validated_blob_sources(blob_mode) + reader = await self._execute_batches( + max_batch_length=max_batch_length, timeout=timeout + ) + if blob_mode == "lazy": + return reader + + async def convert(tbl: pa.Table) -> pa.Table: + tbl = self._finalize_blob_query_table(tbl) + tbl = await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources) + if not self._user_requested_row_id() and "_rowid" in tbl.column_names: + tbl = tbl.drop_columns(["_rowid"]) + return tbl + + schema = (await convert(pa.Table.from_batches([], schema=reader.schema))).schema + + async def batches(): + async for batch in reader: + tbl = await convert(pa.Table.from_batches([batch])) + for converted in tbl.to_batches(): + yield converted + + return AsyncRecordBatchReader._from_batches(schema, batches()) + + async def _execute_batches( + self, + *, + max_batch_length: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> AsyncRecordBatchReader: await self._maybe_add_blob_row_id() return AsyncRecordBatchReader( await self._inner.execute( @@ -3444,9 +3556,10 @@ class AsyncQueryBase(object): If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. blob_mode: str, default "lazy" - Controls how blob columns are returned. Eligible local plain scans - use Lance's scanner, which returns lazy blob handles in ``"lazy"`` - mode and also supports legacy blob columns. Other local blob v2 + Controls how blob columns are returned. Local blob v2 queries support + ``"bytes"`` and ``"descriptions"`` without pylance. Eligible local + plain scans use pylance's scanner for lazy blob handles in ``"lazy"`` + mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. Remote blob queries support only ``"descriptions"`` until a stable @@ -3536,7 +3649,16 @@ class AsyncQueryBase(object): get_uri_scheme(await self._table.uri()) == "memory" ): return None - dataset = await self._table.to_lance() + if ( + blob_mode != "lazy" + and not _query_needs_lance_scanner(self) + and blob_v2_projection_sources(schema, query.columns) + ): + return None + try: + dataset = await self._table.to_lance() + except ImportError as err: + raise _unsupported_blob_pandas_error(str(err)) from err scanner = dataset.scanner( **_scanner_kwargs_for_query( query, @@ -4036,13 +4158,13 @@ class AsyncFTSQuery(AsyncStandardQuery): self._table, ) - async def to_batches( + async def _execute_batches( self, *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, ) -> AsyncRecordBatchReader: - reader = await super().to_batches(timeout=timeout) + reader = await super()._execute_batches(timeout=timeout) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: results = self._reranker.rerank_fts(self.get_query(), results) @@ -4327,13 +4449,13 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): self._inner.nearest_to_text({"query": query}), self._table ) - async def to_batches( + async def _execute_batches( self, *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, ) -> AsyncRecordBatchReader: - reader = await super().to_batches(timeout=timeout) + reader = await super()._execute_batches(timeout=timeout) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: results = self._reranker.rerank_vector(self._query_string, results) @@ -4456,7 +4578,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): return fts_query, vec_query, limit, offset - async def to_batches( + async def _execute_batches( self, *, max_batch_length: Optional[int] = None, @@ -4726,6 +4848,7 @@ class BaseQueryBuilder(object): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: """ Execute the query and return the results as an Apache Arrow RecordBatchReader. @@ -4742,9 +4865,14 @@ class BaseQueryBuilder(object): The maximum time to wait for the query to complete. If not specified, no timeout is applied. If the query does not complete within the specified time, an error will be raised. + blob_mode: str, default "lazy" + Controls blob conversion as described in + :meth:`AsyncQueryBase.to_batches`. """ async_reader = LOOP.run( - self._inner.to_batches(max_batch_length=max_batch_length, timeout=timeout) + self._inner.to_batches( + max_batch_length=max_batch_length, timeout=timeout, blob_mode=blob_mode + ) ) def iter_sync(): diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index f4c6a9e24..96bf88c24 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -843,8 +843,7 @@ def test_to_pandas_does_not_drop_fragment_selection_on_fallback(): table.search().with_row_address(True).to_pandas(blob_mode="descriptions") -@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"]) -def test_to_pandas_reports_lance_dataset_failures(tmp_path, blob_mode): +def test_to_pandas_reports_lance_dataset_failures(tmp_path): table = lancedb.connect(tmp_path).create_table( "dataset_failure", schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), @@ -856,7 +855,59 @@ def test_to_pandas_reports_lance_dataset_failures(tmp_path, blob_mode): table.to_lance = reject_credentials with pytest.raises(PermissionError, match="storage credentials rejected"): - table.search().to_pandas(blob_mode=blob_mode) + table.search().to_pandas(blob_mode="lazy") + + +@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"]) +@pytest.mark.parametrize("with_row_id", [None, True, False]) +def test_to_batches_blob_modes(tmp_path, monkeypatch, blob_mode, with_row_id): + table = _nested_blob_table(lancedb.connect(tmp_path), "batch_blob_modes") + query = table.search().select({"renamed": "info"}) + if with_row_id is not None: + query.with_row_id(with_row_id) + fetched = [] + fetch_blobs = table.fetch_blobs + + def fetch(column, row_ids): + fetched.append(row_ids) + return fetch_blobs(column, row_ids) + + monkeypatch.setattr(table, "fetch_blobs", fetch) + reader = query.to_batches(batch_size=1, blob_mode=blob_mode) + assert fetched == [] + first = reader.read_next_batch() + assert first.schema == reader.schema + assert len(fetched) == (1 if blob_mode == "bytes" else 0) + batches = [first, *reader] + assert all(batch.schema == reader.schema for batch in batches) + assert all(batch.num_rows == 1 for batch in batches) + assert len(fetched) == (3 if blob_mode == "bytes" else 0) + if blob_mode == "bytes": + assert [row["renamed"] for batch in batches for row in batch.to_pylist()] == [ + {"name": "first", "blob": b"hello"}, + {"name": "second", "blob": None}, + None, + ] + if blob_mode != "lazy": + assert ("_rowid" in reader.schema.names) == (with_row_id is True) + assert "_lance_row_id" not in str(reader.schema) + else: + assert "_rowid" in reader.schema.names + + +@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"]) +def test_empty_to_batches_blob_schema(blob_mode): + table = _blob_table("empty_blob_batches", [{"id": 1, "image": b"one"}]) + query = table.search().where("id < 0") + reader = query.to_batches(blob_mode=blob_mode) + assert reader.schema == query.to_arrow(blob_mode=blob_mode).schema + assert reader.read_all().num_rows == 0 + + +def test_to_batches_validates_blob_mode(): + table = _blob_table("invalid_batch_blob_mode", [{"id": 1, "image": b"one"}]) + with pytest.raises(ValueError, match="blob_mode must be one of"): + table.search().to_batches(blob_mode="handles") def test_to_pandas_keeps_to_arrow_overrides_without_blob_mode(): @@ -894,6 +945,12 @@ def test_take_queries_honor_blob_mode(): ] description = table.take_row_ids([0]).to_list(blob_mode="descriptions")[0]["image"] assert "_lance_row_id" not in description + batches = table.take_row_ids([0]).to_batches(blob_mode="bytes") + assert batches.read_all().to_pylist() == [{"id": 1, "image": b"one"}] + batches = table.take_row_ids([0]).to_batches(blob_mode="descriptions") + assert "_rowid" not in batches.schema.names + assert "_lance_row_id" not in str(batches.schema) + assert batches.read_all().num_rows == 1 def test_bytes_mode_follows_swapped_blob_aliases(): @@ -939,6 +996,8 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path): table.search().to_list(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): table.take_row_ids([0]).to_list(blob_mode="bytes") + with pytest.raises(NotImplementedError, match="stable table snapshot"): + table.search().to_batches(blob_mode="bytes") descriptor = table.to_arrow(blob_mode="descriptions")["image"].to_pylist()[0] assert "_lance_row_id" not in descriptor @@ -960,6 +1019,8 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path) await table.to_arrow(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): await table.query().to_list(blob_mode="bytes") + with pytest.raises(NotImplementedError, match="stable table snapshot"): + await table.query().to_batches(blob_mode="bytes") def test_fetch_blobs_round_trip(): @@ -2076,6 +2137,10 @@ def test_blob_mode_for_every_query_shape(shape, blob_mode, with_row_id): assert all("_lance_row_id" not in image for image in images.values()) df = query.to_pandas(blob_mode=blob_mode) assert dict(zip(df["id"], df["image"])) == images + if shape in ("scan", "vector"): + reader = query.to_batches(batch_size=1, blob_mode=blob_mode) + assert reader.schema == hits.schema + assert reader.read_all().equals(hits) @pytest.mark.asyncio @@ -2102,6 +2167,48 @@ async def test_async_blob_bytes_for_every_query_shape(shape): assert dict(zip(df["id"], df["image"])) == {1: b"alpha", 2: b"beta"} +@pytest.mark.asyncio +@pytest.mark.parametrize("shape", ["scan", "vector", "fts", "hybrid"]) +@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"]) +async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch): + db = await lancedb.connect_async("memory:///") + table = await _hybrid_blob_table_async(db) + query = table.query() + if shape in ("vector", "hybrid"): + query = query.nearest_to([1.0, 0.0]) + if shape in ("fts", "hybrid"): + query = query.nearest_to_text("hello") + if shape == "scan": + query = query.where("id < 3") + query = query.select({"id": "id", "payload": "image"}).limit(2) + fetched = [] + fetch_blobs = table.fetch_blobs + + async def fetch(column, row_ids): + fetched.append(row_ids) + return await fetch_blobs(column, row_ids) + + monkeypatch.setattr(table, "fetch_blobs", fetch) + reader = await query.to_batches(max_batch_length=1, blob_mode=blob_mode) + assert fetched == [] + first = await reader.__anext__() + assert len(fetched) == (1 if blob_mode == "bytes" else 0) + batches = [first, *[batch async for batch in reader]] + assert all(batch.num_rows == 1 for batch in batches) + assert all(batch.schema == reader.schema for batch in batches) + if blob_mode == "bytes": + assert len(fetched) == 2 + assert { + row["id"]: row["payload"] for b in batches for row in b.to_pylist() + } == { + 1: b"alpha", + 2: b"beta", + } + if blob_mode != "lazy": + assert "_rowid" not in reader.schema.names + assert "_lance_row_id" not in str(reader.schema) + + class _KeepAllScoresReranker(Reranker): """Rebuilds the merged table like model rerankers with return_score="all".""" diff --git a/python/python/tests/test_blob_query_without_pylance.py b/python/python/tests/test_blob_query_without_pylance.py new file mode 100644 index 000000000..cd9fd73ee --- /dev/null +++ b/python/python/tests/test_blob_query_without_pylance.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import subprocess +import sys +import textwrap + +import pytest + + +@pytest.mark.parametrize("api", ["sync", "async"]) +@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"]) +def test_blob_query_without_pylance(tmp_path, api, result): + script = """\ +import importlib.abc +import sys + +class MissingLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + +sys.meta_path.insert(0, MissingLance()) +""" + textwrap.dedent( + """\ + import asyncio + import lancedb + import pyarrow as pa + + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")]) + rows = [{"id": 1, "video": b"one"}, {"id": 2, "video": None}, + {"id": 3, "video": b"three"}] + + def check(data): + assert data == [{"filename": 2, "payload": None}, + {"filename": 3, "payload": b"three"}], data + + async def main(): + if sys.argv[2] == "async": + db = await lancedb.connect_async(sys.argv[1]) + table = await db.create_table("videos", schema=schema) + await table.add(rows) + query = table.query() + else: + db = lancedb.connect(sys.argv[1]) + table = db.create_table("videos", schema=schema) + table.add(rows) + query = table.search() + query = query.select({"filename": "id", "payload": "video"}).offset(1) + if sys.argv[3] == "pandas": + frame = query.to_pandas(blob_mode="bytes", split_blocks=True) + if sys.argv[2] == "async": + frame = await frame + check(frame.to_dict("records")) + frame = table.to_pandas(blob_mode="bytes") + if sys.argv[2] == "async": + frame = await frame + assert frame.to_dict("records") == rows + elif sys.argv[3] == "batches": + if sys.argv[2] == "async": + reader = await query.to_batches( + max_batch_length=1, blob_mode="bytes") + batches = [batch async for batch in reader] + else: + reader = query.to_batches(batch_size=1, blob_mode="bytes") + batches = list(reader) + assert reader.schema.field("payload").type == pa.large_binary() + assert all(batch.num_rows <= 1 for batch in batches) + assert all(batch.schema == reader.schema for batch in batches) + check([row for batch in batches for row in batch.to_pylist()]) + else: + try: + frame = query.to_pandas() + if sys.argv[2] == "async": + await frame + except RuntimeError as error: + message = str(error) + assert "pip install pylance" in message, message + assert ".." not in message, message + assert "Use a plain scan query" not in message, message + assert "but The" not in message, message + else: + raise AssertionError("lazy handles should require pylance") + assert "lance" not in sys.modules + + asyncio.run(main()) + """ + ) + completed = subprocess.run( + [sys.executable, "-c", script, str(tmp_path), api, result], + capture_output=True, + text=True, + ) + assert completed.returncode == 0, completed.stderr diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 3d7c01fc5..b898a8888 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -675,10 +675,10 @@ def test_blob_v2_vector_projection_and_plain_scan_options(tmp_db, monkeypatch): query = table.search().where("id = 1") - def fail_to_arrow(*args, **kwargs): - raise AssertionError("the native scanner should handle bytes with flatten") + def fail_to_lance(*args, **kwargs): + raise AssertionError("blob v2 bytes should not open a pylance dataset") - monkeypatch.setattr(query, "to_arrow", fail_to_arrow) + monkeypatch.setattr(table, "to_lance", fail_to_lance) assert query.to_pandas(blob_mode="bytes", flatten=True)["blob"].tolist() == [b"one"] flattened_lazy = table.search().where("id = 1").to_pandas(flatten=True) From f6a348ac5bf0b0fa3ffb16c340f45e2563f8b6d8 Mon Sep 17 00:00:00 2001 From: Jay Pokale Date: Wed, 28 Oct 2026 01:03:36 +0530 Subject: [PATCH 136/180] fix(python): keep FTS scores in RRF and MRR rerankers with return_score="all" (#4677) `RRFReranker.rerank_hybrid` and `MRRReranker.rerank_hybrid` merge the vector and FTS results with the base `merge_results`, which keeps only the first copy of a duplicated row. With `return_score="all"`, a row that both searches found therefore comes back with `_score = None`, even though the FTS search scored it. `LinearCombinationReranker` already copies the FTS score onto such rows. Reproduction against `lancedb` 0.40.0: ```python import pyarrow as pa from lancedb.rerankers import RRFReranker vector = pa.table({"_rowid": pa.array([1, 2], pa.uint64()), "text": ["a", "b"], "_distance": pa.array([0.1, 0.2], pa.float32())}) fts = pa.table({"_rowid": pa.array([2, 3], pa.uint64()), "text": ["b", "c"], "_score": pa.array([5.0, 4.0], pa.float32())}) RRFReranker(return_score="all").rerank_hybrid("q", vector, fts).to_pylist() # row 2: _distance=0.2, _score=None (expected _score=5.0) ``` `table.search(query_type="hybrid")` is not affected, because `_combine_hybrid_results` restores the original `_distance` and `_score` by `_rowid` after reranking. The wrong value shows up when `rerank_hybrid` is called directly, for example from a custom reranker that wraps RRF or MRR. The fix uses `_merge_and_keep_scores` when `return_score="all"`, the same pattern the model-based rerankers (`CohereReranker`, `CrossEncoderReranker`, `JinaReranker`, `OpenaiReranker`, `VoyageAIReranker`, ...) already use. The relevance-only path is unchanged. Tests: added `test_rank_fusion_return_score_all_keeps_both_scores` for both rerankers. It fails without the fix and passes with it. I ran it against the released 0.40.0 package with this branch's `rerankers/{base,rrf,mrr}.py` dropped in; `rrf.py` and `mrr.py` on `main` are identical to 0.40.0. The other reranker tests give the same results with and without the change. `ruff format` and `ruff check` are clean. I used an AI assistant (Claude) while working on this; I reviewed and tested the change. Co-authored-by: Xuanwo --- python/python/lancedb/rerankers/mrr.py | 7 +++++- python/python/lancedb/rerankers/rrf.py | 8 +++++-- python/python/tests/test_rerankers.py | 32 ++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/rerankers/mrr.py b/python/python/lancedb/rerankers/mrr.py index 81a03c9ca..38f742bb8 100644 --- a/python/python/lancedb/rerankers/mrr.py +++ b/python/python/lancedb/rerankers/mrr.py @@ -97,7 +97,12 @@ class MRRReranker(Reranker): weighted_mrr = self.weight_vector * vector_rr + self.weight_fts * fts_rr final_mrr_scores[result_id] = weighted_mrr - combined_results = self.merge_results(vector_results, fts_results) + # With return_score="all", a row found by both searches must keep its + # `_distance` and its `_score`. + if self.score == "all": + combined_results = self._merge_and_keep_scores(vector_results, fts_results) + else: + combined_results = self.merge_results(vector_results, fts_results) combined_row_ids = combined_results["_rowid"].to_pylist() relevance_scores = [final_mrr_scores[row_id] for row_id in combined_row_ids] combined_results = combined_results.append_column( diff --git a/python/python/lancedb/rerankers/rrf.py b/python/python/lancedb/rerankers/rrf.py index 9c835a3ea..c9b54a5a7 100644 --- a/python/python/lancedb/rerankers/rrf.py +++ b/python/python/lancedb/rerankers/rrf.py @@ -54,8 +54,12 @@ class RRFReranker(Reranker): for i, result_id in enumerate(ids, 1): rrf_score_map[result_id] += 1 / (i + self.K) - # Sort the results based on RRF score - combined_results = self.merge_results(vector_results, fts_results) + # Sort the results based on RRF score. With return_score="all", a row found + # by both searches must keep its `_distance` and its `_score`. + if self.score == "all": + combined_results = self._merge_and_keep_scores(vector_results, fts_results) + else: + combined_results = self.merge_results(vector_results, fts_results) combined_row_ids = combined_results["_rowid"].to_pylist() relevance_scores = [rrf_score_map[row_id] for row_id in combined_row_ids] combined_results = combined_results.append_column( diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index dd6cb4ab5..78b64613e 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -428,6 +428,38 @@ def test_rrf_multivector_ranks_each_result_list(): assert result["_rowid"].to_pylist() == [2, 1, 3] +@pytest.mark.parametrize("reranker_cls", [RRFReranker, MRRReranker]) +def test_rank_fusion_return_score_all_keeps_both_scores(reranker_cls): + # A row found by both searches must keep its vector `_distance` and its FTS + # `_score` when the reranker is asked to return all scores. + vector_results = pa.table( + { + "_rowid": pa.array([1, 2], type=pa.uint64()), + "text": ["a", "b"], + "_distance": pa.array([0.1, 0.2], type=pa.float32()), + } + ) + fts_results = pa.table( + { + "_rowid": pa.array([2, 3], type=pa.uint64()), + "text": ["b", "c"], + "_score": pa.array([5.0, 4.0], type=pa.float32()), + } + ) + + result = reranker_cls(return_score="all").rerank_hybrid( + "query", vector_results, fts_results + ) + rows = {row["_rowid"]: row for row in result.to_pylist()} + + assert rows[1]["_distance"] == pytest.approx(0.1) + assert rows[1]["_score"] is None + assert rows[2]["_distance"] == pytest.approx(0.2) + assert rows[2]["_score"] == pytest.approx(5.0) + assert rows[3]["_distance"] is None + assert rows[3]["_score"] == pytest.approx(4.0) + + def test_rrf_reranker_distance(): data = pa.table( { From 45dbf5eff5ccdc79bbd5777a51feb06ba06faca5 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 27 Oct 2026 13:37:00 -0700 Subject: [PATCH 137/180] fix: use SQL for all remote materialized view APIs (#4673) Remote materialized-view APIs now use SQL for the full lifecycle. Create and refresh already submit SQL; this change moves describe, paginated listing, and drop onto `DESCRIBE MATERIALIZED VIEW`, `SHOW MATERIALIZED VIEWS`, and `DROP MATERIALIZED VIEW`. Async create, refresh, and drop return the existing Job handle with `job_type = "query"`. The handle has one `id`: the connection-scoped SQL query ID, also accepted by `describe_query`. Submission starts the query, the job drains its result once, and repeated waits reuse the completed result. Synchronous drop waits for catalog removal; physical cleanup proceeds in the background. Listing uses namespace-scoped keyset pagination with opaque resume tokens. Streamed and deferred SQL responses share the same path. Adds transport coverage and updates Python/TypeScript documentation for query-backed drop jobs. --------- Co-authored-by: Xuanwo --- docs/src/js/classes/Connection.md | 9 +- docs/web/basics/jobs.mdx | 10 +- nodejs/__test__/remote.test.ts | 28 +-- nodejs/lancedb/connection.ts | 9 +- python/python/lancedb/db.py | 25 ++- python/python/tests/test_listing.py | 10 +- .../python/tests/test_materialized_views.py | 136 ++++-------- rust/lancedb/src/materialized_view.rs | 17 +- rust/lancedb/src/remote/db.rs | 199 +++--------------- rust/lancedb/src/remote/sql.rs | 1 + .../src/remote/sql/materialized_view.rs | 129 ++++++++++++ rust/lancedb/src/remote/sql_test.rs | 166 ++++++++++++++- rust/lancedb/src/remote/table.rs | 56 ++--- 13 files changed, 420 insertions(+), 375 deletions(-) create mode 100644 rust/lancedb/src/remote/sql/materialized_view.rs diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index ffe7106b7..2496bc2a9 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -436,8 +436,8 @@ abstract dropMaterializedView(name, namespacePath?): Promise Drop the materialized view named `name`. -The view may become unavailable before physical cleanup finishes. Use -[dropMaterializedViewAsync](Connection.md#dropmaterializedviewasync) to retain and wait for the cleanup job. +Remote drops wait for the SQL command to remove the catalog binding. +Physical cleanup continues in the background. Rejects a table that exists but is not a materialized view. @@ -459,8 +459,9 @@ Rejects a table that exists but is not a materialized view. abstract dropMaterializedViewAsync(name, namespacePath?): Promise ``` -Start dropping the materialized view named `name` and return its cleanup -job without waiting for completion. +Start dropping the materialized view named `name` and return its job. +Remote jobs have type `query` and use the SQL query ID as `id`. Waiting +confirms catalog removal; physical cleanup continues in the background. Rejects a table that exists but is not a materialized view. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index a87663a51..26dd4dd8b 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -72,10 +72,12 @@ SQL-backed job handles follow the query lifecycle described below. ### SQL-backed job handles -Remote materialized-view CREATE and REFRESH use the SQL query backend. Python's -`create_materialized_view_async()` and `mv.refresh_async()` still return job -handles with `status()`, `wait()` and `cancel()`. Synchronous creation and refresh -wait on the same SQL execution before returning. +Remote materialized-view CREATE, REFRESH, and DROP use the SQL query backend. +Python's `create_materialized_view_async()`, `mv.refresh_async()`, and +`drop_materialized_view_async()` return job handles with `status()`, `wait()`, +and `cancel()`. Synchronous creation, refresh, and drop wait on the same SQL +execution before returning. A completed DROP means the catalog binding has been +removed; physical cleanup continues in the background. The existing `job.job_type` identifies query-backed handles as `"query"` from submission, and `job.id` contains the connection-scoped SQL query UUID string. diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index d443537b0..80befcc67 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -481,23 +481,6 @@ describe("remote connection", () => { expect(insertRequests).toBe(2); }); - it("lists materialized views through the namespace route", async () => { - await withMockDatabase( - (req, res) => { - expect(req.method).toBe("GET"); - expect(req.url).toBe("/v1/namespace/$/materialized_view/list"); - res - .writeHead(200, { "content-type": "application/json" }) - .end(JSON.stringify({ views: ["daily_sales"] })); - }, - async (db) => { - expect(await collect(db.listMaterializedViews())).toEqual([ - "daily_sales", - ]); - }, - ); - }); - it("creates a view and decodes the schema it resolved to", async () => { await withMockDatabase( (req, res) => { @@ -1725,14 +1708,13 @@ async function collect(items: AsyncIterable): Promise { } describe("lazy resource listings", () => { - for (const kind of ["views", "materializedViews", "jobs"] as const) { + for (const kind of ["views", "jobs"] as const) { const listing = ( db: Connection, options: { pageToken?: string; pageLimit?: number } = {}, ) => { if (kind === "jobs") return db.listJobs(options); - if (kind === "views") return db.listViews(["team"], options); - return db.listMaterializedViews(options); + return db.listViews(["team"], options); }; const page = (names: string[], token?: string) => { const items = @@ -1807,11 +1789,7 @@ describe("lazy resource listings", () => { limit: 2, }); } else { - expect(url.pathname).toBe( - kind === "views" - ? "/v1/namespace/team/view/list" - : "/v1/namespace/$/materialized_view/list", - ); + expect(url.pathname).toBe("/v1/namespace/team/view/list"); expect(url.searchParams.get("page_token")).toBe(token); expect(url.searchParams.get("limit")).toBe("2"); } diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 80fe2c722..62f218e16 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -308,8 +308,8 @@ export abstract class Connection { /** * Drop the materialized view named `name`. * - * The view may become unavailable before physical cleanup finishes. Use - * {@link dropMaterializedViewAsync} to retain and wait for the cleanup job. + * Remote drops wait for the SQL command to remove the catalog binding. + * Physical cleanup continues in the background. * * Rejects a table that exists but is not a materialized view. */ @@ -319,8 +319,9 @@ export abstract class Connection { ): Promise; /** - * Start dropping the materialized view named `name` and return its cleanup - * job without waiting for completion. + * Start dropping the materialized view named `name` and return its job. + * Remote jobs have type `query` and use the SQL query ID as `id`. Waiting + * confirms catalog removal; physical cleanup continues in the background. * * Rejects a table that exists but is not a materialized view. */ diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index f38608188..fe38f17f0 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -721,9 +721,8 @@ class DBConnection(EnforceOverrides): ) -> None: """Drop a materialized view. - The view may become unavailable before physical cleanup finishes. Use - :meth:`drop_materialized_view_async` to retain and wait for the cleanup - job. + Remote drops wait for the SQL command to remove the catalog binding. + Physical cleanup continues in the background. """ raise NotImplementedError( "materialized views are not supported on this connection type" @@ -732,11 +731,11 @@ class DBConnection(EnforceOverrides): def drop_materialized_view_async( self, name: str, namespace_path: Optional[List[str]] = None ) -> Job[None]: - """Start dropping a materialized view and return its cleanup job. + """Start dropping a materialized view and return its job. - The job may already be complete for a local database. On LanceDB Cloud - and Enterprise, its ``id`` is the server job identifier from the - ``202 Accepted`` drop response. + The job may already be complete for a local database. Remote jobs have + type ``query`` and use the SQL query ID as ``id``. Waiting confirms + catalog removal; physical cleanup continues in the background. """ raise NotImplementedError( "materialized views are not supported on this connection type" @@ -2946,9 +2945,8 @@ class AsyncConnection(object): ) -> None: """Drop a materialized view. - The view may become unavailable before physical cleanup finishes. Use - :meth:`drop_materialized_view_async` to retain and wait for the cleanup - job. + Remote drops wait for the SQL command to remove the catalog binding. + Physical cleanup continues in the background. """ if namespace_path is None: namespace_path = [] @@ -2960,10 +2958,11 @@ class AsyncConnection(object): *, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[None]: - """Start dropping a materialized view and return its cleanup job. + """Start dropping a materialized view and return its job. - Await :meth:`AsyncJob.wait` before assuming physical cleanup has - finished. + For remote connections, the job has type ``query`` and its ID identifies + the SQL query. Await :meth:`AsyncJob.wait` for catalog removal; physical + cleanup continues in the background. """ if namespace_path is None: namespace_path = [] diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index b0b973bbf..2d1e6497a 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -66,7 +66,7 @@ def response_page(kind, names, token): ] else: items = names - key = "views" if kind == "materialized_views" else kind + key = kind return {key: items, "page_token": token} @@ -85,7 +85,7 @@ async def advance(items, asynchronous): return await items.__anext__() if asynchronous else next(items) -KINDS = ["secrets", "views", "jobs", "functions", "materialized_views"] +KINDS = ["secrets", "views", "jobs", "functions"] @pytest.mark.asyncio @@ -236,9 +236,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous) ) db = await connection(endpoint, asynchronous) method = getattr(db, "list_" + kind) - kwargs = ( - {} if kind in ("jobs", "materialized_views") else {"namespace_path": ["team"]} - ) + kwargs = {} if kind == "jobs" else {"namespace_path": ["team"]} items = method(page_token="start/token", page_limit=2, **kwargs) assert requests == [] assert items.page_token() == "start/token" @@ -273,7 +271,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous) assert path.path == "/v1/jobs/list" assert body == {"page_token": token, "limit": 2} else: - namespace = "$" if kind == "materialized_views" else "team" + namespace = "team" resource = kind.removesuffix("s") assert path.path == f"/v1/namespace/{namespace}/{resource}/list" expected = {"page_token": [token], "limit": ["2"]} diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 04dbe2fec..0966297f7 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors + import contextlib import http.server import json @@ -30,89 +31,6 @@ def make_db(tmp_path): return db -@contextlib.contextmanager -def mock_remote_materialized_views(): - requests = [] - - class Handler(http.server.BaseHTTPRequestHandler): - def log_message(self, *args): - pass - - def do_GET(self): - requests.append(self.path) - encoded = json.dumps({"views": ["daily_sales"]}).encode() - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(encoded))) - self.end_headers() - self.wfile.write(encoded) - - with http.server.HTTPServer(("localhost", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() - try: - yield f"http://localhost:{server.server_address[1]}", requests - finally: - server.shutdown() - thread.join() - - -@contextlib.contextmanager -def mock_remote_materialized_view_drop(): - requests = [] - - class Handler(http.server.BaseHTTPRequestHandler): - def log_message(self, *args): - pass - - def do_POST(self): - length = int(self.headers.get("Content-Length", 0)) - body = json.loads(self.rfile.read(length) or b"{}") - requests.append((self.path, body)) - assert self.path.endswith("/drop") - job_id = "mv-drop-123" - encoded = json.dumps({"job_id": job_id}).encode() - self.send_response(202) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(encoded))) - self.end_headers() - self.wfile.write(encoded) - - with http.server.HTTPServer(("localhost", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() - try: - yield f"http://localhost:{server.server_address[1]}", requests - finally: - server.shutdown() - thread.join() - - -def test_remote_list_uses_namespace_route(): - with mock_remote_materialized_views() as (host, requests): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - assert list(db.list_materialized_views()) == ["daily_sales"] - assert requests == ["/v1/namespace/$/materialized_view/list"] - - -def test_remote_drop_async_returns_server_job(): - with mock_remote_materialized_view_drop() as (host, requests): - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=host, - client_config={"retry_config": {"retries": 0}}, - ) - job = db.drop_materialized_view_async("adults") - assert job.id == "mv-drop-123" - assert requests == [("/v1/materialized_view/adults/drop", {})] - - @contextlib.contextmanager def mock_remote_materialized_view_refresh(): requests = [] @@ -123,11 +41,8 @@ def mock_remote_materialized_view_refresh(): def do_POST(self): requests.append(self.path) - if self.path == "/v1/materialized_view/view/describe": - response = {"query": "SELECT * FROM source"} - else: - assert self.path == "/v1/table/view/describe/" - response = {"version": 42, "schema": {"fields": []}} + assert self.path == "/v1/table/view/describe/" + response = {"version": 42, "schema": {"fields": []}} encoded = json.dumps(response).encode() self.send_response(200) self.send_header("Content-Type", "application/json") @@ -159,6 +74,16 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full): def do_get(self, context, ticket): self.commands.append(ticket.ticket) + if b"DESCRIBE MATERIALIZED VIEW" in ticket.ticket: + return flight.RecordBatchStream( + pa.table( + { + "name": ["view"], + "query": ["SELECT * FROM source"], + } + ) + ) + assert b"REFRESH MATERIALIZED VIEW" in ticket.ticket # SQL completion carries no refresh statistics. return flight.RecordBatchStream(pa.table({"status": ["ok"]})) @@ -199,9 +124,24 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full): "RefreshMaterializedViewResult(mode=None, rows_written=None, " "source_version=None, version=42)" ) - (command,) = server.commands - assert b'REFRESH MATERIALIZED VIEW "view"' in command - assert (b"WITH (full = true)" in command) is full + describes = [ + command + for command in server.commands + if b"DESCRIBE MATERIALIZED VIEW" in command + ] + refreshes = [ + command + for command in server.commands + if b"REFRESH MATERIALIZED VIEW" in command + ] + assert len(describes) == 2 + assert len(refreshes) == 1 + assert all( + b'DESCRIBE MATERIALIZED VIEW "view"' in command for command in describes + ) + (refresh,) = refreshes + assert b'REFRESH MATERIALIZED VIEW "view"' in refresh + assert (b"WITH (full = true)" in refresh) is full assert not any("count_rows" in path for path in requests) @@ -639,8 +579,6 @@ async def test_async_namespace_connection_materialized_views(tmp_path): def test_stored_queries_and_legacy_layouts_are_read(): - import json - import pyarrow as pa from lancedb.materialized_view import _definition_from_schema @@ -795,13 +733,11 @@ def test_embedded_create_refuses_automatic_refresh_before_creating_view( @pytest.mark.parametrize("seconds", [0, -1, float("nan"), float("inf")]) def test_remote_create_rejects_invalid_interval_without_request(seconds): - with mock_remote_materialized_view_drop() as (host, requests): - db = lancedb.connect("db://dev", api_key="fake", host_override=host) - with pytest.raises(ValueError, match="positive, finite"): - db.create_materialized_view_async( - "adults", "people", auto_refresh_interval_seconds=seconds - ) - assert requests == [] + db = lancedb.connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1") + with pytest.raises(ValueError, match="positive, finite"): + db.create_materialized_view_async( + "mv", "source", auto_refresh_interval_seconds=seconds + ) @pytest.mark.experimental_functions diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 5a7169b7c..266cdab59 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1987,8 +1987,8 @@ impl Connection { /// Drop a materialized view. /// /// The view may become unavailable before its physical data is removed. - /// Use [`Connection::drop_materialized_view_async`] to retain the cleanup - /// job and wait for it explicitly. + /// Remote drops wait for the SQL command to remove the catalog binding; + /// physical cleanup proceeds in the background. pub async fn drop_materialized_view( &self, name: impl AsRef, @@ -1999,8 +1999,9 @@ impl Connection { return self .database() .drop_materialized_view_async(name, namespace_path) - .await - .map(|_| ()); + .await? + .wait() + .await; } let table = self .open_table(name) @@ -2011,12 +2012,12 @@ impl Connection { self.drop_table(name, namespace_path).await } - /// Start dropping a materialized view and return its cleanup job. + /// Start dropping a materialized view and return its job. /// /// This validates that the named resource is a materialized view rather - /// than an ordinary table. Call [`Job::wait`] before assuming physical - /// cleanup has finished. When the backend performs cleanup inline, the - /// returned job is already finished and has no job ID. + /// than an ordinary table. For remote connections the job has type `query` + /// and its ID identifies the SQL query. Waiting completes once the catalog + /// binding is removed; physical cleanup continues in the background. /// /// ```no_run /// # use lancedb::Connection; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 5c299dc5a..394dc4af2 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -47,6 +47,7 @@ use super::client::{ Sender, }; use super::sql::SqlClient; +use super::sql::materialized_view::quote_identifier; use super::table::RemoteTable; use super::util::parse_server_version; use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; @@ -929,36 +930,26 @@ impl Database for RemoteDatabase { name: &str, namespace_path: &[String], ) -> Result { - let identifier = build_table_identifier(name, namespace_path)?; - let request = self - .client - .post(&format!("/v1/materialized_view/{identifier}/drop")); - let (request_id, response) = self.client.send(request).await?; - let response = self.client.check_response(&request_id, response).await?; - let status = response.status(); - let body = response.text().await.err_to_http(request_id.clone())?; - let job = match status { - StatusCode::OK => Job::new_done(), - StatusCode::ACCEPTED => { - let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { - source: "materialized-view drop response did not contain a valid job_id".into(), - request_id, - status_code: Some(status), - })?; - Job::new(Box::new(RemoteJob::new(self.client.clone(), job_id))) - } - _ => { - return Err(Error::Http { - source: "materialized-view drop must return 200 OK or 202 Accepted".into(), - request_id, - status_code: Some(status), - }); - } - }; - self.table_cache - .remove(&build_cache_key(name, namespace_path)) - .await; - Ok(job) + validate_table_name(name)?; + validate_namespace(namespace_path)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })?; + let cache = self.table_cache.clone(); + let key = build_cache_key(name, namespace_path); + client + .submit_as_job( + format!("DROP MATERIALIZED VIEW {}", quote_identifier(name)), + namespace_path.to_vec(), + move || async move { + cache.remove(&key).await; + Ok(()) + }, + ) + .await } async fn list_materialized_views( @@ -966,23 +957,13 @@ impl Database for RemoteDatabase { namespace_path: &[String], options: ListingOptions, ) -> Result> { - let namespace_id = build_namespace_identifier(namespace_path)?; - let path = format!("/v1/namespace/{namespace_id}/materialized_view/list"); - let mut req = self.client.get(&path); - if let Some(token) = options.page_token { - req = req.query(&[("page_token", token)]); - } - if let Some(limit) = options.page_limit { - req = req.query(&[("limit", limit)]); - } - let (request_id, response) = self.client.send(req).await?; - let response = self.client.check_response(&request_id, response).await?; - let response: RemoteListViewsResponse = response.json().await.err_to_http(request_id)?; - let items = response.views; - Ok(ListingPage { - items, - page_token: response.page_token, - }) + self.sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })? + .list_materialized_views(namespace_path, options) + .await } async fn create_function_async( @@ -2065,27 +2046,6 @@ mod tests { } } - #[tokio::test] - async fn test_drop_materialized_view_uses_item_route_and_job() { - let db = super::RemoteDatabase::new_mock(|request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/materialized_view/analytics$adults/drop" - ); - assert!(request.body().is_none()); - http::Response::builder() - .status(202) - .body(serde_json::json!({"job_id": "j1-mv-drop"}).to_string()) - .unwrap() - }); - let job = db - .drop_materialized_view_async("adults", &["analytics".into()]) - .await - .unwrap(); - assert_eq!(job.id(), Some("j1-mv-drop")); - } - #[tokio::test] async fn test_drop_function_async_returns_job() { let db = super::RemoteDatabase::new_mock(|request| { @@ -2137,100 +2097,6 @@ mod tests { } } - #[tokio::test] - async fn test_drop_materialized_view_completed_inline() { - let db = super::RemoteDatabase::new_mock(|request| { - assert_eq!(request.method(), "POST"); - assert_eq!(request.url().path(), "/v1/materialized_view/adults/drop"); - http::Response::builder().status(200).body("{}").unwrap() - }); - let job = db - .drop_materialized_view_async("adults", &[]) - .await - .unwrap(); - assert_eq!(job.id(), None); - assert_eq!(job.status().await.unwrap(), "finished"); - job.wait().await.unwrap(); - } - - #[tokio::test] - async fn test_drop_materialized_view_rejects_incomplete_acceptance() { - for body in ["{}", r#"{"job_id":""}"#, r#"{"job_id":null}"#] { - let db = super::RemoteDatabase::new_mock(move |_| { - http::Response::builder().status(202).body(body).unwrap() - }); - let error = db - .drop_materialized_view_async("adults", &[]) - .await - .err() - .unwrap(); - assert!(error.to_string().contains("valid job_id")); - } - } - - #[tokio::test] - async fn test_drop_materialized_view_rejects_unexpected_success_status() { - let db = super::RemoteDatabase::new_mock(|_| { - http::Response::builder().status(204).body("").unwrap() - }); - let error = db - .drop_materialized_view_async("adults", &[]) - .await - .err() - .unwrap(); - assert!(error.to_string().contains("200 OK or 202 Accepted")); - } - - #[tokio::test] - async fn test_list_materialized_views_follows_empty_pages() { - let page = Arc::new(AtomicUsize::new(0)); - let db = super::RemoteDatabase::new_mock({ - let page = page.clone(); - move |request| { - assert_eq!(request.method(), "GET"); - assert_eq!( - request.url().path(), - "/v1/namespace/analytics/materialized_view/list" - ); - match page.fetch_add(1, Ordering::SeqCst) { - 0 => { - assert!(request.url().query().is_none()); - http::Response::builder() - .status(200) - .body( - serde_json::json!({"views": [], "page_token": "next"}).to_string(), - ) - .unwrap() - } - 1 => { - assert_eq!(request.url().query(), Some("page_token=next")); - http::Response::builder() - .status(200) - .body(serde_json::json!({"views": ["adults"]}).to_string()) - .unwrap() - } - _ => panic!("listing requested too many pages"), - } - } - }); - assert_eq!( - Listing::new(Default::default(), { - let db = Arc::new(db); - move |options| { - let db = db.clone(); - async move { - db.list_materialized_views(&["analytics".into()], options) - .await - } - } - }) - .try_collect::>() - .await - .unwrap(), - ["adults"] - ); - } - #[tokio::test] async fn test_retries() { // We'll record the request_id here, to check it matches the one in the error. @@ -3912,7 +3778,7 @@ mod tests { assert!(items.try_next().await.unwrap().is_none()); assert!(items.try_next().await.unwrap().is_none()); } - for resource in ["secret", "view", "function", "materialized_view", "jobs"] { + for resource in ["secret", "view", "function", "jobs"] { let count = Arc::new(AtomicUsize::new(0)); let conn = Connection::new_with_handler({ let count = count.clone(); @@ -3927,11 +3793,7 @@ mod tests { .unwrap(); assert_eq!(body, serde_json::json!({"page_token": token, "limit": 2})); } else { - let ns = if resource == "materialized_view" { - "$" - } else { - "team" - }; + let ns = "team"; assert_eq!( request.url().path(), format!("/v1/namespace/{ns}/{resource}/list") @@ -3971,7 +3833,6 @@ mod tests { "secret" => check(conn.list_secrets(&namespace, options), count).await, "view" => check(conn.list_views(&namespace, options), count).await, "function" => check(conn.list_functions(&namespace, options), count).await, - "materialized_view" => check(conn.list_materialized_views(options), count).await, _ => check(conn.list_jobs(options), count).await, } } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 846e852f5..207a0cbec 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -35,6 +35,7 @@ use crate::remote::client::{ClientConfig, TlsConfig}; use crate::remote::retry::ResolvedRetryConfig; use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; +pub(super) mod materialized_view; mod stream; use stream::{StreamingQuery, StreamingQueryHandle, Submission}; diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs new file mode 100644 index 000000000..46c0a7bd2 --- /dev/null +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{Array, RecordBatch, StringArray}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use futures::TryStreamExt; + +use super::SqlClient; +use crate::database::ExecuteQueryRequest; +use crate::error::{Error, Result}; +use crate::listing::{ListingOptions, ListingPage}; +use crate::materialized_view::{MaterializedViewDefinition, MaterializedViewInfo}; +use crate::utils::{validate_namespace, validate_table_name}; + +pub(in crate::remote) fn quote_identifier(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn strings(batch: &RecordBatch, name: &str) -> Result> { + let values = batch + .column_by_name(name) + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| Error::Runtime { + message: format!("materialized-view SQL result is missing UTF-8 column '{name}'"), + })?; + if values.null_count() != 0 { + return Err(Error::Runtime { + message: format!("materialized-view SQL result contains null '{name}'"), + }); + } + Ok(values + .iter() + .map(|value| value.unwrap().to_owned()) + .collect()) +} + +impl SqlClient { + pub(in crate::remote) async fn describe_materialized_view( + &self, + name: &str, + namespace: &[String], + ) -> Result { + validate_table_name(name)?; + validate_namespace(namespace)?; + let query = self + .execute(ExecuteQueryRequest { + query: format!("DESCRIBE MATERIALIZED VIEW {}", quote_identifier(name)), + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let mut reader = query.reader().await?; + let mut definitions = Vec::new(); + while let Some(batch) = reader.try_next().await? { + definitions.extend(strings(&batch, "query")?); + } + let [definition_sql] = + <[String; 1]>::try_from(definitions).map_err(|_| Error::Runtime { + message: "DESCRIBE MATERIALIZED VIEW must return exactly one definition".into(), + })?; + let parsed_definition = MaterializedViewDefinition::from_sql(&definition_sql).ok(); + Ok(MaterializedViewInfo { + definition_sql, + parsed_definition, + }) + } + + pub(in crate::remote) async fn list_materialized_views( + &self, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(100); + if limit == 0 || limit > i32::MAX as u32 { + return Err(Error::InvalidInput { + message: "page limit must be between 1 and i32::MAX".into(), + }); + } + let invalid_token = || Error::InvalidInput { + message: "invalid materialized-view page token for this database or namespace".into(), + }; + let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { + let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; + let (database, prefix, path, last): (String, Option, Vec, String) = + serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; + if database != self.inner.database + || prefix != self.inner.database_prefix + || path != namespace + { + return Err(invalid_token()); + } + format!(" WHERE name > '{}'", last.replace('\'', "''")) + } else { + String::new() + }; + let query = self + .execute(ExecuteQueryRequest { + query: format!( + "SHOW MATERIALIZED VIEWS{after} LIMIT {}", + u64::from(limit) + 1 + ), + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let mut reader = query.reader().await?; + let mut items = Vec::new(); + while let Some(batch) = reader.try_next().await? { + items.extend(strings(&batch, "name")?); + } + let page_token = if items.len() > limit as usize { + items.truncate(limit as usize); + let cursor = serde_json::to_vec(&( + &self.inner.database, + &self.inner.database_prefix, + namespace, + items.last().unwrap(), + )) + .map_err(|error| Error::Runtime { + message: error.to_string(), + })?; + Some(URL_SAFE_NO_PAD.encode(cursor)) + } else { + None + }; + Ok(ListingPage { items, page_token }) + } +} diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 260471612..6a0421fa6 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1028,7 +1028,21 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { let (socket, _) = listener.accept().await?; Ok::<_, std::io::Error>(Some((socket, listener))) }); - let service = TestSqlService::default(); + let result = RecordBatch::try_from_iter(vec![ + ( + "name", + Arc::new(StringArray::from(vec!["view"])) as ArrayRef, + ), + ( + "query", + Arc::new(StringArray::from(vec!["SELECT * FROM source"])) as ArrayRef, + ), + ]) + .unwrap(); + let service = TestSqlService { + result, + ..Default::default() + }; let statements = service.statements.clone(); let headers = service.headers.clone(); let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); @@ -1057,7 +1071,6 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { .unwrap_or_default(); captured.lock().unwrap().push(body["version"].clone()); let text = match request.url().path() { - "/v1/materialized_view/ns$view/describe" => r#"{"query": "SELECT * FROM source"}"#, "/v1/table/ns$view/describe/" => r#"{"version": 42, "schema": {"fields": []}}"#, other => panic!("unexpected REST request: {other}"), }; @@ -1111,6 +1124,7 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { assert_eq!( *statements.lock().unwrap(), [ + "DESCRIBE MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", ] @@ -1994,3 +2008,151 @@ async fn malformed_adaptive_decision_never_resubmits_the_statement() { assert_eq!(polls.load(Ordering::SeqCst), 0); } } + +#[tokio::test] +async fn remote_drop_materialized_view_uses_a_query_job() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client.clone()); + let job = db + .drop_materialized_view_async("daily_sales", &["team".into(), "reports".into()]) + .await + .unwrap(); + assert_eq!(job.job_type().as_deref(), Some("query")); + let id = Uuid::parse_str(job.id().unwrap()).unwrap(); + job.wait().await.unwrap(); + job.wait().await.unwrap(); + assert_eq!( + client.describe(id).await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!( + *statements.lock().unwrap(), + ["DROP MATERIALIZED VIEW \"daily_sales\""] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { + for defer in [false, true] { + let result = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringArray::from(vec!["a", "b'c", "z"])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + let first = db + .list_materialized_views( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!(first.items, ["a", "b'c"]); + let token = first.page_token.unwrap(); + db.list_materialized_views( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(&token), + ) + .await + .unwrap(); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW MATERIALIZED VIEWS LIMIT 3", + "SHOW MATERIALIZED VIEWS WHERE name > 'b''c' LIMIT 3" + ] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team$reports") + ); + for (path, token) in [(vec![], token), (namespace, "invalid".into())] { + assert!(matches!( + db.list_materialized_views( + &path, + crate::listing::ListingOptions::default().page_token(token) + ) + .await, + Err(Error::InvalidInput { .. }) + )); + } + assert_eq!(statements.lock().unwrap().len(), 2); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_describe_materialized_view_preserves_the_sql_definition() { + for defer in [false, true] { + let definition = "SELECT s.x, d.label FROM source s JOIN dim d ON s.id = d.id"; + let result = RecordBatch::try_from_iter(vec![( + "query", + Arc::new(StringArray::from(vec![definition])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }), + "daily_sales".into(), + vec!["analytics".into()], + "analytics$daily_sales".into(), + Default::default(), + Some(client), + ); + let info = table.materialized_view_info().await.unwrap(); + assert_eq!(info.definition_sql, definition); + assert!(info.parsed_definition.is_none()); + assert_eq!( + *statements.lock().unwrap(), + ["DESCRIBE MATERIALIZED VIEW \"daily_sales\""] + ); + shutdown.send(()).unwrap(); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 214e06d4e..7be8db77c 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -18,9 +18,7 @@ use crate::index::IndexStatistics; use crate::index::scalar::FtsQuery; use crate::index::waiter::{MAX_WAIT, wait_for_index}; use crate::job::Job; -use crate::materialized_view::{ - MaterializedViewDefinition, MaterializedViewInfo, RefreshMaterializedViewResult, -}; +use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult}; use crate::query::wal_fusion::PkFusionMemory; // WAL-PK-FUSION: delete. use crate::query::{QueryFilter, QueryRequest, Select, VectorQueryRequest}; use crate::remote::job::RemoteJob; @@ -2201,24 +2199,13 @@ impl BaseTable for RemoteTable { &self.identifier } async fn materialized_view_info(&self) -> Result { - #[derive(Deserialize)] - struct DescribeMaterializedViewResponse { - query: String, - } - - let request = self.client.post(&format!( - "/v1/materialized_view/{}/describe", - self.identifier - )); - let (request_id, response) = self.send(request, true).await?; - let response = self.check_table_response(&request_id, response).await?; - let response: DescribeMaterializedViewResponse = - response.json().await.err_to_http(request_id)?; - let parsed_definition = MaterializedViewDefinition::from_sql(&response.query).ok(); - Ok(MaterializedViewInfo { - definition_sql: response.query, - parsed_definition, - }) + self.sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote table client".into(), + })? + .describe_materialized_view(&self.name, &self.namespace) + .await } async fn refresh_materialized_view_async( @@ -14610,26 +14597,15 @@ mod tests { } #[tokio::test] - async fn test_materialized_view_describe_and_refresh_requires_sql() { - const QUERY: &str = - "SELECT s.x, d.label FROM analytics.source s JOIN analytics.dim d ON s.id = d.id"; - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/materialized_view/my_table/describe" => http::Response::builder() - .status(200) - .body( - json!({ - "name": "my_table", - "query": QUERY - }) - .to_string(), - ) - .unwrap(), - path => panic!("unexpected request: {path}"), + async fn test_materialized_view_requires_sql() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()) }); - let view = crate::MaterializedView::from_table(table).await.unwrap(); - assert_eq!(view.definition_sql(), QUERY); - assert!(view.definition().is_err()); - let error = view.refresh().execute().await.unwrap_err(); + let error = table + .base_table() + .materialized_view_info() + .await + .unwrap_err(); assert!(error.to_string().contains("SQL is unavailable")); } From bb6aa1a147778fc1cf815f36430735cf17213aef Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Tue, 27 Oct 2026 21:51:10 -0700 Subject: [PATCH 138/180] feat: add a cascade option to drop_database (#4697) The remote catalog could only drop an empty database: it always asked the server for a restricted drop. `DropDatabaseRequest::cascade`, `drop_database(..., cascade=True)` in Python and `dropDatabase(name, { cascade: true })` in TypeScript ask the server to drop everything in the database first. The name stays taken until the server finishes cleaning up the dropped objects' storage. A restricted drop remains the default. --- docs/src/js/classes/Catalog.md | 6 +++++- nodejs/__test__/catalog.test.ts | 7 +++++-- nodejs/lancedb/catalog.ts | 10 +++++++--- nodejs/src/catalog.rs | 11 ++++++++-- python/python/lancedb/_lancedb.pyi | 2 +- python/python/lancedb/catalog.py | 26 ++++++++++++++++++------ python/python/tests/test_catalog.py | 4 ++-- python/src/catalog.rs | 9 +++++++-- rust/lancedb/src/catalog.rs | 16 ++++++++++++--- rust/lancedb/src/remote/catalog.rs | 31 +++++++++++++++++++++++++++-- 10 files changed, 98 insertions(+), 24 deletions(-) diff --git a/docs/src/js/classes/Catalog.md b/docs/src/js/classes/Catalog.md index 8351380e2..31d3aabc6 100644 --- a/docs/src/js/classes/Catalog.md +++ b/docs/src/js/classes/Catalog.md @@ -70,7 +70,9 @@ Create a database, or open an existing database when existOk is true. dropDatabase(name, options): Promise ``` -Drop an empty database. The server rejects nonempty databases. +Drop a database. A nonempty database is an error unless `cascade` is set, +which drops everything in it first; the name stays taken until the server +finishes cleaning up their storage. #### Parameters @@ -78,6 +80,8 @@ Drop an empty database. The server rejects nonempty databases. * **options** = `{}` +* **options.cascade?**: `boolean` + * **options.ignoreMissing?**: `boolean` #### Returns diff --git a/nodejs/__test__/catalog.test.ts b/nodejs/__test__/catalog.test.ts index f8b14ca6f..3d647695c 100644 --- a/nodejs/__test__/catalog.test.ts +++ b/nodejs/__test__/catalog.test.ts @@ -86,7 +86,10 @@ describe("remote catalog", () => { value: "team/search", }); expect(names.pageToken()).toBe("next"); - await catalog.dropDatabase("team/search", { ignoreMissing: true }); + await catalog.dropDatabase("team/search", { + ignoreMissing: true, + cascade: true, + }); expect(requests[0].url).toBe("/v1/namespace/team%2Fsearch/create"); expect(requests[0].body).toEqual({ mode: "ExistOk" }); expect(requests[5].url).toBe( @@ -94,7 +97,7 @@ describe("remote catalog", () => { ); expect(requests[6].body).toEqual({ mode: "Skip", - behavior: "Restrict", + behavior: "Cascade", }); for (const [i, request] of requests.entries()) { expect(request.headers["x-lancedb-database"]).toBe( diff --git a/nodejs/lancedb/catalog.ts b/nodejs/lancedb/catalog.ts index e344d8187..c91e5a70f 100644 --- a/nodejs/lancedb/catalog.ts +++ b/nodejs/lancedb/catalog.ts @@ -82,12 +82,16 @@ export class Catalog { return new LocalConnection(await this.inner.connectDatabase(name)); } - /** Drop an empty database. The server rejects nonempty databases. */ + /** + * Drop a database. A nonempty database is an error unless `cascade` is set, + * which drops everything in it first; the name stays taken until the server + * finishes cleaning up their storage. + */ async dropDatabase( name: string, - options: { ignoreMissing?: boolean } = {}, + options: { ignoreMissing?: boolean; cascade?: boolean } = {}, ): Promise { - await this.inner.dropDatabase(name, options.ignoreMissing); + await this.inner.dropDatabase(name, options.ignoreMissing, options.cascade); } /** diff --git a/nodejs/src/catalog.rs b/nodejs/src/catalog.rs index 82edda5da..d55bb3508 100644 --- a/nodejs/src/catalog.rs +++ b/nodejs/src/catalog.rs @@ -124,10 +124,17 @@ impl Catalog { .default_error() } #[napi] - pub async fn drop_database(&self, name: String, ignore_missing: Option) -> Result<()> { + pub async fn drop_database( + &self, + name: String, + ignore_missing: Option, + cascade: Option, + ) -> Result<()> { self.inner .drop_database( - DropDatabaseRequest::new(name).ignore_missing(ignore_missing.unwrap_or(false)), + DropDatabaseRequest::new(name) + .ignore_missing(ignore_missing.unwrap_or(false)) + .cascade(cascade.unwrap_or(false)), ) .await .default_error() diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index d5fcac30f..66fdd3a7c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -990,7 +990,7 @@ class Catalog: ) -> Connection: ... async def connect_database(self, name: str) -> Connection: ... async def drop_database( - self, name: str, *, ignore_missing: bool = False + self, name: str, *, ignore_missing: bool = False, cascade: bool = False ) -> None: ... def list_databases( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py index 666d414a4..9a0dc3412 100644 --- a/python/python/lancedb/catalog.py +++ b/python/python/lancedb/catalog.py @@ -130,9 +130,15 @@ class AsyncCatalog: self._inner.list_databases(page_token=page_token, page_limit=page_limit) ) - async def drop_database(self, name: str, *, ignore_missing: bool = False) -> None: - """Drop an empty database. A nonempty database is an error.""" - await self._inner.drop_database(name, ignore_missing=ignore_missing) + async def drop_database( + self, name: str, *, ignore_missing: bool = False, cascade: bool = False + ) -> None: + """Drop a database. A nonempty database is an error unless ``cascade`` is set, + which drops everything in it first; the name stays taken until the server + finishes cleaning up their storage.""" + await self._inner.drop_database( + name, ignore_missing=ignore_missing, cascade=cascade + ) class Catalog: @@ -207,9 +213,17 @@ class Catalog: self._inner.list_databases(page_token=page_token, page_limit=page_limit) ) - def drop_database(self, name: str, *, ignore_missing: bool = False) -> None: - """Drop an empty database. A nonempty database is an error.""" - LOOP.run(self._inner.drop_database(name, ignore_missing=ignore_missing)) + def drop_database( + self, name: str, *, ignore_missing: bool = False, cascade: bool = False + ) -> None: + """Drop a database. A nonempty database is an error unless ``cascade`` is set, + which drops everything in it first; the name stays taken until the server + finishes cleaning up their storage.""" + LOOP.run( + self._inner.drop_database( + name, ignore_missing=ignore_missing, cascade=cascade + ) + ) async def connect_catalog_async( diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py index b2036b7a6..b259778dd 100644 --- a/python/python/tests/test_catalog.py +++ b/python/python/tests/test_catalog.py @@ -86,12 +86,12 @@ def test_catalog_sync_scope_and_serialization(catalog_server): connection.execute_query_async("SELECT 1") assert restored.table_names() == [] assert list(catalog.list_databases()) == ["team/search"] - catalog.drop_database("team/search", ignore_missing=True) + catalog.drop_database("team/search", ignore_missing=True, cascade=True) assert requests[0][0] == "/v1/namespace/team%2Fsearch/create" assert requests[0][2] == {"mode": "ExistOk"} assert requests[1][0] == "/v1/namespace/team%2Fsearch/describe" assert requests[4][0] == "/v1/namespace/$/list" - assert requests[5][2] == {"mode": "Skip", "behavior": "Restrict"} + assert requests[5][2] == {"mode": "Skip", "behavior": "Cascade"} for i, (_, headers, _) in enumerate(requests): headers = {key.lower(): value for key, value in headers.items()} assert headers.get("x-lancedb-database") == ( diff --git a/python/src/catalog.rs b/python/src/catalog.rs index 9e375b314..fb2e7e8a0 100644 --- a/python/src/catalog.rs +++ b/python/src/catalog.rs @@ -60,16 +60,21 @@ impl Catalog { }) } - #[pyo3(signature = (name, *, ignore_missing=false))] + #[pyo3(signature = (name, *, ignore_missing=false, cascade=false))] fn drop_database<'py>( self_: PyRef<'py, Self>, name: String, ignore_missing: bool, + cascade: bool, ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { inner - .drop_database(DropDatabaseRequest::new(name).ignore_missing(ignore_missing)) + .drop_database( + DropDatabaseRequest::new(name) + .ignore_missing(ignore_missing) + .cascade(cascade), + ) .await .infer_error() }) diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index ad8674b77..18373ed5a 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -59,7 +59,7 @@ impl> From for CreateDatabaseRequest { } } -/// Options for restricted database deletion. Tables must be removed first. +/// Options for database deletion. The database must be empty unless `cascade` is set. #[derive(Clone, Debug)] #[non_exhaustive] pub struct DropDatabaseRequest { @@ -67,6 +67,8 @@ pub struct DropDatabaseRequest { pub name: String, /// Succeed if the database is absent. pub ignore_missing: bool, + /// Drop everything in the database first. + pub cascade: bool, } impl DropDatabaseRequest { @@ -75,6 +77,7 @@ impl DropDatabaseRequest { Self { name: name.into(), ignore_missing: false, + cascade: false, } } @@ -83,6 +86,13 @@ impl DropDatabaseRequest { self.ignore_missing = value; self } + + /// Drop every table, view, function, secret and namespace in the database first. The + /// server cleans up their storage in the background, and the name stays taken until then. + pub fn cascade(mut self, value: bool) -> Self { + self.cascade = value; + self + } } impl> From for DropDatabaseRequest { @@ -204,7 +214,7 @@ pub trait Catalog: Send + Sync + std::fmt::Debug + 'static { fn uri(&self) -> &str; /// Create a database, or open it when `exist_ok` permits. async fn create_database(&self, request: CreateDatabaseRequest) -> Result>; - /// Drop an empty database. This must not cascade to tables. + /// Drop a database, which must be empty unless the request cascades. async fn drop_database(&self, request: DropDatabaseRequest) -> Result<()>; /// List a page of database names. async fn list_databases(&self, request: ListDatabasesRequest) -> Result; @@ -267,7 +277,7 @@ impl CatalogConnection { )) } - /// Drop an empty database; pass a name or [`DropDatabaseRequest`] for additional options. + /// Drop a database; pass a name or [`DropDatabaseRequest`] for options such as `cascade`. pub async fn drop_database(&self, request: impl Into) -> Result<()> { self.catalog.drop_database(request.into()).await } diff --git a/rust/lancedb/src/remote/catalog.rs b/rust/lancedb/src/remote/catalog.rs index df3782368..95facd04b 100644 --- a/rust/lancedb/src/remote/catalog.rs +++ b/rust/lancedb/src/remote/catalog.rs @@ -226,7 +226,14 @@ impl Catalog for RemoteCatalog { } .into(), ), - behavior: Some("Restrict".into()), + behavior: Some( + if request.cascade { + "Cascade" + } else { + "Restrict" + } + .into(), + ), ..Default::default() }) .await; @@ -474,7 +481,7 @@ mod tests { } #[tokio::test] - async fn catalog_preserves_errors_and_never_cascades() { + async fn catalog_preserves_errors_and_restricts_drops_by_default() { let (endpoint, task) = server(vec![ (404, json!({"error": "missing"})), (409, json!({"error": "exists"})), @@ -522,6 +529,26 @@ mod tests { ); } + #[tokio::test] + async fn drop_database_cascades_only_when_asked() { + let (endpoint, task) = server(vec![(200, json!({})), (200, json!({}))]).await; + let catalog = RemoteCatalog::try_new(endpoint, RemoteCatalogOptions::default()).unwrap(); + catalog.drop_database("db".into()).await.unwrap(); + catalog + .drop_database(DropDatabaseRequest::new("db").cascade(true)) + .await + .unwrap(); + let requests = task.await.unwrap(); + assert_eq!( + requests[0].body, + json!({"mode": "Fail", "behavior": "Restrict"}) + ); + assert_eq!( + requests[1].body, + json!({"mode": "Fail", "behavior": "Cascade"}) + ); + } + #[tokio::test] async fn database_names_follow_pages_lazily() { use futures::TryStreamExt; From 45f987a29b6c12feb2b5fc613a6593e5f636a7ce Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 28 Oct 2026 05:01:10 +0000 Subject: [PATCH 139/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.15=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index ebadc517a..59a609130 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.15" +current_version = "0.41.0-beta.16" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 6197bf30d..46412bc3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5729,7 +5729,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.15" +version = "0.41.0-beta.16" dependencies = [ "ahash", "anyhow", @@ -5840,7 +5840,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.15" +version = "0.41.0-beta.16" dependencies = [ "arrow-array", "arrow-buffer", @@ -5865,7 +5865,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.15" +version = "0.41.0-beta.16" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 55f6009c3..792af15b1 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.15 + 0.41.0-beta.16 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index c3a769c85..ff7c875b4 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.15 + 0.41.0-beta.16 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 2340c084c..9e3191813 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.15 + 0.41.0-beta.16 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index f41ed6cf3..9e775431d 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.15" +version = "0.41.0-beta.16" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 59602e4f4..a6629d05b 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 5063b8cee..7a5adb2da 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 98b088c0f..8ce3a976c 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index a24a6cc0d..50b091c6a 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index e1d6a690a..19ec044d1 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 88b68ff34..5265ae63f 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index dfc492e82..99f3ef75e 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 9b10144c7..f87115ae1 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.15", + "version": "0.41.0-beta.16", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index f84ab80a3..f02ba4279 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.15" +version = "0.41.0-beta.16" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 9da1023da..d688aeaae 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.15" +version = "0.41.0-beta.16" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 149cf1052ac561b5b879bd5417cb2b1a8f9d2f02 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 28 Oct 2026 08:16:42 -0700 Subject: [PATCH 140/180] fix(ci): bundle Vale rules to avoid private release downloads (#4707) The prose check fails because it downloads its Vale rules from the now-private docs repository. Keep the five unchanged rules from `vale-lancedb-v0.1.0` in this repository and disable `vale sync` in CI. This also works for contributors without access to the docs repository. The update instructions record the release and archive checksum. --- .github/vale/README.md | 17 ++++++++ .github/vale/styles/LanceDB/Dashes.yml | 40 +++++++++++++++++++ .github/vale/styles/LanceDB/PlainLanguage.yml | 32 +++++++++++++++ .github/vale/styles/LanceDB/ProductNames.yml | 34 ++++++++++++++++ .github/vale/styles/LanceDB/VagueHeadings.yml | 19 +++++++++ .github/vale/styles/LanceDB/VaguePhrases.yml | 31 ++++++++++++++ .github/workflows/docs-style.yml | 8 ++-- .vale.ini | 11 ++--- CONTRIBUTING.md | 9 ++--- 9 files changed, 187 insertions(+), 14 deletions(-) create mode 100644 .github/vale/README.md create mode 100644 .github/vale/styles/LanceDB/Dashes.yml create mode 100644 .github/vale/styles/LanceDB/PlainLanguage.yml create mode 100644 .github/vale/styles/LanceDB/ProductNames.yml create mode 100644 .github/vale/styles/LanceDB/VagueHeadings.yml create mode 100644 .github/vale/styles/LanceDB/VaguePhrases.yml diff --git a/.github/vale/README.md b/.github/vale/README.md new file mode 100644 index 000000000..ad0573fdb --- /dev/null +++ b/.github/vale/README.md @@ -0,0 +1,17 @@ +# LanceDB prose rules + +These five rule files are copied unchanged from the `LanceDB.zip` asset of +`lancedb/docs` release `vale-lancedb-v0.1.0`. The archive SHA-256 is +`0730a43e919774121068811d5687c61dfc7a0421cff78e1393f5e565b622cb0f`. + +Keeping the rules here lets contributors and CI run Vale without access to the +source repository. The root `.vale.ini` preserves the release's MDX settings +and built-in repeated-word check. No `vale sync` is needed. + +The rules check product names, dashes, plain language, vague headings and vague +phrases. Findings are suggestions and do not fail the CI check. + +To update, a maintainer downloads the next published package, verifies its +checksum and replaces `styles/LanceDB` with the release's files. Check the +package's `.vale.ini` for configuration changes, and update the version and +checksum here in the same PR. diff --git a/.github/vale/styles/LanceDB/Dashes.yml b/.github/vale/styles/LanceDB/Dashes.yml new file mode 100644 index 000000000..7bb10c96f --- /dev/null +++ b/.github/vale/styles/LanceDB/Dashes.yml @@ -0,0 +1,40 @@ +extends: existence +message: "Avoid '%s' in prose. Use a comma, a colon, parentheses or two sentences." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#punctuation +level: warning +nonword: true +# An em dash in prose, and a double hyphen or en dash used as one, with a +# space on each side. A table cell holding only an em dash, meaning "none", +# ranges such as 1–3 and flags such as --force are left alone, and code is +# never prose. +raw: + - '(?.mdx`. -StylesPath = .vale/styles -Packages = https://github.com/lancedb/docs/releases/download/vale-lancedb-v0.1.0/LanceDB.zip +StylesPath = .github/vale/styles +MinAlertLevel = suggestion + +[*.mdx] +BasedOnStyles = LanceDB +Vale.Repetition = warning diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fa854317d..4a73f8b35 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,13 +88,12 @@ npm i -g mint # https://mintlify.com/docs/installation cd docs/web && mint dev ``` -Wording, names and punctuation follow the -[LanceDB style guide](https://github.com/lancedb/docs/blob/main/STYLE.md). -[Vale](https://vale.sh) checks part of it, and pull requests show its -suggestions on the lines they change. To check a page yourself: +[Vale](https://vale.sh) checks wording, names and punctuation using the +[bundled LanceDB rules](.github/vale/README.md). Pull requests show suggestions +on the lines they change. With Vale 3.24.0 installed, check a page with: ```bash -vale sync && vale docs/web/indexing/vector-index.mdx +vale docs/web/indexing/vector-index.mdx ``` This repository holds a page at every path the site publishes, so the whole From 4359688f3261b011a86ee887c471d75a6b95f476 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 28 Oct 2026 08:26:40 -0700 Subject: [PATCH 141/180] ci: let the Vale action install its pinned CLI (#4708) Let the pinned Vale action install Vale 3.24.0 instead of maintaining a separate download and extraction step --- .github/workflows/docs-style.yml | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/.github/workflows/docs-style.yml b/.github/workflows/docs-style.yml index 6be8b0f8f..51847f22c 100644 --- a/.github/workflows/docs-style.yml +++ b/.github/workflows/docs-style.yml @@ -13,10 +13,6 @@ permissions: contents: read pull-requests: read -env: - VALE_VERSION: 3.24.0 - VALE_SHA256: 867534ddb678abca7f214bc4706ead0922bd5252ffe8035fc227013f66c8b214 - jobs: prose: name: Lint changed prose @@ -26,19 +22,10 @@ jobs: with: persist-credentials: false - - name: Install Vale - run: | - archive="vale_${VALE_VERSION}_Linux_64-bit.tar.gz" - curl --fail --location --silent --show-error --output "$RUNNER_TEMP/$archive" \ - "https://github.com/vale-cli/vale/releases/download/v${VALE_VERSION}/$archive" - echo "${VALE_SHA256} $RUNNER_TEMP/$archive" | sha256sum --check - tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" vale - echo "$RUNNER_TEMP" >> "$GITHUB_PATH" - - name: Annotate changed lines uses: vale-cli/vale-action@518a9136acc6e6668ce7c00d367051e0941e87ff # v3.0.0 with: - version: none + version: '3.24.0' sync: false files: docs/web reporter: github-pr-annotations From 659ea11ac41a31afc3e8e0e5280fde5c4be4ad4f Mon Sep 17 00:00:00 2001 From: alexcastgonz <82875882+pcbeingused333@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:16:28 -0400 Subject: [PATCH 142/180] fix(embeddings): default Cohere to embed-multilingual-v3.0, the v2.0 models are retired (#4698) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cohere retired `embed-english-v2.0`, `embed-english-light-v2.0` and `embed-multilingual-v2.0` on April 4, 2026 ([deprecations](https://docs.cohere.com/docs/deprecations), which lists `embed-english-v3.0`, `embed-multilingual-v3.0` and `embed-v4.0` as the embedding alternatives). `CohereEmbeddingFunction` still defaulted to `embed-multilingual-v2.0`, so every call without an explicit `name` fails. The default is now `embed-multilingual-v3.0`, the multilingual v3 model, and the retired models are removed from the docstring and the Cohere integration page (the page also listed `embed-english-v2.0` as the default, which did not match the code). The docs example, its generated snippet, the docs test and the slow Cohere test use the new name. This changes the default vector size: `ndims()` returns 1024 for `embed-multilingual-v3.0`, where the old default gave 768. Tables created from a schema that uses `cohere.ndims()` get 1024-dimension vectors from now on. A table that already holds 768-dimension vectors from the retired model needs a re-embed with a current model, since the old model can no longer be called. The `ndims()` entries for the v2 names are left as they are. Test: `test_cohere_default_model_is_not_a_retired_v2_model` in `python/python/tests/test_embeddings.py` checks the default name and that `ndims()` is 1024. The repository's pytest session could not be run for this change (its `conftest.py` needs a newer native module than the released wheel); the body of that test was run against the released `lancedb` 0.40.0 with this version of `cohere.py` in place, where it passes, and it returns `embed-multilingual-v2.0` / 768 without the change. ruff check and format are clean on the touched Python files. No Cohere request was made. This change was made with Claude Code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: Xuanwo --- docs/web-tests/py/test_integrations.py | 2 +- docs/web/embedding/index.mdx | 2 +- docs/web/integrations/embedding/cohere.mdx | 14 +++++++++----- docs/web/snippets/integrations.mdx | 2 +- python/python/lancedb/embeddings/cohere.py | 16 ++++++++++------ python/python/tests/test_embeddings.py | 10 ++++++++++ python/python/tests/test_embeddings_slow.py | 2 +- 7 files changed, 33 insertions(+), 15 deletions(-) diff --git a/docs/web-tests/py/test_integrations.py b/docs/web-tests/py/test_integrations.py index 577847504..84c4560ae 100644 --- a/docs/web-tests/py/test_integrations.py +++ b/docs/web-tests/py/test_integrations.py @@ -93,7 +93,7 @@ def test_embedding_cohere_usage() -> None: cohere = ( EmbeddingFunctionRegistry.get_instance() .get("cohere") - .create(name="embed-multilingual-v2.0") + .create(name="embed-multilingual-v3.0") ) class TextModel(LanceModel): diff --git a/docs/web/embedding/index.mdx b/docs/web/embedding/index.mdx index 4402feddf..4039ed840 100644 --- a/docs/web/embedding/index.mdx +++ b/docs/web/embedding/index.mdx @@ -181,7 +181,7 @@ LanceDB supports most popular embedding providers. | OpenAI | `openai` | `text-embedding-ada-002` | | Sentence Transformers | `sentence-transformers` | `all-MiniLM-L6-v2` | | Hugging Face | `huggingface` | `colbert-ir/colbertv2.0` | -| Cohere | `cohere` | `embed-english-v3.0` | +| Cohere | `cohere` | `embed-multilingual-v3.0` | | ... | ... | ... | ### Multimodal embedding {#multimodal-embedding} diff --git a/docs/web/integrations/embedding/cohere.mdx b/docs/web/integrations/embedding/cohere.mdx index b9a8e3378..3c56fec76 100644 --- a/docs/web/integrations/embedding/cohere.mdx +++ b/docs/web/integrations/embedding/cohere.mdx @@ -18,16 +18,20 @@ Supported models are: - embed-multilingual-v3.0 - embed-english-light-v3.0 - embed-multilingual-light-v3.0 -- embed-english-v2.0 -- embed-english-light-v2.0 -- embed-multilingual-v2.0 + +The v2.0 models (`embed-english-v2.0`, `embed-english-light-v2.0` and `embed-multilingual-v2.0`) were retired by Cohere on April 4, 2026. + +The previous default, `embed-multilingual-v2.0`, produced 768-dimensional vectors. +The new default, `embed-multilingual-v3.0`, produces 1024-dimensional vectors. +Existing tables containing vectors from a v2.0 model must be re-embedded with an +active model into a table whose vector column has the matching dimension. Supported parameters (to be passed in `create` method) are: | Parameter | Type | Default Value | Description | |---|---|--------|---------| -| `name` | `str` | `"embed-english-v2.0"` | The model ID of the cohere model to use. Supported base models for Text Embeddings: embed-english-v3.0, embed-multilingual-v3.0, embed-english-light-v3.0, embed-multilingual-light-v3.0, embed-english-v2.0, embed-english-light-v2.0, embed-multilingual-v2.0 | +| `name` | `str` | `"embed-multilingual-v3.0"` | The model ID of the cohere model to use. Supported base models for Text Embeddings: embed-english-v3.0, embed-multilingual-v3.0, embed-english-light-v3.0, embed-multilingual-light-v3.0 | | `source_input_type` | `str` | `"search_document"` | The type of input data to be used for the source column. | | `query_input_type` | `str` | `"search_query"` | The type of input data to be used for the query. | @@ -52,4 +56,4 @@ Usage Example: {PyEmbeddingCohereUsage} - \ No newline at end of file + diff --git a/docs/web/snippets/integrations.mdx b/docs/web/snippets/integrations.mdx index 67bb654cf..dca2d0c1f 100644 --- a/docs/web/snippets/integrations.mdx +++ b/docs/web/snippets/integrations.mdx @@ -2,7 +2,7 @@ export const PyEmbeddingAwsUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\n\nmodel = get_registry().get(\"bedrock-text\").create()\n\nclass TextModel(LanceModel):\n text: str = model.SourceField()\n vector: Vector(model.ndims()) = model.VectorField()\n\ndf = pd.DataFrame({\"text\": [\"hello world\", \"goodbye world\"]})\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"bedrock-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\n\ntbl.add(df)\nrs = tbl.search(\"hello\").limit(1).to_pandas()\nprint(rs.head())\n"; -export const PyEmbeddingCohereUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\ncohere = (\n EmbeddingFunctionRegistry.get_instance()\n .get(\"cohere\")\n .create(name=\"embed-multilingual-v2.0\")\n)\n\nclass TextModel(LanceModel):\n text: str = cohere.SourceField()\n vector: Vector(cohere.ndims()) = cohere.VectorField()\n\ndata = [{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}]\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"cohere-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\ntbl.add(data)\n"; +export const PyEmbeddingCohereUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\ncohere = (\n EmbeddingFunctionRegistry.get_instance()\n .get(\"cohere\")\n .create(name=\"embed-multilingual-v3.0\")\n)\n\nclass TextModel(LanceModel):\n text: str = cohere.SourceField()\n vector: Vector(cohere.ndims()) = cohere.VectorField()\n\ndata = [{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}]\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"cohere-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\ntbl.add(data)\n"; export const PyEmbeddingColpaliSetup = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\nimport requests\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, MultiVector\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"colpali-demo\"))\nfunc = get_registry().get(\"colpali\").create()\n\nclass Images(LanceModel):\n label: str\n image_uri: str = func.SourceField()\n image_bytes: bytes = func.SourceField()\n vector: MultiVector(func.ndims()) = func.VectorField()\n vec_from_bytes: MultiVector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"images\", schema=Images)\nlabels = [\"cat\", \"dog\", \"horse\"]\nuris = [\n \"http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg\",\n \"http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg\",\n \"http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg\",\n]\nimage_bytes = [requests.get(uri).content for uri in uris]\ntable.add(\n pd.DataFrame({\"label\": labels, \"image_uri\": uris, \"image_bytes\": image_bytes})\n)\n"; diff --git a/python/python/lancedb/embeddings/cohere.py b/python/python/lancedb/embeddings/cohere.py index 8fc460f9a..286f658ad 100644 --- a/python/python/lancedb/embeddings/cohere.py +++ b/python/python/lancedb/embeddings/cohere.py @@ -22,16 +22,20 @@ class CohereEmbeddingFunction(TextEmbeddingFunction): Parameters ---------- - name : str, default "embed-multilingual-v2.0" + name : str, default "embed-multilingual-v3.0" The name of the model to use. List of acceptable models: * embed-english-v3.0 * embed-multilingual-v3.0 * embed-english-light-v3.0 * embed-multilingual-light-v3.0 - * embed-english-v2.0 - * embed-english-light-v2.0 - * embed-multilingual-v2.0 + + The v2.0 models (embed-english-v2.0, embed-english-light-v2.0 and + embed-multilingual-v2.0) were retired by Cohere on April 4, 2026. + The previous default produced 768-dimensional vectors, while the new + default produces 1024-dimensional vectors. Existing tables containing + vectors from a v2.0 model must be re-embedded with an active model into + a table whose vector column has the matching dimension. source_input_type : str, default "search_document" The input type for the source column in the database @@ -65,7 +69,7 @@ class CohereEmbeddingFunction(TextEmbeddingFunction): cohere = EmbeddingFunctionRegistry .get_instance() .get("cohere") - .create(name="embed-multilingual-v2.0") + .create(name="embed-multilingual-v3.0") class TextModel(LanceModel): text: str = cohere.SourceField() @@ -81,7 +85,7 @@ class CohereEmbeddingFunction(TextEmbeddingFunction): """ - name: str = "embed-multilingual-v2.0" + name: str = "embed-multilingual-v3.0" source_input_type: str = "search_document" query_input_type: str = "search_query" client: ClassVar = None diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 3c968a821..32503c04f 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -1115,3 +1115,13 @@ def test_jina_embeddings_use_their_own_api_key(monkeypatch): func_b.compute_source_embeddings(["hello"]) assert sent == ["Bearer key-a", "Bearer key-b"] + + +def test_cohere_default_model_is_not_a_retired_v2_model(): + # Cohere retired embed-english-v2.0, embed-english-light-v2.0 and + # embed-multilingual-v2.0 on April 4, 2026. + cohere = get_registry().get("cohere").create() + + assert cohere.name == "embed-multilingual-v3.0" + assert "v2.0" not in cohere.name + assert cohere.ndims() == 1024 diff --git a/python/python/tests/test_embeddings_slow.py b/python/python/tests/test_embeddings_slow.py index b584598c7..4de85070f 100644 --- a/python/python/tests/test_embeddings_slow.py +++ b/python/python/tests/test_embeddings_slow.py @@ -272,7 +272,7 @@ def test_cohere_embedding_function(): cohere = ( get_registry() .get("cohere") - .create(name="embed-multilingual-v2.0", max_retries=0) + .create(name="embed-multilingual-v3.0", max_retries=0) ) class TextModel(LanceModel): From 882be897789f3f8733a0a5bc6b9821c80097c681 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 28 Oct 2026 09:40:13 -0700 Subject: [PATCH 143/180] docs: clarify how to contribute website documentation The contributor guide mixes up shared documentation, Enterprise placeholders and the SDK reference. It also describes section merging that the assembler doesn't do. This replaces the overlapping instructions with guidance on where to write, how whole-page replacement works, how to preview changes and how to keep unfinished docs hidden. It explains that source changes enter a saved release edition before they appear on staging, and points SDK contributors to the existing reference guide. --- CONTRIBUTING.md | 136 +++++++++++++++++++++++++++++------------------- docs/README.md | 11 ++-- 2 files changed, 89 insertions(+), 58 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4a73f8b35..b7ecc16bb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,42 +72,68 @@ are wrappers around the Rust library. * `node`: **Deprecated** Typescript package source code * `java`: Java package source code * `docs/src`: SDK reference, built with mkdocs -* `docs/web`: the open-source pages of [docs.lancedb.com](https://docs.lancedb.com) +* `docs/web`: website guides for LanceDB OSS and the APIs used by both OSS and Enterprise * `docs/web-tests`: the tests the documentation's code examples are extracted from ## Documentation -The open-source pages of [docs.lancedb.com](https://docs.lancedb.com) live in -`docs/web`, so a change to behaviour and the change to the page describing it -belong in the same pull request. +Update the docs in the same pull request as the behavior they describe. You can +merge docs before a feature launches; keep the unfinished material hidden until +it is ready for readers. -Preview them locally — this serves `docs/web` on its own, with no other checkout: +### Choose the right place + +- `docs/web/` holds website guides for LanceDB OSS and the APIs used by both + OSS and Enterprise. +- `docs/src/` holds the SDK reference. See [docs/README.md](docs/README.md) for + its build and API-generation instructions. +- `docs/web-tests/` and `rust/lancedb/tests/` hold tests used to generate the + website's code examples. + +Document SDK APIs here, and explain which operations work in OSS and Enterprise. +Put Enterprise-specific deployment and operating instructions in the Enterprise +documentation. + +Some pages are placeholders that the website build replaces with an Enterprise +page. Changes to a placeholder won't appear on the combined site. Put +instructions that both products need on a separate page and link to it. + +### Preview and check your change + +From the repository root: ```bash -npm i -g mint # https://mintlify.com/docs/installation -cd docs/web && mint dev +npm i -g mint@4.2.888 +(cd docs/web && mint dev) ``` +This previews this checkout, including your uncommitted changes. It doesn't +include the other documentation sources or render the availability labels. +Use the [combined preview](https://github.com/lancedb/docs#development) when +checking Enterprise replacements or links to pages from another source. +Staging shows saved release editions, so it won't show a new source change +just because that change merged. + +Follow the [style guide](https://github.com/lancedb/docs/blob/main/STYLE.md). [Vale](https://vale.sh) checks wording, names and punctuation using the [bundled LanceDB rules](.github/vale/README.md). Pull requests show suggestions -on the lines they change. With Vale 3.24.0 installed, check a page with: +on the lines they change. With Vale 3.24.0 installed, check a page locally with: ```bash vale docs/web/indexing/vector-index.mdx ``` -This repository holds a page at every path the site publishes, so the whole -navigation resolves locally. Enterprise pages exist here as open-source pages -- -what the capability is, and what the embedded form does instead. A separate -private repository supplies the fuller version of each, which replaces the page -at the same path when the published site is assembled. +Keep existing `{#anchor}` values when changing headings, so links to those +sections keep working. Give new headings stable anchors. For links in rendered +components, write the path directly, such as `href="/quickstart"`, and spell out +attributes rather than using property spreads. That lets versioned docs keep +links inside the selected edition. Code examples aren't subject to this rule. -Four things to know before editing: +### Code examples -**Code examples are not written into the pages.** They live in real tests under -`docs/web-tests/{py,ts,rs}`, `docs/web-tests/blob-v2/{py,ts,rs}`, and -`rust/lancedb/tests`, are extracted into `docs/web/snippets/`, and are imported -by the pages. Edit the test, then regenerate from the repository root: +Edit the test that produces an example, then regenerate its snippet. The +sources are `docs/web-tests/{py,ts,rs}`, `docs/web-tests/blob-v2/{py,ts,rs}` and +`rust/lancedb/tests`. Run this from the repository root: ```bash uv run docs/web-tests/mdx_snippets_gen.py \ @@ -116,55 +142,57 @@ uv run docs/web-tests/mdx_snippets_gen.py \ -s rust/lancedb/tests -o docs/web/snippets ``` -Review the diff before committing: a few modules currently regenerate with -unrelated changes, so commit only the snippets for the examples you changed. +Run the tests for the examples you changed; generating a snippet doesn't run +its example. Review the generated diff and commit only the relevant snippets +with their tests. Don't assume the PR checks execute every documentation +example. -Run the Python, TypeScript and Rust examples in `docs/web-tests/{py,ts,rs}` -locally before submitting the change. These examples are not yet wired into -pull-request CI; that integration remains follow-up work. +### Say where a feature works -**Every heading carries an explicit `{#anchor}`.** Those anchors are how the -Enterprise pages attach their additions to the right section, so they are -assigned once and never regenerated. Leave an existing anchor alone even when -you reword the heading above it; only new headings need a new one. - -**A page can declare where it applies.** Its frontmatter says whether LanceDB -OSS and LanceDB Enterprise support the feature: use only `available` or -`unavailable`, and one sentence that explains its scope. Availability describes -product support, not whether a particular deployment has enabled or configured -the feature. A supported feature stays `available` when it requires setup, a -supported SDK or server version, or has differences between offerings. State -those requirements in the summary or the relevant section, including unsupported -subfeatures. Do not use `varies`, infer support from an unknown status, or mark an -absent capability available. Narrow a page to the capability it actually covers -when necessary. For example: +Use `availability` in a page's frontmatter to describe the support covered by +that page. Each product is either `available` or `unavailable`; use the summary +and body for setup requirements, SDK differences and unsupported operations. +For example, a page about signing in to Enterprise could declare: ```yaml availability: oss: unavailable enterprise: available summary: >- - Requests to a deployment carry an API key or an OAuth token. Embedded + These sign-in instructions apply to LanceDB Enterprise. Embedded LanceDB has no server to sign in to. ``` -The assembled site renders this as a label above the page's content and as a -sidebar tag when only one offering has the feature. Do not also open the page -with a badge of its own, and keep a qualification that only one section needs -in that section's text. A `mint dev` preview of `docs/web` alone renders -neither the labels nor the tags. +Check these claims with the feature owner. Don't use `varies`, treat an API +stub as working support, or mark a supported feature unavailable just because +it needs configuration. If one label can't describe the whole page accurately, +make the page's scope narrower and explain the differences. -**A feature can be documented before its release.** List a draft page in -`docs/web/.mintignore`, keep it out of the navigation in `docs.json`, and do not -link to it from published pages. Wrap a draft section in an MDX comment, -`{/* ... */}`, whose first line names the release, such as -`Draft for the Feature X release.` Keep draft table rows and list items in a -comment below the table or list, since a comment between rows or items breaks -it. Drafts are hidden from readers but stay in the source, and availability does -not change what is published. At release, remove the comments and the -`.mintignore` entries, and restore the navigation and links. See +Assembly turns this declaration into a page label and, for a feature supported +by only one product, a sidebar tag. Don't add those badges by hand. Availability +labels do not hide unreleased content. + +### Write docs before launch + +You don't need to hold a documentation PR until launch. Use these controls: + +- For a whole page, add its path to `docs/web/.mintignore`. Leave it out of + `docs/web/docs.json`, redirects and links from published pages. Removing a + sidebar entry alone doesn't hide a page. +- For a section, wrap it in an MDX comment, `{/* ... */}`, with a note such as + `Draft for the Feature X release.` Put draft table rows and list items in a + comment below the table or list, not between entries. + +Drafts remain in the source. Use them to avoid advertising an unfinished +feature, not to keep information confidential. See [Writing docs before release](https://github.com/lancedb/docs#writing-docs-before-release) -in the documentation repository's README for previews and release checks. +for examples and how to preview a draft. + +Before the intended release, remove the draft controls, restore the navigation +and links, and check the result. Those changes must be in the source commit the +edition uses. A later change to `main` doesn't update an edition already saved. +For a mistake in an existing edition, fix the source and request a +[recorded correction](https://github.com/lancedb/docs#correcting-a-saved-edition). ## Release process diff --git a/docs/README.md b/docs/README.md index c5a99943d..5e434c520 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,10 +1,13 @@ # LanceDB Documentation -LanceDB docs are available at [docs.lancedb.com](https://docs.lancedb.com). +For website guides in `docs/web`, start with +[Documentation in CONTRIBUTING.md](../CONTRIBUTING.md#documentation). That +covers editing pages, generated examples, previews, availability and drafts. -The SDK docs are built and deployed automatically by [Github Actions](../.github/workflows/docs.yml) -whenever a commit is pushed to the `main` branch. So it is possible for the docs to show -unreleased features. +This page covers the SDK reference in `docs/src`, built with MkDocs. Its +[GitHub Actions workflow](../.github/workflows/docs.yml) builds and deploys on +pushes to `main`, so it can include unreleased APIs. That is separate from the +release editions of the Mintlify website. ## Building the docs From ece54d8917ecce44b64539c44b68fc5841797f5d Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 28 Oct 2026 17:30:53 +0000 Subject: [PATCH 144/180] =?UTF-8?q?Bump=20version:=200.41.0-beta.16=20?= =?UTF-8?q?=E2=86=92=200.41.0-beta.17?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 59a609130..af2f32902 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.41.0-beta.16" +current_version = "0.41.0-beta.17" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 46412bc3a..40811ab1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5729,7 +5729,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.41.0-beta.16" +version = "0.41.0-beta.17" dependencies = [ "ahash", "anyhow", @@ -5840,7 +5840,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.41.0-beta.16" +version = "0.41.0-beta.17" dependencies = [ "arrow-array", "arrow-buffer", @@ -5865,7 +5865,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.41.0-beta.16" +version = "0.41.0-beta.17" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 792af15b1..ed0ec9dd4 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.41.0-beta.16 + 0.41.0-beta.17 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index ff7c875b4..c89980194 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.16 + 0.41.0-beta.17 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9e3191813..aa5be0b95 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.41.0-beta.16 + 0.41.0-beta.17 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 9e775431d..3ed65c704 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.41.0-beta.16" +version = "0.41.0-beta.17" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index a6629d05b..e417308eb 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 7a5adb2da..d7dfa44be 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 8ce3a976c..f4a768871 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 50b091c6a..a2266260d 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 19ec044d1..6af065156 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 5265ae63f..694449160 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 99f3ef75e..d852a1e3e 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index f87115ae1..cf0c7682e 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.41.0-beta.16", + "version": "0.41.0-beta.17", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index f02ba4279..07b7f2e39 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.41.0-beta.16" +version = "0.41.0-beta.17" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index d688aeaae..9655b1160 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.41.0-beta.16" +version = "0.41.0-beta.17" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 12d86ea2512734138e4195d15ef4f65a376d9605 Mon Sep 17 00:00:00 2001 From: J Ganesh Kumar Reddy Date: Wed, 28 Oct 2026 23:48:16 +0530 Subject: [PATCH 145/180] feat(nodejs): add col() expression builder for camelCase column names ## Summary Fixes #3211 by exposing the shared Rust/DataFusion expression builder through Node bindings. Case-sensitive references such as `col("firstName")` can be composed and passed to `where()`, while SQL strings remain supported. The expression-object representation follows [the design requested on #3290](https://github.com/lancedb/lancedb/pull/3290#discussion_r3632371998). That earlier PR remains open; no claim is made that the issue was unclaimed or that maintainers have selected this implementation. ## Review corrections - Construct the named native struct correctly and parse casts through `arrow_schema::DataType`. - Preserve numeric values: use Int64 only for JavaScript safe integers; retain Float64 otherwise. Explicit `litInt` rejects unsupported numbers with a documented `RangeError`. - Correct test syntax/API calls and align SQL assertions with the shared dialect, including reserved and case-sensitive names. - Use typed, isolated temporary test tables with cleanup, and cover an actual large-number filter threshold. - Document the public methods and commit generated API documentation. Synced with current main `0bceaaf3` through a normal merge. The diff is limited to seven Node source/test/config files and eleven generated documentation files; no Rust core change. ## Validation [Linux validation run](https://github.com/Ganesh1729-ui/lancedb/actions/runs/38244794288) on Node 24 / Rust 1.97.0 with the repository's `ci` profile and `remote,lancedb/metrics-otel` features: - Rebuilt native addon, TypeScript build, Biome, Rust formatting and native Clippy pass. - Expression/query/Arrow/table suites: **1,129 passed**; expression suite repeated: **42 passed**. - Using the original JavaScript numeric dispatch with the rebuilt addon: **8 regressions fail, 2 controls pass**. - Strict TypeDoc generation passes. Final local typing/docs/lint checks pass; the PR source equals the validated source except for the separate validation workflow, which is excluded from this PR. Full provider/model/S3, other feature combinations and OS/Node matrices were not run in this follow-up. Upstream checks and maintainer review remain separate. ## AI assistance AI was used for implementation, review and testing. No prior human review is claimed. --- docs/src/js/classes/AutoQuery.md | 13 +- docs/src/js/classes/Expr.md | 365 +++++++++++++++++++++++++++ docs/src/js/classes/Query.md | 13 +- docs/src/js/classes/VectorQuery.md | 13 +- docs/src/js/functions/col.md | 21 ++ docs/src/js/functions/func.md | 23 ++ docs/src/js/functions/lit.md | 21 ++ docs/src/js/functions/litBool.md | 21 ++ docs/src/js/functions/litInt.md | 21 ++ docs/src/js/globals.md | 7 + docs/src/js/type-aliases/ExprLike.md | 13 + nodejs/__test__/expr.test.ts | 346 +++++++++++++++++++++++++ nodejs/lancedb/expr.ts | 182 +++++++++++++ nodejs/lancedb/index.ts | 2 + nodejs/lancedb/query.ts | 18 +- nodejs/src/expr.rs | 221 ++++++++++++++++ nodejs/src/lib.rs | 1 + nodejs/typedoc.json | 1 + rust/lancedb/src/expr.rs | 43 ++++ rust/lancedb/src/expr/sql.rs | 95 +++++-- 20 files changed, 1406 insertions(+), 34 deletions(-) create mode 100644 docs/src/js/classes/Expr.md create mode 100644 docs/src/js/functions/col.md create mode 100644 docs/src/js/functions/func.md create mode 100644 docs/src/js/functions/lit.md create mode 100644 docs/src/js/functions/litBool.md create mode 100644 docs/src/js/functions/litInt.md create mode 100644 docs/src/js/type-aliases/ExprLike.md create mode 100644 nodejs/__test__/expr.test.ts create mode 100644 nodejs/lancedb/expr.ts create mode 100644 nodejs/src/expr.rs diff --git a/docs/src/js/classes/AutoQuery.md b/docs/src/js/classes/AutoQuery.md index f12668b90..60f568e07 100644 --- a/docs/src/js/classes/AutoQuery.md +++ b/docs/src/js/classes/AutoQuery.md @@ -469,29 +469,34 @@ where(predicate): this A filter statement to be applied to this query. -The filter should be supplied as an SQL query string. For example: +The filter may be an SQL query string or an expression built with `col`, +which preserves case-sensitive column names. For example: #### Parameters -* **predicate**: `string` +* **predicate**: `string` \| [`Expr`](Expr.md) #### Returns `this` -#### Example +#### Examples ```ts x > 10 y > 0 AND y < 100 x > 5 OR y = 'test' +``` + +```ts +table.query().where(col("firstName").eq("Alice")); +``` Filtering performance can often be improved by creating a scalar index on the filter column(s). Calling this multiple times combines the filters with a logical AND rather than replacing the previous filter. -``` #### Inherited from diff --git a/docs/src/js/classes/Expr.md b/docs/src/js/classes/Expr.md new file mode 100644 index 000000000..7342cf793 --- /dev/null +++ b/docs/src/js/classes/Expr.md @@ -0,0 +1,365 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / Expr + +# Class: Expr + +A SQL expression backed by the shared LanceDB expression builder. + +## Example + +```ts +table.query().where(col("firstName").eq("Alice")).toArray(); +``` + +## Constructors + +### new Expr() + +```ts +new Expr(inner): Expr +``` + +#### Parameters + +* **inner**: `Expr` + +#### Returns + +[`Expr`](Expr.md) + +## Properties + +### inner + +```ts +inner: Expr; +``` + +## Methods + +### add() + +```ts +add(other): Expr +``` + +Add a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### and() + +```ts +and(other): Expr +``` + +Combine two predicates with AND. + +#### Parameters + +* **other**: [`Expr`](Expr.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### cast() + +```ts +cast(dataType): Expr +``` + +Cast to an Arrow data type, such as "Int64". + +#### Parameters + +* **dataType**: `string` + +#### Returns + +[`Expr`](Expr.md) + +*** + +### contains() + +```ts +contains(substr): Expr +``` + +Test whether a string contains a substring. + +#### Parameters + +* **substr**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### div() + +```ts +div(other): Expr +``` + +Divide by a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### eq() + +```ts +eq(other): Expr +``` + +Compare for equality. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### gt() + +```ts +gt(other): Expr +``` + +Compare for greater than. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### gte() + +```ts +gte(other): Expr +``` + +Compare for greater than or equal to. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### isIn() + +```ts +isIn(values): Expr +``` + +Test membership in a list of values. + +#### Parameters + +* **values**: [`ExprLike`](../type-aliases/ExprLike.md)[] + +#### Returns + +[`Expr`](Expr.md) + +*** + +### lower() + +```ts +lower(): Expr +``` + +Convert a string to lowercase. + +#### Returns + +[`Expr`](Expr.md) + +*** + +### lt() + +```ts +lt(other): Expr +``` + +Compare for less than. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### lte() + +```ts +lte(other): Expr +``` + +Compare for less than or equal to. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### mul() + +```ts +mul(other): Expr +``` + +Multiply by a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### ne() + +```ts +ne(other): Expr +``` + +Compare for inequality. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### not() + +```ts +not(): Expr +``` + +Negate this predicate. + +#### Returns + +[`Expr`](Expr.md) + +*** + +### or() + +```ts +or(other): Expr +``` + +Combine two predicates with OR. + +#### Parameters + +* **other**: [`Expr`](Expr.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### sub() + +```ts +sub(other): Expr +``` + +Subtract a value. + +#### Parameters + +* **other**: [`ExprLike`](../type-aliases/ExprLike.md) + +#### Returns + +[`Expr`](Expr.md) + +*** + +### toSql() + +```ts +toSql(): string +``` + +Serialize with the LanceDB SQL dialect, preserving column case. + +#### Returns + +`string` + +*** + +### upper() + +```ts +upper(): Expr +``` + +Convert a string to uppercase. + +#### Returns + +[`Expr`](Expr.md) diff --git a/docs/src/js/classes/Query.md b/docs/src/js/classes/Query.md index 8e216d1f4..7434e7b8e 100644 --- a/docs/src/js/classes/Query.md +++ b/docs/src/js/classes/Query.md @@ -543,29 +543,34 @@ where(predicate): this A filter statement to be applied to this query. -The filter should be supplied as an SQL query string. For example: +The filter may be an SQL query string or an expression built with `col`, +which preserves case-sensitive column names. For example: #### Parameters -* **predicate**: `string` +* **predicate**: `string` \| [`Expr`](Expr.md) #### Returns `this` -#### Example +#### Examples ```ts x > 10 y > 0 AND y < 100 x > 5 OR y = 'test' +``` + +```ts +table.query().where(col("firstName").eq("Alice")); +``` Filtering performance can often be improved by creating a scalar index on the filter column(s). Calling this multiple times combines the filters with a logical AND rather than replacing the previous filter. -``` #### Inherited from diff --git a/docs/src/js/classes/VectorQuery.md b/docs/src/js/classes/VectorQuery.md index 04ced2ef4..d98f05893 100644 --- a/docs/src/js/classes/VectorQuery.md +++ b/docs/src/js/classes/VectorQuery.md @@ -825,29 +825,34 @@ where(predicate): this A filter statement to be applied to this query. -The filter should be supplied as an SQL query string. For example: +The filter may be an SQL query string or an expression built with `col`, +which preserves case-sensitive column names. For example: #### Parameters -* **predicate**: `string` +* **predicate**: `string` \| [`Expr`](Expr.md) #### Returns `this` -#### Example +#### Examples ```ts x > 10 y > 0 AND y < 100 x > 5 OR y = 'test' +``` + +```ts +table.query().where(col("firstName").eq("Alice")); +``` Filtering performance can often be improved by creating a scalar index on the filter column(s). Calling this multiple times combines the filters with a logical AND rather than replacing the previous filter. -``` #### Inherited from diff --git a/docs/src/js/functions/col.md b/docs/src/js/functions/col.md new file mode 100644 index 000000000..6cff91cf7 --- /dev/null +++ b/docs/src/js/functions/col.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / col + +# Function: col() + +```ts +function col(name): Expr +``` + +Reference a column by its exact, case-sensitive name. + +## Parameters + +* **name**: `string` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/func.md b/docs/src/js/functions/func.md new file mode 100644 index 000000000..05f6901aa --- /dev/null +++ b/docs/src/js/functions/func.md @@ -0,0 +1,23 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / func + +# Function: func() + +```ts +function func(name, ...args): Expr +``` + +Call a registered SQL function, such as `func("lower", col("firstName"))`. + +## Parameters + +* **name**: `string` + +* ...**args**: [`ExprLike`](../type-aliases/ExprLike.md)[] + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/lit.md b/docs/src/js/functions/lit.md new file mode 100644 index 000000000..c9db2cf4d --- /dev/null +++ b/docs/src/js/functions/lit.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / lit + +# Function: lit() + +```ts +function lit(value): Expr +``` + +Create a string or numeric literal. Unsafe integers are represented as Float64. + +## Parameters + +* **value**: `string` \| `number` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/litBool.md b/docs/src/js/functions/litBool.md new file mode 100644 index 000000000..d857d8b74 --- /dev/null +++ b/docs/src/js/functions/litBool.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / litBool + +# Function: litBool() + +```ts +function litBool(value): Expr +``` + +Create a boolean literal. + +## Parameters + +* **value**: `boolean` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/functions/litInt.md b/docs/src/js/functions/litInt.md new file mode 100644 index 000000000..6556f7572 --- /dev/null +++ b/docs/src/js/functions/litInt.md @@ -0,0 +1,21 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / litInt + +# Function: litInt() + +```ts +function litInt(value): Expr +``` + +Create an Int64 literal from a JavaScript safe integer. Other numbers throw RangeError. + +## Parameters + +* **value**: `number` + +## Returns + +[`Expr`](../classes/Expr.md) diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index e3830e9ad..25a32b29c 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -28,6 +28,7 @@ - [Catalog](classes/Catalog.md) - [Connection](classes/Connection.md) - [DatabaseNames](classes/DatabaseNames.md) +- [Expr](classes/Expr.md) - [HeaderProvider](classes/HeaderProvider.md) - [Index](classes/Index.md) - [Job](classes/Job.md) @@ -165,6 +166,7 @@ - [Data](type-aliases/Data.md) - [DataLike](type-aliases/DataLike.md) - [DataTypeLike](type-aliases/DataTypeLike.md) +- [ExprLike](type-aliases/ExprLike.md) - [FieldLike](type-aliases/FieldLike.md) - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) @@ -179,11 +181,16 @@ - [RecordBatchIterator](functions/RecordBatchIterator.md) - [blob](functions/blob.md) +- [col](functions/col.md) - [connect](functions/connect.md) - [connectCatalog](functions/connectCatalog.md) - [connectNamespace](functions/connectNamespace.md) +- [func](functions/func.md) - [instrumentLanceDbMetrics](functions/instrumentLanceDbMetrics.md) - [isBlobField](functions/isBlobField.md) +- [lit](functions/lit.md) +- [litBool](functions/litBool.md) +- [litInt](functions/litInt.md) - [makeArrowTable](functions/makeArrowTable.md) - [makeJsonField](functions/makeJsonField.md) - [packBits](functions/packBits.md) diff --git a/docs/src/js/type-aliases/ExprLike.md b/docs/src/js/type-aliases/ExprLike.md new file mode 100644 index 000000000..d0628c982 --- /dev/null +++ b/docs/src/js/type-aliases/ExprLike.md @@ -0,0 +1,13 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / ExprLike + +# Type Alias: ExprLike + +```ts +type ExprLike: Expr | string | number | boolean; +``` + +Values accepted by expression operators. diff --git a/nodejs/__test__/expr.test.ts b/nodejs/__test__/expr.test.ts new file mode 100644 index 000000000..492929c04 --- /dev/null +++ b/nodejs/__test__/expr.test.ts @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import * as http from "http"; +import type { AddressInfo } from "net"; +import * as tmp from "tmp"; + +import { type Table, connect } from "../lancedb"; +import { + Table as ArrowTable, + Field, + Int64, + Schema, + Utf8, + tableToIPC, +} from "../lancedb/arrow"; +import { Expr, col, func, lit, litBool, litInt } from "../lancedb/expr"; + +describe("expr", () => { + describe("col", () => { + it("returns an Expr instance", () => { + const e = col("age"); + expect(e).toBeInstanceOf(Expr); + }); + + it("preserves camelCase in toSql()", () => { + expect(col("firstName").toSql()).toBe("`firstName`"); + }); + + it("preserves snake_case without quotes", () => { + expect(col("first_name").toSql()).toBe("first_name"); + }); + + it("Quotes identifiers with spaces", () => { + expect(col("first name").toSql()).toBe("`first name`"); + }); + + it("Quotes identifiers with leading digits", () => { + expect(col("2fast").toSql()).toBe("`2fast`"); + }); + + it("Quotes unicode identifiers", () => { + expect(col("名前").toSql()).toBe("`名前`"); + }); + }); + + describe("lit", () => { + it("creates a string literal", () => { + expect(lit("hello").toSql()).toBe("'hello'"); + }); + + it("creates an integer literal", () => { + expect(lit(42).toSql()).toBe("42"); + }); + + it("creates a float literal", () => { + expect(lit(3.14).toSql()).toBe("3.14"); + }); + }); + + describe("numeric literals", () => { + it.each([Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER])( + "preserves the safe integer boundary %s", + (value) => { + expect(lit(value).toSql()).toBe(String(value)); + expect(litInt(value).toSql()).toBe(String(value)); + }, + ); + + it.each([1e20, -1e20])("preserves the large number %s", (value) => { + expect(Number(lit(value).toSql())).toBe(value); + expect(col("price").gt(value).toSql()).toBe( + col("price").gt(lit(value)).toSql(), + ); + }); + + it.each([1.5, 1e20, -1e20, Number.NaN, Number.POSITIVE_INFINITY])( + "rejects %s as an explicit integer literal", + (value) => expect(() => litInt(value)).toThrow(RangeError), + ); + }); + + describe("Expr operators", () => { + it("eq", () => { + expect(col("x").eq(lit(1)).toSql()).toBe("(x = 1)"); + }); + + it("ne", () => { + expect(col("x").ne(lit(1)).toSql()).toBe("(x <> 1)"); + }); + + it("lt", () => { + expect(col("age").lt(lit(18)).toSql()).toBe("(age < 18)"); + }); + + it("lte", () => { + expect(col("age").lte(lit(18)).toSql()).toBe("(age <= 18)"); + }); + + it("gt", () => { + expect(col("age").gt(lit(18)).toSql()).toBe("(age > 18)"); + }); + + it("gte", () => { + expect(col("age").gte(lit(18)).toSql()).toBe("(age >= 18)"); + }); + + it("and", () => { + const e = col("age") + .gt(lit(18)) + .and(col("status").eq(lit("active"))); + expect(e.toSql()).toBe("((age > 18) AND (`status` = 'active'))"); + }); + + it("or", () => { + const e = col("a") + .eq(lit(1)) + .or(col("b").eq(lit(2))); + expect(e.toSql()).toBe("((a = 1) OR (b = 2))"); + }); + + it("not", () => { + const e = col("active").eq(litBool(true)).not(); + expect(e.toSql()).toBe("NOT (active = true)"); + }); + + it("add", () => { + expect(col("x").add(lit(1)).toSql()).toBe("(x + 1)"); + }); + + it("sub", () => { + expect(col("x").sub(lit(1)).toSql()).toBe("(x - 1)"); + }); + + it("mul", () => { + expect(col("price").mul(lit(1.1)).toSql()).toBe("(price * 1.1)"); + }); + + it("div", () => { + expect(col("total").div(lit(2)).toSql()).toBe("(total / 2)"); + }); + }); + + describe("Expr string methods", () => { + it("lower", () => { + expect(col("name").lower().toSql()).toBe("lower(`name`)"); + }); + + it("upper", () => { + expect(col("name").upper().toSql()).toBe("upper(`name`)"); + }); + + it("contains", () => { + expect(col("text").contains(lit("hello")).toSql()).toBe( + "contains(`text`, 'hello')", + ); + }); + }); + + describe("membership and casts", () => { + it("accepts scalar list members", () => { + expect(col("age").isIn([18, 21]).toSql()).toBe("age IN (18, 21)"); + }); + it("casts to an Arrow type", () => { + expect(col("age").cast("Int64").toSql()).toBe("arrow_cast(age, 'Int64')"); + }); + it("rejects an invalid Arrow type", () => { + expect(() => col("age").cast("invalid")).toThrow("Invalid data type"); + }); + }); + + describe("func", () => { + it("lower", () => { + expect(func("lower", col("name")).toSql()).toBe("lower(`name`)"); + }); + }); + + describe("camelCase integration", () => { + let db: Awaited>; + let table: Table; + let tmpDir: tmp.DirResult; + + beforeAll(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + db = await connect(tmpDir.name); + table = await db.createTable("test", [ + { id: 1, firstName: "Alice", lastName: "Smith" }, + { id: 2, firstName: "Bob", lastName: "Jones" }, + { id: 3, firstName: "Charlie", lastName: "Brown" }, + ]); + }); + + afterAll(() => { + table.close(); + db.close(); + tmpDir.removeCallback(); + }); + + it("filters on camelCase column", async () => { + const results = await table + .query() + .where(col("firstName").eq(lit("Alice"))) + .toArray(); + expect(results.length).toBe(1); + expect(results[0].firstName).toBe("Alice"); + }); + + it("filters on multiple camelCase columns", async () => { + const results = await table + .query() + .where( + col("firstName") + .eq(lit("Bob")) + .and(col("lastName").eq(lit("Jones"))), + ) + .toArray(); + expect(results.length).toBe(1); + expect(results[0].firstName).toBe("Bob"); + }); + + it("preserves an unsafe integer filter threshold", async () => { + const prices = await db.createTable("prices", [ + { price: 9.5e18 }, + { price: 1.1e20 }, + ]); + try { + const results = await prices + .query() + .where(col("price").gt(1e20)) + .toArray(); + expect(results.map((row) => row.price)).toEqual([1.1e20]); + } finally { + prices.close(); + } + }); + + it("filters with gt on camelCase column", async () => { + const results = await table + .query() + .where(col("id").gt(lit(1))) + .toArray(); + expect(results.length).toBe(2); + }); + + it.each([ + ["backslash", "\\"], + ["quote", "'"], + ["backslash quote", "\\'"], + ["OR true payload", "\\') OR true --"], + ["line comment payload", "\\' -- OR true"], + ["block comment payload", "\\') /* OR true */ --"], + ])("filters the exact %s value", async (label, value) => { + const escaped = await db.createTable( + `escaped_${label.replaceAll(" ", "_")}`, + [ + { id: 1, tenant: value }, + { id: 2, tenant: "different tenant" }, + ], + ); + try { + const results = await escaped + .query() + .where(col("tenant").eq(lit(value))) + .toArray(); + expect(results).toHaveLength(1); + expect(results[0].id).toBe(1); + expect(results[0].tenant).toBe(value); + } finally { + escaped.close(); + } + }); + }); + + it("sends a quoted expression value to remote as one literal", async () => { + const value = "\\') OR true --"; + const schema = new Schema([ + new Field("id", new Int64(), false), + new Field("tenant", new Utf8(), false), + ]); + const response = Buffer.from(tableToIPC(new ArrowTable(schema), "stream")); + let remoteFilter: unknown; + + const server = http.createServer((req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "tenants", + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: false }, + { name: "tenant", type: { type: "string" }, nullable: false }, + ], + }, + }), + ); + return; + } + if (path.endsWith("/query/")) { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + remoteFilter = JSON.parse(body).filter; + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + }) + .end(response); + }); + return; + } + res.writeHead(404).end(); + }); + + await new Promise((resolve) => + server.listen(0, "127.0.0.1", resolve), + ); + const address = server.address() as AddressInfo; + + try { + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${address.port}`, + }); + try { + const remoteTable = await db.openTable("tenants"); + await remoteTable + .query() + .where(col("tenant").eq(lit(value))) + .toArrow(); + } finally { + db.close(); + } + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } + + expect(remoteFilter).toBe("(tenant = '\\'') OR true --')"); + }); +}); diff --git a/nodejs/lancedb/expr.ts b/nodejs/lancedb/expr.ts new file mode 100644 index 000000000..5880bec60 --- /dev/null +++ b/nodejs/lancedb/expr.ts @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + Expr as NativeExpr, + col as nativeCol, + func as nativeFunc, + lit as nativeLit, + litBool as nativeLitBool, + litInt as nativeLitInt, +} from "./native.js"; + +export { Expr as NativeExpr } from "./native"; + +/** Values accepted by expression operators. */ +export type ExprLike = Expr | string | number | boolean; + +function coerce(value: ExprLike): Expr { + if (value instanceof Expr) { + return value; + } + if (typeof value === "string") { + return lit(value); + } + if (typeof value === "boolean") { + return litBool(value); + } + if (typeof value === "number") { + return lit(value); + } + throw new TypeError(`Unsupported literal type: ${typeof value}`); +} + +/** + * A SQL expression backed by the shared LanceDB expression builder. + * + * @example + * ```ts + * table.query().where(col("firstName").eq("Alice")).toArray(); + * ``` + */ +export class Expr { + inner: NativeExpr; + + constructor(inner: NativeExpr) { + this.inner = inner; + } + + /** Compare for equality. */ + eq(other: ExprLike): Expr { + return new Expr(this.inner.eq(coerce(other).inner)); + } + + /** Compare for inequality. */ + ne(other: ExprLike): Expr { + return new Expr(this.inner.ne(coerce(other).inner)); + } + + /** Compare for less than. */ + lt(other: ExprLike): Expr { + return new Expr(this.inner.lt(coerce(other).inner)); + } + + /** Compare for less than or equal to. */ + lte(other: ExprLike): Expr { + return new Expr(this.inner.lte(coerce(other).inner)); + } + + /** Compare for greater than. */ + gt(other: ExprLike): Expr { + return new Expr(this.inner.gt(coerce(other).inner)); + } + + /** Compare for greater than or equal to. */ + gte(other: ExprLike): Expr { + return new Expr(this.inner.gte(coerce(other).inner)); + } + + /** Combine two predicates with AND. */ + and(other: Expr): Expr { + return new Expr(this.inner.and(other.inner)); + } + + /** Combine two predicates with OR. */ + or(other: Expr): Expr { + return new Expr(this.inner.or(other.inner)); + } + + /** Negate this predicate. */ + not(): Expr { + return new Expr(this.inner.not()); + } + + /** Add a value. */ + add(other: ExprLike): Expr { + return new Expr(this.inner.add(coerce(other).inner)); + } + + /** Subtract a value. */ + sub(other: ExprLike): Expr { + return new Expr(this.inner.sub(coerce(other).inner)); + } + + /** Multiply by a value. */ + mul(other: ExprLike): Expr { + return new Expr(this.inner.mul(coerce(other).inner)); + } + + /** Divide by a value. */ + div(other: ExprLike): Expr { + return new Expr(this.inner.div(coerce(other).inner)); + } + + /** Convert a string to lowercase. */ + lower(): Expr { + return new Expr(this.inner.lower()); + } + + /** Convert a string to uppercase. */ + upper(): Expr { + return new Expr(this.inner.upper()); + } + + /** Test whether a string contains a substring. */ + contains(substr: ExprLike): Expr { + return new Expr(this.inner.contains(coerce(substr).inner)); + } + + /** Test membership in a list of values. */ + isIn(values: ExprLike[]): Expr { + return new Expr(this.inner.isIn(values.map((v) => coerce(v).inner))); + } + + /** Cast to an Arrow data type, such as "Int64". */ + cast(dataType: string): Expr { + return new Expr(this.inner.cast(dataType)); + } + + /** Serialize with the LanceDB SQL dialect, preserving column case. */ + toSql(): string { + return this.inner.toSql(); + } +} + +/** Reference a column by its exact, case-sensitive name. */ +export function col(name: string): Expr { + return new Expr(nativeCol(name)); +} + +/** Create a string or numeric literal. Unsafe integers are represented as Float64. */ +export function lit(value: string | number): Expr { + if (typeof value === "string") { + return new Expr(nativeLit(value)); + } + if (Number.isSafeInteger(value)) { + return new Expr(nativeLitInt(value)); + } + return new Expr(nativeLit(value)); +} + +/** Create a boolean literal. */ +export function litBool(value: boolean): Expr { + return new Expr(nativeLitBool(value)); +} + +/** Create an Int64 literal from a JavaScript safe integer. Other numbers throw RangeError. */ +export function litInt(value: number): Expr { + if (!Number.isSafeInteger(value)) { + throw new RangeError("Integer literals must be safe integers"); + } + return new Expr(nativeLitInt(value)); +} + +/** Call a registered SQL function, such as `func("lower", col("firstName"))`. */ +export function func(name: string, ...args: ExprLike[]): Expr { + return new Expr( + nativeFunc( + name, + args.map((a) => coerce(a).inner), + ), + ); +} diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 0f1b5f333..b9c334a08 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -207,6 +207,8 @@ export { MultiVector, } from "./arrow"; export { IntoSql, packBits } from "./util"; +export { Expr, col, lit, litBool, litInt, func } from "./expr"; +export type { ExprLike } from "./expr"; /** * Options for tokenizing a full-text search query without a table index. diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index b96e4fda6..27133a326 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -17,6 +17,7 @@ import { tableFromIPC, vectorFromArray, } from "./arrow"; +import { Expr } from "./expr"; import { type IvfPqOptions } from "./indices"; import { JsFullTextQuery, @@ -649,11 +650,16 @@ export class StandardQueryBase< /** * A filter statement to be applied to this query. * - * The filter should be supplied as an SQL query string. For example: + * The filter may be an SQL query string or an expression built with `col`, + * which preserves case-sensitive column names. For example: * @example * x > 10 * y > 0 AND y < 100 * x > 5 OR y = 'test' + * @example + * ```ts + * table.query().where(col("firstName").eq("Alice")); + * ``` * * Filtering performance can often be improved by creating a scalar index * on the filter column(s). @@ -661,8 +667,14 @@ export class StandardQueryBase< * Calling this multiple times combines the filters with a logical AND rather * than replacing the previous filter. */ - where(predicate: string): this { - this.doCall((inner: NativeQueryType) => inner.onlyIf(predicate)); + where(predicate: string | Expr): this { + this.doCall((inner: NativeQueryType) => { + if (predicate instanceof Expr) { + inner.onlyIf(predicate.toSql()); + } else { + inner.onlyIf(predicate); + } + }); return this; } /** diff --git a/nodejs/src/expr.rs b/nodejs/src/expr.rs new file mode 100644 index 000000000..c12f81a96 --- /dev/null +++ b/nodejs/src/expr.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Napi bindings for the LanceDB expression builder API. + +use std::ops::{Add, Div, Mul, Not, Sub}; + +use lancedb::expr::{ + DfExpr, col as ldb_col, contains, expr_cast, is_in, lit as df_lit, lower, upper, +}; +use napi::bindgen_prelude::*; +use napi_derive::napi; + +#[napi] +#[derive(Clone)] +pub struct Expr { + pub(crate) inner: DfExpr, +} + +#[napi] +impl Expr { + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn eq(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn ne(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().not_eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn lt(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().lt(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn lte(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().lt_eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn gt(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().gt(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn gte(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().gt_eq(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn and(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().and(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn or(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().or(other.inner.clone()), + } + } + + #[napi] + pub fn not(&self) -> Self { + Self { + inner: self.inner.clone().not(), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn add(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().add(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn sub(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().sub(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn mul(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().mul(other.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn div(&self, other: &Expr) -> Self { + Self { + inner: self.inner.clone().div(other.inner.clone()), + } + } + + #[napi] + pub fn lower(&self) -> Self { + Self { + inner: lower(self.inner.clone()), + } + } + + #[napi] + pub fn upper(&self) -> Self { + Self { + inner: upper(self.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn contains(&self, substr: &Expr) -> Self { + Self { + inner: contains(self.inner.clone(), substr.inner.clone()), + } + } + + #[napi] + #[allow(clippy::use_self)] // NAPI doesn't allow Self here but clippy reports it + pub fn is_in(&self, list: Vec<&Expr>) -> Self { + let items: Vec = list.into_iter().map(|e| e.inner.clone()).collect(); + Self { + inner: is_in(self.inner.clone(), items), + } + } + + #[napi] + pub fn cast(&self, data_type: String) -> napi::Result { + let arrow_type = data_type + .parse::() + .map_err(|e| napi::Error::from_reason(format!("Invalid data type: {}", e)))?; + Ok(Self { + inner: expr_cast(self.inner.clone(), arrow_type), + }) + } + + #[napi] + pub fn to_sql(&self) -> napi::Result { + lancedb::expr::expr_to_sql_string(&self.inner) + .map_err(|e| napi::Error::from_reason(e.to_string())) + } +} + +/// Create a column reference expression. +/// +/// The column name is preserved exactly as given (case-sensitive), so +/// `col("firstName")` correctly references a field named `firstName`. +#[napi] +#[allow(dead_code)] +pub fn col(name: String) -> Expr { + Expr { + inner: ldb_col(name), + } +} + +/// Create a literal (constant) value expression. +#[napi] +#[allow(dead_code)] +pub fn lit(value: napi::bindgen_prelude::Either) -> napi::Result { + match value { + Either::A(s) => Ok(Expr { inner: df_lit(s) }), + Either::B(f) => Ok(Expr { inner: df_lit(f) }), + } +} + +/// Create a literal boolean value expression. +#[napi] +#[allow(dead_code)] +pub fn lit_bool(value: bool) -> Expr { + Expr { + inner: df_lit(value), + } +} + +/// Create a literal integer value expression. +#[napi] +#[allow(dead_code)] +pub fn lit_int(value: i64) -> Expr { + Expr { + inner: df_lit(value), + } +} + +/// Call an arbitrary registered SQL function by name. +#[napi] +#[allow(dead_code)] +pub fn func(name: String, args: Vec<&Expr>) -> napi::Result { + let df_args: Vec = args.into_iter().map(|e| e.inner.clone()).collect(); + lancedb::expr::func(&name, df_args) + .map(|inner| Expr { inner }) + .map_err(|e| napi::Error::from_reason(e.to_string())) +} diff --git a/nodejs/src/lib.rs b/nodejs/src/lib.rs index a92b8db98..cb40a51de 100644 --- a/nodejs/src/lib.rs +++ b/nodejs/src/lib.rs @@ -14,6 +14,7 @@ mod blob; mod catalog; mod connection; mod error; +mod expr; mod header; mod index; mod iterator; diff --git a/nodejs/typedoc.json b/nodejs/typedoc.json index c601ee61e..2c22b35ac 100644 --- a/nodejs/typedoc.json +++ b/nodejs/typedoc.json @@ -1,6 +1,7 @@ { "intentionallyNotExported": [ "lancedb/native.d.ts:Query", + "lancedb/native.d.ts:Expr", "lancedb/native.d.ts:VectorQuery", "lancedb/native.d.ts:TakeQuery", "lancedb/native.d.ts:RecordBatchIterator", diff --git a/rust/lancedb/src/expr.rs b/rust/lancedb/src/expr.rs index 1625d9632..04d1b0e9e 100644 --- a/rust/lancedb/src/expr.rs +++ b/rust/lancedb/src/expr.rs @@ -295,6 +295,49 @@ mod tests { ); } + #[test] + fn test_string_placeholder_does_not_rewrite_user_string() { + let marker = "__lancedb_string_placeholder_0__"; + let expr = col("value") + .eq(lit(marker)) + .and(col("other").eq(lit("ordinary"))); + assert_eq!( + expr_to_sql_string(&expr).unwrap(), + "((`value` = '__lancedb_string_placeholder_0__') AND (`other` = 'ordinary'))" + ); + } + + #[test] + fn test_string_literals_use_standard_quote_escaping() { + use datafusion_sql::sqlparser::{ + dialect::GenericDialect, tokenizer::Token, tokenizer::Tokenizer, + }; + + for value in [ + r"\", + "'", + r"\') OR true --", + "tenant -- 'not a comment", + "tenant /* 'not a comment */", + ] { + let expr = col("tenant").eq(lit(value)); + let sql = expr_to_sql_string(&expr).unwrap(); + assert_eq!(canonicalize_sql_predicate(&sql).unwrap(), sql); + + let string_literals = Tokenizer::new(&GenericDialect {}, &sql) + .with_unescape(false) + .tokenize() + .unwrap() + .into_iter() + .filter_map(|token| match token { + Token::SingleQuotedString(value) => Some(value), + _ => None, + }) + .collect::>(); + assert_eq!(string_literals, vec![value.replace('\'', "''")]); + } + } + #[test] fn test_binary_binding_skips_quoted_identifiers() { use datafusion_common::ScalarValue; diff --git a/rust/lancedb/src/expr/sql.rs b/rust/lancedb/src/expr/sql.rs index 2a1ca201d..96bb5b60c 100644 --- a/rust/lancedb/src/expr/sql.rs +++ b/rust/lancedb/src/expr/sql.rs @@ -104,9 +104,15 @@ pub fn canonicalize_sql_predicate(predicate: &str) -> crate::Result { .collect()) } -/// Prefix for placeholder strings inserted in place of binary literals. Chosen -/// to be extremely unlikely to occur in user data. +/// Prefixes for placeholder strings inserted in place of literals. Chosen to +/// be extremely unlikely to occur in user data. const BINARY_PLACEHOLDER_PREFIX: &str = "__lancedb_binary_placeholder_"; +const STRING_PLACEHOLDER_PREFIX: &str = "__lancedb_string_placeholder_"; + +enum LiteralBinding { + String(String), + Binary(Vec), +} fn bytes_to_hex_sql(bytes: &[u8]) -> String { let hex: String = bytes.iter().map(|b| format!("{b:02X}")).collect(); @@ -137,19 +143,28 @@ fn typed_string_literal(value: String, data_type: DataType) -> Expr { ) } -fn next_binary_placeholder(user_strings: &HashSet, next_id: &mut usize) -> String { +fn next_placeholder( + prefix: &str, + user_strings: &HashSet, + bindings: &HashMap, + next_id: &mut usize, +) -> String { loop { - let placeholder = format!("{BINARY_PLACEHOLDER_PREFIX}{}__", *next_id); + let placeholder = format!("{prefix}{}__", *next_id); *next_id += 1; - if !user_strings.contains(&placeholder) { + if !user_strings.contains(&placeholder) && !bindings.contains_key(&placeholder) { return placeholder; } } } -fn bind_binary_literals( +fn escape_string_literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +fn bind_literals( sql: &str, - mut bindings: HashMap>, + mut bindings: HashMap, ) -> crate::Result { let bytes = sql.as_bytes(); let mut output = Vec::with_capacity(bytes.len()); @@ -179,7 +194,7 @@ fn bind_binary_literals( let Some(identifier_end) = identifier_end else { return Err(crate::Error::InvalidInput { - message: "unterminated identifier while binding binary literal".to_string(), + message: "unterminated identifier while binding literals".to_string(), }); }; output.extend_from_slice(&bytes[identifier_start..identifier_end]); @@ -214,13 +229,17 @@ fn bind_binary_literals( let Some(content_end) = content_end else { return Err(crate::Error::InvalidInput { - message: "unterminated string while binding binary literal".to_string(), + message: "unterminated string while binding literals".to_string(), }); }; let placeholder = &sql[content_start..content_end]; if !escaped && let Some(value) = bindings.remove(placeholder) { - output.extend_from_slice(bytes_to_hex_sql(&value).as_bytes()); + let rendered = match value { + LiteralBinding::String(value) => escape_string_literal(&value), + LiteralBinding::Binary(value) => bytes_to_hex_sql(&value), + }; + output.extend_from_slice(rendered.as_bytes()); } else { output.extend_from_slice(&bytes[literal_start..index]); } @@ -228,12 +247,12 @@ fn bind_binary_literals( if !bindings.is_empty() { return Err(crate::Error::InvalidInput { - message: "failed to bind binary literal while serializing expression".to_string(), + message: "failed to bind literals while serializing expression".to_string(), }); } String::from_utf8(output).map_err(|e| crate::Error::InvalidInput { - message: format!("failed to bind binary literal: {e}"), + message: format!("failed to bind literals: {e}"), }) } @@ -253,7 +272,7 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { // * decimal literals need an explicit cast to preserve precision and scale; // * casts need exact Arrow type names rather than SQL type aliases; // * an empty IN list is valid in DataFusion but invalid SQL; - // * binary literals are unsupported by the unparser and need placeholders. + // * literals are replaced with placeholders and restored after unparsing. // Eliminate empty membership expressions before visiting their children. // Otherwise a discarded binary child could leave behind a stale binding. let rewritten = expr @@ -270,14 +289,19 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { .data; let user_strings = string_literals(&rewritten); - let mut next_placeholder_id = 0; - let mut binary_bindings = HashMap::new(); + let mut next_binary_placeholder_id = 0; + let mut bindings = HashMap::new(); let rewritten = rewritten .transform(|e: Expr| match e { Expr::Literal(ScalarValue::Binary(Some(bytes)), m) | Expr::Literal(ScalarValue::LargeBinary(Some(bytes)), m) => { - let placeholder = next_binary_placeholder(&user_strings, &mut next_placeholder_id); - binary_bindings.insert(placeholder.clone(), bytes); + let placeholder = next_placeholder( + BINARY_PLACEHOLDER_PREFIX, + &user_strings, + &bindings, + &mut next_binary_placeholder_id, + ); + bindings.insert(placeholder.clone(), LiteralBinding::Binary(bytes)); Ok(Transformed::yes(Expr::Literal( ScalarValue::Utf8(Some(placeholder)), m, @@ -345,11 +369,44 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { })? .data; + // DataFusion's SQLParser serializer treats a quote after a backslash as + // already escaped, but Lance's dialect does not support backslash escapes. + // Replace every string with an inert placeholder so the serializer cannot + // misinterpret its contents, then restore each value with standard SQL + // single-quote doubling below. + let mut next_string_placeholder_id = 0; + let rewritten = rewritten + .transform(|e: Expr| match e { + Expr::Literal( + ScalarValue::Utf8(Some(value)) + | ScalarValue::LargeUtf8(Some(value)) + | ScalarValue::Utf8View(Some(value)), + m, + ) if !bindings.contains_key(&value) => { + let placeholder = next_placeholder( + STRING_PLACEHOLDER_PREFIX, + &user_strings, + &bindings, + &mut next_string_placeholder_id, + ); + bindings.insert(placeholder.clone(), LiteralBinding::String(value)); + Ok(Transformed::yes(Expr::Literal( + ScalarValue::Utf8(Some(placeholder)), + m, + ))) + } + other => Ok(Transformed::no(other)), + }) + .map_err(|e| crate::Error::InvalidInput { + message: format!("failed to rewrite string literals: {}", e), + })? + .data; + let sql = run_unparser(&rewritten)?; - if binary_bindings.is_empty() { + if bindings.is_empty() { Ok(sql) } else { - bind_binary_literals(&sql, binary_bindings) + bind_literals(&sql, bindings) } } From edb79d38e3c486217d30020609428ed759dddd54 Mon Sep 17 00:00:00 2001 From: Joshua Snider Date: Wed, 28 Oct 2026 15:05:40 -0400 Subject: [PATCH 146/180] docs: correct the documented default retry statuses (#3964) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #2349 changed the default retryable status codes to `[409, 429, 500, 502, 503, 504]`, but only the Rust docstring was updated. The Python and TypeScript bindings — and the generated TypeScript API reference — still document the old `[429, 500, 502, 503]`. The actual default is set in `ResolvedRetryConfig::try_from` in `rust/lancedb/src/remote/retry.rs`, and `rust/lancedb/src/remote/client.rs` already documents it correctly. This brings the other three in line. Docs only — no behavior change. Split out from #3963 per the "one problem at a time" guidance in `CONTRIBUTING.md`. --- docs/src/js/interfaces/RetryConfig.md | 2 +- nodejs/src/remote.rs | 2 +- python/python/lancedb/remote/__init__.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/src/js/interfaces/RetryConfig.md b/docs/src/js/interfaces/RetryConfig.md index a9e4e6046..4f9336b66 100644 --- a/docs/src/js/interfaces/RetryConfig.md +++ b/docs/src/js/interfaces/RetryConfig.md @@ -84,7 +84,7 @@ optional statuses: number[]; ``` The HTTP status codes for which to retry the request. Default is -[429, 500, 502, 503]. +[409, 429, 500, 502, 503, 504]. You can also set this via the environment variable `LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers. diff --git a/nodejs/src/remote.rs b/nodejs/src/remote.rs index c776ea597..2a6985477 100644 --- a/nodejs/src/remote.rs +++ b/nodejs/src/remote.rs @@ -69,7 +69,7 @@ pub struct RetryConfig { /// `LANCE_CLIENT_RETRY_BACKOFF_JITTER`. pub backoff_jitter: Option, /// The HTTP status codes for which to retry the request. Default is - /// [429, 500, 502, 503]. + /// [409, 429, 500, 502, 503, 504]. /// /// You can also set this via the environment variable /// `LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers. diff --git a/python/python/lancedb/remote/__init__.py b/python/python/lancedb/remote/__init__.py index bb9a32122..15015a8e0 100644 --- a/python/python/lancedb/remote/__init__.py +++ b/python/python/lancedb/remote/__init__.py @@ -124,7 +124,7 @@ class RetryConfig: `LANCE_CLIENT_RETRY_BACKOFF_JITTER`. statuses: Optional[List[int] The HTTP status codes for which to retry the request. Default is - [429, 500, 502, 503]. + [409, 429, 500, 502, 503, 504]. You can also set this via the environment variable `LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers. From 057a39a1c70e15c78461bb7e3db8cef4c067cd3e Mon Sep 17 00:00:00 2001 From: JiMyung Lee Date: Thu, 29 Oct 2026 05:03:30 +0900 Subject: [PATCH 147/180] docs: row counts in list_indices can be set for remote tables Remote list_indices fills num_indexed_rows / num_unindexed_rows from the server's enriched response and only leaves them unset for servers that do not report them. The Node and Rust documentation previously implied those fields were always unavailable for remote tables. Synchronize the generated TypeScript API reference with the Node source comments. Closes #4301 Co-authored-by: desty --- docs/src/js/interfaces/IndexConfig.md | 4 ++-- nodejs/src/table.rs | 4 ++-- rust/lancedb/src/index.rs | 5 +++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/src/js/interfaces/IndexConfig.md b/docs/src/js/interfaces/IndexConfig.md index 6622c0189..c217e38e8 100644 --- a/docs/src/js/interfaces/IndexConfig.md +++ b/docs/src/js/interfaces/IndexConfig.md @@ -100,7 +100,7 @@ optional numIndexedRows: number; The number of rows indexed, across all segments. -`undefined` for remote tables. +May be `undefined` for remote tables if the server does not report it. *** @@ -124,7 +124,7 @@ optional numUnindexedRows: number; The number of rows not yet covered by this index. -`undefined` for remote tables. +May be `undefined` for remote tables if the server does not report it. *** diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index a1410ad85..2f7d91a2a 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -879,11 +879,11 @@ pub struct IndexConfig { pub created_at: Option>, /// The number of rows indexed, across all segments. /// - /// `undefined` for remote tables. + /// May be `undefined` for remote tables if the server does not report it. pub num_indexed_rows: Option, /// The number of rows not yet covered by this index. /// - /// `undefined` for remote tables. + /// May be `undefined` for remote tables if the server does not report it. pub num_unindexed_rows: Option, /// The total size in bytes of all index files across all segments. /// diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 712a15fa0..5ce345e7e 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -497,13 +497,14 @@ pub struct IndexConfig { /// The number of rows indexed, across all segments. /// /// This is approximate and may include rows that have since been deleted. - /// `None` if unavailable (e.g. for remote tables). + /// `None` if unavailable (e.g. for remote tables whose server does not + /// report it). pub num_indexed_rows: Option, /// The number of rows in the table that are not yet covered by this index. /// /// Computed as the table's total row count minus [`Self::num_indexed_rows`]. /// Optimizing the index will fold these rows into it. `None` if unavailable - /// (e.g. for remote tables). + /// (e.g. for remote tables whose server does not report it). pub num_unindexed_rows: Option, /// The total size in bytes of all index files across all segments. /// From b4cbaf2f67f548f8b12de3a9916a741354300aba Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Wed, 28 Oct 2026 13:41:23 -0700 Subject: [PATCH 148/180] docs: show stateful class Functions The Functions page only showed a plain function, so it never said where a class's `__init__` runs. Users loading a large model need to know it is not the client: registration reads the signature and ships the source. This adds a section on class Functions: `__init__` runs once per instance on the worker, then `__call__` per row or batch and `close()` on retirement, state is per instance, and `__init__` parameters are initialization fields set per binding. The example's test asserts that registering the class does not construct it. --- docs/web-tests/py/test_function.py | 44 ++++++++++++++++++++++++++++++ docs/web/management/function.mdx | 41 ++++++++++++++++++++++++++++ docs/web/snippets/function.mdx | 4 +++ 3 files changed, 89 insertions(+) diff --git a/docs/web-tests/py/test_function.py b/docs/web-tests/py/test_function.py index f66a50aec..a89424316 100644 --- a/docs/web-tests/py/test_function.py +++ b/docs/web-tests/py/test_function.py @@ -50,6 +50,25 @@ def describe(value: float): return {"half": value / 2, "note": None} +# --8<-- [start:function_class_define] +@udf(pip=["sentence-transformers"]) +class embed: + def __init__(self, model: str = "all-MiniLM-L6-v2"): + # Runs on the worker, once per instance: only the worker needs the package. + from sentence_transformers import SentenceTransformer + + self.model = SentenceTransformer(model) + + def __call__(self, text: str) -> list[float]: + return self.model.encode(text).tolist() + + def close(self): + del self.model + + +# --8<-- [end:function_class_define] + + # A Function version as the service returns it after registration: the SDK's # shared golden reply, with the name and signature of the definition above. SERVICE_REPLY = ( @@ -166,6 +185,31 @@ def test_function_version_binds_a_column(tmp_path): table.add_columns({"doubled": application}) +def test_class_function_is_constructed_only_where_it_runs(): + # Registration reads __init__'s signature; it never constructs the class, + # so the model's package need not be installed here. + assert "sentence_transformers" not in sys.modules + signature = embed.registration_request.signature + assert [ + (field.name, field.arrow_type, field.nullable) + for field in signature.initialization + ] == [("model", "utf8", True)] + assert [(p.name, p.arrow_type) for p in signature.inputs] == [("text", "utf8")] + assert "sentence_transformers" not in sys.modules + + embedder = registered_version(embed) + # --8<-- [start:function_class_apply] + from lancedb import col + + application = embedder(text=col("text"), model="all-mpnet-base-v2") + # --8<-- [end:function_class_apply] + assert application.initialization == {"model": "all-mpnet-base-v2"} + # The default applies to an omitted field. + assert embedder(text=col("text")).initialization == {} + with pytest.raises(TypeError, match="unknown arguments"): + embedder(text=col("text"), device="cuda") + + def test_function_enterprise(monkeypatch): require_deployment() diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 6df99b5fd..fd9cb7c19 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -19,6 +19,8 @@ import { PyFunctionApply as FunctionApply, PyFunctionRefresh as FunctionRefresh, PyFunctionInspect as FunctionInspect, + PyFunctionClassDefine as FunctionClassDefine, + PyFunctionClassApply as FunctionClassApply, } from '/snippets/function.mdx'; import { PyConnectEnterprisePlaceholders as FunctionConnect } from '/snippets/connection.mdx'; @@ -143,6 +145,45 @@ rows added since the last one and recomputes rows whose inputs changed, and leaves filled rows with unchanged inputs alone. See [Refresh a column](/feature-engineering/refresh-column). +## Keep state in a class {#classes} + +A function that loads a model or opens a client should not do it for every +row. Decorate a class instead: its `__init__` does the expensive setup once, +and `__call__` handles each row or batch. + + +{FunctionClassDefine} + + +Registering the class does not construct it. `@udf` reads the signature of +`__init__` and packages the source, so the client never loads the model. On +the cluster, each instance of the function calls `__init__` once. It then calls +`__call__` for every row or batch it processes, and `close()`, if defined, once +when it retires. Import heavy packages inside `__init__`, as above, so only the +worker needs them installed, and declare them in `pip`. + +State belongs to one instance. An instance reuses it across every batch it +serves, but instances do not share it, so each one holds its own copy of the +model. Plan memory, or a GPU, for one copy per instance. + +The annotated parameters of `__init__` are the function's initialization +fields. Their values come from each binding rather than from the function, so +one registered version can run with different settings on different columns: + + +{FunctionClassApply} + + +Pass the application to `add_columns` as [above](#apply). Initialization values +are fixed for every row of a binding and take booleans, integers, floats, +strings, and lists or structs of them. A parameter with a default may be +omitted. Initialization values are stored with the binding, so keep +credentials out of them: pass `secrets=[EnvVarSecret(...)]` to +`create_function` and read the variable in `__init__`. + +Calling the decorated class in your own process constructs it, the same as an +undecorated class, so local tests can create an instance and call it directly. + ## Read and produce blobs {#blobs} A Function can bind a [Blob v2 column](/management/table#managed-blobs) and diff --git a/docs/web/snippets/function.mdx b/docs/web/snippets/function.mdx index 728810e2a..fb7f907c3 100644 --- a/docs/web/snippets/function.mdx +++ b/docs/web/snippets/function.mdx @@ -2,6 +2,10 @@ export const PyFunctionApply = "from lancedb import col\n\ntable.add_columns({\"doubled\": version(value=col(\"value\"))})\n"; +export const PyFunctionClassApply = "from lancedb import col\n\napplication = embedder(text=col(\"text\"), model=\"all-mpnet-base-v2\")\n"; + +export const PyFunctionClassDefine = "@udf(pip=[\"sentence-transformers\"])\nclass embed:\n def __init__(self, model: str = \"all-MiniLM-L6-v2\"):\n # Runs on the worker, once per instance: only the worker needs the package.\n from sentence_transformers import SentenceTransformer\n\n self.model = SentenceTransformer(model)\n\n def __call__(self, text: str) -> list[float]:\n return self.model.encode(text).tolist()\n\n def close(self):\n del self.model\n"; + export const PyFunctionConnect = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n uri=os.environ[\"LANCEDB_URI\"], # db://your-database\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ.get(\"LANCEDB_REGION\", \"us-east-1\"),\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"],\n)\n"; export const PyFunctionCreateTable = "import pyarrow as pa\n\nschema = pa.schema([pa.field(\"value\", pa.float64(), nullable=False)])\ntable = db.create_table(\n \"function_demo\",\n [{\"value\": 1.0}, {\"value\": 2.0}, {\"value\": 3.0}],\n schema=schema,\n)\n"; From 4d7a64712f7fbe39bffaf110f3eb790943bd7874 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Wed, 28 Oct 2026 14:04:41 -0700 Subject: [PATCH 149/180] docs: adopt Embedded/Distributed terminology across docs and SDKs (#4713) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Adopts the product terminology guide across the docs site pages, SDK docstrings and error messages. "LanceDB OSS" and local mode become **LanceDB Embedded**. "Remote" as the execution model becomes **LanceDB Distributed**, which LanceDB Enterprise provides. Where free vs paid is the point, pages contrast "LanceDB Embedded (open source)" with "LanceDB Enterprise". This is a first trial of the Embedded name, so reviewers can judge it in context. - **Embedded vs Distributed** for where execution runs (`optimize()`, consistency, branching, maintenance). Main pages define it once: "LanceDB Enterprise runs LanceDB Distributed: …" - **LanceDB Cloud** is kept only for legacy-Cloud specifics (`db://` region, the brute-force KNN limit) and marked legacy. "Cloud and Enterprise" becomes Enterprise or Distributed. - **Plan executor** becomes "executor" or the fleet name. - **Error messages** change, e.g. `optimize is not supported for remote tables.` → `... in LanceDB Distributed.` Tests that match on them are updated. - **Vale rules** (`EmbeddedName`, `OSSProduct`, `RemoteExecution`, `DistributedEnterprise`, `LegacyCloud`, `InternalNames`) enforce the terms in prose. Unchanged: identifiers (`availability.oss`, the `remote` module and feature, `RemoteTable`, `db://`), heading anchors, internal code comments, and Geneva. ## Evidence - Rust lib tests for the changed messages and the Python tests in `test_remote_db.py`, `test_materialized_views.py` and `test_table.py` pass locally. - Not run locally: - The Node tests: `remote.test.ts` and `table.test.ts` have updated assertions. - Vale. - The `experimental_functions`-marked materialized-view tests. - `docs/src` API reference was hand-edited to match the docstrings rather than regenerated. ## Merge Risk **Door:** two-way; prose and message text only. **Blast Radius:** `docs`, `error-messages`: callers matching on old error strings would break. Companion PRs: lancedb/docs (assembler labels, STYLE.md) and sophon (Enterprise pages). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .claude-plugin/marketplace.json | 2 +- .github/vale/README.md | 12 +- .../styles/LanceDB/DistributedEnterprise.yml | 19 +++ .github/vale/styles/LanceDB/EmbeddedName.yml | 22 ++++ .github/vale/styles/LanceDB/InternalNames.yml | 25 ++++ .github/vale/styles/LanceDB/LegacyCloud.yml | 21 ++++ .github/vale/styles/LanceDB/OSSProduct.yml | 28 +++++ .github/vale/styles/LanceDB/ProductNames.yml | 1 - .../vale/styles/LanceDB/RemoteExecution.yml | 33 ++++++ CONTRIBUTING.md | 15 +-- README.md | 4 +- docs/openapi.yml | 6 +- docs/src/java/java.md | 12 +- docs/src/js/classes/Connection.md | 6 +- docs/src/js/classes/Table.md | 27 ++--- docs/src/js/functions/connect.md | 10 +- docs/src/js/functions/connectNamespace.md | 2 +- docs/src/js/interfaces/AddDataOptions.md | 4 +- docs/src/js/interfaces/ClientConfig.md | 2 +- docs/src/js/interfaces/ConnectionOptions.md | 20 ++-- docs/src/js/interfaces/IndexConfig.md | 20 ++-- .../RefreshMaterializedViewResult.md | 6 +- docs/src/js/type-aliases/BlobReadOptions.md | 2 +- docs/src/python/python.md | 34 +++--- docs/web/agent-branch-experiments.mdx | 6 +- docs/web/api-reference/rest/index.mdx | 2 +- docs/web/architecture.mdx | 30 ++--- docs/web/basics/agentic-skills.mdx | 16 +-- docs/web/basics/connect.mdx | 17 +-- docs/web/basics/guarantees.mdx | 4 +- docs/web/basics/jobs.mdx | 13 ++- docs/web/basics/lakehouse.mdx | 2 +- docs/web/basics/lance.mdx | 4 +- docs/web/basics/naming.mdx | 2 +- docs/web/basics/offerings.mdx | 13 ++- docs/web/basics/query.mdx | 2 +- docs/web/basics/sdk.mdx | 17 +-- docs/web/basics/sql.mdx | 8 +- docs/web/curation/index.mdx | 4 +- docs/web/curation/sampling.mdx | 4 +- docs/web/deployment/monitoring.mdx | 4 +- docs/web/deployment/storage.mdx | 4 +- docs/web/deployment/support.mdx | 4 +- docs/web/embedding/index.mdx | 8 +- docs/web/embedding/quickstart.mdx | 8 +- docs/web/enterprise/authentication.mdx | 4 +- docs/web/enterprise/deployment/index.mdx | 2 +- docs/web/enterprise/distributed-search.mdx | 8 +- docs/web/enterprise/index.mdx | 2 +- docs/web/enterprise/security.mdx | 2 +- .../add-computed-column.mdx | 4 +- docs/web/feature-engineering/index.mdx | 6 +- .../materialized-views.mdx | 8 +- .../feature-engineering/refresh-column.mdx | 10 +- docs/web/governance/authorization.mdx | 2 +- docs/web/index.mdx | 15 ++- docs/web/indexing/fts-index.mdx | 2 +- docs/web/indexing/reindexing.mdx | 8 +- docs/web/indexing/vector-index.mdx | 8 +- docs/web/ingestion/create-table.mdx | 2 +- docs/web/ingestion/delete.mdx | 4 +- docs/web/ingestion/index.mdx | 4 +- docs/web/ingestion/insert.mdx | 8 +- docs/web/ingestion/merge-insert.mdx | 4 +- docs/web/ingestion/update.mdx | 4 +- docs/web/integrations/ai/agno.mdx | 2 +- docs/web/integrations/ai/hermes-agent.mdx | 2 +- docs/web/integrations/data/dlt.mdx | 4 +- docs/web/integrations/data/duckdb.mdx | 2 +- docs/web/integrations/data/polars_arrow.mdx | 2 +- docs/web/maintenance/background-jobs.mdx | 2 +- docs/web/maintenance/cleanup.mdx | 7 +- docs/web/maintenance/compaction.mdx | 10 +- docs/web/management/database.mdx | 26 +++-- docs/web/management/function.mdx | 13 ++- docs/web/management/materialized-view.mdx | 4 +- docs/web/management/namespace.mdx | 6 +- docs/web/management/table.mdx | 17 +-- docs/web/quickstart.mdx | 5 +- docs/web/reranking/index.mdx | 2 +- docs/web/search/explain.mdx | 19 +-- docs/web/search/filtering.mdx | 2 +- docs/web/search/full-text-search.mdx | 10 +- docs/web/search/hybrid-search.mdx | 8 +- docs/web/search/index.mdx | 8 +- docs/web/search/vector-search.mdx | 6 +- .../images/overview/lancedb-architecture.svg | 6 +- .../assets/images/overview/lancedb-suite.svg | 4 +- docs/web/tables/branching.mdx | 12 +- docs/web/tables/consistency.mdx | 14 ++- docs/web/training/data-loading.mdx | 2 +- docs/web/training/torch.mdx | 6 +- .../agents/nvidia-rag-blueprint/index.mdx | 4 +- java/README.md | 6 +- .../LanceDbNamespaceClientBuilder.java | 2 +- .../java/com/lancedb/LanceDbRestClient.java | 2 +- .../java/com/lancedb/LanceDbTableRTE.java | 2 +- nodejs/__test__/remote.test.ts | 12 +- nodejs/__test__/table.test.ts | 8 +- nodejs/lancedb/blob.ts | 2 +- nodejs/lancedb/connection.ts | 6 +- nodejs/lancedb/header.ts | 2 +- nodejs/lancedb/index.ts | 12 +- nodejs/lancedb/table.ts | 31 ++--- nodejs/src/lib.rs | 20 ++-- nodejs/src/remote.rs | 2 +- nodejs/src/table.rs | 31 ++--- python/python/lancedb/__init__.py | 50 ++++---- python/python/lancedb/db.py | 81 +++++++------ python/python/lancedb/functions.py | 8 +- python/python/lancedb/index.py | 10 +- python/python/lancedb/materialized_view.py | 25 ++-- python/python/lancedb/namespace.py | 2 +- python/python/lancedb/permutation.py | 4 +- python/python/lancedb/query.py | 17 +-- python/python/lancedb/remote/__init__.py | 4 +- python/python/lancedb/remote/db.py | 28 +++-- python/python/lancedb/remote/header.py | 2 +- python/python/lancedb/remote/table.py | 42 +++---- python/python/lancedb/sql.py | 2 +- python/python/lancedb/table.py | 109 ++++++++++-------- .../python/tests/test_materialized_views.py | 6 +- python/python/tests/test_remote_db.py | 20 ++-- python/python/tests/test_remote_options.py | 12 +- python/python/tests/test_table.py | 4 +- python/src/table.rs | 6 +- rust/lancedb/src/blob.rs | 14 +-- rust/lancedb/src/connection.rs | 104 +++++++++-------- rust/lancedb/src/connection/create_table.rs | 4 +- rust/lancedb/src/database.rs | 4 +- rust/lancedb/src/database/listing.rs | 2 +- rust/lancedb/src/function.rs | 4 +- rust/lancedb/src/index.rs | 20 ++-- rust/lancedb/src/lib.rs | 12 +- rust/lancedb/src/materialized_view.rs | 22 ++-- rust/lancedb/src/materialized_view/refresh.rs | 6 +- rust/lancedb/src/query.rs | 8 +- rust/lancedb/src/remote.rs | 2 +- rust/lancedb/src/remote/client.rs | 5 +- rust/lancedb/src/remote/db.rs | 26 +++-- rust/lancedb/src/remote/oauth.rs | 2 +- rust/lancedb/src/remote/table.rs | 38 +++--- rust/lancedb/src/sql.rs | 2 +- rust/lancedb/src/table.rs | 57 +++++---- rust/lancedb/src/table/add_columns.rs | 8 +- rust/lancedb/src/table/add_data.rs | 2 +- rust/lancedb/src/table/computed_columns.rs | 4 +- rust/lancedb/src/table/refresh.rs | 3 +- 148 files changed, 981 insertions(+), 755 deletions(-) create mode 100644 .github/vale/styles/LanceDB/DistributedEnterprise.yml create mode 100644 .github/vale/styles/LanceDB/EmbeddedName.yml create mode 100644 .github/vale/styles/LanceDB/InternalNames.yml create mode 100644 .github/vale/styles/LanceDB/LegacyCloud.yml create mode 100644 .github/vale/styles/LanceDB/OSSProduct.yml create mode 100644 .github/vale/styles/LanceDB/RemoteExecution.yml diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index bfc6290db..f5d93eb0a 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -8,7 +8,7 @@ { "name": "lancedb", "source": "./plugins/lancedb", - "description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work across local LanceDB OSS tables and remote LanceDB Enterprise/Cloud tables.", + "description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work with both LanceDB Embedded and LanceDB Enterprise.", "version": "0.1.0", "author": { "name": "LanceDB" diff --git a/.github/vale/README.md b/.github/vale/README.md index ad0573fdb..2cfbd1633 100644 --- a/.github/vale/README.md +++ b/.github/vale/README.md @@ -1,8 +1,16 @@ # LanceDB prose rules -These five rule files are copied unchanged from the `LanceDB.zip` asset of -`lancedb/docs` release `vale-lancedb-v0.1.0`. The archive SHA-256 is +`Dashes`, `PlainLanguage`, `ProductNames`, `VagueHeadings` and `VaguePhrases` +come from the `LanceDB.zip` asset of `lancedb/docs` release +`vale-lancedb-v0.1.0`, whose archive SHA-256 is `0730a43e919774121068811d5687c61dfc7a0421cff78e1393f5e565b622cb0f`. +`ProductNames` no longer swaps in "LanceDB OSS". + +The product-terminology rules were added here: `EmbeddedName`, +`RemoteExecution`, `OSSProduct`, `DistributedEnterprise`, `InternalNames` +(warnings) and `LegacyCloud` (suggestion). They enforce the names in the +docs repository's `STYLE.md#names`. Run every rule's tests from +`.github/vale` with `vale test --coverage styles`. Keeping the rules here lets contributors and CI run Vale without access to the source repository. The root `.vale.ini` preserves the release's MDX settings diff --git a/.github/vale/styles/LanceDB/DistributedEnterprise.yml b/.github/vale/styles/LanceDB/DistributedEnterprise.yml new file mode 100644 index 000000000..813d10375 --- /dev/null +++ b/.github/vale/styles/LanceDB/DistributedEnterprise.yml @@ -0,0 +1,19 @@ +extends: existence +message: "'%s' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +level: warning +ignorecase: false +tokens: + - 'Distributed(?:\s+(?:and|or)\s+|\s*/\s*)(?:LanceDB\s+)?Enterprise' + - 'Enterprise(?:\s+(?:and|or)\s+|\s*/\s*)(?:LanceDB\s+)?Distributed' +tests: + - name: flags Distributed and Enterprise side by side + input: Choose Distributed or Enterprise. LanceDB Enterprise and LanceDB Distributed differ, and so does Distributed/Enterprise. + want: | + 1:8:LanceDB.DistributedEnterprise:'Distributed or Enterprise' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both. + 1:43:LanceDB.DistributedEnterprise:'Enterprise and LanceDB Distributed' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both. + 1:98:LanceDB.DistributedEnterprise:'Distributed/Enterprise' reads as two products. LanceDB Enterprise provides LanceDB Distributed: name the product or the execution model, not both. + - name: leaves the defining sentence and the Embedded pair alone + input: | + LanceDB Enterprise runs LanceDB Distributed. Compare Embedded and Distributed execution. Distributed search and enterprise teams are fine. + want: '' diff --git a/.github/vale/styles/LanceDB/EmbeddedName.yml b/.github/vale/styles/LanceDB/EmbeddedName.yml new file mode 100644 index 000000000..a372c8a04 --- /dev/null +++ b/.github/vale/styles/LanceDB/EmbeddedName.yml @@ -0,0 +1,22 @@ +extends: substitution +message: "Use '%s' instead of '%s'." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +level: warning +ignorecase: false +# The in-process execution model is LanceDB Embedded, whether the data is on +# local disk or in object storage. Identifiers such as the `oss` product key +# are code, and code is never prose. +swap: + 'LanceDB\s+(?:OSS|Oss|oss|Local|local)': LanceDB Embedded + '[Ll]ocal\s+mode': LanceDB Embedded +tests: + - name: replaces the old names of the execution model + input: Start with LanceDB OSS, also called LanceDB Local, and move off local mode later. + want: | + 1:12:LanceDB.EmbeddedName:Use 'LanceDB Embedded' instead of 'LanceDB OSS'. + 1:37:LanceDB.EmbeddedName:Use 'LanceDB Embedded' instead of 'LanceDB Local'. + 1:65:LanceDB.EmbeddedName:Use 'LanceDB Embedded' instead of 'local mode'. + - name: leaves the current name, other uses of local, and code alone + input: | + LanceDB Embedded reads local disk or object storage. Run LanceDB locally, set `availability.oss`, or call `LanceDB OSS` in a literal. + want: '' diff --git a/.github/vale/styles/LanceDB/InternalNames.yml b/.github/vale/styles/LanceDB/InternalNames.yml new file mode 100644 index 000000000..0818090e1 --- /dev/null +++ b/.github/vale/styles/LanceDB/InternalNames.yml @@ -0,0 +1,25 @@ +extends: substitution +message: "Use '%s' instead of the internal name '%s'." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +level: warning +ignorecase: false +# Internal component names stay out of public text. Environment variables such +# as `PHALANX_*` and Helm keys such as `planExecutorNodes` are code. Geneva is +# a product name and is not listed. +swap: + Phalanx: query node + '[Pp]lan\s+[Ee]xecutor': executor + '[Pp]lan\s+[Ee]xecutors': executors + Sophon: LanceDB Enterprise +tests: + - name: replaces internal component names + input: Phalanx sends work to a Plan Executor. Plan executors cache data in Sophon. + want: | + 1:1:LanceDB.InternalNames:Use 'query node' instead of the internal name 'Phalanx'. + 1:25:LanceDB.InternalNames:Use 'executor' instead of the internal name 'Plan Executor'. + 1:40:LanceDB.InternalNames:Use 'executors' instead of the internal name 'Plan executors'. + 1:69:LanceDB.InternalNames:Use 'LanceDB Enterprise' instead of the internal name 'Sophon'. + - name: leaves Geneva, configuration keys and code alone + input: | + Geneva runs on the executor + cache fleet. Set `PHALANX_REMOTE_FTS_SCORER` and `planExecutorNodes`. + want: '' diff --git a/.github/vale/styles/LanceDB/LegacyCloud.yml b/.github/vale/styles/LanceDB/LegacyCloud.yml new file mode 100644 index 000000000..668f66011 --- /dev/null +++ b/.github/vale/styles/LanceDB/LegacyCloud.yml @@ -0,0 +1,21 @@ +extends: existence +message: "'%s' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +level: suggestion +ignorecase: false +# A suggestion, because `db://` URIs, `api_key` and `region` for the hosted +# service are still documented as LanceDB Cloud. +tokens: + - 'LanceDB\s+Cloud' + - 'Cloud\s*/\s*Enterprise' + - 'Enterprise\s*/\s*Cloud' +tests: + - name: suggests checking each LanceDB Cloud mention + input: Connect to LanceDB Cloud with an API key. Cloud/Enterprise users get the cache. + want: | + 1:12:LanceDB.LegacyCloud:'LanceDB Cloud' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'. + 1:43:LanceDB.LegacyCloud:'Cloud/Enterprise' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise' or 'LanceDB Distributed'. + - name: leaves other clouds and code alone + input: | + Deploy into your own cloud account on Google Cloud. Pass `LanceDB Cloud` as a literal. + want: '' diff --git a/.github/vale/styles/LanceDB/OSSProduct.yml b/.github/vale/styles/LanceDB/OSSProduct.yml new file mode 100644 index 000000000..248129208 --- /dev/null +++ b/.github/vale/styles/LanceDB/OSSProduct.yml @@ -0,0 +1,28 @@ +extends: existence +message: "Avoid '%s'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +level: warning +ignorecase: false +# Bare OSS used as a product, as in "OSS and Enterprise" or "in OSS". "LanceDB +# OSS" is reported by LanceDB.EmbeddedName. +tokens: + - 'OSS(?:\s+(?:and|or|vs\.?|versus)\s+|\s*/\s*)(?:LanceDB\s+)?Enterprise' + - 'Enterprise(?:\s+(?:and|or|vs\.?|versus)\s+|\s*/\s*)OSS' + - '(?:in|on|from|using|than)\s+OSS' +tests: + - name: flags OSS presented as a product + input: Compare OSS vs Enterprise. It works in OSS and on OSS, unlike OSS/Enterprise. + want: | + 1:9:LanceDB.OSSProduct:Avoid 'OSS vs Enterprise'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property. + 1:37:LanceDB.OSSProduct:Avoid 'in OSS'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property. + 1:48:LanceDB.OSSProduct:Avoid 'on OSS'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property. + 1:63:LanceDB.OSSProduct:Avoid 'OSS/Enterprise'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property. + - name: flags the pair in either order + input: Both OSS and LanceDB Enterprise ship it, as do Enterprise or OSS. + want: | + 1:6:LanceDB.OSSProduct:Avoid 'OSS and LanceDB Enterprise'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property. + 1:48:LanceDB.OSSProduct:Avoid 'Enterprise or OSS'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property. + - name: leaves open source, identifiers and code alone + input: | + LanceDB Embedded (open source) and LanceDB Enterprise share the format. Set `oss: available` or read `in OSS` literally. + want: '' diff --git a/.github/vale/styles/LanceDB/ProductNames.yml b/.github/vale/styles/LanceDB/ProductNames.yml index e4621a521..2122679ef 100644 --- a/.github/vale/styles/LanceDB/ProductNames.yml +++ b/.github/vale/styles/LanceDB/ProductNames.yml @@ -9,7 +9,6 @@ swap: '(?:Lancedb|LanceDb|lanceDB|LANCEDB|Lance DB)': LanceDB 'LanceDB (?:cloud|CLOUD)': LanceDB Cloud 'LanceDB (?:enterprise|ENTERPRISE)': LanceDB Enterprise - 'LanceDB (?:oss|Oss)': LanceDB OSS '(?:HuggingFace|Huggingface|Hugging face)': Hugging Face Langchain: LangChain Typescript: TypeScript diff --git a/.github/vale/styles/LanceDB/RemoteExecution.yml b/.github/vale/styles/LanceDB/RemoteExecution.yml new file mode 100644 index 000000000..dc450993b --- /dev/null +++ b/.github/vale/styles/LanceDB/RemoteExecution.yml @@ -0,0 +1,33 @@ +extends: existence +message: "Avoid '%s'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product." +link: https://github.com/lancedb/docs/blob/main/STYLE.md#names +level: warning +ignorecase: false +# Remote storage, remote URLs and a git remote are other things and stay. Class +# names such as `RemoteTable` are code, and code is never prose. +tokens: + - '[Rr]emote\s+(?:mode|tables?|connections?|databases?)' +tests: + - name: flags remote as the execution model + input: In remote mode, a remote table is opened through a remote connection. + want: | + 1:4:LanceDB.RemoteExecution:Avoid 'remote mode'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + 1:19:LanceDB.RemoteExecution:Avoid 'remote table'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + 1:52:LanceDB.RemoteExecution:Avoid 'remote connection'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + - name: flags plurals and a heading + input: | + ## Remote tables + + Remote databases hold remote tables. + want: | + 1:4:LanceDB.RemoteExecution:Avoid 'Remote tables'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + 3:1:LanceDB.RemoteExecution:Avoid 'Remote databases'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + 3:23:LanceDB.RemoteExecution:Avoid 'remote tables'. Write 'LanceDB Distributed' for the execution model or 'LanceDB Enterprise' for the product. + - name: leaves other remotes and code alone + input: | + Push to the git remote, read remote storage and fetch a remote URL. `open_table` returns a `RemoteTable`; see `remote table` in the API. + + ```python + remote_table = db.open_table("remote table") + ``` + want: '' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b7ecc16bb..c3bf61471 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,7 +72,7 @@ are wrappers around the Rust library. * `node`: **Deprecated** Typescript package source code * `java`: Java package source code * `docs/src`: SDK reference, built with mkdocs -* `docs/web`: website guides for LanceDB OSS and the APIs used by both OSS and Enterprise +* `docs/web`: website guides for LanceDB Embedded and the APIs used by both Embedded and Distributed * `docs/web-tests`: the tests the documentation's code examples are extracted from ## Documentation @@ -83,14 +83,14 @@ it is ready for readers. ### Choose the right place -- `docs/web/` holds website guides for LanceDB OSS and the APIs used by both - OSS and Enterprise. +- `docs/web/` holds website guides for LanceDB Embedded and the APIs used by both + Embedded and Distributed. - `docs/src/` holds the SDK reference. See [docs/README.md](docs/README.md) for its build and API-generation instructions. - `docs/web-tests/` and `rust/lancedb/tests/` hold tests used to generate the website's code examples. -Document SDK APIs here, and explain which operations work in OSS and Enterprise. +Document SDK APIs here, and explain which operations work in Embedded and Distributed. Put Enterprise-specific deployment and operating instructions in the Enterprise documentation. @@ -150,7 +150,8 @@ example. ### Say where a feature works Use `availability` in a page's frontmatter to describe the support covered by -that page. Each product is either `available` or `unavailable`; use the summary +that page. Each product (`oss` for LanceDB Embedded, `enterprise` for LanceDB +Enterprise) is either `available` or `unavailable`; use the summary and body for setup requirements, SDK differences and unsupported operations. For example, a page about signing in to Enterprise could declare: @@ -159,8 +160,8 @@ availability: oss: unavailable enterprise: available summary: >- - These sign-in instructions apply to LanceDB Enterprise. Embedded - LanceDB has no server to sign in to. + These sign-in instructions apply to LanceDB Enterprise. LanceDB + Embedded has no server to sign in to. ``` Check these claims with the feature owner. Don't use `varies`, treat an API diff --git a/README.md b/README.md index 7bf5d39fc..ea9431298 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ LanceDB is a central location where developers can build, train and analyze thei - **Advanced Features**: Zero-copy, automatic versioning, manage versions of your data without needing extra infrastructure. GPU support in building vector index. ### **Products**: -- **Open Source & Local**: 100% open source, runs locally or in your cloud. No vendor lock-in. -- **Cloud and Enterprise**: Production-scale vector search with no servers to manage. Complete data sovereignty and security. +- **LanceDB Embedded (open source)**: 100% open source, runs in your application's process; your data can live on local disk or in object storage. No vendor lock-in. +- **LanceDB Enterprise**: Production-scale distributed search, indexing, and maintenance. Plus, complete data sovereignty and security. ### **Ecosystem**: - **Columnar Storage**: Built on the Lance columnar format for efficient storage and analytics. diff --git a/docs/openapi.yml b/docs/openapi.yml index e619aa038..0eb5e02b8 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -1,9 +1,9 @@ openapi: 3.1.0 info: version: 1.0.0 - title: LanceDB Cloud API + title: LanceDB REST API description: | - LanceDB Cloud API is a RESTful API that allows users to access and modify data stored in LanceDB Cloud. + The LanceDB REST API is a RESTful API that allows users to access and modify data stored in LanceDB Enterprise or LanceDB Cloud (legacy). Table actions are considered temporary resource creations and all use POST method. contact: name: LanceDB support @@ -12,7 +12,7 @@ info: servers: - url: https://{db}.{region}.api.lancedb.com - description: LanceDB Cloud REST endpoint. + description: LanceDB Cloud (legacy) REST endpoint. For LanceDB Enterprise, use your deployment's endpoint. variables: db: default: "" diff --git a/docs/src/java/java.md b/docs/src/java/java.md index ed0ec9dd4..4bac3f752 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -1,10 +1,10 @@ # Java SDK -The LanceDB Java SDK provides a convenient way to interact with LanceDB Cloud and Enterprise deployments using the Lance REST Namespace API. +The LanceDB Java SDK provides a convenient way to interact with LanceDB Enterprise deployments using the Lance REST Namespace API. !!! note - The Java SDK currently only works for LanceDB remote database that connects to LanceDB Cloud and Enterprise. - Local database support is a work in progress. Check [LANCEDB-2848](https://github.com/lancedb/lancedb/issues/2848) for the latest progress. + The Java SDK currently only works with LanceDB Distributed, connecting to LanceDB Enterprise or LanceDB Cloud (legacy). + LanceDB Embedded support is a work in progress. Check [LANCEDB-2848](https://github.com/lancedb/lancedb/issues/2848) for the latest progress. ## Installation @@ -20,7 +20,7 @@ Add the following dependency to your `pom.xml`: ## Quick Start -### Connecting to LanceDB Cloud +### Connecting to LanceDB Cloud (legacy) ```java import com.lancedb.LanceDbNamespaceClientBuilder; @@ -51,8 +51,8 @@ LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder() |--------|-------------|----------| | `apiKey(String)` | LanceDB API key | Yes | | `database(String)` | Database name | Yes | -| `endpoint(String)` | Custom endpoint URL for Enterprise deployments | No | -| `region(String)` | AWS region (default: "us-east-1") | No | +| `endpoint(String)` | Custom endpoint URL for LanceDB Enterprise deployments | No | +| `region(String)` | LanceDB Cloud (legacy) region (default: "us-east-1") | No | | `config(String, String)` | Additional configuration parameters | No | ### Opening a Table with Vended Credentials diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 2496bc2a9..14f283cc9 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -180,9 +180,9 @@ abstract createMaterializedView( Define a materialized view named `name` over the table `source`. -Local creation and refresh require a source build with the +LanceDB Embedded creation and refresh require a source build with the `experimental-functions` Cargo feature, disabled in published packages. -Remote Cloud/Enterprise operations do not require this feature. +LanceDB Distributed operations do not require this feature. The view is populated before creation returns. Set `withNoData` to create only its definition and empty backing table. The view is a normal table: @@ -827,7 +827,7 @@ abstract renameTable( Rename a table. -Currently only supported by LanceDB Cloud. Local OSS connections and +Currently only supported in LanceDB Distributed. LanceDB Embedded connections and namespace-backed connections (via [connectNamespace](../functions/connectNamespace.md)) reject with a "not supported" error. diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index ded04d4c8..b1929019c 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -69,9 +69,9 @@ abstract addColumns(newColumnTransforms): Promise Add new columns with defined values. -Local computed-column declaration and refresh require a source build with -the `experimental-functions` Cargo feature. Published packages disable it; -remote Cloud/Enterprise operations remain available. +LanceDB Embedded computed-column declaration and refresh require a source +build with the `experimental-functions` Cargo feature. Published packages +disable it; LanceDB Distributed operations remain available. The `{ computed }` form stores the expression rather than evaluating it now: the column is committed with no values, and rows get them from @@ -83,7 +83,7 @@ computed, so a mutated input is reflected by the next refresh. While a declaration reads a column, that column cannot be renamed, retyped or dropped. -On LanceDB Cloud and Enterprise the expression is planned by the +In LanceDB Distributed the expression is planned by the server, and the refresh runs as a server job -- see [Table#refreshColumnAsync](Table.md#refreshcolumnasync). @@ -679,7 +679,7 @@ The per-row errors Function refreshes recorded on this table. A refresh running under a skip policy records each row it skipped with the input that failed and the error. This lists those records, newest job first, plus a summary for any fragment whose per-row detail was -capped. LanceDB Cloud and Enterprise only; reading errors needs read +capped. LanceDB Distributed only; reading errors needs read access to the table, since a message carries the value that failed. #### Parameters @@ -932,7 +932,7 @@ Prewarm one or more columns of data in the table. Prewarming is generally useful for columns used in filters or projections. Large columns (e.g. high-dimensional vectors or binary data) may not be practical to prewarm. - This feature is currently only supported on remote tables. + This feature is currently only supported in LanceDB Distributed. #### Returns @@ -1043,8 +1043,8 @@ Local refresh requires a source build with `experimental-functions`. Rows appended since the last refresh are filled by the next one, and rows whose inputs changed since they were computed are recomputed; -everything else is left as it is. Local tables only: a remote refresh -runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). +everything else is left as it is. LanceDB Embedded only: in LanceDB +Distributed a refresh runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). #### Parameters @@ -1068,14 +1068,15 @@ abstract refreshColumnAsync(column): Promise Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh job instead of blocking until it completes. -Local refresh requires a source build with `experimental-functions`. -Remote Cloud/Enterprise jobs do not require this feature. +LanceDB Embedded refresh requires a source build with +`experimental-functions`. LanceDB Distributed jobs do not require this +feature. The job may already be complete when returned; callers must not assume the column is filled until [Job.wait](Job.md#wait) resolves. Invalid input -- an unknown column, or one that is not computed -- rejects here rather -than failing the job. On local tables the job runs in-process; on -LanceDB Cloud and Enterprise it is the server's backfill job. +than failing the job. In LanceDB Embedded the job runs in-process; in +LanceDB Distributed it is the server's backfill job. #### Parameters @@ -1304,7 +1305,7 @@ Tokenize a full-text search query using the tokenizer configured on an FTS index Specify exactly one of `column` or `indexName`. Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in -the client process from index metadata. For remote tables, this means the +the client process from index metadata. In LanceDB Distributed, this means the same tokenizer model files must also exist locally (under `LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may differ from what the diff --git a/docs/src/js/functions/connect.md b/docs/src/js/functions/connect.md index 009b7d785..5cfd11a71 100644 --- a/docs/src/js/functions/connect.md +++ b/docs/src/js/functions/connect.md @@ -20,15 +20,15 @@ Connect to a LanceDB instance at the given URI. Accepted formats: -- `/path/to/database` - local database +- `/path/to/database` - database on the local file system - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage -- `db://host:port` - remote database (LanceDB cloud) +- `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database ### Parameters * **uri**: `string` The uri of the database. If the database uri starts - with `db://` then it connects to a remote database. + with `db://` then it connects to LanceDB Enterprise or LanceDB Cloud (legacy). * **options?**: `Partial`<[`ConnectionOptions`](../interfaces/ConnectionOptions.md)> The options to use when connecting to the database @@ -80,9 +80,9 @@ Connect to a LanceDB instance at the given URI. Accepted formats: -- `/path/to/database` - local database +- `/path/to/database` - database on the local file system - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage -- `db://host:port` - remote database (LanceDB cloud) +- `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database ### Parameters diff --git a/docs/src/js/functions/connectNamespace.md b/docs/src/js/functions/connectNamespace.md index d49a8ced7..7f0ddb972 100644 --- a/docs/src/js/functions/connectNamespace.md +++ b/docs/src/js/functions/connectNamespace.md @@ -18,7 +18,7 @@ function connectNamespace( Connect to a LanceDB database through a namespace. Unlike [connect](connect.md), which routes by URI scheme (local path vs. -`db://` cloud), `connectNamespace` always returns a namespace-backed +`db://`), `connectNamespace` always returns a namespace-backed connection. The `implName` selects the namespace implementation: - `"dir"` — directory namespace, configured with [DirNamespaceConfig](../interfaces/DirNamespaceConfig.md). diff --git a/docs/src/js/interfaces/AddDataOptions.md b/docs/src/js/interfaces/AddDataOptions.md index eb10fdb0f..26c5ccef8 100644 --- a/docs/src/js/interfaces/AddDataOptions.md +++ b/docs/src/js/interfaces/AddDataOptions.md @@ -18,8 +18,8 @@ optional allowExternalBlobOutsideBases: boolean; Whether blob URIs outside registered external bases may be written. -Defaults to `false`. This option is supported only for local/native -tables; remote tables return an error when it is enabled. An enabled write +Defaults to `false`. This option is supported only in LanceDB Embedded; +LanceDB Distributed returns an error when it is enabled. An enabled write stores the absolute URI reference without registering a base or copying the external object into the database. The object must remain accessible when the blob is read later. diff --git a/docs/src/js/interfaces/ClientConfig.md b/docs/src/js/interfaces/ClientConfig.md index d5ce32117..cc075ceed 100644 --- a/docs/src/js/interfaces/ClientConfig.md +++ b/docs/src/js/interfaces/ClientConfig.md @@ -80,7 +80,7 @@ optional userId: string; User identifier for tracking purposes. -This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. +This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise. It can be set directly, or via the `LANCEDB_USER_ID` environment variable. Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment variable that contains the user ID value. diff --git a/docs/src/js/interfaces/ConnectionOptions.md b/docs/src/js/interfaces/ConnectionOptions.md index 42f80f077..04cbff0ea 100644 --- a/docs/src/js/interfaces/ConnectionOptions.md +++ b/docs/src/js/interfaces/ConnectionOptions.md @@ -14,7 +14,7 @@ optional apiKey: string; ``` -(For LanceDB cloud only): the API key to use with LanceDB Cloud. +(For LanceDB Enterprise or LanceDB Cloud only): the API key to use. Can also be set via the environment variable `LANCEDB_API_KEY`. @@ -26,7 +26,7 @@ Can also be set via the environment variable `LANCEDB_API_KEY`. optional clientConfig: ClientConfig; ``` -(For LanceDB cloud only): configuration for the remote HTTP client. +(For LanceDB Enterprise or LanceDB Cloud only): configuration for the HTTP client. *** @@ -36,8 +36,8 @@ optional clientConfig: ClientConfig; optional hostOverride: string; ``` -(For LanceDB cloud only): the host to use for LanceDB cloud. Used -for testing purposes. +(For LanceDB Enterprise only): the host of the LanceDB Enterprise +deployment to connect to. *** @@ -47,7 +47,7 @@ for testing purposes. optional manifestEnabled: boolean; ``` -(For LanceDB OSS only): use directory namespace manifests as the source +(For LanceDB Embedded only): use directory namespace manifests as the source of truth for table metadata. Existing directory-listed root tables are migrated into the manifest on access. @@ -59,7 +59,7 @@ migrated into the manifest on access. optional namespaceClientProperties: Record; ``` -(For LanceDB OSS only): extra properties for the backing namespace +(For LanceDB Embedded only): extra properties for the backing namespace client used by manifest-enabled native connections. *** @@ -70,7 +70,7 @@ client used by manifest-enabled native connections. optional oauthConfig: NativeOAuthConfig; ``` -(For LanceDB cloud only): OAuth configuration for IdP-based +(For LanceDB Enterprise only): OAuth configuration for IdP-based authentication (e.g., Azure Entra ID). When set, token acquisition and refresh are handled entirely in Rust. TypeScript users should pass the public `OAuthConfig` type exported from `@lancedb/lancedb`. @@ -105,7 +105,7 @@ storage, raising per-read latency and cost. optional region: string; ``` -(For LanceDB cloud only): the region to use for LanceDB cloud. +(For LanceDB Cloud only): the region to use for LanceDB Cloud (legacy). Defaults to 'us-east-1'. *** @@ -116,7 +116,7 @@ Defaults to 'us-east-1'. optional session: Session; ``` -(For LanceDB OSS only): the session to use for this connection. Holds +(For LanceDB Embedded only): the session to use for this connection. Holds shared caches and other session-specific state. *** @@ -127,6 +127,6 @@ shared caches and other session-specific state. optional storageOptions: Record; ``` -(For LanceDB OSS only): configuration for object storage. +(For LanceDB Embedded only): configuration for object storage. The available options are described at https://docs.lancedb.com/storage/ diff --git a/docs/src/js/interfaces/IndexConfig.md b/docs/src/js/interfaces/IndexConfig.md index c217e38e8..df3b81c52 100644 --- a/docs/src/js/interfaces/IndexConfig.md +++ b/docs/src/js/interfaces/IndexConfig.md @@ -31,7 +31,7 @@ optional createdAt: Date; When the index was created. -`undefined` for remote tables or indices created before timestamps were tracked. +`undefined` in LanceDB Distributed or indices created before timestamps were tracked. *** @@ -43,8 +43,8 @@ optional indexDetails: any; Index-type-specific details parsed as a JavaScript object. -Falls back to a raw string if JSON parsing fails. `undefined` for -remote tables or when details are unavailable. +Falls back to a raw string if JSON parsing fails. `undefined` in +LanceDB Distributed or when details are unavailable. *** @@ -66,7 +66,7 @@ optional indexUuid: string; The UUID of the first segment of the index. -`undefined` for remote tables, which do not yet surface this. +`undefined` in LanceDB Distributed, which does not yet surface this. *** @@ -78,7 +78,7 @@ optional indexVersion: number; The on-disk index format version. -`undefined` for remote tables. +`undefined` in LanceDB Distributed. *** @@ -100,7 +100,7 @@ optional numIndexedRows: number; The number of rows indexed, across all segments. -May be `undefined` for remote tables if the server does not report it. +May be `undefined` in LanceDB Distributed if the server does not report it. *** @@ -112,7 +112,7 @@ optional numSegments: number; The number of segments that make up the index. -`undefined` for remote tables. +`undefined` in LanceDB Distributed. *** @@ -124,7 +124,7 @@ optional numUnindexedRows: number; The number of rows not yet covered by this index. -May be `undefined` for remote tables if the server does not report it. +May be `undefined` in LanceDB Distributed if the server does not report it. *** @@ -136,7 +136,7 @@ optional sizeBytes: number; The total size in bytes of all index files across all segments. -`undefined` for remote tables or indices without size tracking. +`undefined` in LanceDB Distributed or indices without size tracking. *** @@ -148,4 +148,4 @@ optional typeUrl: string; The protobuf type URL, a precise type identifier for the index. -`undefined` for remote tables. +`undefined` in LanceDB Distributed. diff --git a/docs/src/js/interfaces/RefreshMaterializedViewResult.md b/docs/src/js/interfaces/RefreshMaterializedViewResult.md index 05321683e..e1ec3eb65 100644 --- a/docs/src/js/interfaces/RefreshMaterializedViewResult.md +++ b/docs/src/js/interfaces/RefreshMaterializedViewResult.md @@ -14,7 +14,7 @@ optional mode: string; ``` -How the view was brought up to date: "rebuild", or absent for remote SQL refreshes. +How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes. *** @@ -24,7 +24,7 @@ How the view was brought up to date: "rebuild", or absent for remote SQL refresh optional rowsWritten: number; ``` -Rows written by this refresh, or absent for remote SQL refreshes. +Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes. *** @@ -34,7 +34,7 @@ Rows written by this refresh, or absent for remote SQL refreshes. optional sourceVersion: number; ``` -Source version refreshed to, or absent for remote SQL refreshes. +Source version refreshed to, or absent for LanceDB Distributed SQL refreshes. *** diff --git a/docs/src/js/type-aliases/BlobReadOptions.md b/docs/src/js/type-aliases/BlobReadOptions.md index 17264b0e4..53184aa48 100644 --- a/docs/src/js/type-aliases/BlobReadOptions.md +++ b/docs/src/js/type-aliases/BlobReadOptions.md @@ -21,4 +21,4 @@ optional signal: AbortSignal; ``` Cancels the read. The call rejects with `signal.reason`, and the native -read stops, including in-flight requests to a remote table. +read stops, including in-flight requests to a LanceDB Distributed table. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index d42d70c4a..84188aecb 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -27,8 +27,8 @@ connect, per-table storage and write options on create, and `index_cache_size`, Omit these options to use server-managed storage and caching. Connection-level `storage_options` supported by an Enterprise deployment remain available. -The synchronous remote `create_table` uses the same positional order as the -local API: `name, data, schema, mode, exist_ok, on_bad_vectors, fill_value, +The synchronous LanceDB Distributed `create_table` uses the same positional order as the +LanceDB Embedded API: `name, data, schema, mode, exist_ok, on_bad_vectors, fill_value, embedding_functions`. Prefer keyword arguments for optional parameters. ## Connections (Synchronous) @@ -227,14 +227,14 @@ async for entry in catalog.authz.list_acls(subject=Subject.role("reader")): ## Remote SQL -Submit SQL against a remote LanceDB database through the connection. +Submit SQL against a LanceDB Distributed database through the connection. The connected database and `default_namespace_path=["public"]` are used for unqualified tables. Fully qualified references can still query other databases and namespaces available to the same deployment. `execute_query` returns a reader as soon as its initial result stream is available. `execute_query_async` returns a query handle once submission is accepted; use it to inspect progress, open a reader, or cancel the query. The SQL client is initialized by the first query and -retained for the lifetime of the remote connection. Query ids are random, +retained for the lifetime of the connection. Query ids are random, connection-scoped references rather than encoded SQL or durable resume tokens. Both APIs start with one Flight call. The server can stream results on that @@ -308,24 +308,24 @@ listing a storage directory. ## Tables (Synchronous) -Local and remote tables use the same arguments for index creation, deletion, +LanceDB Embedded and LanceDB Distributed tables use the same arguments for index creation, deletion, index statistics, and search. For example, `table.delete(where="id = 1")`, `table.create_index("cosine", 2)` (the deprecated vector API), and `table.search([1.0, 1.0], fast_search=True)` work with either backend. `fast_search=True` excludes rows that have not been indexed. `create_scalar_index` defaults to `replace=True` on both backends. Both scalar -and full-text index creation accept `wait_timeout`. Remote maintenance methods -accept the local options: cleanup and compaction warn that they are no-ops, +and full-text index creation accept `wait_timeout`. LanceDB Distributed maintenance methods +accept the LanceDB Embedded options: cleanup and compaction warn that they are no-ops, while `optimize` reports an unsupported operation. Removed Tantivy options produce the same explanatory errors on both backends. -The old remote keyword names `predicate` for `delete`, `index_name` for +The old LanceDB Distributed keyword names `predicate` for `delete`, `index_name` for `drop_index`, `index_uuid` for `index_stats`, and `column` for `create_fts_index` remain available with deprecation warnings. Use `where`, `name`, `index_name`, and `field_names`, respectively. For positional calls, use the argument order documented by `Table` below; specify index options by keyword when migrating -code that used the former remote-only argument order. +code that used the former LanceDB Distributed-only argument order. ::: lancedb.table.Table @@ -429,14 +429,14 @@ scoped to each invocation and support `read`, `readinto`, `seek`, `tell`, ## Materialized Views (Synchronous) -In the 0.41 SDK release, local materialized-view creation and refresh require a +In the 0.41 SDK release, LanceDB Embedded materialized-view creation and refresh require a source build with the `experimental-functions` Cargo feature. Published Python packages leave it disabled. Opening, reading, listing and dropping existing views -remain available, as do remote Cloud and Enterprise operations. The same feature -requirement applies to local SQL computed-column declaration and refresh; ordinary +remain available, as do LanceDB Distributed operations. The same feature +requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary eager `add_columns` transforms remain available. -On Cloud and Enterprise, creation accepts `auto_refresh_enabled` and +In LanceDB Distributed, creation accepts `auto_refresh_enabled` and `auto_refresh_interval_seconds`: ```python @@ -581,13 +581,13 @@ pylance, LanceDB uses a matching `lance.blob.v2` extension type so blob columns still work. Native table queries return descriptors. Call [`fetch_blob_files`][lancedb.table.Table.fetch_blob_files] for lazy reads or [`fetch_blobs`][lancedb.table.Table.fetch_blobs] for eager bytes. -Local tables support these fetch APIs for both legacy blob v1 columns +LanceDB Embedded supports these fetch APIs for both legacy blob v1 columns (`lance-encoding:blob`) and blob v2 columns. For legacy columns, obtain row IDs with `search().with_row_id(True).to_arrow()` and pass the result to the fetch API. One missing or deleted row ID rejects the entire blob-read batch; the APIs do not return partial results. -Remote SQL returns blob bytes by default. Select `blob_descriptor(video)` to +LanceDB Distributed SQL returns blob bytes by default. Select `blob_descriptor(video)` to return an openable reference instead, then use [`open_blob_file`][lancedb.table.Table.open_blob_file] or the lazy iterable [`open_blob_files`][lancedb.table.Table.open_blob_files]: @@ -604,7 +604,7 @@ for row in rows.to_pylist(): frame = extract_frame(video, row["timestamp"]) ``` -This example uses a remote SQL connection that produces source-bearing +This example uses a LanceDB Distributed SQL connection that produces source-bearing descriptors. The descriptor contains `kind`, `position`, `size`, `blob_id`, `blob_uri`, and a `source` struct with `uri`, `version`, `committed_at_micros`, `branch`, `column`, `row_reference`, and `row_is_address`. The opener verifies @@ -636,7 +636,7 @@ async for video in async_videos.open_blob_files(rows["video"]): ``` Payload bytes load on reads. Opening an external blob with unspecified size -can issue a metadata-only HEAD request. Remote reads use authenticated range +can issue a metadata-only HEAD request. LanceDB Distributed reads use authenticated range requests that validate the captured URI and commit timestamp. Blobs inside lists can be written and queried as descriptors. They are omitted diff --git a/docs/web/agent-branch-experiments.mdx b/docs/web/agent-branch-experiments.mdx index 3f4f1cbfa..30a3893e7 100644 --- a/docs/web/agent-branch-experiments.mdx +++ b/docs/web/agent-branch-experiments.mdx @@ -64,13 +64,13 @@ The branch experiments leave you with the results side by side, and they deliberately never touch `main`. Once you've picked a winner, apply it to `main` yourself by rerunning that experiment's validated transformation directly against the `main` table. Rerunning the reviewed operation is the -reliable path on both OSS and Enterprise: it replays exactly the transformation +reliable path on both LanceDB Embedded and LanceDB Enterprise: it replays exactly the transformation you validated on the branch, and it works the same regardless of how the branch evolved. Suppose `nomic-embed-text` wins. Rerun the same Nomic embedding transformation you validated on `embed-nomic` against `main` in batches, then call -`table.optimize()` on OSS. Verify a bounded vector search on `main`, and keep +`table.optimize()` on LanceDB Embedded. Verify a bounded vector search on `main`, and keep the losing branch around until you're confident in the result. See [Branches](/tables/branching) for more on how branches, versions, and tags @@ -96,5 +96,5 @@ branch that's isolated from `main` until you decide you want the new derived column in `main`. Once you've chosen a winner, rerun that validated transformation to ingest it into `main` -yourself, on either LanceDB OSS or Enterprise. See our documentation on [branches](/tables/branching) +yourself, on either LanceDB Embedded or LanceDB Enterprise. See our documentation on [branches](/tables/branching) for more information. diff --git a/docs/web/api-reference/rest/index.mdx b/docs/web/api-reference/rest/index.mdx index d9bb26867..d6364d92c 100644 --- a/docs/web/api-reference/rest/index.mdx +++ b/docs/web/api-reference/rest/index.mdx @@ -9,7 +9,7 @@ description: "API reference for LanceDB" is an OpenAPI protocol that enables reading, writing and managing Lance tables by connecting those metadata services or building a custom metadata server in a standardized way. -LanceDB OSS allows you to interface with Lance tables via the REST Namespace. +LanceDB Embedded allows you to interface with Lance tables via the REST Namespace. LanceDB Enterprise provides an extended REST API with additional endpoints for managing tables and data. If you have specific needs or questions about the Enterprise REST API Namespace, diff --git a/docs/web/architecture.mdx b/docs/web/architecture.mdx index 997bb95b0..be6cc84af 100644 --- a/docs/web/architecture.mdx +++ b/docs/web/architecture.mdx @@ -1,14 +1,17 @@ --- title: "Architecture" sidebarTitle: "Architecture" -description: "How LanceDB Enterprise separates query serving, background work, and storage, and how it compares with embedded LanceDB OSS." +description: "How LanceDB Enterprise separates query serving, background work, and storage, and how it compares with LanceDB Embedded." icon: cubes keywords: ["architecture", "embedded", "distributed", "object storage", "compute", "deployment"] --- -LanceDB OSS is an embedded library for working with Lance tables. LanceDB -Enterprise is a multimodal lakehouse for data curation, feature engineering, -search, and training data access. Its architecture separates query serving, +LanceDB Embedded is an open-source library for working with Lance tables. It runs +in your application's process; your data can live on local disk or in object +storage. LanceDB Enterprise is a multimodal lakehouse for data curation, feature +engineering, search, and training data access. LanceDB Enterprise runs LanceDB +Distributed: query execution, indexing and maintenance run on the Enterprise +service, outside your application. Its architecture separates query serving, read execution, caching, and background work. Both use the open [Lance](/basics/lance) format. @@ -17,23 +20,23 @@ read the resulting tables into training frameworks. Enterprise separates the resources that serve shared data from those that build indexes and run background work, so teams can size them for these different workloads. -![LanceDB OSS runs the application and embedded library in one process, using local disk or object storage. Enterprise applications connect to query serving, with separate read execution and caching, indexing and background workers, and durable object storage. Both use the Lance format, but they do not share a storage location automatically.](/static/assets/images/overview/lancedb-architecture.svg) +![LanceDB Embedded runs the application and embedded library in one process, using local disk or object storage. Enterprise applications connect to query serving, with separate read execution and caching, indexing and background workers, and durable object storage. Both use the Lance format, but they do not share a storage location automatically.](/static/assets/images/overview/lancedb-architecture.svg) The diagram shows the main compute and storage boundaries, not every request path. The control plane governs the Enterprise service. ## A shared format, different storage choices {#storage} -Lance stores table data, versions, and indexes. OSS can read and write tables on +Lance stores table data, versions, and indexes. LanceDB Embedded can read and write tables on local disk or in object storage. Enterprise keeps durable table data and index artifacts in object storage, independently of the machines serving requests. Its caches accelerate reads; they are not the durable source of truth. Sharing a format does not mean that an Enterprise deployment automatically -opens an existing OSS database. Plan how to move or connect your data and +opens an existing LanceDB Embedded database. Plan how to move or connect your data and configure access for your deployment. -## OSS: an embedded library inside your application {#embedded} +## LanceDB Embedded: a library inside your application {#embedded} With an embedded connection, the LanceDB library plans and executes queries, builds indexes, and updates tables inside your process. There is no separate @@ -44,9 +47,10 @@ single-node data pipelines. Your application controls the compute resources and when to run [table maintenance](/maintenance/compaction). You also manage access to the local files or object storage that hold your tables. -## Enterprise: a multimodal lakehouse for shared workloads {#distributed} +## LanceDB Enterprise: distributed execution for shared workloads {#distributed} -Applications connect to remote tables through a LanceDB SDK. The service handles +A LanceDB SDK connects to LanceDB Enterprise, and the service runs operations +with LanceDB Distributed. The service handles requests across a fleet, with components sized for different kinds of work: - **Query serving** receives requests, resolves tables, and plans operations. @@ -81,20 +85,20 @@ and request flows. ## Application changes for Enterprise {#differences} Core operations remain familiar: create a table, add data, and run a search. -With OSS, the application executes those operations. With Enterprise, the SDK +With LanceDB Embedded, the application executes those operations. With Enterprise, the SDK sends requests to the service, and the service manages execution and configured background maintenance. To use Enterprise, configure the cluster endpoint, database URI and credentials, and make your data available in the Enterprise database. Review SDK methods -that behave differently on remote tables, including result retrieval and +that behave differently with LanceDB Distributed, including result retrieval and background jobs. [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise) describes these application changes. If you plan to use materialized views, check the [stable row ID requirements](/basics/limits#schema) before creating source tables. ## Choose for the workload you need to run {#choosing} -Choose OSS when you want an embedded library and can manage its resources and +Choose LanceDB Embedded when you want an embedded library and can manage its resources and maintenance in your application. Choose Enterprise when multiple applications or teams need a shared multimodal diff --git a/docs/web/basics/agentic-skills.mdx b/docs/web/basics/agentic-skills.mdx index 771bb75ff..96222e27a 100644 --- a/docs/web/basics/agentic-skills.mdx +++ b/docs/web/basics/agentic-skills.mdx @@ -158,13 +158,13 @@ LANCEDB_REGION=us-east-1 LANCEDB_HOST_OVERRIDE=https://your-enterprise-endpoint.com ``` -If you're using LanceDB OSS, no connection settings are required, as it runs as an +If you're using LanceDB Embedded, no connection settings are required, as it runs as an embedded retrieval library. A simple prompt like this should work: ```text Agent prompt -# If using OSS +# If using LanceDB Embedded Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB -OSS table. +Embedded table. # If using enterprise Use the lancedb plugin to ingest the dataset in `data/` into a LanceDB @@ -208,7 +208,7 @@ to `batch_size` rows at a time, providing an iterable of batches for the ingesti shown next. #### Table maintenance {#table-maintenance} -For LanceDB OSS, the plugin instructs the agent to call +For LanceDB Embedded, the plugin instructs the agent to call `table.optimize()` after the ingestion loop. This compacts small fragments, cleans up old versions according to the retention policy, and incorporates new data into indexes. @@ -225,7 +225,7 @@ This example dataset has only eight rows, so the default batch size writes it in one call. Larger inputs should still avoid single-row write commits.
-### 3\. Run the OSS pipeline {#3-run-the-oss-pipeline} +### 3\. Run the Embedded pipeline {#3-run-the-oss-pipeline} ```bash uv run python ingest_multimodal.py @@ -258,9 +258,9 @@ The plugin shown in this tutorial should generalize reasonably well to other use If you find any issues, open [an issue](https://github.com/lancedb/lancedb-agent-plugins/issues) on GitHub, clearly describing the intended behavior. -You can choose OSS or Enterprise based on how the work will run: +You can choose LanceDB Embedded or LanceDB Enterprise based on how the work will run: -Start with [LanceDB OSS](/quickstart) during the early stages of a project +Start with [LanceDB Embedded](/quickstart) during the early stages of a project when an agent is helping you prototype, explore a dataset, or run small workflows on a subset of the data. The application owns the storage and lifecycle work, so ask the agent to validate inputs, write in @@ -271,7 +271,7 @@ Choose [LanceDB Enterprise](/enterprise) when the resulting table becomes shared production infrastructure, and the workload needs distributed capacity, private deployment, or platform-managed operations. The data format and the core table API stay the same, so the pipeline's table and search code carries over: -the agent connects to a remote `db://` table, leaves maintenance to the +the agent connects to an Enterprise `db://` table, leaves maintenance to the deployment instead of calling `optimize()`, and submits long-running work as jobs. See [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise). diff --git a/docs/web/basics/connect.mdx b/docs/web/basics/connect.mdx index ac7061bbc..d576b62d8 100644 --- a/docs/web/basics/connect.mdx +++ b/docs/web/basics/connect.mdx @@ -1,7 +1,7 @@ --- title: "Connect to LanceDB" sidebarTitle: "Connect" -description: "Use the embedded LanceDB OSS library with tables in a local directory or object storage, or connect to LanceDB Enterprise." +description: "Use LanceDB Embedded with tables in a local directory or object storage, or connect to LanceDB Enterprise." icon: plug keywords: ["connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"] --- @@ -20,15 +20,18 @@ import { TsConnectObjectStorage, } from '/snippets/connection.mdx'; -The URI you pass to `connect` decides where the work runs. The same Python, -TypeScript and Rust SDKs open all three kinds; -[OSS and Enterprise](/basics/offerings) describes how the two offerings differ. +The URI you pass to `connect` decides where the work runs. LanceDB Embedded +runs in your application's process; your data can live on local disk or in +object storage. LanceDB Enterprise runs LanceDB Distributed: query execution, +indexing and maintenance run on the Enterprise service, outside your +application. The same Python, TypeScript and Rust SDKs open all three kinds; +[Embedded and Enterprise](/basics/offerings) describes how the two offerings differ. | URI | Where queries run | | --- | --- | -| A local path, such as `./data` | OSS: in your process | -| `s3://`, `gs://` or `az://` | OSS: in your process, reading object storage | -| `db://` | LanceDB Enterprise: queries run on your cluster | +| A local path, such as `./data` | LanceDB Embedded: in your process | +| `s3://`, `gs://` or `az://` | LanceDB Embedded: in your process, reading object storage | +| `db://` | LanceDB Enterprise: LanceDB Distributed runs queries on your cluster | ## A local directory {#local} diff --git a/docs/web/basics/guarantees.mdx b/docs/web/basics/guarantees.mdx index 840ea2d50..2774d749b 100644 --- a/docs/web/basics/guarantees.mdx +++ b/docs/web/basics/guarantees.mdx @@ -25,7 +25,7 @@ rewrite data; adding a derived column can write the new column independently. A read of a table uses a consistent snapshot. A consistent snapshot can still be older than another writer's latest commit. [Consistency](/tables/consistency) -explains how OSS and Enterprise choose the version a reader sees. +explains how LanceDB Embedded and LanceDB Enterprise choose the version a reader sees. For an experiment that must keep using the same data, select a specific retained table version rather than relying on a connection's default freshness. @@ -46,7 +46,7 @@ describes commit behavior and compatibility between operations. ## Storage durability {#durability} A committed table version is stored in the table’s configured storage. LanceDB -OSS uses your local filesystem or object store; LanceDB Enterprise uses the +Embedded uses your local filesystem or object store; LanceDB Enterprise uses the cluster’s configured storage. Table version history does not replace backups. Configure storage redundancy diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 26dd4dd8b..20445843e 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -8,7 +8,7 @@ availability: oss: available enterprise: available summary: >- - Job handles track operations in OSS and Enterprise. Enterprise also + Job handles track operations in LanceDB Embedded and LanceDB Enterprise. Enterprise also supports listing server jobs, reopening them by ID and reading their events. --- @@ -19,7 +19,7 @@ column refresh. Use it to check progress, wait for completion and inspect failures. Methods such as Python's `create_index_async` and TypeScript's -`createIndexAsync` return job handles. In OSS, the work runs in your application +`createIndexAsync` return job handles. In LanceDB Embedded, the work runs in your application process; in Enterprise, it runs on server workers or through the SQL query backend. A returned handle can represent an operation that has already finished, so check its status before @@ -58,12 +58,13 @@ Event responses have [row limits](/basics/limits#jobs). An explicit limit can request more than the default, but it does not guarantee a complete event history. -## OSS and Enterprise execution {#in-process} +## Embedded and Distributed execution {#in-process} -The following table describes local operations and Enterprise registry jobs. +The following table describes LanceDB Embedded operations and registry jobs on +LanceDB Distributed (provided by LanceDB Enterprise). SQL-backed job handles follow the query lifecycle described below. -| | OSS | Enterprise registry job | +| | Embedded | Enterprise registry job | | --- | --- | --- | | Execution | In your application process | On server workers | | Job identity | No server ID | A server ID for looking up the job | @@ -72,7 +73,7 @@ SQL-backed job handles follow the query lifecycle described below. ### SQL-backed job handles -Remote materialized-view CREATE, REFRESH, and DROP use the SQL query backend. +On Enterprise, materialized-view CREATE, REFRESH, and DROP use the SQL query backend. Python's `create_materialized_view_async()`, `mv.refresh_async()`, and `drop_materialized_view_async()` return job handles with `status()`, `wait()`, and `cancel()`. Synchronous creation, refresh, and drop wait on the same SQL diff --git a/docs/web/basics/lakehouse.mdx b/docs/web/basics/lakehouse.mdx index 04e07afaf..9ecf6800a 100644 --- a/docs/web/basics/lakehouse.mdx +++ b/docs/web/basics/lakehouse.mdx @@ -44,7 +44,7 @@ framework runs the model; LanceDB provides access to the training data. ## Shared compute and maintenance in Enterprise {#where} -LanceDB OSS runs as an embedded library in your application. LanceDB Enterprise +LanceDB Embedded runs as an embedded library in your application. LanceDB Enterprise provides shared infrastructure for applications and teams working with larger multimodal workloads. diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index f2dd0ecfa..13b7755be 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -14,7 +14,7 @@ multimodal AI. It defines how data is stored and organized into versioned tables -LanceDB OSS and LanceDB Enterprise both use Lance as their storage foundation. +LanceDB Embedded and LanceDB Enterprise both use Lance as their storage foundation. The format is developed as an independent open-source project, with its own specification and tools. @@ -42,4 +42,4 @@ those fields together. - [Lance format specification](https://lance.org/format): how the format works. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. -- [Architecture](/architecture): how LanceDB OSS and Enterprise build on Lance. +- [Architecture](/architecture): how LanceDB Embedded and LanceDB Enterprise build on Lance. diff --git a/docs/web/basics/naming.mdx b/docs/web/basics/naming.mdx index af61c2b6c..b570e5bee 100644 --- a/docs/web/basics/naming.mdx +++ b/docs/web/basics/naming.mdx @@ -14,7 +14,7 @@ Databases, namespaces, tables, views and branches all have names. Choose names that describe their purpose, such as `documents`, `prod` or `training_2026`. Consistent names make data easier to find and application code easier to read. -Use the following rules for names that work across LanceDB OSS and Enterprise. +Use the following rules for names that work across LanceDB Embedded and LanceDB Enterprise. | Object | Characters | Length | | --- | --- | --- | diff --git a/docs/web/basics/offerings.mdx b/docs/web/basics/offerings.mdx index c66b77e78..a2df61b21 100644 --- a/docs/web/basics/offerings.mdx +++ b/docs/web/basics/offerings.mdx @@ -1,6 +1,6 @@ --- -title: "LanceDB OSS or Enterprise?" -sidebarTitle: "OSS and Enterprise" +title: "LanceDB Embedded or Enterprise?" +sidebarTitle: "Embedded and Enterprise" description: "Start with an embedded library, or use the LanceDB Enterprise multimodal lakehouse for shared AI workloads." icon: compass keywords: ["oss", "enterprise", "embedded", "deployment", "availability", "comparison"] @@ -9,15 +9,18 @@ keywords: ["oss", "enterprise", "embedded", "deployment", "availability", "compa LanceDB gives you two ways to work with multimodal data, both built on the open [Lance](/basics/lance) format. -**LanceDB OSS** is an embedded library. Run it inside your application -with tables on local disk or in object storage. You control the application, +**LanceDB Embedded (open source)** is a library that runs in your +application's process; your data can live on local disk or in object storage. +You control the application, its resources, and table maintenance, without a separate database service. [Try the quickstart](/quickstart) to create a table and run your first search. **LanceDB Enterprise** is a multimodal lakehouse for data curation, feature engineering, search, and training data access. It adds query-serving capacity, data caching, and background operations for teams working with shared -multimodal datasets. +multimodal datasets. LanceDB Enterprise runs LanceDB Distributed: query +execution, indexing and maintenance run on the Enterprise service, outside your +application. [Connect to Enterprise](/basics/connect#enterprise) when your cluster is ready. diff --git a/docs/web/basics/query.mdx b/docs/web/basics/query.mdx index 624617918..aa8e9b9df 100644 --- a/docs/web/basics/query.mdx +++ b/docs/web/basics/query.mdx @@ -17,7 +17,7 @@ in the last month. | Interface | When to use it | | --- | --- | -| **SDK query builders** | Build vector, full-text and hybrid searches, apply filters and choose the fields to return. Available in OSS and Enterprise. | +| **SDK query builders** | Build vector, full-text and hybrid searches, apply filters and choose the fields to return. Available in LanceDB Embedded and LanceDB Enterprise. | | **Enterprise SQL** | Write SQL queries for filtering, aggregation, joins and other data curation tasks. Connect through Python or a Flight SQL client. | Both interfaces work with LanceDB tables. Choose the one that supports your diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index b20fc1662..3144c11cf 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -8,13 +8,16 @@ availability: oss: available enterprise: available summary: >- - Python, TypeScript and Rust support both LanceDB OSS and LanceDB Enterprise. + Python, TypeScript and Rust support both LanceDB Embedded and LanceDB Enterprise. Java provides a client for the Enterprise REST API. --- Use a LanceDB SDK to create tables, add data, build indexes and run searches -from your application. Python, TypeScript and Rust work with both the embedded -OSS library and LanceDB Enterprise. +from your application. Python, TypeScript and Rust work with both LanceDB +Embedded and LanceDB Enterprise. LanceDB Embedded runs in your application's +process; your data can live on local disk or in object storage. LanceDB +Enterprise runs LanceDB Distributed: query execution, indexing and maintenance +run on the Enterprise service, outside your application. The [quickstart](/quickstart) includes installation instructions and complete examples in all three languages. For connection settings, see @@ -73,16 +76,16 @@ For PyTorch worker setup and connection factories, see ## Moving to LanceDB Enterprise {#moving-to-enterprise} The core table workflow stays familiar: connect, create or open a table, write -records, and query them. Enterprise runs those operations on remote compute and -manages background maintenance. +records, and query them. Enterprise runs those operations with LanceDB +Distributed and manages background maintenance. - **Configure the connection.** Replace the local path with your database URI, and supply the endpoint, region and credentials provided by your administrator. [Connect to Enterprise](/basics/connect#enterprise) shows these settings. -- **Retrieve query results.** Python's remote tables do not support whole-table +- **Retrieve query results.** Python tables on Enterprise do not support whole-table `to_arrow()` or `to_pandas()` calls. Use a query and select the columns and number of rows you need, for example `table.search().limit(10).to_arrow()`. -- **Handle table listings and namespaces.** Remote table listings are paginated. +- **Handle table listings and namespaces.** Enterprise table listings are paginated. Use the namespace and pagination options described in [Namespaces](/management/namespace). - **Use server-side jobs.** Index builds and feature refreshes can run as diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index c89bd7a20..ce34237b5 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -8,7 +8,7 @@ availability: oss: unavailable enterprise: available summary: >- - Enterprise supports SQL through Arrow Flight SQL. Use the SDK table APIs for embedded OSS tables. See [Connection settings](#sql-is-remote) to connect. + Enterprise supports SQL through Arrow Flight SQL. Use the SDK table APIs for LanceDB Embedded tables. See [Connection settings](#sql-is-remote) to connect. --- Use SQL in LanceDB Enterprise to filter records, join tables, calculate @@ -52,7 +52,7 @@ API and SQL endpoints may use different hosts or ports. See [Connect to Enterprise](/basics/connect#enterprise) for other connection options. SQL runs in Enterprise. Connections to a local directory or an object-storage -bucket use the embedded OSS library and cannot execute SQL statements. Use +bucket use LanceDB Embedded and cannot execute SQL statements. Use SDK table operations to query those tables. ## Run a query in Python {#sql-from-python} @@ -94,7 +94,7 @@ handles, streaming, and cancellation. Use **SQL** for joins, aggregations, window functions, and analytical queries written in SQL. Use **SDK table operations** to build applications around table management, ingestion, filtering, and search, including applications that run -with the embedded OSS library. +with LanceDB Embedded. You can combine them. For example, create and populate a table with an SDK, then query it with SQL to prepare a training dataset. In Python, both workflows @@ -130,7 +130,7 @@ server version supports this form, then use [`EXPLAIN`](/sql/dql/explain) to inspect the query plan. The [SDK vector search API](/search/vector-search) is also available in -Enterprise and OSS. Use it when you prefer the SDK query builder or need to +LanceDB Enterprise and LanceDB Embedded. Use it when you prefer the SDK query builder or need to search embedded tables. For full-text search in SQL, use the [`fts()`](/sql/functions#fts) table diff --git a/docs/web/curation/index.mdx b/docs/web/curation/index.mdx index fd8ea73aa..191ff2fd1 100644 --- a/docs/web/curation/index.mdx +++ b/docs/web/curation/index.mdx @@ -23,8 +23,8 @@ records belong, and save the selected data or the rules used to produce it. | [Rank and deduplicate](/curation/windowing) | Which records to keep when several describe the same item. | The analytical examples in this section use **Enterprise SQL**. Connect with -the [SQL guide](/basics/sql). For sampling through the Python SDK in OSS or -Enterprise, see [Sample without SQL](/curation/sampling#training). +the [SQL guide](/basics/sql). For sampling through the Python SDK in LanceDB Embedded or +LanceDB Enterprise, see [Sample without SQL](/curation/sampling#training). ## Prepare a labeled document dataset {#shape} diff --git a/docs/web/curation/sampling.mdx b/docs/web/curation/sampling.mdx index 643b06bdf..1289275a1 100644 --- a/docs/web/curation/sampling.mdx +++ b/docs/web/curation/sampling.mdx @@ -8,7 +8,7 @@ availability: oss: unavailable enterprise: available summary: >- - Enterprise supports SQL `TABLESAMPLE`. For sampling in OSS and Enterprise through the Python SDK, see [Sample without SQL](#training). + Enterprise supports SQL `TABLESAMPLE`. For sampling in LanceDB Embedded and LanceDB Enterprise through the Python SDK, see [Sample without SQL](#training). --- import { PySampleDataset } from '/snippets/curation_sampling.mdx'; @@ -143,7 +143,7 @@ for sampling. `TABLESAMPLE` cannot be applied directly to a subquery result. ## Sample without SQL {#training} The Python SDK provides a permutation builder for selecting and ordering rows -in OSS and Enterprise. A split selects a subset; a shuffle changes the order +in LanceDB Embedded and LanceDB Enterprise. A split selects a subset; a shuffle changes the order in which records are read. `Permutation.identity(table)` retains stored order. diff --git a/docs/web/deployment/monitoring.mdx b/docs/web/deployment/monitoring.mdx index b31293338..7d19fc1a5 100644 --- a/docs/web/deployment/monitoring.mdx +++ b/docs/web/deployment/monitoring.mdx @@ -11,7 +11,7 @@ LanceDB emits internal metrics (currently object store request counts, bytes tra The bridge is available in the Python and TypeScript SDKs. It is a thin wrapper over LanceDB's `metrics` recorder; your application supplies and configures the OpenTelemetry SDK. -This page covers LanceDB OSS instrumentation. LanceDB Enterprise clusters emit their own metrics from the server side. See [Enterprise monitoring](#enterprise) below. +This page covers LanceDB Embedded instrumentation. LanceDB Enterprise clusters emit their own metrics from the server side. See [Enterprise monitoring](#enterprise) below. ## Available metrics {#what-you-get} @@ -113,7 +113,7 @@ export them with data enrichment. No client-side instrumentation is needed. | Component | Metrics | | --- | --- | | Query node | RPS, query latency, error codes, slow-query count, CPU/memory utilization | -| Plan executor | SSD cache hit/miss rate, CPU/memory utilization | +| Executor | SSD cache hit/miss rate, CPU/memory utilization | [Contact support](/deployment/support) for the comprehensive metric list and help integrating them with your monitoring dashboard. diff --git a/docs/web/deployment/storage.mdx b/docs/web/deployment/storage.mdx index 35b6dd80f..dd370846b 100644 --- a/docs/web/deployment/storage.mdx +++ b/docs/web/deployment/storage.mdx @@ -1,7 +1,7 @@ --- title: "Embedded storage configuration" sidebarTitle: "Embedded Storage" -description: "Choose and configure local disk or object storage for tables accessed by the embedded LanceDB OSS library." +description: "Choose and configure local disk or object storage for tables accessed by LanceDB Embedded." icon: database keywords: ["storage", "s3", "gcs", "azure", "object store", "configuration", "deploy"] availability: @@ -13,7 +13,7 @@ availability: the deployment's own configuration instead. --- -This page is about the embedded library, where your connection chooses and +This page is about LanceDB Embedded, where your connection chooses and configures the storage backend. A LanceDB Enterprise deployment sets up its own storage when it is deployed, so a `db://` connection passes none of these options except an Azure storage account name. See diff --git a/docs/web/deployment/support.mdx b/docs/web/deployment/support.mdx index 5e35d9131..148e71648 100644 --- a/docs/web/deployment/support.mdx +++ b/docs/web/deployment/support.mdx @@ -1,12 +1,12 @@ --- title: "Support" sidebarTitle: "Support" -description: "Where to get help: community Discord for OSS, dedicated support for Enterprise." +description: "Where to get help: community Discord for LanceDB Embedded (open source), dedicated support for LanceDB Enterprise." icon: circle-question keywords: ["support", "help", "discord", "community"] --- -## LanceDB OSS {#oss} +## LanceDB Embedded (open source) {#oss} For a quick question, the [Discord community](https://discord.gg/AUEWnJ7Txb) has channels for diff --git a/docs/web/embedding/index.mdx b/docs/web/embedding/index.mdx index 4039ed840..c35074b20 100644 --- a/docs/web/embedding/index.mdx +++ b/docs/web/embedding/index.mdx @@ -35,7 +35,7 @@ Modern machine learning models can be trained to convert raw data into embedding of floating point numbers. The position of an embedding in vector space captures the semantics of the data, so vectors that are close to each other are considered similar. -LanceDB provides an embedding function registry in OSS as well as its Enterprise versions +LanceDB provides an embedding function registry in LanceDB Embedded as well as LanceDB Enterprise ([see below](#embeddings-in-lancedb-enterprise)) that automatically generates vector embeddings during data ingestion. Query text is embedded automatically too, in the client, for local and Enterprise tables alike, with SDK-specific query @@ -198,7 +198,7 @@ You can find all supported embedding models in the [integrations](/integrations/ Enterprise In LanceDB Enterprise, embedding generation during data ingestion is client-side and the resulting vectors are -stored on the remote table. +stored in the Enterprise table. The Enterprise server does not currently generate embeddings from query text on its own. Any automatic @@ -207,13 +207,13 @@ query-time embedding happens on the client side. ### How string queries are interpreted {#how-string-queries-are-interpreted} -For the Python remote client, `table.search("hello")` can take two different paths: +When the Python SDK connects to Enterprise, `table.search("hello")` can take two different paths: - If the selected vector column has embedding metadata (i.e., the table schema stores the source-column, vector-column, and embedding-function mapping created from fields like `SourceField()` and `VectorField()` during table creation), then the embeddings are computed in the Python client process. - The client uses the same local LanceDB embedding registry used by OSS tables to + The client uses the same local LanceDB embedding registry used by LanceDB Embedded tables to reconstruct the embedding function from schema metadata, compute the query vector in the client process, and send that vector to Enterprise for search. ```python diff --git a/docs/web/embedding/quickstart.mdx b/docs/web/embedding/quickstart.mdx index bcaf90f6f..1111743da 100644 --- a/docs/web/embedding/quickstart.mdx +++ b/docs/web/embedding/quickstart.mdx @@ -42,11 +42,11 @@ from lancedb.embeddings import get_registry ## Step 2: Connect to LanceDB {#step-2-connect-to-lancedb} -Establish a connection to your LanceDB OSS directory or Enterprise cluster: +Establish a connection to your LanceDB Embedded directory or Enterprise cluster: ```python Python icon="python" -# Enter your LanceDB connection URI for OSS or Enterprise here +# Enter your LanceDB connection URI for LanceDB Embedded or Enterprise here db = lancedb.connect(...) ``` @@ -126,8 +126,8 @@ LanceDB preserves them instead of filling only the missing rows. ## Step 6: Query with Automatic Embedding {#step-6-query-with-automatic-embedding} -Note: On LanceDB Enterprise, the server does not generate embeddings from query text. In the Python remote -client, `table.search("greetings")` can still work when the table schema includes embedding metadata, because +Note: On LanceDB Enterprise, the server does not generate embeddings from query text. When the Python +SDK connects to Enterprise, `table.search("greetings")` can still work when the table schema includes embedding metadata, because the client computes the query embedding before sending the vector search. If there is no embedding metadata for that search, `search("greetings")` in `auto` mode is treated as FTS instead. diff --git a/docs/web/enterprise/authentication.mdx b/docs/web/enterprise/authentication.mdx index 9074c641c..74d68ecae 100644 --- a/docs/web/enterprise/authentication.mdx +++ b/docs/web/enterprise/authentication.mdx @@ -9,7 +9,7 @@ availability: enterprise: available summary: >- Requests to a deployment carry an API key or an OAuth token, whichever it is - configured to accept. Embedded LanceDB has no server to sign in to; see + configured to accept. LanceDB Embedded has no server to sign in to; see [Architecture](/architecture). --- @@ -423,5 +423,5 @@ control. All three SDKs deliberately omit the secret from their debug/repr outpu so accidental log lines do not expose the value. -Embedded LanceDB has nothing to authenticate to: your process opens the files +LanceDB Embedded has nothing to authenticate to: your process opens the files directly, and the object store's own credentials are the only gate. diff --git a/docs/web/enterprise/deployment/index.mdx b/docs/web/enterprise/deployment/index.mdx index efaa2c786..38e854282 100644 --- a/docs/web/enterprise/deployment/index.mdx +++ b/docs/web/enterprise/deployment/index.mdx @@ -16,5 +16,5 @@ Deployment is specific to your cloud and account, so the procedure is published with LanceDB Enterprise. [Contact us](https://www.lancedb.com/contact) to get started. -Embedded LanceDB has nothing to deploy: it is a library your process links +LanceDB Embedded has nothing to deploy: it is a library your process links against. See [Architecture](/architecture#embedded). diff --git a/docs/web/enterprise/distributed-search.mdx b/docs/web/enterprise/distributed-search.mdx index ebac960ba..86837e157 100644 --- a/docs/web/enterprise/distributed-search.mdx +++ b/docs/web/enterprise/distributed-search.mdx @@ -8,17 +8,17 @@ availability: enterprise: available summary: >- LanceDB Enterprise distributes index execution and table-data reads across - plan executors. Embedded LanceDB executes searches in the application process. + executors. LanceDB Embedded executes searches in the application process. --- Distributed search spreads index execution, table-data reads, and caching across multiple serving machines in LanceDB Enterprise. Query nodes plan queries and -combine results. Plan executors cache index structures and table data and execute -the remote work. See [Enterprise architecture](/enterprise/architecture). +combine results. Executors cache index structures and table data and execute +the distributed work. See [Enterprise architecture](/enterprise/architecture). ## Embedded search {#embedded-search} -LanceDB OSS runs inside your application process. It searches indexes and reads +LanceDB Embedded runs inside your application process. It searches indexes and reads table data using that process's resources, including its index cache. Reading a table from object storage does not by itself distribute query execution across machines. diff --git a/docs/web/enterprise/index.mdx b/docs/web/enterprise/index.mdx index acf41f6d1..888804756 100644 --- a/docs/web/enterprise/index.mdx +++ b/docs/web/enterprise/index.mdx @@ -1,7 +1,7 @@ --- title: "LanceDB Enterprise" sidebarTitle: "Overview" -description: "What a deployment adds over embedded LanceDB." +description: "What a deployment adds over LanceDB Embedded." icon: building keywords: ["enterprise", "deployment", "cluster"] --- diff --git a/docs/web/enterprise/security.mdx b/docs/web/enterprise/security.mdx index f462203d4..c848be23f 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -16,5 +16,5 @@ Compliance posture (certifications, data residency, encryption at rest and in transit, audit logging) is a property of a deployment, so it is documented with LanceDB Enterprise. -For embedded LanceDB, these are properties of the object store you point it at +For LanceDB Embedded, these are properties of the object store you point it at and the process you run it in; LanceDB adds no layer of its own. diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 707a929f5..49820a454 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -16,9 +16,9 @@ Declaring it is cheap on any table size, because nothing is evaluated until [a refresh](/feature-engineering/refresh-column) asks for it. -In the 0.41 SDK release, local computed-column declaration and refresh require a +In the 0.41 SDK release, computed-column declaration and refresh in LanceDB Embedded require a source build with the `experimental-functions` Cargo feature. Published Python -and TypeScript packages leave it disabled. Remote Cloud and Enterprise operations +and TypeScript packages leave it disabled. LanceDB Enterprise operations do not require this feature. Ordinary eager `add_columns` transforms remain available. diff --git a/docs/web/feature-engineering/index.mdx b/docs/web/feature-engineering/index.mdx index 8f0253444..30a165af4 100644 --- a/docs/web/feature-engineering/index.mdx +++ b/docs/web/feature-engineering/index.mdx @@ -70,7 +70,7 @@ changes incrementally for supported queries; other queries require a full rebuil See [refresh behavior](/feature-engineering/materialized-views#incremental) for version-specific details. -Enterprise runs materialization on remote compute. Use the SDK and refresh +Enterprise runs materialization on the Enterprise service. Use the SDK and refresh options supported by your server version; see [Enterprise refreshes](/feature-engineering/materialized-views#availability). @@ -78,8 +78,8 @@ options supported by your server version; see | | What it produces | Filled by | Available | | --- | --- | --- | --- | -| [Computed column](/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | OSS and Enterprise | -| [Materialized view](/feature-engineering/materialized-views) | a new table derived by a query | a refresh | OSS and Enterprise | +| [Computed column](/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | Embedded and Enterprise | +| [Materialized view](/feature-engineering/materialized-views) | a new table derived by a query | a refresh | Embedded and Enterprise | | [Geneva](/geneva) | columns filled by Python | the `geneva` package | Enterprise | {/* diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 30d2d1bc6..e90f3233c 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -8,7 +8,7 @@ availability: oss: available enterprise: available summary: >- - Local creation and refresh require a source build with the experimental-functions Cargo feature. Enterprise runs the work on remote compute. See [Enterprise refreshes](#availability) for server compatibility requirements. + Creation and refresh in LanceDB Embedded require a source build with the experimental-functions Cargo feature. Enterprise runs the work on the Enterprise service. See [Enterprise refreshes](#availability) for server compatibility requirements. --- import { @@ -21,10 +21,10 @@ filtered or transformed dataset that you can query, index and search repeatedly. Refresh the view after its source data changes. -In the 0.41 SDK release, local materialized-view creation and refresh require a +In the 0.41 SDK release, materialized-view creation and refresh in LanceDB Embedded require a source build with the `experimental-functions` Cargo feature. Published Python and TypeScript packages leave it disabled. Opening, reading, listing and dropping -existing views remain available, as do remote Cloud and Enterprise operations. +existing views remain available, as do LanceDB Enterprise operations. @@ -84,7 +84,7 @@ when maintaining an existing pipeline. Enterprise -Enterprise runs materialized-view creation and refresh on remote compute. +Enterprise runs materialized-view creation and refresh on the Enterprise service. For SQL, see [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view) and [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh#refresh-materialized-view). diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 1aa511234..10ab9fdc8 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -16,9 +16,9 @@ new rows and recompute values whose inputs changed. The example below continues with the `doubled` column from the computed-column guide. -In the 0.41 SDK release, local declaration and refresh require a source build +In the 0.41 SDK release, declaration and refresh in LanceDB Embedded require a source build with the `experimental-functions` Cargo feature. Published Python and TypeScript -packages leave it disabled. Remote Cloud and Enterprise operations do not require +packages leave it disabled. LanceDB Enterprise operations do not require this feature; existing computed-column data remains readable in default builds. @@ -82,9 +82,9 @@ table.add_columns( Both options apply to every computed output declared in that call, including registered Function outputs. Automatic refresh is enabled by default. When -the interval is omitted, the server determines when to refresh. Local tables -persist only an explicitly configured interval; automatic execution requires a -Cloud or Enterprise server with its separate `column_refresh.enabled` switch +the interval is omitted, the server determines when to refresh. LanceDB Embedded +tables persist only an explicitly configured interval; automatic execution requires a +LanceDB Enterprise deployment with its separate `column_refresh.enabled` switch turned on. That server switch is disabled in the base configuration. The interval is a positive minimum delay after the last successful refresh diff --git a/docs/web/governance/authorization.mdx b/docs/web/governance/authorization.mdx index dc5b6fd26..72e4e9534 100644 --- a/docs/web/governance/authorization.mdx +++ b/docs/web/governance/authorization.mdx @@ -8,7 +8,7 @@ availability: oss: unavailable enterprise: available summary: >- - Enterprise supports catalog privileges when its administrator configures enforcement. Embedded LanceDB has no catalog authorization layer: access is whatever the object store allows. + Enterprise supports catalog privileges when its administrator configures enforcement. LanceDB Embedded has no catalog authorization layer: access is whatever the object store allows. --- [Authentication](/enterprise/authentication) establishes who is calling. diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 75044ad0d..11b72505d 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -29,13 +29,16 @@ For a deeper look at how this works in training pipelines, start with [Why Lance ## LanceDB suite {#lancedb-suite} -The LanceDB suite includes LanceDB OSS, an open-source embedded retrieval library, and LanceDB Enterprise, +The LanceDB suite includes LanceDB Embedded (open source), a retrieval library, and LanceDB Enterprise, a multimodal lakehouse platform for the full AI data lifecycle. -OSS is easy to set up on a local machine for search and regular-scale workflows. LanceDB Enterprise is built +LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. +It is easy to set up on a local machine for search and regular-scale workflows. LanceDB Enterprise is built for teams that need scale without building bespoke infrastructure for curation, feature engineering, search and retrieval, and efficient training data access. +LanceDB Enterprise runs LanceDB Distributed: query execution, indexing and maintenance +run on the Enterprise service, outside your application. -![LanceDB suite: OSS search and Enterprise multimodal lakehouse on Lance format](/static/assets/images/overview/lancedb-suite.svg) +![LanceDB suite: LanceDB Embedded search and Enterprise multimodal lakehouse on Lance format](/static/assets/images/overview/lancedb-suite.svg) ## Why teams use LanceDB {#why-teams-use-lancedb} @@ -74,11 +77,11 @@ feature engineering, search and retrieval, and efficient training data access. ## From local development to production scale {#from-local-development-to-production-scale} -LanceDB OSS and LanceDB Enterprise share the same Lance format and table model. Start locally with the embedded OSS -library, then move to Enterprise when your team needs distributed scale, managed infrastructure, private deployment, +LanceDB Embedded and LanceDB Enterprise share the same Lance format and table model. Start locally with +LanceDB Embedded, then move to Enterprise when your team needs distributed scale, managed infrastructure, private deployment, or higher-throughput curation, feature engineering, search and retrieval, and training workflows. -### 1\. LanceDB OSS {#1-lancedb-oss} +### 1\. LanceDB Embedded {#1-lancedb-oss} The fastest way to get started is the open-source embedded library, with client SDKs in Python, TypeScript and Rust. Run it locally in just a few steps, which lets you explore datasets, curate data, and run search and retrieval workloads for agents. Start here: diff --git a/docs/web/indexing/fts-index.mdx b/docs/web/indexing/fts-index.mdx index 4660e8b01..f112c996f 100644 --- a/docs/web/indexing/fts-index.mdx +++ b/docs/web/indexing/fts-index.mdx @@ -14,7 +14,7 @@ availability: import { PyFtsIndexAsync as FtsIndexAsync, PyFtsIndexCreate as FtsIndexCreate, PyFtsIndexNested as FtsIndexNested, PyFtsIndexWait as FtsIndexWait } from '/snippets/indexing.mdx'; LanceDB provides performant full-text search based on BM25, allowing you to incorporate keyword-based search in your retrieval solutions. This page shows -examples on how to create and configure FTS indexes in LanceDB OSS and Enterprise, using the synchronous and asynchronous APIs. +examples on how to create and configure FTS indexes in LanceDB Embedded and LanceDB Enterprise, using the synchronous and asynchronous APIs. In LanceDB Enterprise, `create_fts_index` API returns immediately, but index building happens asynchronously. diff --git a/docs/web/indexing/reindexing.mdx b/docs/web/indexing/reindexing.mdx index 9df3235db..27a51a3d3 100644 --- a/docs/web/indexing/reindexing.mdx +++ b/docs/web/indexing/reindexing.mdx @@ -65,7 +65,7 @@ LanceDB Enterprise supports incremental reindexing through an automated backgrou The benefit of using LanceDB Enterprise is that it automates the reindexing process and operates continuously in the background, minimizing the impact on latency under high loads. -In OSS, you must manually manage the reindexing cadence based on your data growth and performance needs. +In LanceDB Embedded, you must manually manage the reindexing cadence based on your data growth and performance needs. ## Disk utilization {#disk-utilization} @@ -73,7 +73,7 @@ Compaction by itself does not immediately free disk space, and can temporarily i compacted files are written before old-version files are deleted. Disk space is reclaimed when old versions are pruned during cleanup. Set retention only as low as your rollback and time-travel requirements allow. -If you need to reclaim space more aggressively in OSS, use a shorter retention window: +If you need to reclaim space more aggressively in LanceDB Embedded, use a shorter retention window: ```python Python icon=Python from datetime import timedelta @@ -109,11 +109,11 @@ GPU acceleration changes how the vector index is built, not the lifecycle after embedded library, rows appended later still need `optimize()` before they are part of the index; a deployment adds them in the background. `fast_search()` only searches indexed rows. -### Manual GPU indexing in LanceDB OSS {#gpu-manual-gpu-indexing-in-lancedb-oss} +### Manual GPU indexing in LanceDB Embedded {#gpu-manual-gpu-indexing-in-lancedb-oss} You can use the Python SDK to manually create the `IVF_PQ` index on a GPU. You'll need [PyTorch>2.0](https://pytorch.org/). Note that GPU-based indexing is currently only -supported by the synchronous SDK in LanceDB OSS. +supported by the synchronous SDK in LanceDB Embedded. Specify the values `cuda` or `mps` (on Apple Silicon) for the `accelerator` parameter to enable GPU training on your device. diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 037d75f8d..33d6a8575 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -159,7 +159,7 @@ Learn how to configure, build, and search LanceDB vector indexes, including buil The `distance_type` can be specified at search time in addition to build time. If you do this, set it to the same value used to build the vector index. If the search metric does not match the index metric, LanceDB cannot use the index and falls -back to a costly flat search. On LanceDB Cloud, the brute-force KNN safety limit +back to a costly flat search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit can reject that search on a large table instead of executing it. An Enterprise deployment applies the same limit only when it is configured to. @@ -279,7 +279,7 @@ In LanceDB Enterprise, vector indexes are managed **automatically**. The system - GPU-based `IVF_PQ` builds are available on request. [Contact support](/deployment/support) to enable them for your deployment. Build time depends on dataset size, dimensions and GPU resources. Open-Source - LanceDB OSS users can manually create vector indexes by calling `table.create_index()`. + LanceDB Embedded users can manually create vector indexes by calling `table.create_index()`. See the above sections for guidance on manually tuning index parameters as data changes. @@ -290,7 +290,7 @@ In the embedded library the index is built before `create_index()` returns. -Rows appended after an initial index build remain outside the index until refreshed manually (OSS) or automatically (Enterprise). Normal +Rows appended after an initial index build remain outside the index until refreshed manually (Embedded) or automatically (Enterprise). Normal search still checks those unindexed rows with a slower fallback path; `fast_search()` skips that fallback and searches only indexed rows. @@ -330,7 +330,7 @@ Each entry returned by `list_indices()` also carries detailed per-index metadata -These fields are populated for local tables. In LanceDB Enterprise, `list_indices()` returns them except `num_unindexed_rows`; use `index_stats()` for index coverage. +These fields are populated for LanceDB Embedded tables. In LanceDB Enterprise, `list_indices()` returns them except `num_unindexed_rows`; use `index_stats()` for index coverage. #### Custom Index Names diff --git a/docs/web/ingestion/create-table.mdx b/docs/web/ingestion/create-table.mdx index 535ea83e3..00425a1f9 100644 --- a/docs/web/ingestion/create-table.mdx +++ b/docs/web/ingestion/create-table.mdx @@ -8,7 +8,7 @@ availability: oss: available enterprise: available summary: >- - Create and open tables in OSS and Enterprise. + Create and open tables in LanceDB Embedded and LanceDB Enterprise. --- import { diff --git a/docs/web/ingestion/delete.mdx b/docs/web/ingestion/delete.mdx index b7b1f9432..f02320733 100644 --- a/docs/web/ingestion/delete.mdx +++ b/docs/web/ingestion/delete.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Delete rows through the SDKs in OSS and Enterprise. Storage reclamation follows compaction and retention policy. + Delete rows through the SDKs in LanceDB Embedded and LanceDB Enterprise. Storage reclamation follows compaction and retention policy. --- import { RsExample as RsDeleteRows } from '/snippets/ingestion_delete.mdx'; @@ -70,7 +70,7 @@ Compaction rewrites the live data layout; cleanup removes eligible retained versions and files. Retained history can continue to reference data that no longer appears in the latest table version. -In OSS, `optimize()` provides maintenance operations. In Enterprise, managed +In LanceDB Embedded, `optimize()` provides maintenance operations. In Enterprise, managed maintenance and retention follow the service configuration. Choose retention according to the history you need, rather than shortening it as part of a routine delete example. See [Compaction](/maintenance/compaction) and diff --git a/docs/web/ingestion/index.mdx b/docs/web/ingestion/index.mdx index c37b46a62..9eb453cd6 100644 --- a/docs/web/ingestion/index.mdx +++ b/docs/web/ingestion/index.mdx @@ -8,7 +8,7 @@ availability: oss: available enterprise: available summary: >- - Create tables and write records through the SDKs in OSS and Enterprise. Enterprise also provides SQL write statements. + Create tables and write records through the SDKs in LanceDB Embedded and LanceDB Enterprise. Enterprise also provides SQL write statements. --- import { PyWriteWorkflow, TsWriteWorkflowBody, TsWriteWorkflowTail, RsWriteWorkflow } from '/snippets/ingestion_examples.mdx'; @@ -32,7 +32,7 @@ with a stable key when the incoming data should update existing records. ## Connect and prepare the data {#connect-to-lancedb} -Use the [connection guide](/basics/connect) to connect to OSS or Enterprise. +Use the [connection guide](/basics/connect) to connect to LanceDB Embedded or LanceDB Enterprise. The SDK write operations in this section work with both. Enterprise also supports [SQL write statements](/sql#dml); an SDK filter expression does not require a separate SQL connection. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index f2ee0d7db..2c5823f4e 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Append records through the SDKs in OSS and Enterprise. For large Enterprise writes, see [large upload settings](#bulk-ingests-into-a-remote-table). + Append records through the SDKs in LanceDB Embedded and LanceDB Enterprise. For large Enterprise writes, see [large upload settings](#bulk-ingests-into-a-remote-table). --- import { @@ -167,7 +167,7 @@ Wait for the write operation's result, then check the expected records. Progress callbacks describe activity; they do not establish that a write succeeded. If a request fails after the server may have committed it, blindly repeating an append can duplicate rows. The client's automatic retries can do -the same: on a remote table, the Python and TypeScript 0.40.0 clients resend an +the same: on an Enterprise table, the Python and TypeScript 0.40.0 clients resend an append after a retryable status such as `504`, even when the server had already committed it, and `add()` still returns success. Reconcile using your record IDs, or choose an upsert policy designed for replay. @@ -176,9 +176,9 @@ IDs, or choose an upsert policy designed for replay. Enterprise -This section applies only to remote tables (`db://` connections). Embedded (local) writes are unaffected. +This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected. -When you write to a remote LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and +When you write to a LanceDB Enterprise table, the client sends the write as one HTTP `insert` request unless it splits the data into more than one partition, which it does for a large input it can measure or when you set [`write_parallelism`](#write-parallelism). A partitioned write goes up as a multipart write: the client cuts each partition into one or more `insert` parts and uploads them under a single upload id. Each part is streamed. Its size and duration still affect resource use and timeouts: it has to finish within the client read timeout while the server writes it to object storage, so on very large ingests an oversized part can run past that timeout and surface as: ```text diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index 6fa59fd9c..74b161c29 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Merge insert is available through the SDKs in OSS and Enterprise. Use it for key-based updates and inserts. + Merge insert is available through the SDKs in LanceDB Embedded and LanceDB Enterprise. Use it for key-based updates and inserts. --- import { @@ -230,7 +230,7 @@ when changing the input used to generate it. Rust's `when_matched_update_all_expr` and `when_not_matched_by_source_delete_expr` accept DataFusion expressions for -local tables. Use the string predicate variants for Enterprise tables. +LanceDB Embedded tables. Use the string predicate variants for Enterprise tables. ## Complete write workflow {#complete-example} diff --git a/docs/web/ingestion/update.mdx b/docs/web/ingestion/update.mdx index d44a2561e..4a5fdaa24 100644 --- a/docs/web/ingestion/update.mdx +++ b/docs/web/ingestion/update.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Update rows through the SDKs in OSS and Enterprise. Enterprise also supports the SQL UPDATE statement. + Update rows through the SDKs in LanceDB Embedded and LanceDB Enterprise. Enterprise also supports the SQL UPDATE statement. --- import { @@ -71,7 +71,7 @@ Rust's `column` argument is an expression, so the string value includes SQL quot In this separate example, Bob keeps his name and his login count becomes **21**. Python's `values_sql` and TypeScript's `valuesSql` accept expressions. -These SDK expressions work with embedded OSS tables; they do not require an +These SDK expressions work with LanceDB Embedded tables; they do not require an Enterprise SQL endpoint. Enterprise also offers [`UPDATE`](/sql/dml/update). ## Verify the affected data {#verify} diff --git a/docs/web/integrations/ai/agno.mdx b/docs/web/integrations/ai/agno.mdx index b5edef031..9ad9daeac 100644 --- a/docs/web/integrations/ai/agno.mdx +++ b/docs/web/integrations/ai/agno.mdx @@ -139,7 +139,7 @@ We get the response based on the transcript's contents and title as expected. ## Why this works well {#why-this-works-well} -To start, LanceDB OSS can run from a local directory, so transcript data can stay on your machine when you are using the OSS stack. +To start, LanceDB Embedded can run from a local directory, so transcript data can stay on your machine. - You do not need to maintain a separate transcript parser in your application code. - You do not need to hand-roll chunking and retrieval orchestration across multiple modules. diff --git a/docs/web/integrations/ai/hermes-agent.mdx b/docs/web/integrations/ai/hermes-agent.mdx index 12fc39da3..e899e2e60 100644 --- a/docs/web/integrations/ai/hermes-agent.mdx +++ b/docs/web/integrations/ai/hermes-agent.mdx @@ -29,7 +29,7 @@ prompt, plus lexical (keyword) search over past sessions. Both are useful, but k misses paraphrases of what you originally typed, the exact thing you need when recalling a fact you phrased differently months ago. -LanceDB OSS is an embedded retrieval library, which makes it a natural fit here: +LanceDB Embedded is a retrieval library that runs inside your application, which makes it a natural fit here: - **No server to stand up**: it reads and writes a table on local disk, so the plugin ships as a dependency rather than a service to operate. diff --git a/docs/web/integrations/data/dlt.mdx b/docs/web/integrations/data/dlt.mdx index 04d688fb9..f5ede936b 100644 --- a/docs/web/integrations/data/dlt.mdx +++ b/docs/web/integrations/data/dlt.mdx @@ -40,7 +40,7 @@ In this example, we will be fetching movie information from the [Open Movie Data 3. **Specify necessary credentials and/or embedding model details:** - To fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB OSS or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. + To fetch data from the OMDb API, you will need to pass a valid API key into your pipeline. Depending on whether you're using LanceDB Embedded or LanceDB Enterprise, you also may need to provide the necessary credentials to connect to the LanceDB instance. These can be pasted inside `.dlt/secrets.toml`. dlt's LanceDB integration also allows you to automatically embed the data during ingestion. Depending on the embedding model chosen, you may need to paste the necessary credentials inside `.dlt/secrets.toml`: ```toml @@ -52,7 +52,7 @@ In this example, we will be fetching movie information from the [Open Movie Data embedding_model = "all-MiniLM-L6-v2" [destination.lancedb.credentials] uri = ".lancedb" - api_key = "api_key" # API key to connect to LanceDB Enterprise. Leave out if you are using LanceDB OSS. + api_key = "api_key" # API key to connect to LanceDB Enterprise. Leave out if you are using LanceDB Embedded. embedding_model_provider_api_key = "embedding_model_provider_api_key" # Not needed for providers that don't need authentication (ollama, sentence-transformers). ``` See [here](https://dlthub.com/docs/dlt-ecosystem/destinations/lancedb#configure-the-destination) for more information and for a list of available models and model providers. diff --git a/docs/web/integrations/data/duckdb.mdx b/docs/web/integrations/data/duckdb.mdx index 23c4891f9..25c982b90 100644 --- a/docs/web/integrations/data/duckdb.mdx +++ b/docs/web/integrations/data/duckdb.mdx @@ -6,7 +6,7 @@ description: "Learn how to use the DuckDB-Lance extension to query Lance tables LanceDB integrates with [DuckDB](https://duckdb.org/) through the [Lance extension](https://github.com/lance-format/lance-duckdb) for DuckDB. In this page, we'll show how LanceDB manages table lifecycle, and DuckDB provides SQL analytics (including joins) and search over those tables. -Note that earlier versions of LanceDB used to recommend converting Lance tables to Arrow tables via `table.to_arrow()`. Although this method is still available for local tables (because DuckDB [natively scans Arrow tables](https://duckdb.org/2021/12/03/duck-arrow)), it is no longer the recommended workflow for working with Lance tables in DuckDB. This page shows how to use the Lance extension with namespace-attached LanceDB tables, allowing you to pushdown SQL queries directly to the Lance layer. +Note that earlier versions of LanceDB used to recommend converting Lance tables to Arrow tables via `table.to_arrow()`. Although this method is still available for LanceDB Embedded tables (because DuckDB [natively scans Arrow tables](https://duckdb.org/2021/12/03/duck-arrow)), it is no longer the recommended workflow for working with Lance tables in DuckDB. This page shows how to use the Lance extension with namespace-attached LanceDB tables, allowing you to pushdown SQL queries directly to the Lance layer. ## Install {#install} diff --git a/docs/web/integrations/data/polars_arrow.mdx b/docs/web/integrations/data/polars_arrow.mdx index 3acfcfea5..8eaaa6440 100644 --- a/docs/web/integrations/data/polars_arrow.mdx +++ b/docs/web/integrations/data/polars_arrow.mdx @@ -43,7 +43,7 @@ Run vector search and keep the results as a Polars `DataFrame` for further proce ## Work with LazyFrames {#work-with-lazyframes} -When you want to operate on the entire table (potentially larger than RAM), convert to a Polars `LazyFrame` so you can chain transformations without loading everything at once. This works for local tables only; with LanceDB Enterprise, `search(...).to_polars()` returns an eager DataFrame of query results. +When you want to operate on the entire table (potentially larger than RAM), convert to a Polars `LazyFrame` so you can chain transformations without loading everything at once. This works for LanceDB Embedded tables only; with LanceDB Enterprise, `search(...).to_polars()` returns an eager DataFrame of query results. {PyPlatformsPolarsLazyframe} diff --git a/docs/web/maintenance/background-jobs.mdx b/docs/web/maintenance/background-jobs.mdx index 1a710fe79..cfeab74df 100644 --- a/docs/web/maintenance/background-jobs.mdx +++ b/docs/web/maintenance/background-jobs.mdx @@ -48,7 +48,7 @@ log from growing without bound: | --- | --- | | `prewarm_page_cache` | Loads table data into a query node's page cache ahead of a request needing it. | | `prewarm_index_cache` | The same, for index structures. | -| `startup_prewarm_idx` | Runs cache prewarming as part of a plan executor's own startup, rather than on a schedule, when the deployment enables it. | +| `startup_prewarm_idx` | Runs cache prewarming as part of an executor's own startup, rather than on a schedule, when the deployment enables it. | ## Registry housekeeping {#registry} diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 7833fa8a0..4b9e24796 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -18,7 +18,7 @@ those versions referenced. **Enterprise job type:** `cleanup`. Distinct from `compact`: compaction -merges files, cleanup removes them. `optimize()` in OSS runs both in one call; +merges files, cleanup removes them. `optimize()` in LanceDB Embedded runs both in one call; Enterprise schedules them as separate jobs, and runs cleanup only when the deployment's configuration enables it. @@ -89,8 +89,9 @@ directly can corrupt current or historical snapshots. Upgrade all clients and maintenance workers to a version that understands Managed blobs before using them, and reopen handles created before that upgrade. -For local tables, `optimize()` performs compaction and cleanup. Enterprise runs -these as background jobs; the remote Python table does not support `optimize()`. +For LanceDB Embedded tables, `optimize()` performs compaction and cleanup. +Enterprise runs these as background jobs; Python tables connected to Enterprise +do not support `optimize()`. See [Background jobs](/maintenance/background-jobs) for the Enterprise path. ## Disk usage does not drop immediately {#disk} diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 8b0a8c86f..be6685d9c 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -24,7 +24,7 @@ Run optimization as regular table maintenance, particularly after many small writes or a large ingest. {/* -Draft for the OSS compaction SQ partition check release. Keep this section +Draft for the LanceDB Embedded compaction SQ partition check release. Keep this section unpublished until that behavior ships. ### Recover from an oversized SQ partition {#oversized-sq-partition} @@ -62,7 +62,7 @@ needs to. **Enterprise job type:** `compact`. Runs automatically as data accumulates, separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs -even though `optimize()` bundles both in one OSS call. +even though `optimize()` bundles both in one LanceDB Embedded call. ## Retraining indexes {#retrain} @@ -113,7 +113,7 @@ Two things accumulate on a long-lived table as more and more data gets added to - **Many small fragments build up as you write**, slowing down queries that have to scan across more files. **Compaction** merges them back into larger fragments. - **Old versions build up as the table changes**, growing disk usage beyond the live data size (LanceDB retains them for time-travel and rollback). **Cleanup** prunes versions older than a retention window. -In OSS, you run them yourself via `optimize()`, which bundles both into a single call: +In LanceDB Embedded, you run them yourself via `optimize()`, which bundles both into a single call: ```python Python icon="python" from datetime import timedelta @@ -129,7 +129,7 @@ until the first supported release is confirmed. ### Tune compaction for wide rows {#tune-wide-rows} -For an existing local table, derive a fragment row target from the expected +For an existing LanceDB Embedded table, derive a fragment row target from the expected row size. These examples use rows averaging 1 KiB and a 64 KiB fragment target; choose sizes for your workload. Smaller scan batches and one compaction task at a time can also reduce memory use. @@ -148,7 +148,7 @@ separately when needed; Python's `optimize()` includes those steps. TypeScript's `optimize()` does not currently expose the fragment row target, scan batch size, or compaction thread count. These tuning examples apply to -Python and Rust local tables. +Python and Rust tables in LanceDB Embedded. Planning remains row based. The row target bounds later passes after existing oversized fragments have been rewritten; the first pass rewrites those diff --git a/docs/web/management/database.mdx b/docs/web/management/database.mdx index a4b76f195..35b63c308 100644 --- a/docs/web/management/database.mdx +++ b/docs/web/management/database.mdx @@ -8,8 +8,9 @@ availability: oss: available enterprise: available summary: >- - OSS opens tables in a local directory or object storage. Enterprise connects - to remote compute with a database URI and credentials. + LanceDB Embedded opens tables in a local directory or object storage. + LanceDB Enterprise connects with a database URI and credentials and runs + operations with LanceDB Distributed. --- import { PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; @@ -22,14 +23,15 @@ objects, and configure how your application reaches the data. | URI | Offering | Where queries run | | --- | --- | --- | -| `./.lancedb` | OSS, with local storage | In your application | -| `s3://bucket/path`, `gs://bucket/path`, `az://container/path` | OSS, with object storage | In your application | -| `db://my-database` | Enterprise | On remote compute | +| `./.lancedb` | LanceDB Embedded, with local storage | In your application | +| `s3://bucket/path`, `gs://bucket/path`, `az://container/path` | LanceDB Embedded, with object storage | In your application | +| `db://my-database` | LanceDB Enterprise | On the Enterprise service (LanceDB Distributed) | [Connect to LanceDB](/basics/connect) has examples for each connection type. -A connection to object storage still uses the embedded library: your process -reads and writes the bucket directly. Enterprise runs operations remotely and -manages the supporting compute and maintenance. +A connection to object storage still uses LanceDB Embedded: your process +reads and writes the bucket directly. LanceDB Enterprise runs LanceDB +Distributed: query execution, indexing and maintenance run on the Enterprise +service, outside your application. ## Connect to Enterprise {#deployment} @@ -60,7 +62,7 @@ manager. See [Authentication](/enterprise/authentication) for OAuth and ## Storage options {#storage-options} -For OSS tables in object storage, `storage_options` configures credentials, +For LanceDB Embedded tables in object storage, `storage_options` configures credentials, endpoints and options for new tables. This example enables stable row IDs for tables created through the connection: @@ -91,7 +93,7 @@ See [Storage](/deployment/storage) for provider credentials and other options. ## Read consistency {#consistency} -For OSS connections, `read_consistency_interval` controls how often reads check +For LanceDB Embedded connections, `read_consistency_interval` controls how often reads check for table versions committed by other writers. For example, check at most once every five seconds: @@ -112,7 +114,7 @@ const db = await lancedb.connect("./.lancedb", { readConsistencyInterval: 5 }); ``` -By default, an OSS table handle does not automatically pick up another +By default, an Embedded table handle does not automatically pick up another process's writes. Reopen the table, check out its latest version, or configure a consistency interval when you need those updates. A zero interval checks on every read, with the cost of a metadata check. @@ -139,7 +141,7 @@ versions and lifecycle operations. Dropping a table removes its history as well as its current data. You cannot -recover a dropped table through table versioning. The OSS `drop_database()` +recover a dropped table through table versioning. The LanceDB Embedded `drop_database()` and `drop_all_tables()` operations remove all tables without a confirmation prompt. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index fd9cb7c19..7825b0bf6 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -8,7 +8,7 @@ availability: oss: unavailable enterprise: available summary: >- - Enterprise supports Functions when enabled for your Enterprise cluster; the embedded library cannot register or run them. + Enterprise supports Functions when enabled for your Enterprise cluster; LanceDB Embedded cannot register or run them. --- import { @@ -31,8 +31,8 @@ rather than pulling rows to your process. Registering and running a function needs a LanceDB Enterprise deployment with Functions enabled, which they are not by default. On a -local connection `create_function` raises `NotImplementedError`; to derive a -column locally, declare a +LanceDB Embedded connection `create_function` raises `NotImplementedError`; to +derive a column there, declare a [SQL computed column](/feature-engineering/add-computed-column) instead. @@ -282,14 +282,15 @@ as `bytes`; this feature does not add streamed outputs. ## Declare the environment {#environment} -The function runs remotely, so its dependencies are part of its definition: +The function runs on the Enterprise service, not in your application, so its +dependencies are part of its definition: | | | | --- | --- | -| `pip` | requirements for the remote environment | +| `pip` | requirements for the function's execution environment | | `conda`, `conda_channels` | conda packages instead of pip; channels in priority order | | `env` | environment variables | -| `python_version` | remote Python major/minor, defaulting to yours | +| `python_version` | Python major/minor for the execution environment, defaulting to yours | | `gpu` | whether every execution requires a GPU | These are part of the **immutable function version**. Changing a dependency diff --git a/docs/web/management/materialized-view.mdx b/docs/web/management/materialized-view.mdx index 221e02dcb..42245a51a 100644 --- a/docs/web/management/materialized-view.mdx +++ b/docs/web/management/materialized-view.mdx @@ -78,8 +78,8 @@ That also means dropping one removes stored rows, unlike dropping a ## Enterprise compatibility {#deployment} -Enterprise supports creating and refreshing materialized views on remote -compute. Use the SDK version supported by your deployment, or the +Enterprise supports creating and refreshing materialized views on the +Enterprise service. Use the SDK version supported by your deployment, or the [SQL interface](/sql/ddl/materialized-view). See [Enterprise refreshes](/feature-engineering/materialized-views#availability) for compatibility considerations when upgrading an existing pipeline. diff --git a/docs/web/management/namespace.mdx b/docs/web/management/namespace.mdx index dda6b918f..0d80831c9 100644 --- a/docs/web/management/namespace.mdx +++ b/docs/web/management/namespace.mdx @@ -22,7 +22,7 @@ import { } from '/snippets/connection.mdx'; LanceDB organizes Lance tables through a catalog-level abstraction defined by -the *namespace spec*. LanceDB OSS is an embedded library for accessing those +the *namespace spec*. LanceDB Embedded is an embedded library for accessing those tables, and LanceDB Enterprise is a multimodal lakehouse that provides shared compute and catalog services on top of the Lance format. If you're coming from traditional databases or lakehouses, you can think of a namespace as the catalog path that says where a table name lives. @@ -76,7 +76,7 @@ directory. Namespaces can nest inside it, as in this hierarchy: The hierarchy is logical, not a tree of folders: a directory namespace records it in a `__manifest` table in the root directory, and stores each table in a directory of its own there. -As a user of LanceDB OSS, you might never notice namespaces at first, because a plain connection +As a user of LanceDB Embedded, you might never notice namespaces at first, because a plain connection uses only the root namespace, which is implicit. Connecting to this namespace is as simple as connecting to the catalog root: @@ -165,7 +165,7 @@ println!("Created table: {}", table.name()); -- For simple use cases in LanceDB OSS, you don't need to go too deep into namespaces. +- For simple use cases in LanceDB Embedded, you don't need to go too deep into namespaces. - To integrate LanceDB with external catalogs, understand how each namespace implementation resolves table names and locations in your organization's setup. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 182a80ec3..bf256ac97 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -248,7 +248,7 @@ set to the exact version a model saw. A shallow clone depends on the source's files continuing to exist. If the source is [compacted](/maintenance/compaction) past the retention window, the version -the clone points at can be pruned. Local OSS connections support shallow clones +the clone points at can be pruned. LanceDB Embedded connections support shallow clones only; `is_shallow=False` is not implemented. If the copy must outlive the source's history, copy its data into an independent table instead. A deployment that supports cloning also makes shallow clones only, and one whose catalog @@ -462,8 +462,9 @@ pylance. Pandas conversions that need the Lance scanner, including plain-scan `"lazy"` handles and legacy blobs, still require pylance. `to_arrow()`, `to_list()`, `to_batches()`, and the fetch methods do not require pylance. -`blob_mode="bytes"` requires a local table snapshot, so remote and in-memory -tables raise `NotImplementedError`. On a remote table, `Table.to_pandas()` and +`blob_mode="bytes"` requires a LanceDB Embedded table snapshot, so Enterprise +and in-memory tables raise `NotImplementedError`. On an Enterprise table, +`Table.to_pandas()` and `Table.to_arrow()` aren't supported, and a query's `to_pandas()` also raises in the default `"lazy"` mode because it would open `BlobFile` handles. Query with `blob_mode="descriptions"`, then read bytes with `fetch_blobs` or @@ -495,7 +496,7 @@ descriptors. Both `"bytes"` and `"descriptions"` hide automatic row IDs; explicitly requested row IDs remain visible. Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, -including no legacy blobs, blobs inside lists, remote tables, or namespace +including no legacy blobs, blobs inside lists, Enterprise tables, or namespace `QueryTable` pushdown. If concurrent writers can overwrite the table, use a separate reader checked out to a fixed version before querying. Otherwise, an overwrite can invalidate the row IDs used to fetch bytes and raise @@ -686,7 +687,7 @@ between inline values and Managed objects. Enterprise Functions can consume blob columns and return new blobs. Their output payloads are managed by the destination table. -Local tables can also derive blob columns with +LanceDB Embedded tables can also derive blob columns with [SQL computed columns](/feature-engineering/add-computed-column). Deleting a row or replacing its blob does not immediately remove the old @@ -741,8 +742,8 @@ Write raw bytes to a V1 blob column: #### 3\. Convert blob tables to pandas {#multimodal-3-convert-blob-tables-to-pandas} -On local tables with V1 blob columns, `to_pandas()` in Python accepts `blob_mode` -(`"lazy"`, `"bytes"`, or `"descriptions"`). Remote tables raise +On LanceDB Embedded tables with V1 blob columns, `to_pandas()` in Python accepts +`blob_mode` (`"lazy"`, `"bytes"`, or `"descriptions"`). Enterprise tables raise `NotImplementedError`, and `"bytes"` is not supported on in-memory tables. Extra keyword arguments such as `split_blocks` or `self_destruct` are forwarded to the PyArrow / Lance pandas conversion: @@ -1537,7 +1538,7 @@ mixing in lower-level Lance file operations. **System Operations** System operations like `optimize()`, index updates, and table compaction also increment table version numbers. -In LanceDB OSS, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default), +In LanceDB Embedded, `optimize()` can prune older versions based on its retention setting (`cleanup_older_than`, 7 days by default), which is when old-version files are removed and disk space is reclaimed. A deployment prunes them in the background when its configuration enables [cleanup](/maintenance/cleanup); `optimize()` is not available there. diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 3f466041d..645e0565e 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -7,7 +7,8 @@ icon: rocket import { PyConnect, TsConnect, RsConnect, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartVectorSearch1, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1 } from '/snippets/quickstart.mdx'; -This quickstart uses a local database and works without an account or API key. +This quickstart uses LanceDB Embedded with a local database and works without an account or API key. +LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. Follow the steps below, or jump to the [complete examples](#code) to copy a runnable program. @@ -154,7 +155,7 @@ Use the database URI, API key, and endpoint provided by your administrator or th In application code, load credentials from environment variables or a secrets manager. See [connection settings](/basics/connect#enterprise) for an example. -Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between local and server execution, see [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise). +Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between Embedded and Distributed execution, see [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise). diff --git a/docs/web/reranking/index.mdx b/docs/web/reranking/index.mdx index 26db30442..ccaa70e9b 100644 --- a/docs/web/reranking/index.mdx +++ b/docs/web/reranking/index.mdx @@ -8,7 +8,7 @@ availability: oss: available enterprise: available summary: >- - Reranking is available with OSS and Enterprise. + Reranking is available with LanceDB Embedded and LanceDB Enterprise. --- import { diff --git a/docs/web/search/explain.mdx b/docs/web/search/explain.mdx index 383745e5b..1a1fa3330 100644 --- a/docs/web/search/explain.mdx +++ b/docs/web/search/explain.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Query plans are available in OSS and Enterprise. + Query plans are available in LanceDB Embedded and LanceDB Enterprise. --- import { PyQueryPlan, TsQueryPlanBody, TsQueryPlanTail } from '/snippets/search_examples.mdx'; @@ -26,7 +26,7 @@ the query and adds measurements, including execution time and rows processed. Use the first to inspect query structure and the second to investigate work actually performed. Operator names and available measurements can differ -between OSS and Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/sql/dql/explain). +between LanceDB Embedded and LanceDB Enterprise. SQL provides [EXPLAIN and EXPLAIN ANALYZE](/sql/dql/explain). @@ -161,7 +161,7 @@ CoalesceBatchesExec: target_batch_size=1024 #### 5\. Data Retrieval {#5-data-retrieval} -- `RemoteTake` is the deployment's operator for this step; a local plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version +- `RemoteTake` is the deployment's operator for this step; a LanceDB Embedded plan shows Lance's `Take` or a `LanceRead` over the selected row IDs, depending on the library version - Handles efficient data retrieval from remote storage locations - Fetches specific rows and columns needed for the final output - Optimizes network bandwidth by only retrieving required data @@ -328,25 +328,26 @@ ProjectionExec: expr=[chunk_index@4 as chunk_index, title@5 as title, identifier -### Distributed metrics on remote tables {#distributed-metrics-on-remote-tables} +### Distributed metrics on LanceDB Enterprise {#distributed-metrics-on-remote-tables} Enterprise -When you call `analyze_plan` against a LanceDB Enterprise deployment that distributes its queries across a pool of workers, the query runs on those workers. By default the returned plan aggregates each operator's metrics into a single value, matching the local single-node output. Pass a `distributed_metrics` mode when you need to see how work was split across workers: +When you call `analyze_plan` against a LanceDB Enterprise deployment that distributes its queries across a pool of workers, the query runs on those workers. By default the returned plan aggregates each operator's metrics into a single value, matching the single-node output of LanceDB Embedded. Pass a `distributed_metrics` mode when you need to see how work was split across workers: | Mode | What it shows | When to use it | | :------------ | :---------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ | -| `aggregate` | One summary value per operator (default). Same shape as local `analyze_plan`. | Everyday performance checks and comparisons against a local plan. | +| `aggregate` | One summary value per operator (default). Same shape as Embedded `analyze_plan`. | Everyday performance checks and comparisons against an Embedded plan. | | `per_worker` | Metrics reported separately for each worker that participated in the query. | Diagnosing stragglers or uneven work distribution across the cluster. | | `full` | Both the aggregate summary and the per-worker breakdown. | Deep investigations where you need the totals *and* the per-worker detail in a single output. | Python exposes this option through `distributed_metrics`. In TypeScript, pass -the same mode to `analyzePlan()` as its `distributedMetrics` argument. Local -Python queries ignore the distributed mode and return local measurements. +the same mode to `analyzePlan()` as its `distributedMetrics` argument. Python +queries on LanceDB Embedded ignore the distributed mode and return single-node +measurements. ```python Python icon="python" -# Show a per-worker breakdown for a remote query +# Show a per-worker breakdown for a query on LanceDB Enterprise plan = ( table.search(query_embed) .where("identifier > 0 AND identifier < 1000000") diff --git a/docs/web/search/filtering.mdx b/docs/web/search/filtering.mdx index 50d37acc0..a3ad6f735 100644 --- a/docs/web/search/filtering.mdx +++ b/docs/web/search/filtering.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Metadata filtering is available in OSS and Enterprise. + Metadata filtering is available in LanceDB Embedded and LanceDB Enterprise. --- import { PyFilterSearch, TsFilterSearchBody, TsFilterSearchTail } from '/snippets/search_examples.mdx'; diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index bc174d5bd..5e0d7d8d7 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Full-text search is available in OSS and Enterprise. + Full-text search is available in LanceDB Embedded and LanceDB Enterprise. --- import { @@ -131,7 +131,7 @@ tbl ``` -OSS builds the index before the call returns. Enterprise builds it in the +LanceDB Embedded builds the index before the call returns. Enterprise builds it in the background. Wait for completion with Python’s `table.wait_for_index(["text_idx"])` or TypeScript’s `await tbl.waitForIndex(["text_idx"], 300)` before querying it. Use your actual index name if you chose a different one. @@ -187,7 +187,7 @@ values rather than probabilities. ### Keeping the index up to date {#keeping-the-index-up-to-date} -In OSS, new rows can remain outside the FTS index until you optimize the table. +In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. Search includes those rows by scanning them, but that work can increase query latency. Call `optimize()` to update the index: @@ -207,7 +207,7 @@ tbl.optimize(OptimizeAction::All).await?; ``` -Choose an OSS maintenance schedule based on write volume and query latency. +Choose a LanceDB Embedded maintenance schedule based on write volume and query latency. Inspect index coverage with `table.index_stats(...)` and optimize when the unindexed data adds too much work. `.fast_search()` skips unindexed rows, so use it only when omitting recent records is acceptable. @@ -289,7 +289,7 @@ export LANCE_LANGUAGE_MODEL_HOME=/path/to/lance/language_models For example, `jieba/default` is resolved under `/jieba/default/...`, `lindera/ipadic` under `/lindera/ipadic/...`, and `lindera/ko-dic` under `/lindera/ko-dic/...`. Model files must be installed where indexing and queries run: on your machine -for OSS, or on the Enterprise cluster for a remote table. +for LanceDB Embedded, or on the Enterprise cluster for an Enterprise table. Built-in stop-word removal supports Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Portuguese, Russian, Spanish, and Swedish. If you use another stemming language, such as Arabic, Greek, Romanian, Tamil, or Turkish, set `remove_stop_words=False` or pass `custom_stop_words`. diff --git a/docs/web/search/hybrid-search.mdx b/docs/web/search/hybrid-search.mdx index c3e453145..1100c073a 100644 --- a/docs/web/search/hybrid-search.mdx +++ b/docs/web/search/hybrid-search.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Hybrid search is available in OSS and Enterprise. + Hybrid search is available in LanceDB Embedded and LanceDB Enterprise. --- import { PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; @@ -84,9 +84,9 @@ import { Utf8 } from "apache-arrow"; ### 2\. Connect to LanceDB {#2-connect-to-lancedb} -Choose a local OSS connection or use your Enterprise connection details. +Choose a LanceDB Embedded connection or use your Enterprise connection details. -OSS +Embedded ```python Python icon="python" @@ -389,7 +389,7 @@ which relevant rows reach the candidate set before evaluating how a reranker orders them. Record latency as well as relevance: increasing candidate counts or applying a model-based reranker adds work. -Reranking runs in the application for both OSS and Enterprise connections. +Reranking runs in the application for both Embedded and Enterprise connections. See [Reranking](/reranking) for model-free fusion, model-based rerankers, custom implementations and score interpretation. diff --git a/docs/web/search/index.mdx b/docs/web/search/index.mdx index 9d439b204..c4bdd5cae 100644 --- a/docs/web/search/index.mdx +++ b/docs/web/search/index.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Vector, full-text and hybrid search are available in OSS and Enterprise. + Vector, full-text and hybrid search are available in LanceDB Embedded and LanceDB Enterprise. --- import { PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx'; @@ -106,9 +106,9 @@ in [Data loading](/training/data-loading). The SDK buffers Enterprise query responses before exposing batches. Set a query limit rather than relying on batch iteration alone to bound memory. -Direct Lance dataset access through Python's `table.to_lance()` is an OSS -interface. Use the SDK query builders for reads that need to work with both -OSS and Enterprise. +Direct Lance dataset access through Python's `table.to_lance()` is a LanceDB +Embedded interface. Use the SDK query builders for reads that need to work with +both LanceDB Embedded and LanceDB Enterprise. ## Investigate a slow query {#diagnostics} diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index cc6ae5421..59fbc1cc9 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -7,7 +7,7 @@ availability: oss: available enterprise: available summary: >- - Vector search is available in OSS and Enterprise. + Vector search is available in LanceDB Embedded and LanceDB Enterprise. --- import { @@ -131,7 +131,7 @@ Without a vector index, searches use `l2` by default. You can specify `cosine` o When a vector index exists, the search metric must match the metric used to build the index. If you explicitly request a different metric, LanceDB cannot use that -index and falls back to an exhaustive (brute-force) search. On LanceDB Cloud, the +index and falls back to an exhaustive (brute-force) search. On LanceDB Cloud (legacy hosted service), the brute-force KNN safety limit can reject that search on a large table instead of executing it. LanceDB Enterprise doesn't have the limit. @@ -623,7 +623,7 @@ tbl.create_index(metric="cosine", vector_column_name="vector") **Indexing matters more for multivector tables than for single-vector ones.** A brute-force scan over a multivector column has to compare every query vector to every document vector in every row, so the cost grows with both the row count and the number of vectors per row. -In LanceDB OSS, the query will just run, so a large unindexed multivector table can stall a process for a long time before returning results. +In LanceDB Embedded, the query will just run, so a large unindexed multivector table can stall a process for a long time before returning results. On LanceDB Cloud, the brute-force KNN safety check applies a stricter row threshold to multivector columns; roughly 10× lower than for single-vector columns. So an unindexed multivector table can be rejected with a "vector search would use brute-force KNN" error well before a comparable single-vector table would. LanceDB Enterprise doesn't have the limit. Build the index before you start hitting it from production traffic, even if the dataset is small enough that you'd skip indexing for a single-vector workload. diff --git a/docs/web/static/assets/images/overview/lancedb-architecture.svg b/docs/web/static/assets/images/overview/lancedb-architecture.svg index 8fe3ff3c9..585dfe991 100644 --- a/docs/web/static/assets/images/overview/lancedb-architecture.svg +++ b/docs/web/static/assets/images/overview/lancedb-architecture.svg @@ -1,6 +1,6 @@ - LanceDB OSS and Enterprise architecture - OSS runs the application and embedded library in one process with local disk or object storage. Enterprise separates query serving, read execution and caching, and indexing and background workers. The control plane governs the service. Enterprise persists tables in object storage. Both offerings use the Lance format, without automatically sharing storage. + LanceDB Embedded and Enterprise architecture + LanceDB Embedded runs the application and embedded library in one process with local disk or object storage. Enterprise separates query serving, read execution and caching, and indexing and background workers. The control plane governs the service. Enterprise persists tables in object storage. Both offerings use the Lance format, without automatically sharing storage.

For LanceDB Cloud, use the simplified builder API: + *

For LanceDB Cloud (legacy hosted service), use the simplified builder API: * *

{@code
  * import org.lance.namespace.LanceNamespace;
diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java
index 2b40ef798..ee5bcfc7b 100644
--- a/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java
+++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java
@@ -27,7 +27,7 @@ import java.io.IOException;
 import java.io.UncheckedIOException;
 
 /**
- * Minimal HTTP client for LanceDB Cloud and Enterprise routes that the Lance Namespace
+ * Minimal HTTP client for LanceDB Enterprise routes that the Lance Namespace
  * specification does not cover.
  *
  * 

Most table operations reach LanceDB through {@link org.lance.namespace.LanceNamespace}, which diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java index b0a61233c..606f31076 100644 --- a/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java +++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableRTE.java @@ -22,7 +22,7 @@ import java.util.Optional; import java.util.OptionalLong; /** - * The RTE write path for one LanceDB Cloud or Enterprise table. + * The RTE write path for one LanceDB Enterprise table. * *

Installing an {@link RTEWriteSpec} routes {@code mergeInsert} upserts through Lance's RTE — an * LSM-style append — instead of the standard merge path. Rows land in an in-memory memtable, freeze diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 80befcc67..8d5c21aa3 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -115,14 +115,14 @@ describe("remote connection", () => { ...options, mode: "overwrite", }), - ).rejects.toThrow(/write_options.*remote/); + ).rejects.toThrow(/write_options.*LanceDB Distributed/); await expect( db.createEmptyTable( "test", new Schema([new Field("value", new Int64(), true)]), options, ), - ).rejects.toThrow(/write_options.*remote/); + ).rejects.toThrow(/write_options.*LanceDB Distributed/); }, ); expect(requests).toEqual([]); @@ -140,7 +140,9 @@ describe("remote connection", () => { async (db) => { await expect( db.openTable("test", undefined, options), - ).rejects.toThrow(/not supported for remote/); + ).rejects.toThrow( + /not supported for table access in LanceDB Distributed/, + ); }, ); expect(requests).toEqual([]); @@ -316,7 +318,7 @@ describe("remote connection", () => { ], ]; for (const [run, operation] of cases) { - let message = `LanceDBError: not supported: ${operation} is not supported for remote tables.`; + let message = `LanceDBError: not supported: ${operation} is not supported in LanceDB Distributed.`; if (operation === "IVF_HNSW_PQ") { message += " Please use IVF_HNSW_SQ instead."; } @@ -463,7 +465,7 @@ describe("remote connection", () => { table.add([{ id: 1n }], { allowExternalBlobOutsideBases: true, }), - ).rejects.toThrow("only supported on local tables"); + ).rejects.toThrow("only supported in LanceDB Embedded"); expect(insertRequests).toBe(0); await expect(table.add([{ id: 2n }])).resolves.toMatchObject({ diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index c9e1efcb6..6db5b2f4d 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4526,14 +4526,14 @@ describe.each(arrowVersions)( ]; const table = await db.createTable("prewarm_data_test", data); - // prewarmData is only supported on remote tables. We verify the call + // prewarmData is only supported in LanceDB Distributed. We verify the call // is wired through napi and surfaces the expected error for both // arg shapes (undefined and string[]). await expect(table.prewarmData()).rejects.toThrow( - "prewarm_data is currently only supported on remote tables", + "prewarm_data is currently only supported in LanceDB Distributed", ); await expect(table.prewarmData(["text"])).rejects.toThrow( - "prewarm_data is currently only supported on remote tables", + "prewarm_data is currently only supported in LanceDB Distributed", ); }); @@ -5506,7 +5506,7 @@ describe("computed columns", () => { const db = await connect(tmpDir.name); const table = await db.createTable("errors_local", [{ x: 1 }]); await expect(table.functionErrors()).rejects.toThrow( - "LanceDB Cloud and Enterprise", + "recorded only in LanceDB Distributed", ); }); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 82729644c..4cfcaf990 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -274,7 +274,7 @@ export class BlobFile { export type BlobReadOptions = { /** * Cancels the read. The call rejects with `signal.reason`, and the native - * read stops, including in-flight requests to a remote table. + * read stops, including in-flight requests to a LanceDB Distributed table. */ signal?: AbortSignal; }; diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 62f218e16..d5a856894 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -270,9 +270,9 @@ export abstract class Connection { /** * Define a materialized view named `name` over the table `source`. * - * Local creation and refresh require a source build with the + * LanceDB Embedded creation and refresh require a source build with the * `experimental-functions` Cargo feature, disabled in published packages. - * Remote Cloud/Enterprise operations do not require this feature. + * LanceDB Distributed operations do not require this feature. * * The view is populated before creation returns. Set `withNoData` to create * only its definition and empty backing table. The view is a normal table: @@ -559,7 +559,7 @@ export abstract class Connection { /** * Rename a table. * - * Currently only supported by LanceDB Cloud. Local OSS connections and + * Currently only supported in LanceDB Distributed. LanceDB Embedded connections and * namespace-backed connections (via {@link connectNamespace}) reject with * a "not supported" error. * diff --git a/nodejs/lancedb/header.ts b/nodejs/lancedb/header.ts index bf86c5332..4926ccec9 100644 --- a/nodejs/lancedb/header.ts +++ b/nodejs/lancedb/header.ts @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors /** - * Header providers for LanceDB remote connections. + * Header providers for LanceDB Enterprise connections. * * This module provides a flexible header management framework for LanceDB remote * connections, allowing users to implement custom header strategies for diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index b9c334a08..52f94f554 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -288,11 +288,11 @@ export async function tokenize( * * Accepted formats: * - * - `/path/to/database` - local database + * - `/path/to/database` - database on the local file system * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage - * - `db://host:port` - remote database (LanceDB cloud) + * - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database * @param {string} uri - The uri of the database. If the database uri starts - * with `db://` then it connects to a remote database. + * with `db://` then it connects to LanceDB Enterprise or LanceDB Cloud (legacy). * @see {@link ConnectionOptions} for more details on the URI format. * @param options - The options to use when connecting to the database * @example @@ -333,9 +333,9 @@ export async function connect( * * Accepted formats: * - * - `/path/to/database` - local database + * - `/path/to/database` - database on the local file system * - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud storage - * - `db://host:port` - remote database (LanceDB cloud) + * - `db://host:port` - LanceDB Enterprise or LanceDB Cloud (legacy) database * @param options - The options to use when connecting to the database * @see {@link ConnectionOptions} for more details on the URI format. * @example @@ -533,7 +533,7 @@ function restConfigToProperties( * Connect to a LanceDB database through a namespace. * * Unlike {@link connect}, which routes by URI scheme (local path vs. - * `db://` cloud), `connectNamespace` always returns a namespace-backed + * `db://`), `connectNamespace` always returns a namespace-backed * connection. The `implName` selects the namespace implementation: * * - `"dir"` — directory namespace, configured with {@link DirNamespaceConfig}. diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 71408803d..8e7cd02a1 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -128,8 +128,8 @@ export interface AddDataOptions { /** * Whether blob URIs outside registered external bases may be written. * - * Defaults to `false`. This option is supported only for local/native - * tables; remote tables return an error when it is enabled. An enabled write + * Defaults to `false`. This option is supported only in LanceDB Embedded; + * LanceDB Distributed returns an error when it is enabled. An enabled write * stores the absolute URI reference without registering a base or copying * the external object into the database. The object must remain accessible * when the blob is read later. @@ -438,7 +438,7 @@ export abstract class Table { * Large columns (e.g. high-dimensional vectors or binary data) may not be * practical to prewarm. * - * This feature is currently only supported on remote tables. + * This feature is currently only supported in LanceDB Distributed. */ abstract prewarmData(columns?: string[]): Promise; @@ -594,9 +594,9 @@ export abstract class Table { /** * Add new columns with defined values. * - * Local computed-column declaration and refresh require a source build with - * the `experimental-functions` Cargo feature. Published packages disable it; - * remote Cloud/Enterprise operations remain available. + * LanceDB Embedded computed-column declaration and refresh require a source + * build with the `experimental-functions` Cargo feature. Published packages + * disable it; LanceDB Distributed operations remain available. * * The `{ computed }` form stores the expression rather than evaluating it * now: the column is committed with no values, and rows get them from @@ -608,7 +608,7 @@ export abstract class Table { * declaration reads a column, that column cannot be renamed, retyped or * dropped. * - * On LanceDB Cloud and Enterprise the expression is planned by the + * In LanceDB Distributed the expression is planned by the * server, and the refresh runs as a server job -- see * {@link Table#refreshColumnAsync}. * @param {AddColumnsSql[] | Field | Field[] | Schema} newColumnTransforms Either: @@ -640,8 +640,8 @@ export abstract class Table { * * Rows appended since the last refresh are filled by the next one, and * rows whose inputs changed since they were computed are recomputed; - * everything else is left as it is. Local tables only: a remote refresh - * runs as a server job, through {@link Table#refreshColumnAsync}. + * everything else is left as it is. LanceDB Embedded only: in LanceDB + * Distributed a refresh runs as a server job, through {@link Table#refreshColumnAsync}. * @param {string} column The name of the computed column to fill. * @returns {Promise} A promise that resolves to the * number of rows filled and the new version number of the table. @@ -651,14 +651,15 @@ export abstract class Table { /** * Like {@link Table#refreshColumn}, but returns a handle to the refresh * job instead of blocking until it completes. - * Local refresh requires a source build with `experimental-functions`. - * Remote Cloud/Enterprise jobs do not require this feature. + * LanceDB Embedded refresh requires a source build with + * `experimental-functions`. LanceDB Distributed jobs do not require this + * feature. * * The job may already be complete when returned; callers must not assume * the column is filled until {@link Job.wait} resolves. Invalid input -- * an unknown column, or one that is not computed -- rejects here rather - * than failing the job. On local tables the job runs in-process; on - * LanceDB Cloud and Enterprise it is the server's backfill job. + * than failing the job. In LanceDB Embedded the job runs in-process; in + * LanceDB Distributed it is the server's backfill job. * @param {string} column The name of the computed column to fill. * @example * ```ts @@ -675,7 +676,7 @@ export abstract class Table { * A refresh running under a skip policy records each row it skipped with * the input that failed and the error. This lists those records, newest * job first, plus a summary for any fragment whose per-row detail was - * capped. LanceDB Cloud and Enterprise only; reading errors needs read + * capped. LanceDB Distributed only; reading errors needs read * access to the table, since a message carries the value that failed. * @param {FunctionErrorsOptions} options Optional filters: `jobId`, * `column`, and `limit` (server default 10000, cap 100000). @@ -994,7 +995,7 @@ export abstract class Table { * Specify exactly one of `column` or `indexName`. * * Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in - * the client process from index metadata. For remote tables, this means the + * the client process from index metadata. In LanceDB Distributed, this means the * same tokenizer model files must also exist locally (under * `LANCE_LANGUAGE_MODEL_HOME`) and must match the files the server uses. A * mismatch cannot be detected: the returned tokens may differ from what the diff --git a/nodejs/src/lib.rs b/nodejs/src/lib.rs index cb40a51de..368a3530c 100644 --- a/nodejs/src/lib.rs +++ b/nodejs/src/lib.rs @@ -54,34 +54,34 @@ pub struct ConnectionOptions { /// often each read pays the cost of checking for updates against object /// storage, raising per-read latency and cost. pub read_consistency_interval: Option, - /// (For LanceDB OSS only): configuration for object storage. + /// (For LanceDB Embedded only): configuration for object storage. /// /// The available options are described at https://docs.lancedb.com/storage/ pub storage_options: Option>, - /// (For LanceDB OSS only): use directory namespace manifests as the source + /// (For LanceDB Embedded only): use directory namespace manifests as the source /// of truth for table metadata. Existing directory-listed root tables are /// migrated into the manifest on access. pub manifest_enabled: Option, - /// (For LanceDB OSS only): extra properties for the backing namespace + /// (For LanceDB Embedded only): extra properties for the backing namespace /// client used by manifest-enabled native connections. pub namespace_client_properties: Option>, - /// (For LanceDB OSS only): the session to use for this connection. Holds + /// (For LanceDB Embedded only): the session to use for this connection. Holds /// shared caches and other session-specific state. pub session: Option, - /// (For LanceDB cloud only): configuration for the remote HTTP client. + /// (For LanceDB Enterprise or LanceDB Cloud only): configuration for the HTTP client. pub client_config: Option, - /// (For LanceDB cloud only): the API key to use with LanceDB Cloud. + /// (For LanceDB Enterprise or LanceDB Cloud only): the API key to use. /// /// Can also be set via the environment variable `LANCEDB_API_KEY`. pub api_key: Option, - /// (For LanceDB cloud only): the region to use for LanceDB cloud. + /// (For LanceDB Cloud only): the region to use for LanceDB Cloud (legacy). /// Defaults to 'us-east-1'. pub region: Option, - /// (For LanceDB cloud only): the host to use for LanceDB cloud. Used - /// for testing purposes. + /// (For LanceDB Enterprise only): the host of the LanceDB Enterprise + /// deployment to connect to. pub host_override: Option, - /// (For LanceDB cloud only): OAuth configuration for IdP-based + /// (For LanceDB Enterprise only): OAuth configuration for IdP-based /// authentication (e.g., Azure Entra ID). When set, token acquisition /// and refresh are handled entirely in Rust. TypeScript users should pass /// the public `OAuthConfig` type exported from `@lancedb/lancedb`. diff --git a/nodejs/src/remote.rs b/nodejs/src/remote.rs index 2a6985477..df882334b 100644 --- a/nodejs/src/remote.rs +++ b/nodejs/src/remote.rs @@ -108,7 +108,7 @@ pub struct ClientConfig { pub tls_config: Option, /// User identifier for tracking purposes. /// - /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. + /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise. /// It can be set directly, or via the `LANCEDB_USER_ID` environment variable. /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 2f7d91a2a..ec16ea5b5 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -831,7 +831,7 @@ impl Table { self.inner_ref()? .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "uses_v2_manifest_paths is not supported for remote tables.".into(), + message: "uses_v2_manifest_paths is not supported in LanceDB Distributed.".into(), }) .default_error()? .uses_v2_manifest_paths() @@ -844,7 +844,8 @@ impl Table { self.inner_ref()? .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "migrate_manifest_paths_v2 is not supported for remote tables.".into(), + message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed." + .into(), }) .default_error()? .migrate_manifest_paths_v2() @@ -867,40 +868,40 @@ pub struct IndexConfig { pub columns: Vec, /// The UUID of the first segment of the index. /// - /// `undefined` for remote tables, which do not yet surface this. + /// `undefined` in LanceDB Distributed, which does not yet surface this. pub index_uuid: Option, /// The protobuf type URL, a precise type identifier for the index. /// - /// `undefined` for remote tables. + /// `undefined` in LanceDB Distributed. pub type_url: Option, /// When the index was created. /// - /// `undefined` for remote tables or indices created before timestamps were tracked. + /// `undefined` in LanceDB Distributed or indices created before timestamps were tracked. pub created_at: Option>, /// The number of rows indexed, across all segments. /// - /// May be `undefined` for remote tables if the server does not report it. + /// May be `undefined` in LanceDB Distributed if the server does not report it. pub num_indexed_rows: Option, /// The number of rows not yet covered by this index. /// - /// May be `undefined` for remote tables if the server does not report it. + /// May be `undefined` in LanceDB Distributed if the server does not report it. pub num_unindexed_rows: Option, /// The total size in bytes of all index files across all segments. /// - /// `undefined` for remote tables or indices without size tracking. + /// `undefined` in LanceDB Distributed or indices without size tracking. pub size_bytes: Option, /// The number of segments that make up the index. /// - /// `undefined` for remote tables. + /// `undefined` in LanceDB Distributed. pub num_segments: Option, /// The on-disk index format version. /// - /// `undefined` for remote tables. + /// `undefined` in LanceDB Distributed. pub index_version: Option, /// Index-type-specific details parsed as a JavaScript object. /// - /// Falls back to a raw string if JSON parsing fails. `undefined` for - /// remote tables or when details are unavailable. + /// Falls back to a raw string if JSON parsing fails. `undefined` in + /// LanceDB Distributed or when details are unavailable. pub index_details: Option, } @@ -1616,11 +1617,11 @@ impl From for FunctionErrors { #[napi(object)] pub struct RefreshMaterializedViewResult { - /// How the view was brought up to date: "rebuild", or absent for remote SQL refreshes. + /// How the view was brought up to date: "rebuild", or absent for LanceDB Distributed SQL refreshes. pub mode: Option, - /// Rows written by this refresh, or absent for remote SQL refreshes. + /// Rows written by this refresh, or absent for LanceDB Distributed SQL refreshes. pub rows_written: Option, - /// Source version refreshed to, or absent for remote SQL refreshes. + /// Source version refreshed to, or absent for LanceDB Distributed SQL refreshes. pub source_version: Option, pub version: i64, } diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index fa1c105e9..74f37fc2e 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -137,18 +137,18 @@ def connect( The uri of the database. When ``namespace_client_impl`` is provided you may omit ``uri`` and connect through a namespace client instead. api_key: str, optional - If presented, connect to LanceDB cloud. + If presented, connect to LanceDB Enterprise or LanceDB Cloud (legacy). Otherwise, connect to a database on file system or cloud storage. Can be set via environment variable `LANCEDB_API_KEY`. OAuth configuration is currently supported only by ``connect_async``; - synchronous LanceDB Cloud connections require an API key. + synchronous ``db://`` connections require an API key. region: str, default "us-east-1" - The region to use for LanceDB Cloud. + The region to use for LanceDB Cloud (legacy). host_override: str, optional - The override url for LanceDB Cloud. + The URL of the LanceDB Enterprise deployment to connect to. sql_host_override: str, optional - The remote SQL service endpoint override. The client connects lazily when SQL - is first executed and retains that connection. + The LanceDB Enterprise SQL service endpoint override. The client + connects lazily when SQL is first executed and retains that connection. read_consistency_interval: timedelta, default None The interval at which to check for updates to the table from other processes. If None, then consistency is not checked. For performance @@ -164,18 +164,19 @@ def connect( often each read pays the cost of checking for updates against object storage, raising per-read latency and cost. client_config: ClientConfig or dict, optional - Configuration options for the LanceDB Cloud HTTP client. If a dict, then + Configuration options for the HTTP client used by ``db://`` connections. + If a dict, then the keys are the attributes of the ClientConfig class. If None, then the default configuration is used. storage_options: dict, optional Additional options for the storage backend. See available options at manifest_enabled : bool, default False - When true for local/native connections, use directory namespace + When true for LanceDB Embedded connections, use directory namespace manifests as the source of truth for table metadata. Existing directory-listed root tables are migrated into the manifest on access. session: Session, optional - (For LanceDB OSS only) + (For LanceDB Embedded only) A session to use for this connection. Sessions allow you to configure cache sizes for index and metadata caches, which can significantly impact memory use and performance. They can also be re-used across @@ -231,7 +232,7 @@ def connect( In-memory databases are not persisted. Tables are dropped when the last connection or table handle referencing them is closed. - Connect to LanceDB cloud: + Connect to LanceDB Enterprise or LanceDB Cloud (legacy): >>> db = lancedb.connect("db://my_database", api_key="ldb_...", ... client_config={"retry_config": {"retries": 5}}) @@ -289,15 +290,17 @@ def connect( if unknown_kwargs: raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}") if session is not None: - raise NotImplementedError("session is not supported for remote connections") + raise NotImplementedError( + "session is not supported for LanceDB Distributed connections" + ) if manifest_enabled: raise NotImplementedError( - "manifest_enabled is not supported for remote connections" + "manifest_enabled is not supported for LanceDB Distributed connections" ) if api_key is None: api_key = os.environ.get("LANCEDB_API_KEY") if api_key is None: - raise ValueError(f"api_key is required to connect to LanceDB cloud: {uri}") + raise ValueError(f"api_key is required to connect to {uri}") if isinstance(request_thread_pool, int): request_thread_pool = ThreadPoolExecutor(request_thread_pool) return RemoteDBConnection( @@ -480,16 +483,16 @@ async def connect_async( uri: str or Path The uri of the database. api_key: str, optional - If present, connect to LanceDB cloud. + If present, connect to LanceDB Enterprise or LanceDB Cloud (legacy). Otherwise, connect to a database on file system or cloud storage. Can be set via environment variable `LANCEDB_API_KEY`. region: str, default "us-east-1" - The region to use for LanceDB Cloud. + The region to use for LanceDB Cloud (legacy). host_override: str, optional - The override url for LanceDB Cloud. + The URL of the LanceDB Enterprise deployment to connect to. sql_host_override: str, optional - The remote SQL service endpoint override. The client connects lazily when SQL - is first executed and retains that connection. + The LanceDB Enterprise SQL service endpoint override. The client + connects lazily when SQL is first executed and retains that connection. read_consistency_interval: timedelta, default None The interval at which to check for updates to the table from other processes. If None, then consistency is not checked. For performance @@ -505,27 +508,28 @@ async def connect_async( often each read pays the cost of checking for updates against object storage, raising per-read latency and cost. client_config: ClientConfig or dict, optional - Configuration options for the LanceDB Cloud HTTP client. If a dict, then + Configuration options for the HTTP client used by ``db://`` connections. + If a dict, then the keys are the attributes of the ClientConfig class. If None, then the default configuration is used. storage_options: dict, optional Additional options for the storage backend. See available options at session: Session, optional - (For LanceDB OSS only) + (For LanceDB Embedded only) A session to use for this connection. Sessions allow you to configure cache sizes for index and metadata caches, which can significantly impact memory use and performance. They can also be re-used across multiple connections to share the same cache state. manifest_enabled : bool, default False - When true for local/native connections, use directory namespace + When true for LanceDB Embedded connections, use directory namespace manifests as the source of truth for table metadata. Existing directory-listed root tables are migrated into the manifest on access. namespace_client_properties : dict, optional Additional directory namespace client properties to use with ``manifest_enabled=True``. oauth_config : OAuthConfig, optional - OAuth configuration for LanceDB Cloud/Enterprise. This is supported by + OAuth configuration for LanceDB Enterprise. This is supported by ``connect_async`` only; synchronous ``connect`` uses API key authentication for ``db://`` URIs. @@ -551,7 +555,7 @@ async def connect_async( ... ) ... # For tests and temporary data, use an in-memory database ... db = await lancedb.connect_async("memory://") - ... # Connect to LanceDB cloud + ... # Connect to LanceDB Enterprise or LanceDB Cloud (legacy) ... db = await lancedb.connect_async("db://my_database", api_key="ldb_...", ... client_config={ ... "retry_config": {"retries": 5}}) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index fe38f17f0..09e032607 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -626,9 +626,9 @@ class DBConnection(EnforceOverrides): ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. - Local creation and refresh require a source build with the + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it - disabled; remote Cloud/Enterprise operations remain available. + disabled; LanceDB Distributed operations remain available. The view is populated before creation returns. Pass ``with_no_data=True`` to create only its definition and empty backing @@ -652,11 +652,11 @@ class DBConnection(EnforceOverrides): with_no_data: bool, default False Skip the initial refresh and leave the backing table empty. auto_refresh_enabled: bool, optional - Enable or disable automatic refresh on Cloud and Enterprise. + Enable or disable automatic refresh in LanceDB Distributed. When omitted, the server determines whether automatic refresh is enabled. - Embedded databases do not support automatic refresh. + LanceDB Embedded does not support automatic refresh. auto_refresh_interval_seconds: float, optional - Positive, finite refresh interval in seconds on Cloud and Enterprise. + Positive, finite refresh interval in seconds in LanceDB Distributed. When omitted, the server determines when to refresh. Returns @@ -681,7 +681,8 @@ class DBConnection(EnforceOverrides): ) -> Job[None]: """Submit materialized-view creation and return its job. - The job may already be complete for a local database. Remote creation + The job may already be complete in LanceDB Embedded. In LanceDB + Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL server. Its job has ``job_type == "query"`` and ``id`` identifies the connection-scoped query. Registry event history is unavailable. @@ -721,7 +722,8 @@ class DBConnection(EnforceOverrides): ) -> None: """Drop a materialized view. - Remote drops wait for the SQL command to remove the catalog binding. + In LanceDB Distributed, drops wait for the SQL command to remove the + catalog binding. Physical cleanup continues in the background. """ raise NotImplementedError( @@ -733,7 +735,8 @@ class DBConnection(EnforceOverrides): ) -> Job[None]: """Start dropping a materialized view and return its job. - The job may already be complete for a local database. Remote jobs have + The job may already be complete in LanceDB Embedded. In LanceDB + Distributed, jobs have type ``query`` and use the SQL query ID as ``id``. Waiting confirms catalog removal; physical cleanup continues in the background. """ @@ -809,7 +812,7 @@ class DBConnection(EnforceOverrides): """ Drop all tables from the database - Remote connections do not currently support this operation. Use + LanceDB Distributed does not currently support this operation. Use ``list_tables()`` and ``drop_table()`` to drop tables individually. Parameters @@ -854,7 +857,7 @@ class DBConnection(EnforceOverrides): For namespace connections, this returns the backing namespace client. - For enterprise (remote) connections, this returns a RestNamespace + For LanceDB Enterprise connections, this returns a RestNamespace with the same URI and authentication headers. Returns @@ -890,7 +893,7 @@ class DBConnection(EnforceOverrides): The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. Parameters ---------- @@ -934,7 +937,7 @@ class DBConnection(EnforceOverrides): The server-side job builds the OCI image, then registers the completed artifact. Waiting on the job returns the immutable Function version. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "Function catalog operations are not supported for this connection type" @@ -962,7 +965,7 @@ class DBConnection(EnforceOverrides): """List every published immutable Function version in a namespace. Functions in child namespaces are not included. Results are ordered by - Function name then version. Local connections raise + Function name then version. LanceDB Embedded connections raise ``NotImplementedError``. Examples @@ -1012,7 +1015,7 @@ class DBConnection(EnforceOverrides): The name is unbound before this returns; the object's content may still be being deleted. Call :meth:`Job.wait` to wait for that to finish. When the server deletes inline, or when nothing was bound, the returned job - is already finished and has no id. Local connections raise + is already finished and has no id. LanceDB Embedded connections raise NotImplementedError. """ raise NotImplementedError( @@ -1041,7 +1044,7 @@ class DBConnection(EnforceOverrides): Fails if it does not exist. Every Function bound to the Secret uses the new value from its next job, and no new Function version is created -- which is how a rotation reaches columns pinned to a version registered - before it. Local connections raise ``NotImplementedError``. + before it. LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "Secret operations are not supported for this connection type" @@ -1057,7 +1060,8 @@ class DBConnection(EnforceOverrides): """The names of every Secret in this database. Names only. No method returns a stored credential, by construction - rather than by policy. Local connections raise ``NotImplementedError``. + rather than by policy. LanceDB Embedded connections raise + ``NotImplementedError``. Returns a lazy iterator. ``page_limit`` limits each request, not the total; ``page_token`` resumes from a saved token. Requests and errors occur during @@ -1075,7 +1079,7 @@ class DBConnection(EnforceOverrides): Functions bound to it fail at their next job, naming the Secret; that is the revocation path. The name becomes free to reuse, and a new Secret under it is picked up by everything still bound to that name. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "Secret operations are not supported for this connection type" @@ -1103,7 +1107,7 @@ class DBConnection(EnforceOverrides): its readers see its sources as they are at read time. There is no replace: a name already taken is an error, and changing a - view is a drop followed by a create. Local connections raise + view is a drop followed by a create. LanceDB Embedded connections raise ``NotImplementedError``. >>> import lancedb @@ -1125,7 +1129,7 @@ class DBConnection(EnforceOverrides): schema that query resolved to. The schema is the one recorded at creation; a source altered since then - shows up when the view is read. Local connections raise + shows up when the view is read. LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( @@ -1139,7 +1143,7 @@ class DBConnection(EnforceOverrides): The tables it reads are untouched: a view holds no rows of its own. Use :meth:`drop_view_async` to get the cleanup job instead of waiting on it. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ raise NotImplementedError( "View operations are not supported for this connection type" @@ -1286,7 +1290,7 @@ class DBConnection(EnforceOverrides): cancellation. Open ``reader()`` directly: a streamed query needs its reader to make progress and reports ``running`` until the stream ends. - Local connections do not support SQL. + LanceDB Embedded connections do not support SQL. """ raise NotImplementedError("SQL is not supported for this connection type") @@ -1764,9 +1768,9 @@ class LanceDBConnection(DBConnection): ) -> MaterializedView: """Define a materialized view named ``name`` over the table ``source``. - Local creation and refresh require a source build with the + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it - disabled; remote Cloud/Enterprise operations remain available. + disabled; LanceDB Distributed operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. @@ -2261,12 +2265,12 @@ class AsyncConnection(object): To obtain a connection you can use the [connect_async][lancedb.connect_async] function. - This could be a native connection (using lance) or a remote connection (e.g. for - connecting to LanceDb Cloud) + This could be a LanceDB Embedded connection (using lance) or a LanceDB Distributed + connection (e.g. for connecting to LanceDB Enterprise) - Local connections do not currently hold any open resources but they may do so in the - future (for example, for shared cache or connections to catalog services) Remote - connections represent an open connection to the remote server. The + Embedded connections do not currently hold any open resources but they may do so in + the future (for example, for shared cache or connections to catalog services) + Distributed connections represent an open connection to the server. The [close][lancedb.db.AsyncConnection.close] method can be used to release any underlying resources eagerly. The connection can also be used as a context manager. @@ -2854,9 +2858,9 @@ class AsyncConnection(object): ) -> AsyncMaterializedView: """Define a materialized view named ``name`` over the table ``source``. - Local creation and refresh require a source build with the + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it - disabled; remote Cloud/Enterprise operations remain available. + disabled; LanceDB Distributed operations remain available. See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ @@ -2890,8 +2894,8 @@ class AsyncConnection(object): ) -> AsyncJob[None]: """Submit materialized-view creation and return its job. - Wait for the returned job before opening or querying the view. Remote - creation uses SQL; ``job_type`` is ``"query"`` and ``id`` + Wait for the returned job before opening or querying the view. In LanceDB + Distributed, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. """ source, native_options = await self._materialized_view_source( @@ -2945,7 +2949,8 @@ class AsyncConnection(object): ) -> None: """Drop a materialized view. - Remote drops wait for the SQL command to remove the catalog binding. + In LanceDB Distributed, drops wait for the SQL command to remove the + catalog binding. Physical cleanup continues in the background. """ if namespace_path is None: @@ -2960,7 +2965,7 @@ class AsyncConnection(object): ) -> AsyncJob[None]: """Start dropping a materialized view and return its job. - For remote connections, the job has type ``query`` and its ID identifies + In LanceDB Distributed, the job has type ``query`` and its ID identifies the SQL query. Await :meth:`AsyncJob.wait` for catalog removal; physical cleanup continues in the background. """ @@ -3135,7 +3140,7 @@ class AsyncConnection(object): [EnvVarSecret][lancedb.secrets.EnvVarSecret], each naming a Secret and the environment variable its value arrives in. ``namespace_path`` is the namespace the Function is registered in; None or an empty list is - the root. Local connections raise ``NotImplementedError``. + the root. LanceDB Embedded connections raise ``NotImplementedError``. """ if not isinstance(definition, UdfDefinition): raise TypeError("create_function_async requires a @udf definition") @@ -3167,7 +3172,7 @@ class AsyncConnection(object): """List every published immutable Function version in a namespace. Functions in child namespaces are not included. Results are ordered by - Function name then version. Local connections raise + Function name then version. LanceDB Embedded connections raise ``NotImplementedError``. Returns a lazy iterator. ``page_limit`` limits each request, not the total; @@ -3422,7 +3427,7 @@ class AsyncConnection(object): references. The namespace defaults to ``["public"]``. ``parameters`` binds values to ``$1`` / ``$name`` placeholders; see [DBConnection.execute_query_async][lancedb.db.DBConnection.execute_query_async]. - Local connections raise ``NotImplementedError``. + LanceDB Embedded connections raise ``NotImplementedError``. """ return AsyncSqlQuery( await self._inner.execute_query_async( @@ -3450,7 +3455,7 @@ class AsyncConnection(object): For namespace connections, this returns the backing namespace client. - For enterprise (remote) connections, this returns a RestNamespace + For LanceDB Enterprise connections, this returns a RestNamespace with the same URI and authentication headers. Returns diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 42c4b27e1..38b45d8b6 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -4,7 +4,7 @@ """Canonical Function values exchanged with LanceDB Enterprise services. These immutable models contain client/wire state only. Catalog persistence, -environment bake, secret resolution, and execution are owned by Sophon. +environment bake, secret resolution, and execution are owned by LanceDB Enterprise. ``RefreshColumnResult`` is also the backend-neutral result of a local expression-backed refresh job. """ @@ -275,7 +275,7 @@ class FunctionSignature(_RemoteValue): class PythonEnvironmentSpec(_RemoteValue): - """One Sophon-managed Python environment source.""" + """One LanceDB Enterprise-managed Python environment source.""" kind: str packages: tuple[str, ...] = () @@ -653,8 +653,8 @@ class FunctionBinding(_RemoteValue): class RefreshColumnResult(_RemoteValue): """Terminal result of an expression-backed or Function-backed refresh Job. - Local jobs produce this value in process. LanceDB Cloud and Enterprise - decode the same value from the durable server-job terminal payload. + LanceDB Embedded jobs produce this value in process. LanceDB Distributed + decodes the same value from the durable server-job terminal payload. """ rows_assigned: _UInt64 diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index 80179f4a7..8c192a2f0 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -145,9 +145,9 @@ class FTS: Lance tokenizer can panic on malformed triples; see https://github.com/lance-format/lance/issues/8812. - Remote tables use the same ``FTS()`` configuration and require a server - that supports JSON FTS. Wait for ``table.wait_for_index(["doc_idx"])`` - before searching a newly created remote index with its default name. + LanceDB Distributed uses the same ``FTS()`` configuration and requires a + server that supports JSON FTS. Wait for ``table.wait_for_index(["doc_idx"])`` + before searching a newly created index there with its default name. Examples -------- @@ -210,12 +210,12 @@ class FTS: memory_limit : int, optional The total memory limit in MiB for the local FTS build stage. The limit is divided evenly among indexing workers. This build-only setting is - not persisted with the index and does not apply to remote tables. + not persisted with the index and does not apply to LanceDB Distributed. num_workers : int, optional The number of workers for a local FTS build. By default Lance uses roughly half of the available CPU cores. The effective value is limited by the available compute capacity. This build-only setting is - not persisted with the index and does not apply to remote tables. + not persisted with the index and does not apply to LanceDB Distributed. document_granularity : DocumentGranularity, default ROW ``ROW`` treats the selected text in one table row as one document. ``LIST_ELEMENT`` treats each element of the deepest list on the indexed diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 7fc110dcc..7b0b3b80a 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -4,9 +4,10 @@ """Materialized views: tables defined by a query over a source table and maintained by refresh. See ``DBConnection.create_materialized_view``. -Local creation and refresh require the ``experimental-functions`` Cargo feature -in a source build. Published packages disable it. Opening, reading, listing and -dropping existing views and remote Cloud/Enterprise operations remain available. +LanceDB Embedded creation and refresh require the ``experimental-functions`` +Cargo feature in a source build. Published packages disable it. Opening, reading, +listing and dropping existing views and LanceDB Distributed operations remain +available. """ from __future__ import annotations @@ -188,13 +189,14 @@ class AsyncMaterializedView: ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. - ``full=True`` forces a remote rebuild; otherwise the server chooses - the refresh mode. Local views always rebuild, and ``source_version`` - selects a source version instead of the latest. Remote SQL refreshes - do not support source-version pinning. + In LanceDB Distributed, ``full=True`` forces a rebuild; otherwise the + server chooses the refresh mode. LanceDB Embedded views always rebuild, + and ``source_version`` selects a source version instead of the latest. + LanceDB Distributed SQL refreshes do not support source-version pinning. - Remote results leave ``mode``, ``rows_written``, and ``source_version`` - as ``None`` because the SQL job adapter does not expose these metrics. + LanceDB Distributed results leave ``mode``, ``rows_written``, and + ``source_version`` as ``None`` because the SQL job adapter does not expose + these metrics. """ return await self._table._inner.refresh_materialized_view( source_version=source_version, full=full @@ -205,8 +207,9 @@ class AsyncMaterializedView: ) -> "AsyncJob[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. - The job may already be complete for a local view. Remote refreshes are - submitted through the SQL service. Options and result metrics follow + The job may already be complete in LanceDB Embedded. In LanceDB + Distributed, refreshes are submitted through the SQL service. Options and + result metrics follow [refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]. """ from ._lancedb import RefreshMaterializedViewResult diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 992926769..3356b363c 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -1675,7 +1675,7 @@ class AsyncLanceNamespaceDBConnection: ) -> AsyncSqlQuery: """Start executing SQL when supported by the underlying connection. - Namespace-backed local connections do not support SQL. + Namespace-backed LanceDB Embedded connections do not support SQL. """ return await self._inner.execute_query_async( query, diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index e95db27f6..0788cb5cb 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -548,7 +548,7 @@ class Permutation: picklable classes implementing ``__call__``. Lambdas and closures over local variables don't pickle with the default protocol. - A factory is optional for normal local and remote LanceDB connections: + A factory is optional for normal LanceDB Embedded and Distributed connections: if not set, ``__getstate__`` captures the table's own picklable reopen state. Use a factory when that default state is not enough, for example when credentials should be loaded from the worker environment instead @@ -587,7 +587,7 @@ class Permutation: {"root": "/data/lance_db"}, ) - LanceDB Cloud, reading credentials from env vars at worker startup + LanceDB Enterprise, reading credentials from env vars at worker startup so secrets aren't pickled into the dataset:: import os, lancedb diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 03560ec31..625a17524 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -125,7 +125,7 @@ def _supports_local_blob_fetch( def _blob_bytes_without_snapshot_error() -> NotImplementedError: return NotImplementedError( "blob_mode='bytes' cannot safely materialize blob columns without a " - "stable table snapshot. Remote tables and namespace QueryTable pushdown " + "stable table snapshot. LanceDB Distributed and namespace QueryTable pushdown " "run the query on a server, so the blob fetch could read another table " "version. Use blob_mode='descriptions'." ) @@ -1147,7 +1147,8 @@ class LanceQueryBuilder(ABC): mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - Remote blob queries support only ``"descriptions"`` until a stable + LanceDB Distributed blob queries support only ``"descriptions"`` until a + stable table snapshot can bind the query and blob fetches. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and @@ -3483,7 +3484,7 @@ class AsyncQueryBase(object): ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. ``"bytes"`` returns payload bytes and raises for legacy blob columns and blobs inside lists. - Remote tables and namespace query pushdown refuse ``"bytes"``. + LanceDB Distributed and namespace query pushdown refuse ``"bytes"``. """ blob_sources = await self._validated_blob_sources(blob_mode) batch_iter = await self.to_batches(timeout=timeout) @@ -3562,7 +3563,8 @@ class AsyncQueryBase(object): mode and for legacy blob columns. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - Remote blob queries support only ``"descriptions"`` until a stable + LanceDB Distributed blob queries support only ``"descriptions"`` until a + stable table snapshot can bind the query and blob fetches. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and @@ -4209,9 +4211,10 @@ class AsyncVectorQueryBase: your actual data to find the smallest possible value that will still give you the desired recall. - LanceDB retains this as `nprobes` through local and remote request - construction. Lance sets both probe bounds to this value. Explicit minimum - or maximum settings can override their respective bounds. + LanceDB retains this as `nprobes` through LanceDB Embedded and LanceDB + Distributed request construction. Lance sets both probe bounds to this + value. Explicit minimum or maximum settings can override their respective + bounds. """ self._inner.nprobes(nprobes) return self diff --git a/python/python/lancedb/remote/__init__.py b/python/python/lancedb/remote/__init__.py index 15015a8e0..4d082d2c8 100644 --- a/python/python/lancedb/remote/__init__.py +++ b/python/python/lancedb/remote/__init__.py @@ -163,7 +163,7 @@ class TlsConfig: @dataclass class ClientConfig: - """Configuration for the LanceDB Cloud HTTP client. + """Configuration for the HTTP client used to connect to LanceDB Enterprise. Attributes ---------- @@ -190,7 +190,7 @@ class ClientConfig: Provider for dynamic headers to be added to each request. user_id: Optional[str] User identifier for tracking purposes. This is sent as the - `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. + `x-lancedb-user-id` header in requests to LanceDB Enterprise. This can also be set via the `LANCEDB_USER_ID` environment variable. Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 291cc52d6..e2defa216 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -101,7 +101,7 @@ def _tls_config_to_dict(config: Optional[TlsConfig]) -> Optional[dict[str, Any]] def _client_config_to_dict(config: ClientConfig) -> dict[str, Any]: if config.header_provider is not None: raise ValueError( - "Cannot serialize a remote connection with a header_provider. " + "Cannot serialize a LanceDB Distributed connection with a header_provider. " "Use static api_key/extra_headers or provide a worker-side " "connection factory instead." ) @@ -119,7 +119,7 @@ def _client_config_to_dict(config: ClientConfig) -> dict[str, Any]: class RemoteDBConnection(DBConnection): - """A connection to a remote LanceDB database.""" + """A connection to a LanceDB Enterprise database.""" def __init__( self, @@ -135,7 +135,7 @@ class RemoteDBConnection(DBConnection): read_consistency_interval: Optional[timedelta] = None, sql_host_override: Optional[str] = None, ): - """Connect to a remote LanceDB database.""" + """Connect to a LanceDB Enterprise database.""" if isinstance(client_config, dict): client_config = ClientConfig(**client_config) elif client_config is None: @@ -246,14 +246,17 @@ class RemoteDBConnection(DBConnection): @property def session(self) -> Optional["Session"]: - """Remote connections do not expose a local cache session.""" - raise NotImplementedError("session is not supported by remote connections") + """LanceDB Distributed connections do not expose a local cache session.""" + raise NotImplementedError( + "session is not supported by LanceDB Distributed connections" + ) @property def read_consistency_interval(self) -> Optional[timedelta]: - """Remote connections do not expose a local read consistency interval.""" + """LanceDB Distributed connections do not expose a read consistency interval.""" raise NotImplementedError( - "read_consistency_interval is not supported by remote connections" + "read_consistency_interval is not supported by LanceDB Distributed " + "connections" ) @override @@ -631,11 +634,11 @@ class RemoteDBConnection(DBConnection): The embedding functions to store in the table schema and use to generate vectors when creating the table or adding data. storage_options: dict, optional - Not supported for remote table creation. Raises NotImplementedError. + Not supported in LanceDB Distributed. Raises NotImplementedError. data_storage_version: str, optional - Not supported for remote table creation. Raises NotImplementedError. + Not supported in LanceDB Distributed. Raises NotImplementedError. enable_v2_manifest_paths: bool, optional - Not supported for remote table creation. Raises NotImplementedError. + Not supported in LanceDB Distributed. Raises NotImplementedError. Returns ------- @@ -708,7 +711,8 @@ class RemoteDBConnection(DBConnection): ): if value is not None: raise NotImplementedError( - f"{option} is not supported for remote table creation" + f"{option} is not supported for table creation in " + "LanceDB Distributed" ) if exist_ok: if mode == "create": @@ -1145,7 +1149,7 @@ class RemoteDBConnection(DBConnection): default_namespace_path: Optional[List[str]] = None, parameters: Optional[QueryParameters] = None, ) -> SqlQuery: - """Start executing SQL through this remote connection. + """Start executing SQL through this LanceDB Distributed connection. Unqualified tables use this connection's database and the ``["public"]`` namespace by default. Fully qualified table names may diff --git a/python/python/lancedb/remote/header.py b/python/python/lancedb/remote/header.py index 5f5bd12d8..9cea0eeff 100644 --- a/python/python/lancedb/remote/header.py +++ b/python/python/lancedb/remote/header.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Header providers for LanceDB remote connections. +"""Header providers for LanceDB Enterprise connections. This module provides a flexible header management framework for LanceDB remote connections, allowing users to implement custom header strategies for diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 935e07eec..7454b3e73 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -126,8 +126,8 @@ class RemoteTable(Table): def _serialized_connection_state(self) -> str: if self._connection_state is None: raise RuntimeError( - "Cannot reopen this remote table because it does not carry " - "serialized connection state" + "Cannot reopen this LanceDB Distributed table because it does not " + "carry serialized connection state" ) if callable(self._connection_state): self._connection_state = self._connection_state() @@ -273,32 +273,32 @@ class RemoteTable(Table): return LOOP.run(self._table.list_versions()) def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table: - """to_arrow() is not supported for remote tables.""" + """to_arrow() is not supported in LanceDB Distributed.""" validate_blob_mode(blob_mode) raise NotImplementedError( - "to_arrow() is not supported for remote tables. " + "to_arrow() is not supported in LanceDB Distributed. " "Use table.search().to_arrow() instead." ) def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs): - """to_pandas() is not supported for remote tables.""" + """to_pandas() is not supported in LanceDB Distributed.""" validate_blob_mode(blob_mode) raise NotImplementedError( - "to_pandas() is not supported for remote tables. " + "to_pandas() is not supported in LanceDB Distributed. " "Use table.search().to_pandas() instead." ) def to_lance(self, **kwargs) -> "lance.LanceDataset": - """Direct Lance dataset access is not supported for remote tables. + """Direct Lance dataset access is not supported in LanceDB Distributed. Use ``table.search().to_arrow()`` to read query results through the server. """ return LOOP.run(self._table.to_lance(**kwargs)) def to_polars(self, batch_size=None) -> "pl.LazyFrame": - """Use ``table.search().to_polars()`` to read remote query results.""" + """Use ``table.search().to_polars()`` to read query results.""" raise NotImplementedError( - "to_polars() is not supported for remote tables. " + "to_polars() is not supported in LanceDB Distributed. " "Use table.search().to_polars() instead." ) @@ -331,7 +331,7 @@ class RemoteTable(Table): """Tokenize a query using the tokenizer configured on an FTS index. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. For remote tables, + rebuilt in the client process from index metadata. In LanceDB Distributed, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may @@ -638,7 +638,7 @@ class RemoteTable(Table): if accelerator is not None: logging.warning( - "GPU accelerator is not supported for remote tables " + "GPU accelerator is not supported in LanceDB Distributed " "and will be ignored." ) @@ -713,7 +713,7 @@ class RemoteTable(Table): ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. - It has the same API signature as the OSS version. + It has the same API signature as the LanceDB Embedded version. Parameters ---------- @@ -743,7 +743,7 @@ class RemoteTable(Table): capped at the number of CPU cores. Lower this if bulk ingestion is using too much memory. allow_external_blob_outside_bases: bool, default False - Not supported for remote tables. Setting this raises. + Not supported in LanceDB Distributed. Setting this raises. Returns ------- @@ -1048,20 +1048,20 @@ class RemoteTable(Table): delete_unverified: bool = False, ): """ - cleanup_old_versions() is a no-op for remote tables. + cleanup_old_versions() is a no-op in LanceDB Distributed. """ warnings.warn( - "cleanup_old_versions() is a no-op for remote tables.", + "cleanup_old_versions() is a no-op in LanceDB Distributed.", stacklevel=2, ) pass def compact_files(self, *args, **kwargs): """ - compact_files() is a no-op for remote tables. + compact_files() is a no-op in LanceDB Distributed. """ warnings.warn( - "compact_files() is a no-op for remote tables.", + "compact_files() is a no-op in LanceDB Distributed.", stacklevel=2, ) pass @@ -1074,7 +1074,7 @@ class RemoteTable(Table): retrain: bool = False, compaction_options: Optional[CompactionOptions] = None, ): - """optimize() is not supported for remote tables.""" + """optimize() is not supported in LanceDB Distributed.""" return LOOP.run( self._table.optimize( cleanup_older_than=cleanup_older_than, @@ -1184,7 +1184,7 @@ class RemoteTable(Table): ) def close_rte_writers(self) -> None: - """No-op for remote tables (no local shard writers).""" + """No-op in LanceDB Distributed (no local shard writers).""" return LOOP.run(self._table.close_rte_writers()) @_deprecated_keyword("index_name", "name") @@ -1213,7 +1213,7 @@ class RemoteTable(Table): This is a hint to the database that the given columns will be accessed in the future and the database should prefetch the data if possible. - Currently only supported on remote tables. + Currently only supported in LanceDB Distributed. This call initiates prewarming and returns once the request is accepted. It is idempotent and safe to call from multiple clients concurrently. @@ -1242,7 +1242,7 @@ class RemoteTable(Table): def uri(self) -> str: """The table URI (storage location). - For remote tables, this fetches the location from the server via describe. + In LanceDB Distributed, this fetches the location from the server via describe. """ return LOOP.run(self._table.uri()) diff --git a/python/python/lancedb/sql.py b/python/python/lancedb/sql.py index 05b82b0d3..d011e25a5 100644 --- a/python/python/lancedb/sql.py +++ b/python/python/lancedb/sql.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Handles to SQL queries running on a remote database.""" +"""Handles to SQL queries running on a LanceDB Distributed database.""" from typing import Any, Mapping, Optional, Sequence, Union from uuid import UUID diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ac82106cc..59c88027d 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1572,9 +1572,10 @@ class Table(ABC): raise NotImplementedError("to_arrow is not supported for this table type") def to_lance(self, **kwargs) -> lance.LanceDataset: - """Return a local table as a lance.LanceDataset. + """Return a LanceDB Embedded table as a lance.LanceDataset. - Remote tables cannot be opened as Lance datasets by the client. Use + LanceDB Distributed tables cannot be opened as Lance datasets by the + client. Use ``table.search().to_arrow()`` to read them through the server. Returns @@ -1586,7 +1587,7 @@ class Table(ABC): def to_polars(self, batch_size=None) -> "pl.LazyFrame": """Return the table as a Polars LazyFrame. - For remote tables, use ``table.search().to_polars()`` to convert query + In LanceDB Distributed, use ``table.search().to_polars()`` to convert query results to a Polars DataFrame. Parameters @@ -2530,7 +2531,7 @@ class Table(ABC): ) -> pa.LargeBinaryArray: """Materialize full blob bytes for ``column`` at the given rows. - Local tables support both legacy blob v1 and blob v2 columns. + LanceDB Embedded supports both legacy blob v1 and blob v2 columns. The result has the same length and order as ``row_ids``. Null blobs produce null slots; valid empty blobs produce ``b""``. @@ -2542,7 +2543,7 @@ class Table(ABC): Blobs inside lists cannot be fetched by row id yet. - Remote servers limit each request to 1024 row IDs and 64 MiB of blob + LanceDB Distributed limits each request to 1024 row IDs and 64 MiB of blob bytes. The client splits requests automatically and reads an individual larger blob through the Range route. This method still materializes all bytes in memory; for large values use :meth:`fetch_blob_files`. @@ -2556,7 +2557,7 @@ class Table(ABC): ) -> pa.LargeBinaryArray: """Materialize row-specific byte ranges from a blob column. - Local tables support both legacy blob v1 and blob v2 columns. + LanceDB Embedded supports both legacy blob v1 and blob v2 columns. Each request is a three-item ``(row_id, offset, length)`` sequence. Requests may be repeated or reordered, including multiple ranges for the same blob. @@ -2569,7 +2570,7 @@ class Table(ABC): results are returned. Row IDs can be obtained from a query with ``with_row_id(True)``. - Remote tables read the requested ranges through version-pinned blob + LanceDB Distributed reads the requested ranges through version-pinned blob handles using HTTP byte-range requests. """ @@ -2581,12 +2582,12 @@ class Table(ABC): ) -> "list[Optional[BlobFile]]": """Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles. - Local tables support both legacy blob v1 and blob v2 columns. + LanceDB Embedded supports both legacy blob v1 and blob v2 columns. Prefer this over :meth:`fetch_blobs` for large payloads. ``row_ids`` is a ``list[int]``, an integer Arrow array or chunked array, or a query ``pyarrow.Table`` carrying row identity via ``_rowid`` or a ``_lance_row_id`` field on the blob descriptor. Null blob values return - ``None``. Remote tables require LanceDB Cloud server 0.5.0 or newer. + ``None``. LanceDB Distributed requires server version 0.5.0 or newer. ``_rowid`` values stay valid after compaction when the table has stable row ids. @@ -2823,8 +2824,8 @@ class Table(ABC): Notes ----- - This function is not available in LanceDb Cloud (since LanceDB - Cloud manages cleanup for you automatically) + This function is not available in LanceDB Distributed, which manages + cleanup for you automatically. """ @abstractmethod @@ -2845,8 +2846,8 @@ class Table(ABC): Notes ----- - This function is not available in LanceDB Cloud (since LanceDB - Cloud manages compaction for you automatically) + This function is not available in LanceDB Distributed, which manages + compaction for you automatically. """ @abstractmethod @@ -2932,7 +2933,7 @@ class Table(ABC): Specify exactly one of ``column`` or ``index_name``. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. For remote tables, + rebuilt in the client process from index metadata. In LanceDB Distributed, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may @@ -2988,12 +2989,12 @@ class Table(ABC): or named-struct result in the named table column. A bare named-struct application expands its ordered result fields as one atomic binding; aliases come from ``rename(columns=...)``. - Function columns are supported only on LanceDB Cloud and - Enterprise. + Function columns are supported only in LanceDB + Distributed. computed: Dict[str, str], optional - Local declaration and refresh require a source build with the + LanceDB Embedded declaration and refresh require a source build with the ``experimental-functions`` Cargo feature, which published packages - do not enable. Remote Cloud/Enterprise operations remain available. + do not enable. LanceDB Distributed operations remain available. A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 @@ -3012,14 +3013,15 @@ class Table(ABC): While a declaration reads a column, that column cannot be renamed, retyped or dropped. - On LanceDB Cloud and Enterprise the expression is planned by the + In LanceDB Distributed the expression is planned by the server, and the refresh runs as a server job -- see [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Cannot be combined with ``transforms``. auto_refresh_enabled: bool, optional Enable automatic refresh for each declared computed output. Defaults - to True. Local tables store this option; scheduling requires a server. + to True. LanceDB Embedded stores this option; scheduling requires a + server. auto_refresh_interval_seconds: int, optional Positive minimum interval after a successful refresh, in seconds. When omitted, the server determines when to refresh. Applies to every @@ -3059,7 +3061,8 @@ class Table(ABC): by the next one, and rows whose inputs changed since they were computed are recomputed; everything else is left as it is. - Local tables only: a remote refresh runs as a server job, through + LanceDB Embedded only. In LanceDB Distributed, a refresh runs as a + server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters @@ -3080,14 +3083,15 @@ class Table(ABC): Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. - Local refresh requires a source build with ``experimental-functions``. - Remote Cloud/Enterprise jobs do not require this feature. + LanceDB Embedded refresh requires a source build with + ``experimental-functions``. + LanceDB Distributed jobs do not require this feature. The job may already be complete when returned; callers must not assume the column is filled until :meth:`Job.wait` returns. Invalid input -- an unknown column, or one that is not computed -- raises here rather - than failing the job. On local tables the job runs in-process; on - LanceDB Cloud and Enterprise it is the server's backfill job. + than failing the job. In LanceDB Embedded the job runs in-process; in + LanceDB Distributed it is the server's backfill job. Returns ------- @@ -3123,7 +3127,7 @@ class Table(ABC): A refresh running under a skip policy records each row it skipped with the input that failed and the error. This lists those records, newest job first, plus a summary for any fragment whose per-row - detail was capped. LanceDB Cloud and Enterprise only; reading errors + detail was capped. LanceDB Distributed only; reading errors needs read access to the table, since a message carries the value that failed. @@ -4186,7 +4190,7 @@ class LanceTable(Table): This is a hint to the database that the given columns will be accessed in the future and the database should prefetch the data if possible. - Currently only supported on remote tables. + Currently only supported in LanceDB Distributed. This call initiates prewarming and returns once the request is accepted. It is idempotent and safe to call from multiple clients concurrently. @@ -4435,7 +4439,7 @@ class LanceTable(Table): using too much memory. allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. - Local tables only. + LanceDB Embedded only. Returns ------- @@ -5077,7 +5081,7 @@ class LanceTable(Table): Specify exactly one of ``column`` or ``index_name``. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. For remote tables, + rebuilt in the client process from index metadata. In LanceDB Distributed, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may @@ -6071,9 +6075,10 @@ class AsyncTable: return AsyncQuery(self._inner.query(), self) async def to_lance(self, **kwargs) -> lance.LanceDataset: - """Return the Lance dataset backing a local table. + """Return the Lance dataset backing a LanceDB Embedded table. - Remote tables cannot be opened as Lance datasets by the client. Use + LanceDB Distributed tables cannot be opened as Lance datasets by the + client. Use [to_arrow][lancedb.table.AsyncTable.to_arrow] or [query][lancedb.table.AsyncTable.query] to read them through the server. @@ -6094,7 +6099,7 @@ class AsyncTable: """ if not self._inner._is_native(): raise NotImplementedError( - "to_lance() is not supported for remote tables; " + "to_lance() is not supported in LanceDB Distributed; " "query the server instead" ) @@ -6127,7 +6132,7 @@ class AsyncTable: Parameters ---------- blob_mode: str, default "lazy" - Controls how Lance blob columns are returned. Remote tables support + Controls how Lance blob columns are returned. LanceDB Distributed supports "descriptions"; "bytes" and "lazy" are not yet supported. **kwargs Forwarded to PyArrow / Lance pandas conversion. @@ -6371,7 +6376,7 @@ class AsyncTable: This is a hint to the database that the given columns will be accessed in the future and the database should prefetch the data if possible. - Currently only supported on remote tables. + Currently only supported in LanceDB Distributed. This call initiates prewarming and returns once the request is accepted. It is idempotent and safe to call from multiple clients concurrently. @@ -6415,8 +6420,8 @@ class AsyncTable: """ Get the table URI (storage location). - For remote tables, this fetches the location from the server via describe. - For local tables, this returns the dataset URI. + In LanceDB Distributed, this fetches the location from the server via describe. + In LanceDB Embedded, this returns the dataset URI. Returns ------- @@ -6499,7 +6504,7 @@ class AsyncTable: using too much memory. allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. - Local tables only. + LanceDB Embedded only. """ schema = await self.schema() @@ -7203,12 +7208,12 @@ class AsyncTable: or named-struct result in the named table column. A bare named-struct application expands its ordered result fields as one atomic binding; aliases come from ``rename(columns=...)``. - Function columns are supported only on LanceDB Cloud and - Enterprise. + Function columns are supported only in LanceDB + Distributed. computed: Dict[str, str], optional - Local declaration and refresh require a source build with the + LanceDB Embedded declaration and refresh require a source build with the ``experimental-functions`` Cargo feature, which published packages - do not enable. Remote Cloud/Enterprise operations remain available. + do not enable. LanceDB Distributed operations remain available. A mapping from output column names to SQL expressions derives each output field from its expression. A direct projection of a Blob v2 @@ -7226,13 +7231,13 @@ class AsyncTable: While a declaration reads a column, that column cannot be renamed, retyped or dropped. - On LanceDB Cloud and Enterprise the expression is planned by + In LanceDB Distributed the expression is planned by the server. Cannot be combined with ``transforms``. auto_refresh_enabled: bool, optional Enable automatic refresh for each computed output declared by this - call. Defaults to True. Local tables store the setting; automatic - scheduling requires Cloud or Enterprise. + call. Defaults to True. LanceDB Embedded stores the setting; automatic + scheduling requires LanceDB Distributed. auto_refresh_interval_seconds: int, optional Positive minimum seconds after a successful refresh before another automatic refresh is eligible. When omitted, the server determines when @@ -7337,7 +7342,8 @@ class AsyncTable: by the next one, and rows whose inputs changed since they were computed are recomputed; everything else is left as it is. - Local tables only: a remote refresh runs as a server job, through + LanceDB Embedded only. In LanceDB Distributed, a refresh runs as a + server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters @@ -7364,7 +7370,7 @@ class AsyncTable: A refresh running under a skip policy records each row it skipped with the input that failed and the error. This lists those records, newest job first, plus a summary for any fragment whose per-row - detail was capped. LanceDB Cloud and Enterprise only; reading errors + detail was capped. LanceDB Distributed only; reading errors needs read access to the table, since a message carries the value that failed. @@ -7402,14 +7408,15 @@ class AsyncTable: Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. - Local refresh requires a source build with ``experimental-functions``. - Remote Cloud/Enterprise jobs do not require this feature. + LanceDB Embedded refresh requires a source build with + ``experimental-functions``. + LanceDB Distributed jobs do not require this feature. The job may already be complete when returned; callers must not assume the column is filled until :meth:`AsyncJob.wait` resolves. Invalid input -- an unknown column, or one that is not computed -- raises here - rather than failing the job. On local tables the job runs - in-process; on LanceDB Cloud and Enterprise it is the server's + rather than failing the job. In LanceDB Embedded the job runs + in-process; in LanceDB Distributed it is the server's backfill job. Returns @@ -7831,7 +7838,7 @@ class AsyncTable: Specify exactly one of ``column`` or ``index_name``. Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are - rebuilt in the client process from index metadata. For remote tables, + rebuilt in the client process from index metadata. In LanceDB Distributed, this means the same tokenizer model files must also exist locally (under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the server uses. A mismatch cannot be detected: the returned tokens may diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 0966297f7..85c02ccc3 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -726,7 +726,7 @@ def test_embedded_create_refuses_automatic_refresh_before_creating_view( tmp_path, options ): db = make_db(tmp_path) - with pytest.raises(NotImplementedError, match="Cloud or Enterprise"): + with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"): db.create_materialized_view("adults", "people", **options) assert "adults" not in db.table_names() @@ -743,7 +743,7 @@ def test_remote_create_rejects_invalid_interval_without_request(seconds): @pytest.mark.experimental_functions def test_namespace_forwards_automatic_refresh_request(tmp_path): db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) - with pytest.raises(NotImplementedError, match="Cloud or Enterprise"): + with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"): db.create_materialized_view("mv", "source", auto_refresh_enabled=True) @@ -751,7 +751,7 @@ def test_namespace_forwards_automatic_refresh_request(tmp_path): @pytest.mark.asyncio async def test_async_namespace_forwards_automatic_refresh_request(tmp_path): db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) - with pytest.raises(NotImplementedError, match="Cloud or Enterprise"): + with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"): await db.create_materialized_view("mv", "source", auto_refresh_enabled=True) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b2515cd26..fe271b1fd 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -910,7 +910,7 @@ def test_table_unimplemented_functions(): message = str(exc_info.value) assert method in message assert "not" in message and "supported" in message - assert "remote tables" in message + assert "LanceDB Distributed" in message assert "cloud" not in message.lower() assert f"search().{method}()" in message @@ -977,7 +977,7 @@ async def test_remote_to_lance_rejection( await table.to_lance(**options) assert requests == opened_requests - assert "to_lance() is not supported for remote tables" in str(sync_error.value) + assert "to_lance() is not supported in LanceDB Distributed" in str(sync_error.value) assert "query the server" in str(sync_error.value) assert str(sync_error.value) == str(async_error.value) @@ -1764,7 +1764,8 @@ def test_remote_create_index_new_api(caplog, rq_kwargs): assert received_requests[5]["replace"] is False assert "replace is not supported" not in caplog.text assert caplog.messages == [ - "GPU accelerator is not supported for remote tables and will be ignored." + "GPU accelerator is not supported in LanceDB Distributed " + "and will be ignored." ] @@ -1822,7 +1823,7 @@ def test_remote_unsupported_operations_sync(method, args, kwargs, operation): with pytest.raises(NotImplementedError) as error: getattr(table, method)(*args, **kwargs) expected = f"LanceDBError: not supported: {operation} is not supported " - expected += "for remote tables." + expected += "in LanceDB Distributed." if operation == "IVF_HNSW_PQ": expected += " Please use IVF_HNSW_SQ instead." assert str(error.value) == expected @@ -1840,7 +1841,7 @@ async def test_remote_unsupported_operations_async(method, args, kwargs, operati with pytest.raises(NotImplementedError) as error: await getattr(table, method)(*args, **kwargs) expected = f"LanceDBError: not supported: {operation} is not supported " - expected += "for remote tables." + expected += "in LanceDB Distributed." if operation == "IVF_HNSW_PQ": expected += " Please use IVF_HNSW_SQ instead." assert str(error.value) == expected @@ -1852,7 +1853,7 @@ def test_remote_unsupported_legacy_hnsw_pq(): with pytest.warns(DeprecationWarning, match="create_index"): with pytest.raises( NotImplementedError, - match="IVF_HNSW_PQ is not supported for remote tables. " + match="IVF_HNSW_PQ is not supported in LanceDB Distributed. " "Please use IVF_HNSW_SQ instead.", ): table.create_index( @@ -1870,14 +1871,15 @@ def test_remote_python_only_messages(): with pytest.raises(NotImplementedError) as error: getattr(table, method)() assert str(error.value) == ( - f"{method}() is not supported for remote tables. " + f"{method}() is not supported in LanceDB Distributed. " f"Use table.search().{method}() instead." ) for method in ["compact_files", "cleanup_old_versions"]: with pytest.warns(UserWarning) as warning: getattr(table, method)() assert ( - str(warning[0].message) == f"{method}() is a no-op for remote tables." + str(warning[0].message) + == f"{method}() is a no-op in LanceDB Distributed." ) @@ -3842,7 +3844,7 @@ async def test_async_remote_to_lance_rejects_storage_access(monkeypatch): raise AssertionError("remote table URI must not be requested") monkeypatch.setattr(table, "uri", fail_uri) - with pytest.raises(NotImplementedError, match="remote tables"): + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): await table.to_lance() diff --git a/python/python/tests/test_remote_options.py b/python/python/tests/test_remote_options.py index 2022aa29d..0dbc21029 100644 --- a/python/python/tests/test_remote_options.py +++ b/python/python/tests/test_remote_options.py @@ -86,7 +86,9 @@ async def test_remote_create_rejects_write_options(storage_options, empty): if not empty: kwargs["data"] = [{"value": 1}] async with mock_lancedb_connection_async(handler) as db: - with pytest.raises(NotImplementedError, match="write_options.*remote"): + with pytest.raises( + NotImplementedError, match="write_options.*LanceDB Distributed" + ): await db.create_table("t", storage_options=storage_options, **kwargs) assert requests == [] @@ -108,7 +110,7 @@ def test_sync_remote_create_rejects_write_options(options): request.end_headers() with mock_lancedb_connection(handler) as db: - with pytest.raises(NotImplementedError, match="remote"): + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): db.create_table("t", [{"value": 1}], **options) assert requests == [] @@ -129,11 +131,11 @@ async def test_remote_open_rejects_local_options(options, asynchronous): if asynchronous: async with mock_lancedb_connection_async(handler) as db: - with pytest.raises(NotImplementedError, match="remote"): + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): await db.open_table("t", **options) else: with mock_lancedb_connection(handler) as db: - with pytest.raises(NotImplementedError, match="remote"): + with pytest.raises(NotImplementedError, match="LanceDB Distributed"): db.open_table("t", **options) assert requests == [] @@ -149,6 +151,6 @@ async def test_remote_open_rejects_location(): request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') async with mock_lancedb_connection_async(handler) as db: - with pytest.raises(NotImplementedError, match="location.*remote"): + with pytest.raises(NotImplementedError, match="location.*LanceDB Distributed"): await db.open_table("t", location="/tmp/zzz") assert requests == [] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 21fce93d3..375eec40c 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5552,7 +5552,9 @@ async def test_computed_column_async(tmp_path): def test_function_errors_are_remote_only(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("t", [{"x": 1}]) - with pytest.raises(NotImplementedError, match="LanceDB Cloud and Enterprise"): + with pytest.raises( + NotImplementedError, match="recorded only in LanceDB Distributed" + ): table.function_errors() diff --git a/python/src/table.rs b/python/src/table.rs index d77fd14b8..f484b3f77 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1922,7 +1922,8 @@ impl Table { inner .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "uses_v2_manifest_paths is not supported for remote tables.".into(), + message: "uses_v2_manifest_paths is not supported in LanceDB Distributed." + .into(), }) .infer_error()? .uses_v2_manifest_paths() @@ -1937,7 +1938,8 @@ impl Table { inner .as_native() .ok_or_else(|| lancedb::Error::NotSupported { - message: "migrate_manifest_paths_v2 is not supported for remote tables.".into(), + message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed." + .into(), }) .infer_error()? .migrate_manifest_paths_v2() diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index ce124e891..409edcc2a 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -288,8 +288,8 @@ impl BlobFile { } } - /// Physical byte offset in the data file. `None` on remote handles. The - /// Cloud byte-range route does not expose storage layout. + /// Physical byte offset in the data file. `None` on LanceDB Distributed handles. The + /// server's byte-range route does not expose storage layout. pub fn position(&self) -> Option { match &self.inner { BlobFileInner::Native(file) => Some(file.position()), @@ -298,8 +298,8 @@ impl BlobFile { } } - /// Path of the data file holding the blob. `None` on remote handles. The - /// Cloud byte-range route does not expose storage layout. + /// Path of the data file holding the blob. `None` on LanceDB Distributed handles. The + /// server's byte-range route does not expose storage layout. pub fn data_path(&self) -> Option<&Path> { match &self.inner { BlobFileInner::Native(file) => Some(file.data_path()), @@ -308,8 +308,8 @@ impl BlobFile { } } - /// Native storage layout. `None` on remote handles. The Cloud byte-range - /// route does not expose layout. + /// Native storage layout. `None` on LanceDB Distributed handles. The server's + /// byte-range route does not expose layout. pub fn kind(&self) -> Option { match &self.inner { BlobFileInner::Native(file) => Some(file.kind()), @@ -318,7 +318,7 @@ impl BlobFile { } } - /// External URI for native handles. Remote handles do not expose storage URIs. + /// External URI for native handles. LanceDB Distributed handles do not expose storage URIs. pub fn uri(&self) -> Option<&str> { match &self.inner { BlobFileInner::Native(file) => file.uri(), diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index bff97bf31..065eb3084 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -174,7 +174,7 @@ impl OpenTableBuilder { /// Advanced parameters that can be used to customize table reads /// - /// Remote connections reject these parameters with [`Error::NotSupported`]. + /// LanceDB Distributed connections reject these parameters with [`Error::NotSupported`]. /// /// If set, these will take precedence over any overlapping `OpenTableOptions` options pub fn lance_read_params(mut self, params: ReadParams) -> Self { @@ -333,7 +333,7 @@ pub struct CloneTableBuilder { request: CloneTableRequest, } -/// Builder for asynchronously executing a SQL statement on a remote database. +/// Builder for asynchronously executing a SQL statement on a LanceDB Distributed database. pub struct ExecuteQueryAsyncBuilder { parent: Arc, request: ExecuteQueryRequest, @@ -497,13 +497,13 @@ impl Connection { &self.internal } - /// Start executing SQL on a remote LanceDB database. + /// Start executing SQL on a LanceDB Distributed database. /// /// The query can reference tables in other databases with SQL dot notation. /// Use [`ExecuteQueryAsyncBuilder::default_namespace_path`] to avoid qualifying /// tables in the default namespace, and [`ExecuteQueryAsyncBuilder::parameters`] /// to bind Arrow values to `$1` / `$name` placeholders instead of writing them - /// into the SQL text. Local connections return [`Error::NotSupported`]. + /// into the SQL text. LanceDB Embedded connections return [`Error::NotSupported`]. /// /// # Example /// @@ -534,8 +534,8 @@ impl Connection { /// connection. Running state with a live query handle is not evicted; /// abandoned state has bounded retention, and server expiration is /// honored. Terminal state is retained briefly. - /// Query ids are not portable to another connection. Local connections - /// return [`Error::NotSupported`]. + /// Query ids are not portable to another connection. LanceDB Embedded + /// connections return [`Error::NotSupported`]. pub async fn describe_query( &self, query_id: uuid::Uuid, @@ -641,8 +641,8 @@ impl Connection { /// /// The server-side job builds the OCI image, then registers the completed /// artifact. Waiting on the returned typed job yields the durable - /// [`crate::function::FunctionVersion`]. Creation is remote-only. - /// Local databases return [`Error::NotSupported`]. + /// [`crate::function::FunctionVersion`]. Creation is supported only in LanceDB Distributed. + /// LanceDB Embedded databases return [`Error::NotSupported`]. /// pub async fn create_function_async( &self, @@ -658,7 +658,7 @@ impl Connection { /// /// Both the logical name and server-assigned version id are required; /// mutable aliases and latest-version lookup are intentionally absent. - /// Local databases return [`Error::NotSupported`]. + /// LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn get_function( &self, name: impl AsRef, @@ -673,7 +673,7 @@ impl Connection { /// List every published immutable Function version in `namespace_path` of /// the remote catalog. Functions in child namespaces are not included. /// - /// Results are ordered by Function name then version. Local databases return + /// Results are ordered by Function name then version. LanceDB Embedded databases return /// [`Error::NotSupported`]. /// /// # Example @@ -711,7 +711,7 @@ impl Connection { /// Remove the current Function name binding, retaining the object history. /// /// Returns `true` when the server appended a Dropped transition and - /// `false` for an idempotent replay. Local databases return + /// `false` for an idempotent replay. LanceDB Embedded databases return /// [`Error::NotSupported`]. pub async fn drop_function( &self, @@ -729,7 +729,7 @@ impl Connection { /// The name is unbound before this returns; the object's content may still be being /// deleted. Await [`Job::wait`][crate::job::Job::wait] to wait for that to finish. When /// the server deletes inline, or when nothing was bound, the returned job is already - /// finished and has no id. Local databases return [`Error::NotSupported`]. + /// finished and has no id. LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn drop_function_async( &self, name: impl AsRef, @@ -745,7 +745,7 @@ impl Connection { /// /// Fails if the name is taken, so a create can never silently become a /// rotation. There is no API that reads a stored credential back; the only - /// consumer is a Function that binds the Secret by name. Local databases + /// consumer is a Function that binds the Secret by name. LanceDB Embedded databases /// return [`Error::NotSupported`]. pub async fn create_secret( &self, @@ -764,7 +764,7 @@ impl Connection { /// Fails if it does not exist. Every Function bound to the Secret resolves /// the new value from its next execution, and no new Function version is /// minted -- which is what lets a rotation reach columns pinned to a - /// version registered before it. Local databases return + /// version registered before it. LanceDB Embedded databases return /// [`Error::NotSupported`]. pub async fn alter_secret( &self, @@ -781,7 +781,7 @@ impl Connection { /// The names of every Secret in this database. /// /// Names only. No path in this API returns a stored credential, by - /// construction rather than by policy. Local databases return + /// construction rather than by policy. LanceDB Embedded databases return /// [`Error::NotSupported`]. /// /// Results are fetched lazily, one page at a time. See [`Listing`] @@ -819,7 +819,7 @@ impl Connection { /// Functions bound to it fail at their next job, naming the Secret; that /// is the revocation path. The name becomes free to reuse, and a new /// Secret under it is picked up by everything still bound to that name. - /// Local databases return [`Error::NotSupported`]. + /// LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn drop_secret( &self, name: impl AsRef, @@ -835,7 +835,7 @@ impl Connection { /// /// Never the value. The type it returns has no field for one, so this is a /// property of the API rather than of what the caller chooses to read. - /// Local databases return [`Error::NotSupported`]. + /// LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn describe_secret( &self, name: impl AsRef, @@ -855,7 +855,7 @@ impl Connection { /// /// There is no replace: a name already taken is an error, and changing a /// view is a drop followed by a create, each authorized against what it - /// actually touches. Local databases return [`Error::NotSupported`]. + /// actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -904,7 +904,7 @@ impl Connection { /// schema that query resolved to. /// /// The schema is the one recorded at creation. A source altered since then - /// shows up when the view is read, not here. Local databases return + /// shows up when the view is read, not here. LanceDB Embedded databases return /// [`Error::NotSupported`]. pub async fn describe_view( &self, @@ -921,7 +921,7 @@ impl Connection { /// /// The tables it reads are untouched: a view holds no rows of its own. /// Use [`Connection::drop_view_async`] to get the cleanup job instead of - /// waiting on it. Local databases return [`Error::NotSupported`]. + /// waiting on it. LanceDB Embedded databases return [`Error::NotSupported`]. pub async fn drop_view(&self, name: impl AsRef, namespace_path: &[String]) -> Result<()> { validate_view_reference(name.as_ref(), namespace_path)?; self.internal.drop_view(name.as_ref(), namespace_path).await @@ -932,7 +932,7 @@ impl Connection { /// The name is free before this returns; the definition dataset may still /// be being deleted. Await [`Job::wait`][crate::job::Job::wait] to wait for /// that. When nothing was bound to the name, the returned job is already - /// finished and has no id. Local databases return [`Error::NotSupported`]. + /// finished and has no id. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// ```no_run /// # use lancedb::Connection; @@ -956,7 +956,7 @@ impl Connection { /// The names of the views in one namespace. /// /// Names only; a definition is query metadata and comes from - /// [`Self::describe_view`]. Local databases return [`Error::NotSupported`]. + /// [`Self::describe_view`]. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// Results are fetched lazily, one page at a time. See [`Listing`] /// for cached-result and continuation-token semantics. Errors terminate iteration. @@ -990,7 +990,7 @@ impl Connection { /// Rename a table in the database. /// - /// This is only supported in LanceDB Cloud. + /// This is only supported in LanceDB Distributed. pub async fn rename_table( &self, old_name: impl AsRef, @@ -1194,7 +1194,7 @@ impl Connection { /// For ListingDatabase, it is the equivalent DirectoryNamespace. /// For RemoteDatabase, it is the equivalent RestNamespace. /// - /// Remote connections using dynamic headers forward them through the + /// LanceDB Distributed connections using dynamic headers forward them through the /// namespace client's per-request context provider. pub async fn namespace_client(&self) -> Result> { self.internal.namespace_client().await @@ -1205,7 +1205,7 @@ impl Connection { /// - impl_type: "dir" for DirectoryNamespace, "rest" for RestNamespace /// - properties: configuration properties for the namespace /// - /// Remote connections using dynamic headers cannot be exported because the + /// LanceDB Distributed connections using dynamic headers cannot be exported because the /// namespace client config only carries static headers. pub async fn namespace_client_config( &self, @@ -1267,10 +1267,10 @@ pub struct ConnectRequest { /// /// ### Accepted URI formats /// - /// - `/path/to/database` - local database on file system. + /// - `/path/to/database` - database on the local file system. /// - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store - /// - `db://dbname` - LanceDB Cloud - /// - `db://` with a host override - remote tables in the storage root + /// - `db://dbname` - LanceDB Enterprise or LanceDB Cloud (legacy) + /// - `db://` with a host override - LanceDB Enterprise tables in the storage root pub uri: String, #[cfg(feature = "remote")] @@ -1347,9 +1347,9 @@ impl ConnectBuilder { } } - /// Set the LanceDB Cloud API key. + /// Set the API key for LanceDB Enterprise or LanceDB Cloud (legacy). /// - /// This option is only used when connecting to LanceDB Cloud (db:// URIs) + /// This option is only used for `db://` URIs /// and will be ignored for other URIs. /// /// # Arguments @@ -1363,9 +1363,9 @@ impl ConnectBuilder { self } - /// Set the LanceDB Cloud region. + /// Set the LanceDB Cloud (legacy) region. /// - /// This option is only used when connecting to LanceDB Cloud (db:// URIs) + /// This option is only used when connecting to LanceDB Cloud (`db://` URIs) /// and will be ignored for other URIs. /// /// # Arguments @@ -1379,12 +1379,12 @@ impl ConnectBuilder { self } - /// Set the LanceDB Cloud host override. + /// Set the host override, used to connect to LanceDB Enterprise. /// - /// This option is only used when connecting to LanceDB Cloud (db:// URIs) + /// This option is only used for `db://` URIs /// and will be ignored for other URIs. - /// Use the URI `db://` together with a host override to connect to remote - /// tables stored directly in the storage root. + /// Use the URI `db://` together with a host override to connect to + /// LanceDB Enterprise tables stored directly in the storage root. /// /// # Arguments /// @@ -1398,7 +1398,7 @@ impl ConnectBuilder { self } - /// Set the SQL service host override for a remote connection. + /// Set the SQL service host override for a LanceDB Enterprise connection. /// /// The SQL client is initialized lazily when the connection first executes /// SQL and is retained for the connection's lifetime. @@ -1417,13 +1417,13 @@ impl ConnectBuilder { /// native LanceDB databases. /// /// See [crate::remote::db::RemoteDatabaseOptions] for the options available for - /// LanceDB Cloud and LanceDB Enterprise. + /// LanceDB Enterprise and LanceDB Cloud (legacy). pub fn database_options(mut self, database_options: &dyn DatabaseOptions) -> Self { database_options.serialize_into_map(&mut self.request.options); self } - /// Set the LanceDB Cloud client configuration. + /// Set the HTTP client configuration for LanceDB Enterprise or LanceDB Cloud (legacy). /// /// ```no_run /// # use lancedb::connect; @@ -1447,7 +1447,7 @@ impl ConnectBuilder { self } - /// Configure OAuth authentication for LanceDB Cloud/Enterprise. + /// Configure OAuth authentication for LanceDB Enterprise. /// /// This creates an [`OAuthHeaderProvider`](crate::remote::OAuthHeaderProvider) /// from the given config and sets it as the header provider. OAuth cannot @@ -1532,7 +1532,7 @@ impl ConnectBuilder { /// Enable or disable manifest-backed directory namespace mode for local /// native connections. - /// Remote connections reject enabling this option with [`Error::NotSupported`]. + /// LanceDB Distributed connections reject enabling this option with [`Error::NotSupported`]. /// /// When enabled, the connection uses the directory namespace database /// directly for all table operations and forces @@ -1568,7 +1568,7 @@ impl ConnectBuilder { } /// Set a custom session for object stores and caching. - /// Remote connections reject this option with [`Error::NotSupported`]. + /// LanceDB Distributed connections reject this option with [`Error::NotSupported`]. /// /// By default, a new session with default configuration will be created. /// This method allows you to provide a custom session with your own @@ -1610,7 +1610,9 @@ impl ConnectBuilder { ] { if provided { return Err(Error::NotSupported { - message: format!("{option} is not supported for remote connections"), + message: format!( + "{option} is not supported for LanceDB Distributed connections" + ), }); } } @@ -1621,14 +1623,14 @@ impl ConnectBuilder { let options = RemoteDatabaseOptions::parse_from_map(&merged_options)?; let region = options.region.ok_or_else(|| Error::InvalidInput { - message: "A region is required when connecting to LanceDb Cloud".to_string(), + message: "A region is required when connecting to LanceDB Cloud".to_string(), })?; let api_key = match (&self.oauth_config, &options.api_key) { (Some(_), None) => String::new(), (Some(_), Some(_)) => { return Err(Error::InvalidInput { message: - "api_key and oauth_config cannot both be set when connecting to LanceDb Cloud" + "api_key and oauth_config cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" .to_string(), }); } @@ -1636,7 +1638,7 @@ impl ConnectBuilder { (None, None) => { return Err(Error::InvalidInput { message: - "An api_key or oauth_config is required when connecting to LanceDb Cloud" + "An api_key or oauth_config is required when connecting to LanceDB Enterprise or LanceDB Cloud" .to_string(), }); } @@ -1645,7 +1647,7 @@ impl ConnectBuilder { if self.oauth_config.is_some() && self.request.client_config.header_provider.is_some() { return Err(Error::InvalidInput { message: - "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDb Cloud" + "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" .to_string(), }); } @@ -1683,7 +1685,7 @@ impl ConnectBuilder { #[cfg(not(feature = "remote"))] fn execute_remote(self) -> Result { Err(Error::Runtime { - message: "cannot connect to LanceDb Cloud unless the 'remote' feature is enabled" + message: "cannot connect to LanceDB Enterprise or LanceDB Cloud unless the 'remote' feature is enabled" .to_string(), }) } @@ -1719,7 +1721,7 @@ impl ConnectBuilder { /// # Arguments /// /// * `uri` - URI where the database is located, can be a local directory, supported remote cloud storage, -/// or a LanceDB Cloud database. See [ConnectOptions::uri] for a list of accepted formats +/// or a LanceDB Enterprise or LanceDB Cloud (legacy) database. See [ConnectOptions::uri] for a list of accepted formats pub fn connect(uri: &str) -> ConnectBuilder { ConnectBuilder::new(uri) } @@ -2020,7 +2022,7 @@ mod tests { match result { Err(Error::InvalidInput { message }) if message - == "api_key and oauth_config cannot both be set when connecting to LanceDb Cloud" => + == "api_key and oauth_config cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" => {} Err(err) => panic!("expected InvalidInput, got {err:?}"), Ok(_) => panic!("expected api_key and oauth_config to be rejected"), @@ -2103,7 +2105,7 @@ mod tests { match result { Err(Error::InvalidInput { message }) if message - == "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDb Cloud" => + == "oauth_config and client_config.header_provider cannot both be set when connecting to LanceDB Enterprise or LanceDB Cloud" => {} Err(err) => panic!("expected InvalidInput, got {err:?}"), Ok(_) => panic!("expected header_provider and oauth_config to be rejected"), diff --git a/rust/lancedb/src/connection/create_table.rs b/rust/lancedb/src/connection/create_table.rs index 9d4408ba7..8842ce59b 100644 --- a/rust/lancedb/src/connection/create_table.rs +++ b/rust/lancedb/src/connection/create_table.rs @@ -46,7 +46,7 @@ impl CreateTableBuilder { /// Apply the given write options when writing the initial data /// - /// Remote connections reject explicit Lance write parameters with + /// LanceDB Distributed connections reject explicit Lance write parameters with /// [`Error::NotSupported`] instead of silently using server defaults. pub fn write_options(mut self, write_options: WriteOptions) -> Self { self.request.write_options = write_options; @@ -73,7 +73,7 @@ impl CreateTableBuilder { /// Set multiple options for the storage layer. /// - /// Table-level storage options are not supported by remote connections. + /// Table-level storage options are not supported by LanceDB Distributed connections. /// /// Options already set on the connection will be inherited by the table, /// but can be overridden here. diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 05386e0b7..939861b88 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -192,7 +192,7 @@ impl CloneTableRequest { } } -/// A request to start a SQL statement on a remote database. +/// A request to start a SQL statement on a LanceDB Distributed database. #[derive(Clone, Debug)] pub struct ExecuteQueryRequest { /// The SQL text. @@ -579,7 +579,7 @@ pub trait Database: async fn resume_job(&self, _job_id: &str) -> Result { job_op_not_supported("resume_job") } - /// Start executing a SQL statement on a remote database. + /// Start executing a SQL statement on a LanceDB Distributed database. async fn execute_query_async( &self, _request: ExecuteQueryRequest, diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 700c855dd..d5749f974 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1261,7 +1261,7 @@ impl Database for ListingDatabase { }); } Err(Error::NotSupported { - message: "rename_table is not supported in LanceDB OSS".into(), + message: "rename_table is not supported in LanceDB Embedded".into(), }) } diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 36e6c30c8..db3dc1c3b 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -771,8 +771,8 @@ impl_json!(FunctionBinding); /// Stable terminal result of an expression-backed or Function-backed column /// refresh [`crate::Job`]. /// -/// Local refresh jobs produce this value in process. LanceDB Cloud and -/// Enterprise decode the same value from the durable job's terminal payload. +/// LanceDB Embedded refresh jobs produce this value in process. LanceDB +/// Distributed decodes the same value from the durable job's terminal payload. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshColumnResult { /// Rows assigned a value by this refresh. diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 5ce345e7e..e9056863a 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -482,47 +482,47 @@ pub struct IndexConfig { /// /// An index may be made up of multiple segments, each with their own UUID. /// This is the UUID of the first segment. `None` if it could not be - /// determined (e.g. for remote tables, which do not yet surface this). + /// determined (e.g. in LanceDB Distributed, which does not yet surface this). pub index_uuid: Option, /// The protobuf type URL, a precise type identifier for the index. /// - /// `None` if unavailable (e.g. for remote tables). + /// `None` if unavailable (e.g. in LanceDB Distributed). pub type_url: Option, /// When the index was created, taken as the minimum creation time across /// all segments. /// /// `None` if unavailable, such as for indices created before creation - /// timestamps were tracked, or for remote tables. + /// timestamps were tracked, or in LanceDB Distributed. pub created_at: Option>, /// The number of rows indexed, across all segments. /// /// This is approximate and may include rows that have since been deleted. - /// `None` if unavailable (e.g. for remote tables whose server does not - /// report it). + /// `None` if unavailable (e.g. in LanceDB Distributed when the server + /// does not report it). pub num_indexed_rows: Option, /// The number of rows in the table that are not yet covered by this index. /// /// Computed as the table's total row count minus [`Self::num_indexed_rows`]. /// Optimizing the index will fold these rows into it. `None` if unavailable - /// (e.g. for remote tables whose server does not report it). + /// (e.g. in LanceDB Distributed when the server does not report it). pub num_unindexed_rows: Option, /// The total size in bytes of all index files across all segments. /// /// `None` if size information is unavailable, such as for indices created - /// before file sizes were tracked, or for remote tables. + /// before file sizes were tracked, or in LanceDB Distributed. pub size_bytes: Option, /// The number of segments that make up the index. /// - /// `None` if unavailable (e.g. for remote tables). + /// `None` if unavailable (e.g. in LanceDB Distributed). pub num_segments: Option, /// The on-disk index format version, taken from the first segment. /// - /// `None` if unavailable (e.g. for remote tables). + /// `None` if unavailable (e.g. in LanceDB Distributed). pub index_version: Option, /// Index-type-specific details, serialized as JSON. /// /// The shape of this JSON varies by index type. `None` if the details - /// could not be produced (e.g. no plugin available) or for remote tables. + /// could not be produced (e.g. no plugin available) or in LanceDB Distributed. pub index_details: Option, } diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 8b1ad97c3..e2d063c40 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -30,11 +30,11 @@ //! - `azure` - Enable Azure Blob Storage object store support. //! - `gcs` - Enable Google Cloud Storage object store support. //! - `oss` - Enable Alibaba Cloud OSS object store support. -//! - `remote` - Enable remote client to connect to LanceDB cloud. +//! - `remote` - Enable the client for connecting to LanceDB Enterprise or LanceDB Cloud (legacy). //! - `experimental-functions` - Opt in to local SQL computed-column declarations //! and refresh, and local materialized-view creation and refresh. Disabled by -//! default, including in published Python and TypeScript packages. Remote -//! Cloud/Enterprise operations, reading existing data, metadata protections, +//! default, including in published Python and TypeScript packages. LanceDB +//! Distributed operations, reading existing data, metadata protections, //! and ordinary eager `add_columns` transforms do not require this feature. //! - `huggingface` - Enable HuggingFace Hub integration for loading datasets from the Hub. //! - `fp16kernels` - Enable FP16 kernels for faster vector search on CPU. @@ -56,10 +56,10 @@ //! //! LanceDB accepts the different form of database path: //! -//! - `/path/to/database` - local database on file system. +//! - `/path/to/database` - database on the local file system. //! - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store -//! - `db://dbname` - Lance Cloud -//! - `db://` with a host override - remote tables in the storage root +//! - `db://dbname` - LanceDB Enterprise or LanceDB Cloud (legacy) +//! - `db://` with a host override - LanceDB Enterprise tables in the storage root //! //! You can also use [`ConnectBuilder`] to configure the connection to the database. //! diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 266cdab59..fa51cbf25 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -171,7 +171,7 @@ pub(crate) fn physical_unnest( return Err(Error::NotSupported { message: format!( "'{name}' in FROM position is a Function; views over Function rows are \ - supported only on LanceDB Cloud and Enterprise" + supported only in LanceDB Distributed" ), }); } @@ -1464,7 +1464,7 @@ async fn prepare_with( ) -> Result { let Some(caller_native) = source.as_native() else { return Err(Error::NotSupported { - message: "materialized views are supported only on local databases".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }); }; let source_namespace = source.namespace().to_vec(); @@ -1492,7 +1492,7 @@ async fn prepare_with( let resolved = Table::new(resolved, database.clone()); let Some(native) = resolved.as_native() else { return Err(Error::NotSupported { - message: "materialized views are supported only on local databases".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }); }; let caller_uri = caller_native.dataset.get().await?.uri().to_string(); @@ -1665,15 +1665,15 @@ impl CreateMaterializedViewBuilder { self } - /// Enable or disable automatic refresh on Cloud and Enterprise. + /// Enable or disable automatic refresh in LanceDB Distributed. /// When omitted, the server determines whether automatic refresh is enabled. - /// Embedded databases do not support automatic refresh. + /// LanceDB Embedded does not support automatic refresh. pub fn auto_refresh_enabled(mut self, enabled: bool) -> Self { self.auto_refresh_enabled = Some(enabled); self } - /// Set a positive, finite refresh interval in seconds on Cloud and Enterprise. + /// Set a positive, finite refresh interval in seconds in LanceDB Distributed. /// When omitted, the server determines when to refresh. /// /// ```no_run @@ -1766,7 +1766,7 @@ impl CreateMaterializedViewBuilder { crate::require_experimental_functions()?; if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { return Err(Error::NotSupported { - message: "automatic materialized-view refresh requires Cloud or Enterprise" + message: "automatic materialized-view refresh requires LanceDB Distributed" .to_string(), }); } @@ -1825,7 +1825,7 @@ impl MaterializedView { /// The query parsed into the local refresh grammar. /// - /// Sophon may store SQL broader than the local grammar; use + /// LanceDB Enterprise may store SQL broader than the local grammar; use /// [`Self::definition_sql`] when the original SQL is sufficient. pub fn definition(&self) -> Result<&MaterializedViewDefinition> { self.parsed_definition @@ -1875,8 +1875,8 @@ pub struct RefreshMaterializedViewBuilder { } impl RefreshMaterializedViewBuilder { - /// Force a complete rebuild instead of letting the remote server choose - /// the refresh mode. Defaults to `false`. Local views always rebuild. + /// Force a complete rebuild instead of letting the server choose + /// the refresh mode. Defaults to `false`. LanceDB Embedded views always rebuild. /// /// ```no_run /// # #![recursion_limit = "256"] @@ -2015,7 +2015,7 @@ impl Connection { /// Start dropping a materialized view and return its job. /// /// This validates that the named resource is a materialized view rather - /// than an ordinary table. For remote connections the job has type `query` + /// than an ordinary table. In LanceDB Distributed the job has type `query` /// and its ID identifies the SQL query. Waiting completes once the catalog /// binding is removed; physical cleanup continues in the background. /// diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 70a795eb3..9f7e3eb1f 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -77,7 +77,7 @@ pub(crate) async fn execute_refresh( ) -> Result { crate::require_experimental_functions()?; let native = view.as_native().ok_or_else(|| Error::NotSupported { - message: "materialized views are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), })?; native.dataset.ensure_mutable()?; let lock = refresh_lock(native.dataset.get().await?.uri()); @@ -199,7 +199,7 @@ pub async fn replace_materialized_view_fragments( stream: SendableRecordBatchStream, ) -> Result { let native = view.as_native().ok_or_else(|| Error::NotSupported { - message: "materialized views are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), })?; native.dataset.ensure_mutable()?; let lock = refresh_lock(native.dataset.get().await?.uri()); @@ -320,7 +320,7 @@ async fn open_source(view: &Table, definition: &MaterializedViewDefinition) -> R }) .await?; let native = source.as_native().ok_or_else(|| Error::NotSupported { - message: "materialized views are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), })?; Ok(native.dataset.get().await?.as_ref().clone()) } diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 9bac51209..70684e84f 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -444,8 +444,8 @@ pub trait QueryBase { /// # } /// ``` /// - /// Note: Expression filters are not supported for remote/server-side queries. - /// Use [`QueryBase::only_if`] with SQL strings for remote tables. + /// Note: Expression filters are not supported for LanceDB Distributed queries. + /// Use [`QueryBase::only_if`] with SQL strings in LanceDB Distributed. /// /// Calling this multiple times combines the expressions with a logical AND /// rather than replacing the previous filter. @@ -1025,7 +1025,7 @@ impl Query { /// By default, there is no embedding model, and the input should be /// vector/slice of floats. /// NaN and infinite components are rejected with [`Error::InvalidInput`] - /// after conversion to Float32, for both local and remote tables. + /// after conversion to Float32, in both LanceDB Embedded and LanceDB Distributed. /// /// If there is only one vector column (a column whose data type is a /// fixed size list of floats) then the column does not need to be specified. @@ -1269,7 +1269,7 @@ impl VectorQuery { /// result. /// /// NaN and infinite components are rejected with [`Error::InvalidInput`] - /// after conversion to Float32, for both local and remote tables. + /// after conversion to Float32, in both LanceDB Embedded and LanceDB Distributed. pub fn add_query_vector(mut self, vector: impl IntoQueryVector) -> Result { self.request.add_query_vector(vector)?; Ok(self) diff --git a/rust/lancedb/src/remote.rs b/rust/lancedb/src/remote.rs index a6b2f0e62..5abe4dcf7 100644 --- a/rust/lancedb/src/remote.rs +++ b/rust/lancedb/src/remote.rs @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors //! This module contains a remote client for a LanceDB server. This is used -//! to communicate with LanceDB cloud. It can also serve as an example for +//! to communicate with LanceDB Enterprise or LanceDB Cloud (legacy). It can also serve as an example for //! building client/server applications with LanceDB or as a client for some //! other custom LanceDB service. diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index bf90b1e77..ae4c1aaa5 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -83,7 +83,8 @@ const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 8 * 1024 * 1024 * 1024; /// timeout (which also covers the request-body upload) fires. const DEFAULT_MAX_REQUEST_DURATION_DIVISOR: u32 = 2; -/// Configuration for the LanceDB Cloud HTTP client. +/// Configuration for the HTTP client used to connect to LanceDB Enterprise or +/// LanceDB Cloud (legacy). #[derive(Clone)] pub struct ClientConfig { pub timeout_config: TimeoutConfig, @@ -108,7 +109,7 @@ pub struct ClientConfig { pub header_provider: Option>, /// User identifier for tracking purposes. /// - /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise. + /// This is sent as the `x-lancedb-user-id` header in requests to LanceDB Enterprise. /// It can be set directly, or via the `LANCEDB_USER_ID` environment variable. /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 394dc4af2..4f97c16e8 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -117,7 +117,7 @@ pub const OPT_REMOTE_SQL_HOST_OVERRIDE: &str = "remote_database_sql_host_overrid #[derive(Clone, Debug, Default)] pub struct RemoteDatabaseOptions { - /// The LanceDB Cloud API key + /// The LanceDB Enterprise or LanceDB Cloud (legacy) API key pub api_key: Option, /// The LanceDB Cloud region pub region: Option, @@ -187,11 +187,11 @@ impl RemoteDatabaseOptionsBuilder { } } - /// Set the LanceDB Cloud API key + /// Set the LanceDB Enterprise or LanceDB Cloud (legacy) API key /// /// # Arguments /// - /// * `api_key` - The LanceDB Cloud API key + /// * `api_key` - The API key pub fn api_key(mut self, api_key: String) -> Self { self.options.api_key = Some(api_key); self @@ -871,7 +871,7 @@ impl Database for RemoteDatabase { async fn read_consistency(&self) -> Result { Err(Error::NotSupported { - message: "Getting the read consistency of a remote database is not yet supported" + message: "Getting the read consistency is not yet supported in LanceDB Distributed" .to_string(), }) } @@ -882,7 +882,9 @@ impl Database for RemoteDatabase { ) -> Result { if request.with_no_data { return Err(Error::NotSupported { - message: "remote materialized views must be populated during creation".to_string(), + message: + "materialized views in LanceDB Distributed must be populated during creation" + .to_string(), }); } if let Some(seconds) = request.auto_refresh_interval_seconds @@ -1475,7 +1477,9 @@ impl Database for RemoteDatabase { ] { if provided { return Err(Error::NotSupported { - message: format!("{option} is not supported for remote table creation"), + message: format!( + "{option} is not supported for table creation in LanceDB Distributed" + ), }); } } @@ -1616,7 +1620,9 @@ impl Database for RemoteDatabase { ] { if provided { return Err(Error::NotSupported { - message: format!("{option} is not supported for remote table access"), + message: format!( + "{option} is not supported for table access in LanceDB Distributed" + ), }); } } @@ -2660,7 +2666,7 @@ mod tests { .execute() .await; assert!(matches!(result, Err(Error::NotSupported { message }) - if message.contains("write_options") && message.contains("remote"))); + if message.contains("write_options") && message.contains("LanceDB Distributed"))); } } @@ -2733,7 +2739,7 @@ mod tests { ] { let result = builder.execute().await; assert!(matches!(result, Err(Error::NotSupported { message }) - if message.contains(option) && message.contains("remote"))); + if message.contains(option) && message.contains("LanceDB Distributed"))); } } @@ -2751,7 +2757,7 @@ mod tests { ] { let result = builder.api_key("fake").region("us-east-1").execute().await; assert!(matches!(result, Err(Error::NotSupported { message }) - if message.contains(option) && message.contains("remote"))); + if message.contains(option) && message.contains("LanceDB Distributed"))); } } diff --git a/rust/lancedb/src/remote/oauth.rs b/rust/lancedb/src/remote/oauth.rs index c7cffa327..95d74274e 100644 --- a/rust/lancedb/src/remote/oauth.rs +++ b/rust/lancedb/src/remote/oauth.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! OAuth authentication for LanceDB Cloud connections. +//! OAuth authentication for LanceDB Enterprise connections. //! //! Protocol mechanics (authorization URL and CSRF state, PKCE, token //! exchanges, refresh, device authorization and polling, standard response diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 7be8db77c..4a7e384eb 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -544,7 +544,7 @@ impl RemoteTable { ) && !self.server_version.support_fts_document_granularity() { return Err(Error::NotSupported { - message: "FTS document granularity requires remote server version 0.6.0 or later" + message: "FTS document granularity requires LanceDB Enterprise server version 0.6.0 or later" .into(), }); } @@ -569,7 +569,7 @@ impl RemoteTable { // Warn if train=false is specified since it's not meaningful if !index.train { log::warn!( - "train=false has no effect remote tables. The index will be created empty and automatically populated in the background." + "train=false has no effect in LanceDB Distributed. The index will be created empty and automatically populated in the background." ); } @@ -623,7 +623,7 @@ impl RemoteTable { } Index::IvfHnswPq(_) => { return Err(Error::NotSupported { - message: "IVF_HNSW_PQ is not supported for remote tables. Please use IVF_HNSW_SQ instead.".into(), + message: "IVF_HNSW_PQ is not supported in LanceDB Distributed. Please use IVF_HNSW_SQ instead.".into(), }); } }; @@ -1067,7 +1067,7 @@ impl RemoteTable { QueryFilter::Datafusion(expr) => expr_to_sql_string(expr)?, QueryFilter::Substrait(_) => { return Err(Error::NotSupported { - message: "Substrait filters are not supported for remote queries" + message: "Substrait filters are not supported in LanceDB Distributed" .to_string(), }); } @@ -1117,7 +1117,7 @@ impl RemoteTable { if let Some(full_text_search) = ¶ms.full_text_search { if full_text_search.wand_factor.is_some() { return Err(Error::NotSupported { - message: "Wand factor is not supported for remote tables.".into(), + message: "Wand factor is not supported in LanceDB Distributed.".into(), }); } @@ -1128,7 +1128,7 @@ impl RemoteTable { { return Err(Error::NotSupported { message: - "FTS document granularity requires remote server version 0.6.0 or later" + "FTS document granularity requires LanceDB Enterprise server version 0.6.0 or later" .into(), }); } @@ -2760,7 +2760,7 @@ impl BaseTable for RemoteTable { if add.allow_external_blob_outside_bases { return Err(Error::NotSupported { - message: "allow_external_blob_outside_bases is only supported on local tables" + message: "allow_external_blob_outside_bases is only supported in LanceDB Embedded" .to_string(), }); } @@ -3432,7 +3432,7 @@ impl BaseTable for RemoteTable { async fn optimize(&self, _action: OptimizeAction) -> Result { self.check_mutable().await?; Err(Error::NotSupported { - message: "optimize is not supported for remote tables.".into(), + message: "optimize is not supported in LanceDB Distributed.".into(), }) } async fn add_columns( @@ -4480,7 +4480,7 @@ mod tests { .unwrap_err(); assert!(matches!(err, Error::NotSupported { .. }), "got {err:?}"); - assert!(err.to_string().contains("local tables")); + assert!(err.to_string().contains("LanceDB Embedded")); } #[tokio::test] @@ -6560,7 +6560,7 @@ mod tests { match result.unwrap_err() { Error::NotSupported { message } => assert_eq!( message, - format!("{operation} is not supported for remote tables.") + format!("{operation} is not supported in LanceDB Distributed.") ), error => panic!("expected not-supported error, got {error}"), } @@ -6588,7 +6588,7 @@ mod tests { .unwrap_err(); assert_not_supported_error( error, - "IVF_HNSW_PQ is not supported for remote tables. Please use IVF_HNSW_SQ instead.", + "IVF_HNSW_PQ is not supported in LanceDB Distributed. Please use IVF_HNSW_SQ instead.", ); } @@ -7692,10 +7692,9 @@ mod tests { panic!("legacy remote query unexpectedly succeeded") }; - assert!( - err.to_string() - .contains("document granularity requires remote server version 0.6.0 or later") - ); + assert!(err.to_string().contains( + "document granularity requires LanceDB Enterprise server version 0.6.0 or later" + )); } #[rstest] @@ -8641,12 +8640,9 @@ mod tests { .execute() .await; - assert!( - result - .unwrap_err() - .to_string() - .contains("document granularity requires remote server version 0.6.0 or later") - ); + assert!(result.unwrap_err().to_string().contains( + "document granularity requires LanceDB Enterprise server version 0.6.0 or later" + )); } #[tokio::test] diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index fee2d5d79..713a79e86 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Handles to SQL queries running on a remote database. +//! Handles to SQL queries running on a LanceDB Distributed database. use std::{fmt, sync::Arc}; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 37edd9161..6ae31fd9e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -551,7 +551,7 @@ pub fn tokenize(query: &str, params: &InvertedIndexParams) -> Result Result<()>; /// Prewarm data for the table. /// - /// Currently only supported on remote tables. + /// Currently only supported in LanceDB Distributed. /// If `columns` is `None`, all columns are prewarmed. async fn prewarm_data(&self, columns: Option>) -> Result<()>; /// Get statistics about the index. @@ -817,9 +817,9 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { ) -> Result; /// Declare computed columns, each defined by a SQL expression. /// - /// Where the declaration is planned depends on the backend: a local table - /// validates and types the expression itself, while a remote one sends the - /// expression for the server to plan. + /// Where the declaration is planned depends on the backend: a LanceDB Embedded + /// table validates and types the expression itself, while a LanceDB Distributed + /// table sends the expression for the server to plan. async fn add_computed_columns( &self, _columns: &[(String, String)], @@ -837,7 +837,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { _options: computed_columns::ComputedColumnOptions, ) -> Result { Err(Error::NotSupported { - message: "Function columns are supported only on LanceDB Cloud and Enterprise".into(), + message: "Function columns are supported only in LanceDB Distributed".into(), }) } /// Fill a computed column's unfilled rows and recompute those whose @@ -846,7 +846,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// The default returns `NotSupported`; Lance-backed tables override it. async fn refresh_column(&self, _column: &str) -> Result { Err(Error::NotSupported { - message: "computed columns are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }) } /// Fill a computed column's unfilled rows and recompute those whose @@ -856,7 +856,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { _column: &str, ) -> Result> { Err(Error::NotSupported { - message: "computed columns are supported only on local tables".into(), + message: "this operation is only supported on LanceDB Embedded".into(), }) } /// The per-row errors Function refreshes recorded on this table; see @@ -866,8 +866,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { _request: &crate::function::FunctionErrorsRequest, ) -> Result { Err(Error::NotSupported { - message: "per-row Function errors are recorded only on LanceDB Cloud and Enterprise" - .into(), + message: "per-row Function errors are recorded only in LanceDB Distributed".into(), }) } /// Alter columns in the table. @@ -994,7 +993,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// [`FieldMetadataUpdate::remove`] deletes a key and /// [`FieldMetadataUpdate::replace`] swaps the field's whole map. /// - /// The default returns `NotSupported`; Lance-backed and remote tables override it. + /// The default returns `NotSupported`; Lance-backed and LanceDB Distributed tables override it. async fn update_field_metadata( &self, _updates: &[FieldMetadataUpdate], @@ -1265,8 +1264,8 @@ impl Table { /// /// Native tables support both legacy blob v1 and blob v2 columns. /// Output matches `row_ids` in length and order. Null blobs are null; - /// valid empty blobs contain empty byte strings. Cloud limits individual - /// requests to 1024 row ids and 64 MiB of blob bytes; the remote client + /// valid empty blobs contain empty byte strings. LanceDB Distributed limits individual + /// requests to 1024 row ids and 64 MiB of blob bytes; the client /// splits requests and reads a single larger blob through the Range route. /// This method still materializes all bytes in memory, so prefer /// [`Self::fetch_blob_files`] for large selections. @@ -1317,7 +1316,7 @@ impl Table { /// ranges for the same blob. The output has the same length and order as /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. - /// Remote tables read through version-pinned [`BlobFile`] handles using + /// LanceDB Distributed tables read through version-pinned [`BlobFile`] handles using /// HTTP byte-range requests. /// /// `_rowid` values stay valid after compaction when the table has stable @@ -1576,7 +1575,7 @@ impl Table { } /// See [Table::create_index] - /// For remote tables, this allows an optional wait_timeout to poll until asynchronous indexing is complete + /// In LanceDB Distributed, this allows an optional wait_timeout to poll until asynchronous indexing is complete pub fn create_index_with_timeout( &self, columns: &[impl AsRef], @@ -1862,7 +1861,7 @@ impl Table { error_if_tagged_old_versions: Option, ) -> Result { let native = self.as_native().ok_or_else(|| Error::NotSupported { - message: "optimize is not supported on LanceDB cloud.".into(), + message: "optimize is not supported in LanceDB Distributed.".into(), })?; let prune = optimize::cleanup_old_versions_before( native, @@ -1892,7 +1891,7 @@ impl Table { /// [`freshness`](crate::table::freshness)); everything else is left as /// it is. /// - /// Local tables only: a remote refresh runs as a server job, through + /// LanceDB Embedded only: in LanceDB Distributed a refresh runs as a server job, through /// [`Table::refresh_column_async`]. /// /// ``` @@ -1915,8 +1914,8 @@ impl Table { /// wait returns the durable [`crate::function::RefreshColumnResult`] for /// both expression-backed and Function-backed columns. Invalid input /// -- an unknown column, or one that is not computed -- is reported by - /// this call rather than by the job. On local tables the job runs as an - /// in-process task; on LanceDB Cloud and Enterprise it is the server's + /// this call rather than by the job. In LanceDB Embedded the job runs as an + /// in-process task; in LanceDB Distributed it is the server's /// backfill job. /// /// ``` @@ -1942,7 +1941,7 @@ impl Table { /// capped. Filter by job or column through the request; a listing that /// hit its limit reports [`FunctionErrors::truncated`]. /// - /// LanceDB Cloud and Enterprise only, and the caller needs read access + /// LanceDB Distributed only, and the caller needs read access /// to the table, since a message carries the value that failed. /// /// ``` @@ -2293,7 +2292,7 @@ impl Table { /// Tokenize a full-text search query using the tokenizer configured on an FTS index. /// /// Model-backed tokenizers such as `jieba/*` and `lindera/*` are rebuilt in - /// the client process from index metadata. For remote tables, this means the + /// the client process from index metadata. In LanceDB Distributed, this means the /// same tokenizer model files must also exist locally, and must match the /// files the server uses: the client cannot detect a mismatch, so it may /// return tokens the server's index never produces. If the model files are @@ -2331,7 +2330,7 @@ impl Table { /// /// The column must have exactly one FTS index. Model-backed tokenizers such /// as `jieba/*` and `lindera/*` are rebuilt in the client process from - /// index metadata. For remote tables, this means the same tokenizer model + /// index metadata. In LanceDB Distributed, this means the same tokenizer model /// files must also exist locally, and must match the files the server uses /// (see [`Self::tokenize`]). pub async fn tokenize_with_column(&self, query: &str, column: &str) -> Result> { @@ -2420,7 +2419,7 @@ impl Table { /// Get the table URI (storage location) /// /// Returns the full storage location of the table (e.g., S3/GCS path). - /// For remote tables, this fetches the location from the server via describe. + /// In LanceDB Distributed, this fetches the location from the server via describe. pub async fn uri(&self) -> Result { self.inner.uri().await } @@ -2465,7 +2464,7 @@ impl Table { /// Drop an index from the table. /// - /// Note: This is not yet available in LanceDB cloud. + /// Note: This is not yet available in LanceDB Distributed. /// /// This does not delete the index from disk, it just removes it from the table. /// To delete the index, run [`Self::optimize()`] after dropping the index. @@ -2498,7 +2497,7 @@ impl Table { /// This is a hint to the database that the given columns will be accessed in /// the future and the database should prefetch the data if possible. This /// can reduce cold-start latency for subsequent queries. Currently only - /// supported on remote tables. + /// supported in LanceDB Distributed. /// /// This call initiates prewarming and returns once the request is accepted. /// It is idempotent and safe to call from multiple clients concurrently — @@ -2841,7 +2840,7 @@ impl NativeTable { /// The registry belongs to this handle, its clones and its branch handles, /// and is not stored with the table: a handle opened separately starts from /// Lance's built-ins. Set it before the handle's first LSM write; writers - /// already open keep the registry they were opened with. Local tables only, + /// already open keep the registry they were opened with. LanceDB Embedded only, /// reached through [`Table::as_native`]. /// /// ``` @@ -3695,7 +3694,7 @@ impl BaseTable for NativeTable { async fn prewarm_data(&self, _columns: Option>) -> Result<()> { Err(Error::NotSupported { - message: "prewarm_data is currently only supported on remote tables.".into(), + message: "prewarm_data is currently only supported in LanceDB Distributed.".into(), }) } @@ -4312,7 +4311,7 @@ mod tests { assert_eq!(table.name, "test") } - /// The per-row error store is a server feature; a local table says so + /// The per-row error store is a server feature; a LanceDB Embedded table says so /// rather than answering with an empty listing. #[tokio::test] async fn test_function_errors_are_remote_only() { @@ -4332,7 +4331,7 @@ mod tests { .await .unwrap_err(); assert!( - matches!(&err, Error::NotSupported { message } if message.contains("Cloud and Enterprise")), + matches!(&err, Error::NotSupported { message } if message.contains("LanceDB Distributed")), "{err:?}" ); } diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 0f13718fd..24329d323 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -69,10 +69,10 @@ impl AddColumnsBuilder { /// renamed, retyped or dropped while a declaration reads it, since the /// expression names it. /// - /// Local declaration and refresh require the `experimental-functions` - /// Cargo feature. Remote operations do not require this feature. + /// LanceDB Embedded declaration and refresh require the `experimental-functions` + /// Cargo feature. LanceDB Distributed operations do not require this feature. /// - /// On LanceDB Cloud and Enterprise the expression is planned by the + /// In LanceDB Distributed the expression is planned by the /// server, and the refresh runs as a server job -- see /// [`Table::refresh_column_async`](super::Table::refresh_column_async). /// @@ -147,7 +147,7 @@ impl AddColumnsBuilder { /// Configure automatic refresh for every output declared in this call. /// Settings are stored with the declaration. They require computed or - /// Function columns; local tables persist them without starting a scheduler. + /// Function columns; LanceDB Embedded persists them without starting a scheduler. /// /// ``` /// # use lancedb::{Table, table::computed_columns::ComputedColumnOptions}; diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 445f29a18..8c5dc4b45 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -152,7 +152,7 @@ impl AddDataBuilder { /// /// The row keeps a reference, so the object has to stay readable. /// [`crate::table::Table::fetch_blobs`] reads from that location. - /// Defaults to `false`. Local tables only. + /// Defaults to `false`. LanceDB Embedded only. pub fn allow_external_blob_outside_bases(mut self, allow: bool) -> Self { self.allow_external_blob_outside_bases = allow; self diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 942c43d4e..09a751d7a 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -60,8 +60,8 @@ pub const AUTO_REFRESH_ENABLED_META_KEY: &str = "computed_column.auto_refresh_en /// Minimum interval between successful automatic refreshes, in seconds. pub const AUTO_REFRESH_INTERVAL_META_KEY: &str = "computed_column.auto_refresh_interval_seconds"; -/// Scheduling settings persisted on each computed output. Local tables store -/// these settings; automatic scheduling requires a Cloud or Enterprise server. +/// Scheduling settings persisted on each computed output. LanceDB Embedded +/// stores these settings; automatic scheduling requires LanceDB Distributed. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct ComputedColumnOptions { diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index c5eadeeaf..a3f313ba7 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -368,7 +368,8 @@ fn declared_expression(dataset: &Dataset, column: &str) -> Result { match declaration.kind { ComputedColumnKind::Sql { expression } => Ok(expression), ComputedColumnKind::Function { .. } => Err(Error::NotSupported { - message: "registered Function columns are refreshed only by a remote server Job".into(), + message: "registered Function columns are refreshed only by a LanceDB Distributed job" + .into(), }), ComputedColumnKind::Unrecognized { kind } => Err(Error::NotSupported { message: format!( From 84fc48198b918b7a399475fc53eb011efae14087 Mon Sep 17 00:00:00 2001 From: Nishil Rathod <161206163+NishilRathod@users.noreply.github.com> Date: Thu, 29 Oct 2026 02:55:00 +0530 Subject: [PATCH 150/180] docs: add guide for using LanceDB in VS Code extensions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #1849 This was lancedb/docs#371. After lancedb/docs#355 moved the open-source pages, their navigation and the snippet tests into this repository's `docs/web` and `docs/web-tests`, that PR could no longer merge there, so I've moved the same change here. ## Why #1849 asks for an example of LanceDB in a VS Code extension, because people kept running into problems there (#927, #1713). An earlier attempt, #3682, added a README link. @prrao87 asked for something else instead: a quick guide on the docs site, under **Integrations › AI Platforms & Frameworks**, showing how to use LanceDB in an extension and what results look like. The author of #3682 agreed and closed it. This PR is that guide. ## What it adds - **`docs/web/integrations/ai/vscode.mdx`**: a new page, also added to `docs/web/docs.json`. It builds a small extension with two commands. One indexes the workspace's Markdown into a LanceDB table using the built-in `huggingface` embedding function, so no API key is needed. The other searches it by meaning. The page covers the parts that are specific to VS Code: - storing the table under `context.storageUri` instead of a relative path, which is the cause of #927; - `@types/node` ≥ 22 and `skipLibCheck`, which covers #1713 and the DOM-type errors from `apache-arrow`/onnxruntime typings; - pinning `apache-arrow` inside LanceDB's peer range; - marking `@lancedb/lancedb` and `@huggingface/transformers` as esbuild externals, and removing `node_modules/**` from the template's `.vscodeignore`; - storing each file's URI so a hit opens in the right folder of a multi-root workspace; - building one VSIX per platform with `vsce package --target`, with a table mapping each target to LanceDB's native package, and a note that the sample's local model (via `onnxruntime-node`) doesn't run on Alpine; - keeping the Transformers.js model cache in `globalStorageUri`, which only works if it's loaded with `import()`; - a troubleshooting table listing each error message with its cause and fix. - **`docs/web-tests/ts/vscode_search.ts`** and **`vscode_search.test.ts`**: the LanceDB code the page shows (connect, chunk, index, search), plus jest tests for it. - **`docs/web-tests/ts/vscode_extension.ts`**: the extension's `src/extension.ts`. Jest can't run it because it needs the VS Code extension host, so it was tested in a real extension instead (see below). This follows the precedent of `integrations.ts`. - **`docs/web/snippets/vscode_search.mdx`** and **`vscode_extension.mdx`**: generated with the command in CONTRIBUTING.md. ## Changes from lancedb/docs#371 - **New paths only.** The page, tests and snippets are the same content, at their paths in this repository. - **One link.** `/tables/update` doesn't exist under `docs/web`, so the `mergeInsert` link now points to `/ingestion/merge-insert`. - **Heading anchors.** Every heading now has an explicit `{#anchor}`, as CONTRIBUTING.md asks. ## How I tested it - **Snippet tests.** In this repository at `c2c8269f`, `vscode_search.test.ts` passes (2 tests) with the pinned `@lancedb/lancedb` 0.31.0. On Windows the `npm test` script fails before it starts, because it runs `node` on the `.bin/jest` shell shim. I ran `node --experimental-vm-modules node_modules/jest/bin/jest.js --testEnvironment jest-environment-node-single-context vscode_search` instead. - **Lint.** `biome ci` is clean for the three new files, and they carry the SPDX header that `license-header-check.yml` looks for. - **Snippets.** I regenerated them with CONTRIBUTING.md's command, `mdx_snippets_gen.py -s docs/web-tests/py -s docs/web-tests/ts -s docs/web-tests/rs -o docs/web/snippets`, run with `python` since I don't have `uv`. It reproduces the two new snippet files exactly, once the Windows CRLF endings are normalised. As CONTRIBUTING.md warns, it also rewrites `build_with_ai_agents.mdx`, `integrations.mdx`, `search.mdx` and `storage.mdx`. I left those out. - **Links.** `mint broken-links` from `docs/web` reports no entries on the new page, and its three internal links (`/embedding/quickstart`, `/ingestion/merge-insert`, `/search/full-text-search`) resolve to pages here. - **Real extension.** I built a sample extension from exactly the code on the page, scaffolded with `yo code` (TypeScript + esbuild) and using `@lancedb/lancedb` 0.39.0. I ran it with `@vscode/test-cli` in VS Code 1.140 on Windows x64. The integration test runs both commands against a six-file workspace and checks the top hits. The "Sample results" block on the page is copied from that run, and after the review fixes below it reproduces line for line in VS Code 1.141. - **Multi-root workspace.** A second test configuration opens two folders that both contain `docs/auth.md`. It types a query and picks the top hit through the real picker, then checks that the right folder's file opens at the right line. It fails on the code before the review fix and passes after it. - **Packaged VSIX.** I packaged `vsce package --target win32-x64` (200 MB, or 148 MB with the onnxruntime trimming in the Tip). Then I unpacked it outside the project and ran the same tests against the unpacked copy, so they couldn't pick up the project's `node_modules`. They pass. - **Negative checks behind the troubleshooting rows:** - With `node_modules/**` left in `.vscodeignore`, activation fails with `Cannot find module '@lancedb/lancedb'` and the commands report `command '…' not found`. - Without the externals, esbuild fails with `No loader is configured for ".node" files`. - Installing LanceDB into a project that already has `apache-arrow` 21 fails with `ERESOLVE`. - `require("@huggingface/transformers")` returns a different `env` object from `import()`. - **Rendering.** For lancedb/docs#371, `mint dev` rendered the page, its 14 code blocks and the sidebar entry. I haven't re-rendered it from `docs/web`; only the paths, one link and the heading anchors changed. **Not tested:** - macOS. I couldn't reproduce the read-only working directory from #927; the page's fix (an absolute storage path) doesn't depend on the OS. - Linux and macOS VSIX builds. ## Notes for reviewers - I added `_distance` to `.select(...)`, because LanceDB warns that it will stop adding the column automatically. ## AI disclosure I used Claude Code to research the issue and its history, write the sample extension, the tests and this page, move the change here, and draft this description. I ran every check listed above myself, and the outputs quoted on the page come from those runs. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- docs/web-tests/ts/vscode_extension.ts | 117 ++++++++++ docs/web-tests/ts/vscode_search.test.ts | 67 ++++++ docs/web-tests/ts/vscode_search.ts | 77 ++++++ docs/web/docs.json | 3 +- docs/web/integrations/ai/vscode.mdx | 297 ++++++++++++++++++++++++ docs/web/snippets/vscode_extension.mdx | 4 + docs/web/snippets/vscode_search.mdx | 12 + 7 files changed, 576 insertions(+), 1 deletion(-) create mode 100644 docs/web-tests/ts/vscode_extension.ts create mode 100644 docs/web-tests/ts/vscode_search.test.ts create mode 100644 docs/web-tests/ts/vscode_search.ts create mode 100644 docs/web/integrations/ai/vscode.mdx create mode 100644 docs/web/snippets/vscode_extension.mdx create mode 100644 docs/web/snippets/vscode_search.mdx diff --git a/docs/web-tests/ts/vscode_extension.ts b/docs/web-tests/ts/vscode_extension.ts new file mode 100644 index 000000000..abd5c98ad --- /dev/null +++ b/docs/web-tests/ts/vscode_extension.ts @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +// The `src/extension.ts` of the sample extension in the VS Code integration guide. +// It needs the VS Code extension host, so jest doesn't run it: the LanceDB code it +// calls is tested in vscode_search.test.ts, and the extension itself was tested +// with @vscode/test-cli. + +// --8<-- [start:vscode_extension] +import * as vscode from "vscode"; +import { + type Chunk, + chunkMarkdown, + indexChunks, + openDatabase, + searchChunks, +} from "./search"; + +export async function activate(context: vscode.ExtensionContext) { + // One index per workspace. `storageUri` is undefined when no folder is open. + const storage = context.storageUri ?? context.globalStorageUri; + + // Transformers.js downloads the embedding model on first use. Keep it in + // global storage so every workspace shares one copy and it survives + // extension updates. Use `import()`: LanceDB loads the ES module build, and + // `require()` would return a separate copy whose settings LanceDB never sees. + const { env } = await import("@huggingface/transformers"); + env.cacheDir = vscode.Uri.joinPath(context.globalStorageUri, "models").fsPath; + + context.subscriptions.push( + vscode.commands.registerCommand("lancedbSearch.index", async () => { + const files = await vscode.workspace.findFiles( + "**/*.md", + "**/node_modules/**", + ); + const chunks: Chunk[] = []; + for (const file of files) { + const bytes = await vscode.workspace.fs.readFile(file); + // Store the file's URI, not a path relative to its folder: in a + // multi-root workspace `findFiles` searches every folder, and only the + // URI says which one a result came from. + chunks.push( + ...chunkMarkdown(file.toString(), new TextDecoder().decode(bytes)), + ); + } + if (chunks.length === 0) { + vscode.window.showWarningMessage("No Markdown files to index."); + return 0; + } + + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Indexing ${files.length} Markdown files`, + }, + async () => { + await vscode.workspace.fs.createDirectory(storage); + await indexChunks(await openDatabase(storage.fsPath), chunks); + }, + ); + vscode.window.showInformationMessage( + `Indexed ${chunks.length} paragraphs from ${files.length} files.`, + ); + return chunks.length; + }), + + // Called with a query (for example from a test or another extension), the + // command returns the matching rows instead of showing a picker. + vscode.commands.registerCommand( + "lancedbSearch.search", + async (query?: string) => { + const text = + query ?? + (await vscode.window.showInputBox({ + prompt: "Search Markdown by meaning", + })); + if (!text) { + return []; + } + const results = await searchChunks( + await openDatabase(storage.fsPath), + text, + ); + if (query !== undefined) { + return results; + } + + const picked = await vscode.window.showQuickPick( + results.map((row) => { + const uri = vscode.Uri.parse(row.path); + return { + label: `${vscode.workspace.asRelativePath(uri)}:${row.line + 1}`, + description: `distance ${row._distance.toFixed(3)}`, + detail: row.text, + uri, + line: row.line, + }; + }), + { placeHolder: text, matchOnDetail: true }, + ); + if (picked) { + const editor = await vscode.window.showTextDocument(picked.uri); + const start = new vscode.Position(picked.line, 0); + editor.selection = new vscode.Selection(start, start); + editor.revealRange( + new vscode.Range(start, start), + vscode.TextEditorRevealType.InCenter, + ); + } + return results; + }, + ), + ); +} + +export function deactivate() {} +// --8<-- [end:vscode_extension] diff --git a/docs/web-tests/ts/vscode_search.test.ts b/docs/web-tests/ts/vscode_search.test.ts new file mode 100644 index 000000000..21dd4d816 --- /dev/null +++ b/docs/web-tests/ts/vscode_search.test.ts @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { expect, test } from "@jest/globals"; +import { withTempDirectory } from "./util.ts"; +import { + chunkMarkdown, + indexChunks, + openDatabase, + searchChunks, +} from "./vscode_search.ts"; + +// The same files make up the sample workspace used in the docs page. +const workspace: Record = { + "README.md": + "# Acme CLI\n\nAcme CLI syncs your local notes to the Acme cloud.\n\nInstall it with `npm install -g acme-cli`, then run `acme login`.\n", + "docs/auth.md": + "# Authentication\n\nAcme uses personal access tokens. Create one under Settings > Tokens.\n\nIf a token leaks, revoke it on the Tokens page and generate a replacement.\nRevoked tokens stop working immediately.\n", + "docs/sync.md": + "# Syncing\n\nRun `acme sync` to upload changed notes. Only files modified since the last sync are sent.\n\nConflicts are resolved by keeping both copies and adding `.conflict` to the older one.\n", + "docs/config.md": + "# Configuration\n\nSettings live in `~/.acme/config.toml`.\n\nSet `sync.interval` to control how often background sync runs, in minutes.\n", + "docs/troubleshooting.md": + "# Troubleshooting\n\nIf `acme sync` hangs, check that your proxy allows connections to api.acme.dev on port 443.\n\nRun `acme doctor` to print diagnostics you can attach to a bug report.\n", + "CONTRIBUTING.md": + "# Contributing\n\nRun `npm test` before opening a pull request. New commands need a page in docs/.\n", +}; + +test("chunkMarkdown splits paragraphs and records their start line", () => { + expect(chunkMarkdown("docs/auth.md", workspace["docs/auth.md"])).toEqual([ + { path: "docs/auth.md", line: 0, text: "# Authentication" }, + { + path: "docs/auth.md", + line: 2, + text: "Acme uses personal access tokens. Create one under Settings > Tokens.", + }, + { + path: "docs/auth.md", + line: 4, + text: "If a token leaks, revoke it on the Tokens page and generate a replacement.\nRevoked tokens stop working immediately.", + }, + ]); +}); + +test("index workspace Markdown and search it by meaning", async () => { + await withTempDirectory(async (storageDir) => { + const chunks = Object.entries(workspace).flatMap(([filePath, content]) => + chunkMarkdown(filePath, content), + ); + await indexChunks(await openDatabase(storageDir), chunks); + + // Each command in the extension opens its own connection, so search + // through a fresh one to check the table is usable after a reload. + const db = await openDatabase(storageDir); + const leaked = await searchChunks( + db, + "my credentials were exposed, what should I do?", + ); + expect(leaked[0].path).toBe("docs/auth.md"); + expect(leaked[0].line).toBe(4); + + const firewall = await searchChunks( + db, + "uploads are stuck behind the company firewall", + ); + expect(firewall[0].path).toBe("docs/troubleshooting.md"); + }); +}, 100_000); diff --git a/docs/web-tests/ts/vscode_search.ts b/docs/web-tests/ts/vscode_search.ts new file mode 100644 index 000000000..d090084a1 --- /dev/null +++ b/docs/web-tests/ts/vscode_search.ts @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +// --8<-- [start:vscode_imports] +import * as path from "node:path"; +import * as lancedb from "@lancedb/lancedb"; +import "@lancedb/lancedb/embedding/transformers"; +import { Int32, Utf8 } from "apache-arrow"; +// --8<-- [end:vscode_imports] + +// --8<-- [start:vscode_chunk] +export type Chunk = { path: string; line: number; text: string }; + +// Split a Markdown file into paragraphs, keeping the line each one starts on +// so a search result can jump straight to it. +export function chunkMarkdown(filePath: string, content: string): Chunk[] { + const lines = content.split(/\r?\n/); + const chunks: Chunk[] = []; + let start = 0; + for (let i = 0; i <= lines.length; i++) { + if (i === lines.length || lines[i].trim() === "") { + const text = lines.slice(start, i).join("\n").trim(); + if (text) { + chunks.push({ path: filePath, line: start, text }); + } + start = i + 1; + } + } + return chunks; +} +// --8<-- [end:vscode_chunk] + +// --8<-- [start:vscode_connect] +// Pass an absolute directory, such as `context.storageUri.fsPath`. A relative +// path resolves against the extension host's working directory, which is not +// your workspace and may be read-only (on macOS it is usually `/`). +export async function openDatabase(storageDir: string) { + return lancedb.connect(path.join(storageDir, "lancedb")); +} +// --8<-- [end:vscode_connect] + +// --8<-- [start:vscode_index] +export async function indexChunks(db: lancedb.Connection, chunks: Chunk[]) { + // Runs all-MiniLM-L6-v2 locally through Transformers.js: no API key needed. + const embedder = (await lancedb.embedding + .getRegistry() + .get("huggingface") + ?.create()) as lancedb.embedding.EmbeddingFunction; + + const schema = lancedb.embedding.LanceSchema({ + path: new Utf8(), + line: new Int32(), + text: embedder.sourceField(new Utf8()), + vector: embedder.vectorField(), + }); + + // LanceDB fills in the `vector` column from `text` as the rows are written. + return db.createTable("chunks", chunks, { schema, mode: "overwrite" }); +} +// --8<-- [end:vscode_index] + +// --8<-- [start:vscode_search] +export async function searchChunks( + db: lancedb.Connection, + query: string, + limit = 5, +) { + // The table stores its embedding function in its metadata, so a text query + // is embedded with the same model that embedded the rows. + const table = await db.openTable("chunks"); + return table + .search(query) + .select(["path", "line", "text", "_distance"]) + .limit(limit) + .toArray(); +} +// --8<-- [end:vscode_search] diff --git a/docs/web/docs.json b/docs/web/docs.json index 54203f1a0..66ce3acd3 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -490,7 +490,8 @@ "integrations/ai/genkit", "integrations/ai/kiln", "integrations/ai/prompttools", - "integrations/ai/synthetic-data-kit" + "integrations/ai/synthetic-data-kit", + "integrations/ai/vscode" ] } ] diff --git a/docs/web/integrations/ai/vscode.mdx b/docs/web/integrations/ai/vscode.mdx new file mode 100644 index 000000000..4c9319dd5 --- /dev/null +++ b/docs/web/integrations/ai/vscode.mdx @@ -0,0 +1,297 @@ +--- +title: "VS Code extensions" +sidebarTitle: "VS Code" +description: "Embed LanceDB in a VS Code extension to search a workspace by meaning, with no server, and bundle and package its native binaries correctly." +keywords: ["vscode", "visual studio code", "extension", "electron", "esbuild", "vsix", "semantic search"] +--- + +import { + TsVscodeChunk, + TsVscodeConnect, + TsVscodeImports, + TsVscodeIndex, + TsVscodeSearch, +} from '/snippets/vscode_search.mdx'; +import { TsVscodeExtension } from '/snippets/vscode_extension.mdx'; + +A VS Code extension runs in the *extension host*, a Node.js process, so LanceDB's TypeScript SDK +(`@lancedb/lancedb`) runs inside it like any other npm package. There's no database server to +start: the extension opens a table on local disk and queries it in-process. That makes LanceDB +a good fit for features such as semantic search over a workspace, retrieval for an AI assistant, +or a cache of embeddings that survives restarts. + +The extension host differs from a plain Node.js script in three ways that trip people up: + +- **Where you can write.** Relative paths resolve against the extension host's working + directory, not the workspace, and that directory may be read-only. +- **Bundling.** The default extension template bundles everything with esbuild, which can't + bundle LanceDB's native `.node` binary. +- **Packaging.** LanceDB installs a native binary for the current platform only, so a VSIX + built on one OS doesn't run on another. + +This guide builds a small extension that handles all three. It indexes the Markdown files in a +workspace and searches them by meaning, using a local embedding model, so no API key is needed. + + +**What you'll build** + +- **LanceDB: Index Markdown in Workspace** splits every `*.md` file into paragraphs and stores + them in a LanceDB table, with embeddings from `Xenova/all-MiniLM-L6-v2` run locally through + Transformers.js. +- **LanceDB: Search Markdown** embeds your query, shows the five closest paragraphs, and opens + the one you pick. + + +## Create the extension {#create-the-extension} + + + +Use the official generator. Choose **New Extension (TypeScript)** and **esbuild** as the bundler. + +```bash +npx --package yo --package generator-code -- yo code +``` + + + +```bash +npm install @lancedb/lancedb apache-arrow@18.1.0 +``` + +Your code imports Arrow types directly, so add `apache-arrow` as a dependency, pinned inside +LanceDB's peer dependency range (`>=15.0.0 <=18.1.0`). If the project already depends on a +newer `apache-arrow`, installing LanceDB fails with `ERESOLVE`. + +LanceDB also needs `@types/node` 22 or later. The generator's template already uses a recent +version; an old one causes `Cannot find module 'node:stream'` errors. + +You don't need to install `@huggingface/transformers` yourself. LanceDB pins it as an optional +dependency, and installing a different version gives your code a copy that LanceDB doesn't use. + + + +The type declarations of `apache-arrow` and the ONNX runtime used by Transformers.js refer to +browser types such as `ReadableStreamReadResult` and `HTMLCanvasElement`. The template's +`tsconfig.json` doesn't include the DOM library, so `tsc` reports errors inside `node_modules`. +Turn on `skipLibCheck`: + +```json tsconfig.json icon="brackets-curly" +{ + "compilerOptions": { + "skipLibCheck": true + } +} +``` + + + +## Store the database in extension storage {#store-the-database-in-extension-storage} + +Give LanceDB an absolute path inside the storage VS Code reserves for your extension: + +- `context.storageUri`: a folder for the current workspace. It's `undefined` when no folder is + open. Use it for anything derived from the workspace, such as this index. +- `context.globalStorageUri`: a folder shared by all workspaces. Use it for things like + downloaded models. + +Neither folder is guaranteed to exist, so create it before connecting. Both live outside the +user's project, so the index never shows up in their files or in version control. + +Don't pass a relative path such as `lancedb.connect("data")`. It resolves against the extension +host's working directory, which isn't the workspace and may be read-only: this causes the +`Read-only file system (os error 30)` error on macOS. + +Put the LanceDB code in its own module, `src/search.ts`: + + + {TsVscodeImports} + + + + {TsVscodeConnect} + + +## Index and search {#index-and-search} + +Split each file into paragraphs, and keep the line each one starts on so a result can open the +file at the right place: + + + {TsVscodeChunk} + + +Create the table with LanceDB's built-in `huggingface` [embedding function](/embedding/quickstart). +Because the `text` column is declared as the function's source field, LanceDB computes the +`vector` column for you as the rows are written: + + + {TsVscodeIndex} + + +The table remembers its embedding function, so you can search it with plain text after VS Code +restarts: + + + {TsVscodeSearch} + + +`mode: "overwrite"` rebuilds the index each time, which is fine for a few thousand paragraphs. +For larger workspaces, update only the files that changed with +[`mergeInsert`](/ingestion/merge-insert). + +## Wire up the commands {#wire-up-the-commands} + +Declare the two commands in `package.json`: + +```json package.json icon="brackets-curly" +"contributes": { + "commands": [ + { + "command": "lancedbSearch.index", + "title": "Index Markdown in Workspace", + "category": "LanceDB" + }, + { + "command": "lancedbSearch.search", + "title": "Search Markdown", + "category": "LanceDB" + } + ] +} +``` + +Then register them in `src/extension.ts`: + + + {TsVscodeExtension} + + +A few details in this file are specific to running inside VS Code: + +- The index goes in `storageUri`, so each workspace gets its own table. +- The embedding model (about 90 MB) downloads on first use. By default Transformers.js caches it + inside `node_modules` in the installed extension, which is replaced on every update. Setting + `env.cacheDir` keeps it in global storage. Load the module with `import()`, not `require()`: + LanceDB loads the ES module build of `@huggingface/transformers`, and `require()` returns a + separate copy whose settings LanceDB never sees. +- Each paragraph is stored with its file's URI, not a path relative to a workspace folder. In a + multi-root workspace, `findFiles` searches every folder and two folders can hold the same + relative path, so only the URI opens the right file. `asRelativePath` turns it back into a + short label, which names the folder when there's more than one. +- When another extension or a test passes a query to `lancedbSearch.search`, it returns the + rows instead of opening a picker. That's how the results below were produced, with each URI + shown through `asRelativePath`. + +## Sample results {#sample-results} + +Here are the results of running the extension in VS Code against a small workspace of six +Markdown files that document a fictional CLI. The columns are the vector distance (lower is +closer), the file and line, and the paragraph. + +```text +query: my credentials were exposed, what should I do? + 33.100 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. + 40.091 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. + 42.334 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. + 43.105 docs/auth.md:3 Acme uses personal access tokens. Create one under Settings > Tokens. + 45.664 README.md:5 Install it with `npm install -g acme-cli`, then run `acme login`. + +query: uploads are stuck behind the company firewall + 38.420 docs/troubleshooting.md:3 If `acme sync` hangs, check that your proxy allows connections to api.acme.dev on port 443. + 39.212 docs/sync.md:3 Run `acme sync` to upload changed notes. Only files modified since the last sync are sent. + 40.859 docs/auth.md:5 If a token leaks, revoke it on the Tokens page and generate a replacement. Revoked tokens stop working immediately. + 42.537 docs/troubleshooting.md:5 Run `acme doctor` to print diagnostics you can attach to a bug report. + 45.853 CONTRIBUTING.md:3 Run `npm test` before opening a pull request. New commands need a page in docs/. +``` + +Neither top result shares a keyword with its query: "credentials were exposed" matches "a +token leaks", and "stuck behind the company firewall" matches "hangs … proxy". Picking a result +in the search box opens the file at that paragraph. + +## Bundle with esbuild {#bundle-with-esbuild} + +The template bundles your code and its dependencies into `dist/extension.js`. esbuild can't +bundle native binaries, so building with LanceDB fails with +`No loader is configured for ".node" files`. Mark the packages that load native code as +external so they're loaded from `node_modules` at runtime: + +```js esbuild.js icon="square-js" +external: [ + "vscode", + "@lancedb/lancedb", + "@huggingface/transformers", + // LanceDB loads apache-arrow from node_modules anyway; bundling it ships a second copy. + "apache-arrow", +], +``` + +External packages must be in the VSIX, but the template's `.vscodeignore` excludes +`node_modules/**`. Delete that line. `vsce` then includes your production dependencies and +leaves out the dev dependencies. If you skip this step, the packaged extension fails to +activate with `Cannot find module '@lancedb/lancedb'`, and its commands report +`command 'lancedbSearch.index' not found`. + +## Package a VSIX for each platform {#package-a-vsix-for-each-platform} + +npm installs LanceDB's native binary only for the machine it runs on, such as +`@lancedb/lancedb-win32-x64-msvc` on 64-bit Windows. Build one VSIX per platform, each on a +matching machine or CI runner, and publish them all. The Marketplace serves each user the right one. + +```bash +npx @vscode/vsce package --target win32-x64 +``` + +| `vsce` target | LanceDB native package | +|:--|:--| +| `win32-x64` | `@lancedb/lancedb-win32-x64-msvc` | +| `win32-arm64` | `@lancedb/lancedb-win32-arm64-msvc` | +| `linux-x64` | `@lancedb/lancedb-linux-x64-gnu` | +| `linux-arm64` | `@lancedb/lancedb-linux-arm64-gnu` | +| `alpine-x64` | `@lancedb/lancedb-linux-x64-musl` | +| `alpine-arm64` | `@lancedb/lancedb-linux-arm64-musl` | +| `darwin-arm64` | `@lancedb/lancedb-darwin-arm64` | + +LanceDB doesn't publish a binary for Intel Macs (`darwin-x64`). + +The table covers LanceDB's own binaries. This sample's local model also needs +`onnxruntime-node`, which Transformers.js loads when the extension activates. Its Linux binaries +link against glibc and it publishes no musl build, so the sample as written doesn't run on +Alpine, whatever `--target` you pass. To ship the `alpine-*` targets, embed with a hosted API or +use [full-text search](/search/full-text-search) instead, or build ONNX Runtime for musl yourself. + + +Native binaries make the VSIX large: the `win32-x64` build of this extension is about 200 MB. +`onnxruntime-node`, which Transformers.js uses, ships binaries for every platform. Excluding +the ones a target doesn't need brings the `win32-x64` build to about 150 MB. Keep one ignore +file per target and pass it with `--ignoreFile`: + +```text .vscodeignore.win32-x64 +node_modules/onnxruntime-node/bin/napi-v3/darwin/** +node_modules/onnxruntime-node/bin/napi-v3/linux/** +node_modules/onnxruntime-node/bin/napi-v3/win32/arm64/** +``` + +If you don't need a local model, embed text with a hosted API instead, or use +[full-text search](/search/full-text-search), which needs no model at all. + + +## Keep the extension host responsive {#keep-the-extension-host-responsive} + +All extensions share one extension host, and loading the model and computing embeddings in it +can stall the others. While the sample indexes, VS Code may briefly report that the extension +host is unresponsive. That's fine for a handful of files. For a large workspace, move indexing into a +[worker thread](https://nodejs.org/api/worker_threads.html) or a child process, and index in +batches as files change instead of all at once. + +## Troubleshooting {#troubleshooting} + +| Error | Cause | Fix | +|:--|:--|:--| +| `Read-only file system (os error 30)` | A relative database path resolved against the extension host's working directory | Connect to an absolute path under `context.storageUri` or `context.globalStorageUri` | +| `No loader is configured for ".node" files` | esbuild tried to bundle a native binary | Mark `@lancedb/lancedb` and `@huggingface/transformers` as `external` | +| `Cannot find module '@lancedb/lancedb'`, or `command '…' not found` | The VSIX doesn't contain `node_modules` | Remove `node_modules/**` from `.vscodeignore` | +| A native module isn't found on another OS | The VSIX was built on a different platform | Package one VSIX per `--target` on a matching machine | +| `Cannot find module 'node:stream' or its corresponding type declarations` | `@types/node` is too old | Use `@types/node` 22 or later | +| `Cannot find name 'HTMLCanvasElement'` and similar errors in `node_modules` | Dependency typings refer to DOM types | Set `"skipLibCheck": true` | +| `ERESOLVE` with `peer apache-arrow@">=15.0.0 <=18.1.0"` | The project depends on a newer `apache-arrow` | Install `apache-arrow@18.1.0` | +| The model downloads again after an update | Transformers.js caches inside the extension's `node_modules` | Set `env.cacheDir` through `import("@huggingface/transformers")` | diff --git a/docs/web/snippets/vscode_extension.mdx b/docs/web/snippets/vscode_extension.mdx new file mode 100644 index 000000000..df5618c38 --- /dev/null +++ b/docs/web/snippets/vscode_extension.mdx @@ -0,0 +1,4 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const TsVscodeExtension = "import * as vscode from \"vscode\";\nimport {\n type Chunk,\n chunkMarkdown,\n indexChunks,\n openDatabase,\n searchChunks,\n} from \"./search\";\n\nexport async function activate(context: vscode.ExtensionContext) {\n // One index per workspace. `storageUri` is undefined when no folder is open.\n const storage = context.storageUri ?? context.globalStorageUri;\n\n // Transformers.js downloads the embedding model on first use. Keep it in\n // global storage so every workspace shares one copy and it survives\n // extension updates. Use `import()`: LanceDB loads the ES module build, and\n // `require()` would return a separate copy whose settings LanceDB never sees.\n const { env } = await import(\"@huggingface/transformers\");\n env.cacheDir = vscode.Uri.joinPath(context.globalStorageUri, \"models\").fsPath;\n\n context.subscriptions.push(\n vscode.commands.registerCommand(\"lancedbSearch.index\", async () => {\n const files = await vscode.workspace.findFiles(\n \"**/*.md\",\n \"**/node_modules/**\",\n );\n const chunks: Chunk[] = [];\n for (const file of files) {\n const bytes = await vscode.workspace.fs.readFile(file);\n // Store the file's URI, not a path relative to its folder: in a\n // multi-root workspace `findFiles` searches every folder, and only the\n // URI says which one a result came from.\n chunks.push(\n ...chunkMarkdown(file.toString(), new TextDecoder().decode(bytes)),\n );\n }\n if (chunks.length === 0) {\n vscode.window.showWarningMessage(\"No Markdown files to index.\");\n return 0;\n }\n\n await vscode.window.withProgress(\n {\n location: vscode.ProgressLocation.Notification,\n title: `Indexing ${files.length} Markdown files`,\n },\n async () => {\n await vscode.workspace.fs.createDirectory(storage);\n await indexChunks(await openDatabase(storage.fsPath), chunks);\n },\n );\n vscode.window.showInformationMessage(\n `Indexed ${chunks.length} paragraphs from ${files.length} files.`,\n );\n return chunks.length;\n }),\n\n // Called with a query (for example from a test or another extension), the\n // command returns the matching rows instead of showing a picker.\n vscode.commands.registerCommand(\n \"lancedbSearch.search\",\n async (query?: string) => {\n const text =\n query ??\n (await vscode.window.showInputBox({\n prompt: \"Search Markdown by meaning\",\n }));\n if (!text) {\n return [];\n }\n const results = await searchChunks(\n await openDatabase(storage.fsPath),\n text,\n );\n if (query !== undefined) {\n return results;\n }\n\n const picked = await vscode.window.showQuickPick(\n results.map((row) => {\n const uri = vscode.Uri.parse(row.path);\n return {\n label: `${vscode.workspace.asRelativePath(uri)}:${row.line + 1}`,\n description: `distance ${row._distance.toFixed(3)}`,\n detail: row.text,\n uri,\n line: row.line,\n };\n }),\n { placeHolder: text, matchOnDetail: true },\n );\n if (picked) {\n const editor = await vscode.window.showTextDocument(picked.uri);\n const start = new vscode.Position(picked.line, 0);\n editor.selection = new vscode.Selection(start, start);\n editor.revealRange(\n new vscode.Range(start, start),\n vscode.TextEditorRevealType.InCenter,\n );\n }\n return results;\n },\n ),\n );\n}\n\nexport function deactivate() {}\n"; + diff --git a/docs/web/snippets/vscode_search.mdx b/docs/web/snippets/vscode_search.mdx new file mode 100644 index 000000000..4d2423e7f --- /dev/null +++ b/docs/web/snippets/vscode_search.mdx @@ -0,0 +1,12 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const TsVscodeChunk = "export type Chunk = { path: string; line: number; text: string };\n\n// Split a Markdown file into paragraphs, keeping the line each one starts on\n// so a search result can jump straight to it.\nexport function chunkMarkdown(filePath: string, content: string): Chunk[] {\n const lines = content.split(/\\r?\\n/);\n const chunks: Chunk[] = [];\n let start = 0;\n for (let i = 0; i <= lines.length; i++) {\n if (i === lines.length || lines[i].trim() === \"\") {\n const text = lines.slice(start, i).join(\"\\n\").trim();\n if (text) {\n chunks.push({ path: filePath, line: start, text });\n }\n start = i + 1;\n }\n }\n return chunks;\n}\n"; + +export const TsVscodeConnect = "// Pass an absolute directory, such as `context.storageUri.fsPath`. A relative\n// path resolves against the extension host's working directory, which is not\n// your workspace and may be read-only (on macOS it is usually `/`).\nexport async function openDatabase(storageDir: string) {\n return lancedb.connect(path.join(storageDir, \"lancedb\"));\n}\n"; + +export const TsVscodeImports = "import * as path from \"node:path\";\nimport * as lancedb from \"@lancedb/lancedb\";\nimport \"@lancedb/lancedb/embedding/transformers\";\nimport { Int32, Utf8 } from \"apache-arrow\";\n"; + +export const TsVscodeIndex = "export async function indexChunks(db: lancedb.Connection, chunks: Chunk[]) {\n // Runs all-MiniLM-L6-v2 locally through Transformers.js: no API key needed.\n const embedder = (await lancedb.embedding\n .getRegistry()\n .get(\"huggingface\")\n ?.create()) as lancedb.embedding.EmbeddingFunction;\n\n const schema = lancedb.embedding.LanceSchema({\n path: new Utf8(),\n line: new Int32(),\n text: embedder.sourceField(new Utf8()),\n vector: embedder.vectorField(),\n });\n\n // LanceDB fills in the `vector` column from `text` as the rows are written.\n return db.createTable(\"chunks\", chunks, { schema, mode: \"overwrite\" });\n}\n"; + +export const TsVscodeSearch = "export async function searchChunks(\n db: lancedb.Connection,\n query: string,\n limit = 5,\n) {\n // The table stores its embedding function in its metadata, so a text query\n // is embedded with the same model that embedded the rows.\n const table = await db.openTable(\"chunks\");\n return table\n .search(query)\n .select([\"path\", \"line\", \"text\", \"_distance\"])\n .limit(limit)\n .toArray();\n}\n"; + From 5f6f7b591d7d7a3004477c8c689c1b2033316f12 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:27:22 -0700 Subject: [PATCH 151/180] fix(python): bind packaged BlobReader annotations to the worker type (#4726) Packaged UDFs omit globals used only in postponed annotations, so a `BlobReader` input has a correct wire signature but `typing.get_type_hints()` on the loaded function raises `NameError`. Use the resolved input signature to bind reader annotations to an imported `lance_blob.BlobReader` alias. Preserve signature nullability and avoid collisions with existing globals. Regression tests cover functions and callable classes, eager and postponed annotations, aliases, forward references, qualified names, and body globals. Validation: - Confirmed the new regression fails with `NameError: name 'BlobReader' is not defined` against the original packager at `057a39a1c70e15c78461bb7e3db8cef4c067cd3e`. - The packaging, first-class Function slice 1 and 2, and BlobReader suites pass all 159 tests with Python file-import directory caches refreshed before lookups. The standard run passes 156 tests; three temporary-module import failures reproduce unchanged on the original packager because directory timestamps do not advance between file writes in this environment. All 37 new regression cases pass in the standard run. - Python Ruff lint and formatting checks pass. Repository-wide Ruff lint reports 48 existing errors in documentation examples. Fixes #4718 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/functions.py | 57 +++++++++++- .../python/tests/test_function_packaging.py | 92 ++++++++++++++++++- 2 files changed, 143 insertions(+), 6 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 38b45d8b6..2ab658293 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1462,8 +1462,8 @@ class _SourcePackager: self._packaged: set[int] = set() self._names: dict[str, Any] = {} - def package(self, target: Any) -> str: - entry = self._definition(target, entry=True) + def package(self, target: Any, signature: FunctionSignature) -> str: + entry = self._definition(target, entry=True, signature=signature) parts = [_SOURCE_HEADER] if self._imports: parts.extend(["", *(self._imports[name] for name in sorted(self._imports))]) @@ -1472,12 +1472,20 @@ class _SourcePackager: parts.extend(["", entry, ""]) return "\n".join(parts) - def _definition(self, target: Any, *, entry: bool) -> str: + def _definition( + self, target: Any, *, entry: bool, signature: Optional[FunctionSignature] = None + ) -> str: definition = _definition_node(target, entry=entry) if not inspect.isclass(target) and inspect.getclosurevars(target).nonlocals: raise ValueError( "@udf cannot package functions that capture closure values" ) + namespace = _definition_namespace(target) + reader_name = ( + self._blob_annotations(definition, signature, namespace) + if signature is not None + else None + ) source = ast.unparse(definition) references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n") dynamic = _namespace_acquisition(definition, references) @@ -1485,9 +1493,10 @@ class _SourcePackager: raise ValueError( f"@udf cannot package dynamic namespace access: {dynamic!r}" ) - namespace = _definition_namespace(target) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) + if reader_name is not None: + self._bind(reader_name, BlobReader) unresolved = [] for name in sorted(references): if name == target.__name__: @@ -1508,6 +1517,44 @@ class _SourcePackager: ) return source + def _blob_annotations( + self, + definition: Union[ast.FunctionDef, ast.ClassDef], + signature: FunctionSignature, + namespace: Mapping[str, Any], + ) -> Optional[str]: + """Bind reader inputs to the worker type, including postponed aliases.""" + readers = { + parameter.name: parameter + for parameter in signature.inputs + if parameter.blob_access == "reader" + } + if not readers: + return None + call = definition + if isinstance(definition, ast.ClassDef): + call = next( + ( + member + for member in definition.body + if isinstance(member, ast.FunctionDef) and member.name == "__call__" + ), + None, + ) + if call is None: + return None + # Avoid shadowing globals used by the body or other packaged definitions. + name = "_lance_blob_reader" + while name in namespace or name in self._names or name == definition.name: + name += "_" + for argument in (*call.args.args, *call.args.kwonlyargs): + if argument.arg in readers: + annotation = name + if readers[argument.arg].nullable: + annotation += " | None" + argument.annotation = ast.parse(annotation, mode="eval").body + return name + def _claim(self, name: str, meaning: Any) -> None: claimed = self._names.setdefault(name, meaning) if claimed != meaning: @@ -1845,7 +1892,7 @@ class UdfDefinition: code_files, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) - ).package(function) + ).package(function, signature) if code_files: kind = _PYTHON_BUNDLE_ARTIFACT source = json.dumps( diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 6e1e1cf43..fe86de14e 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -11,9 +11,10 @@ import json import subprocess import sys import textwrap +import types import warnings from pathlib import Path -from typing import Annotated, Optional +from typing import Annotated, Optional, get_type_hints import pyarrow as pa import pytest @@ -126,6 +127,95 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.parametrize("class_udf", [False, True]) +@pytest.mark.parametrize("postponed", [False, True]) +@pytest.mark.parametrize( + ("annotation", "nullable"), + [ + ("BlobReader", False), + ("Reader", False), + ('"Reader"', False), + ("Reader | None", True), + ("Optional[Reader]", True), + ('Optional["Reader"]', True), + ("MaybeReader", True), + ("lancedb.BlobReader", False), + ("lancedb.BlobReader | None", True), + ], +) +def test_blob_reader_annotations_resolve_in_the_artifact( + helper_package, monkeypatch, class_udf, postponed, annotation, nullable +): + definition = ( + f"class read_blob:\n" + f" def __call__(self, video: {annotation}) -> int:\n" + f" return 0\n" + if class_udf + else f"def read_blob(video: {annotation}) -> int:\n return 0\n" + ) + module = helper_package( + "fx_blob_annotations", + { + "__init__.py": ( + ("from __future__ import annotations\n" if postponed else "") + + "import lancedb\n" + "from typing import Optional\n" + "from lancedb import BlobReader, BlobReader as Reader\n" + "from lancedb.functions import udf\n" + "MaybeReader = Optional[Reader]\n\n" + f"@udf\n{definition}" + ) + }, + ) + request = module.read_blob.registration_request + parameter = request.signature.inputs[0] + assert parameter.arrow_type == "blob_v2" + assert parameter.blob_access == "reader" + assert parameter.nullable is nullable + + # Workers provide lance_blob rather than importing the client SDK's reader. + worker = types.ModuleType("lance_blob") + worker.BlobReader = type("BlobReader", (), {}) + monkeypatch.setitem(sys.modules, "lance_blob", worker) + namespace = {} + exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace) + packaged = namespace["read_blob"] + if class_udf: + packaged = packaged.__call__ + assert get_type_hints(packaged) == { + "video": Optional[worker.BlobReader] if nullable else worker.BlobReader, + "return": int, + } + + +def test_blob_reader_annotation_does_not_shadow_body_globals( + helper_package, monkeypatch +): + module = helper_package( + "fx_blob_annotation_globals", + { + "__init__.py": """ + from lancedb import BlobReader + from lancedb.functions import udf + + _lance_blob_reader = 7 + + @udf + def read_blob(video: BlobReader) -> int: + return _lance_blob_reader + """ + }, + ) + worker = types.ModuleType("lance_blob") + worker.BlobReader = type("BlobReader", (), {}) + monkeypatch.setitem(sys.modules, "lance_blob", worker) + namespace = {} + exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace) + packaged = namespace["read_blob"] + assert get_type_hints(packaged)["video"] is worker.BlobReader + assert packaged(worker.BlobReader()) == 7 + + @pytest.mark.parametrize( ("init", "message"), [ From ca60b402aa35c6d1357b8da2e01edba8afe55ba7 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:57:48 -0700 Subject: [PATCH 152/180] fix(python): reject invalid punctuation in UDF names (#4724) Function names containing periods or hyphens passed `@udf` validation and failed only when registered with the server. Restrict the name pattern to ASCII letters, digits, and underscores, preserving the existing first-character rule so invalid names fail when the decorator runs. Document the accepted format and add regression coverage for dotted and hyphenated names, including trailing punctuation, alongside valid name overrides. Fixes #4720 Validation: - The four new invalid-name cases failed before the validator change because no `ValueError` was raised. - `cd python && uv run --extra tests pytest python/tests/test_first_class_function_slice2.py -q`: 86 passed. - Ruff 0.9.9: `ruff check python` and `ruff format --check python` passed. - Repository-root `ruff check .` reports 48 pre-existing errors in `docs/web-tests/`. Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/functions.py | 4 +++- .../tests/test_first_class_function_slice2.py | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 2ab658293..c22bf927a 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -674,7 +674,7 @@ class RefreshColumnResult(_RemoteValue): return self.published_version -_FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$") +_FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") _FUNCTION_BLOB_V2_TYPE = "blob_v2" _ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name" @@ -2106,6 +2106,8 @@ def udf( The synchronous callable, or the class whose instances are called. name : str, optional The remote Function name. Defaults to the callable name. + Must start with an ASCII letter or underscore and contain only ASCII + letters, digits, and underscores. input_schema : pyarrow.Schema, optional Explicit input fields in the exact order of the callable parameters. Must be provided together with ``output_schema``. diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 61e511345..392becf8c 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -89,6 +89,27 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): } +@pytest.mark.parametrize( + "name", ["examples.image_info", "image-info", "image_info.", "image_info-"] +) +def test_udf_rejects_function_names_with_periods_or_hyphens(name): + with pytest.raises(ValueError, match="invalid Function name"): + + @udf(name=name) + def image_info(value: int) -> int: + return value + + +@pytest.mark.parametrize("name", ["image_info", "ImageInfo123", "_image_info", "f"]) +def test_udf_accepts_function_names_with_letters_digits_and_underscores(name): + @udf(name=name) + def image_info(value: int) -> int: + return value + + assert image_info.registration_request.name == name + assert image_info(1) == 1 + + def test_secret_bound_udf_matches_its_shared_registration_golden(): assert analyze_caption(" hello ") == "hello" bound = analyze_caption.bind_secrets( From 3035636bed18e204d7c9d6f4364f110667cc5f0a Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:02:41 -0700 Subject: [PATCH 153/180] fix(python): restore blob extensions in table schemas (#4728) Reading a Blob v2 table in a fresh process could return its storage struct if neither `blob()` nor pylance had registered the extension. Both local and remote schema reads were affected, so `field.type` could depend on import order. Restore metadata-only blob fields on every table schema read through the existing BlobType resolver and Arrow's schema deserializer. Preserve nested fields, nullability, custom metadata, and both supported storage layouts. The fallback deserializer now honors the stored shape too. Fresh-process regressions cover local and remote tables, sync/async reads, and operation with and without pylance. The four native cases failed before removing the native-table guard. Existing merge-insert tests now require the restored extension type while continuing to verify updated and inserted blob contents. Validation: - All 12 fresh-process local/remote schema regression cases pass. - `uv run --extra tests pytest python/tests/test_table.py python/tests/test_blob.py python/tests/test_namespace.py python/tests/test_util.py -q -m 'not slow and not s3_test'`: 835 passed, 11 skipped. - Python package Ruff lint and formatting checks pass. - Repository-wide `ruff check .` reports 48 pre-existing diagnostics in unchanged `docs/web-tests` files. Fixes #4719 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/schema.py | 24 ++++- python/python/lancedb/table.py | 5 +- python/python/tests/test_blob.py | 90 +++++++++++++++++-- python/python/tests/test_remote_db.py | 124 ++++++++++++++++++++++++++ 4 files changed, 229 insertions(+), 14 deletions(-) diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py index 8bec17058..342053d6a 100644 --- a/python/python/lancedb/schema.py +++ b/python/python/lancedb/schema.py @@ -32,8 +32,8 @@ _resolved_blob_type = None class _FallbackBlobType(pa.ExtensionType): """lance.blob.v2 extension type used when pylance is not installed.""" - def __init__(self) -> None: - pa.ExtensionType.__init__(self, _BLOB_V2_STORAGE_TYPE, _BLOB_EXTENSION_NAME) + def __init__(self, storage_type: pa.DataType = _BLOB_V2_STORAGE_TYPE) -> None: + pa.ExtensionType.__init__(self, storage_type, _BLOB_EXTENSION_NAME) def __arrow_ext_serialize__(self) -> bytes: return b"" @@ -42,7 +42,7 @@ class _FallbackBlobType(pa.ExtensionType): def __arrow_ext_deserialize__( cls, storage_type: pa.DataType, serialized: bytes ) -> "_FallbackBlobType": - return cls() + return cls(storage_type) def __reduce__(self): return type(self).__arrow_ext_deserialize__, ( @@ -183,6 +183,24 @@ def _resolve_blob_type(): return _resolved_blob_type +def _restore_blob_extensions(schema: pa.Schema) -> pa.Schema: + """Restore blob fields read before their extension type was registered.""" + unrestored = _collect_blob_paths( + schema, + lambda field: ( + not isinstance(field.type, pa.ExtensionType) + and _metadata_marks_blob_v2(field.metadata or {}) + ), + ) + if not unrestored: + return schema + + _resolve_blob_type() + # Arrow's deserializer uses the registered class and preserves nested fields, + # storage layouts, nullability, and unrelated metadata. Only the schema is read. + return pa.ipc.read_schema(schema.serialize()) + + def blob( name: str, nullable: bool = True, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 59c88027d..98a841bd0 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -110,6 +110,7 @@ from .util import ( ) from .index import lang_mapping from .schema import ( + _restore_blob_extensions, blob_v2_column_paths, is_blob_v2_field, row_addressable_blob_v2_paths, @@ -6023,10 +6024,10 @@ class AsyncTable: async def schema(self) -> pa.Schema: """The [Arrow Schema](https://arrow.apache.org/docs/python/api/datatypes.html#) - of this Table + of this Table. Blob v2 fields retain their Arrow extension type. """ - return await self._inner.schema() + return _restore_blob_extensions(await self._inner.schema()) async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]: """ diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index 96bf88c24..b1da5472a 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -231,6 +231,78 @@ def test_blob_type_works_without_pylance(): assert result.returncode == 0, result.stderr +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("with_pylance", [False, True]) +def test_local_schema_restores_blob_extensions(tmp_path, use_async, with_pylance): + db = lancedb.connect(tmp_path) + db.create_table( + "images", + schema=pa.schema( + [ + pa.field("id", pa.int64()), + lancedb.blob("image", nullable=False, inline_size_threshold=8192), + ], + metadata={"schema-key": "schema-value"}, + ), + ) + + # Reopening must restore the type before blob() or pylance registers it in + # the reader process, including when pylance is not installed. + script = textwrap.dedent( + """\ + import asyncio + import importlib.abc + import sys + import pyarrow as pa + + if sys.argv[3] == "False": + class NoLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + sys.meta_path.insert(0, NoLance()) + import lancedb + + assert "lance.blob" not in sys.modules + + async def read_schema(): + db = await lancedb.connect_async(sys.argv[1]) + table = await db.open_table("images") + return await table.schema() + + if sys.argv[2] == "True": + schema = asyncio.run(read_schema()) + else: + schema = lancedb.connect(sys.argv[1]).open_table("images").schema + + image = schema.field("image") + assert isinstance(image.type, pa.ExtensionType), image + assert image.type == lancedb.blob("x").type + assert type(image.type) is lancedb.BlobType + assert not image.nullable + assert image.metadata == { + b"lance-encoding:blob-inline-size-threshold": b"8192" + } + assert schema.field("id") == pa.field("id", pa.int64()) + assert schema.metadata == {b"schema-key": b"schema-value"} + """ + ) + result = subprocess.run( + [ + sys.executable, + "-c", + script, + str(tmp_path), + str(use_async), + str(with_pylance), + ], + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + + def test_blob_resolves_pylance_type_without_eager_import(): script = textwrap.dedent( """\ @@ -1295,12 +1367,13 @@ def test_merge_insert_bytes_after_reopen_without_touching_blob_type(tmp_path): script = textwrap.dedent( f"""\ import lancedb + import pyarrow as pa db = lancedb.connect({str(tmp_path)!r}) table = db.open_table("images") image_type = table.schema.field("image").type - if type(image_type).__name__ != "StructType": - raise SystemExit(f"expected StructType, got {{type(image_type)}}") + if not isinstance(image_type, pa.ExtensionType): + raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}") result = ( table.merge_insert("id") .when_matched_update_all() @@ -1339,12 +1412,13 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path): script = _HIDE_LANCE_BLOB + textwrap.dedent( f"""\ import lancedb + import pyarrow as pa db = lancedb.connect({str(tmp_path)!r}) table = db.open_table("images") image_type = table.schema.field("image").type - if type(image_type).__name__ != "StructType": - raise SystemExit(f"expected StructType, got {{type(image_type)}}") + if not isinstance(image_type, pa.ExtensionType): + raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}") result = ( table.merge_insert("id") .when_matched_update_all() @@ -1374,7 +1448,7 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path): assert result.returncode == 0, result.stderr -def test_merge_insert_blob_array_into_reopened_unregistered_table(tmp_path): +def test_merge_insert_blob_array_into_reopened_table(tmp_path): db = lancedb.connect(tmp_path) schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) table = db.create_table("images", schema=schema) @@ -1388,10 +1462,8 @@ def test_merge_insert_blob_array_into_reopened_unregistered_table(tmp_path): db = lancedb.connect({str(tmp_path)!r}) table = db.open_table("images") image_type = table.schema.field("image").type - if type(image_type).__name__ != "StructType": - raise SystemExit( - f"expected StructType before lance import, got {{type(image_type)}}" - ) + if not isinstance(image_type, pa.ExtensionType): + raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}") import lance diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index fe271b1fd..32fec4b57 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -10,7 +10,9 @@ import json import multiprocessing as mp import pickle import re +import subprocess import sys +import textwrap import threading import time from unittest.mock import MagicMock, patch @@ -3534,6 +3536,128 @@ BLOB_DESCRIBE_RESPONSE = { } +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("with_pylance", [False, True]) +@pytest.mark.parametrize("nested", [False, True]) +def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested): + description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE)) + without_ranges = description["schema"]["fields"].pop() + without_ranges["name"] = "without_ranges" + image = json.loads(json.dumps(without_ranges)) + image["name"] = "image" + image["nullable"] = False + image["metadata"]["lance-encoding:blob-inline-size-threshold"] = "8192" + image["type"]["fields"].extend( + {"name": name, "type": {"type": "uint64"}, "nullable": True} + for name in ("position", "size") + ) + plain = { + "name": "plain", + "type": image["type"], + "nullable": True, + "metadata": {"app-key": "app-value"}, + } + fields = [image, without_ranges, plain] + if nested: + fields = [ + { + "name": "nested", + "type": {"type": "struct", "fields": fields}, + "nullable": False, + }, + { + "name": "images", + "type": {"type": "list", "fields": [image]}, + "nullable": True, + }, + ] + description["schema"]["fields"].extend(fields) + description["schema"]["metadata"] = {"schema-key": "schema-value"} + + def handler(request): + assert request.path == "/v1/table/test/describe/" + send_json(request, description) + + # A fresh interpreter must read the schema before blob() or a pylance import + # registers the extension type and hides the original failure. + script = textwrap.dedent( + """\ + import asyncio + import importlib.abc + import sys + import pyarrow as pa + + if sys.argv[3] == "False": + class NoLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + sys.meta_path.insert(0, NoLance()) + import lancedb + + assert "lance.blob" not in sys.modules + options = dict(api_key="fake", host_override=sys.argv[1]) + + async def read_schema(): + db = await lancedb.connect_async("db://dev", **options) + table = await db.open_table("test") + return await table.schema() + + if sys.argv[2] == "True": + schema = asyncio.run(read_schema()) + else: + db = lancedb.connect("db://dev", **options) + schema = db.open_table("test").schema + + assert schema.metadata == {b"schema-key": b"schema-value"} + assert schema.field("id") == pa.field("id", pa.int64(), nullable=False) + if sys.argv[4] == "True": + assert not schema.field("nested").nullable + fields = schema.field("nested").type + assert schema.field("images").type.value_field.equals( + fields.field("image"), check_metadata=True + ) + else: + fields = schema + + image = fields.field("image") + assert isinstance(image.type, pa.ExtensionType), image + assert image.type == lancedb.blob("x").type + assert type(image.type) is lancedb.BlobType + assert not image.nullable + assert image.metadata == { + b"lance-encoding:blob-inline-size-threshold": b"8192" + } + plain = fields.field("plain") + assert plain.type == image.type.storage_type + assert plain.metadata == {b"app-key": b"app-value"} + without_ranges = fields.field("without_ranges") + assert isinstance(without_ranges.type, pa.ExtensionType), without_ranges + assert type(without_ranges.type) is lancedb.BlobType + assert without_ranges.type.storage_type == pa.struct([ + pa.field("data", pa.large_binary()), pa.field("uri", pa.string()) + ]) + assert without_ranges.nullable + """ + ) + with mock_lancedb_connection(handler) as db: + result = subprocess.run( + [ + sys.executable, + "-c", + script, + db.host_override, + str(use_async), + str(with_pylance), + str(nested), + ], + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + + @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) @pytest.mark.parametrize("mode", ["merge", "overwrite"]) From fc5170cbed8e3cfbc0c098816f6c7470f01690bc Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:04:04 -0700 Subject: [PATCH 154/180] fix(python): expose function source digests (#4729) Function descriptions include `source_digest`, but both the Rust response model and Python `FunctionVersion` discarded it. Clients therefore could not compare a catalog entry with `udf_def.registration_request.artifact.digest`. Preserve the digest through Rust serialization and expose it on Python `FunctionVersion`, with a documented Rust accessor. Missing or null digests decode as `None`, keeping older responses compatible. Regression tests cover serialization, immutability, registration jobs, get, and synchronous/asynchronous list responses while keeping the image digest independent. Validation: - Confirmed that the original Python model silently discarded a server-provided source digest. - Rebuilt the Python extension in the uv-managed environment; both focused Function test files passed (106 tests). - Focused Rust Function model tests passed (10 tests). - Full workspace `cargo check --quiet --features remote --tests --examples` and `cargo clippy --quiet --features remote --tests --examples` passed. - Rust formatting and Ruff checks/formatting for changed Python files passed. - Repository-wide Ruff reports 138 existing violations in unchanged docs/CI files. Fixes #4723 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/functions.py | 7 +++ .../tests/test_first_class_function_slice1.py | 21 +++++++++ .../tests/test_first_class_function_slice2.py | 11 +++++ rust/lancedb/src/function.rs | 45 +++++++++++++++++++ 4 files changed, 84 insertions(+) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index c22bf927a..a3e56247a 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -366,6 +366,12 @@ class FunctionVersion(_RemoteValue): [SecretReference][lancedb.functions.SecretReference] carries a Secret's; they are what [get_function][lancedb.db.DBConnection.get_function] takes. An empty ``namespace_path`` is the root namespace. + + ``source_digest`` identifies the registered source artifact, independently + of the built ``image``. Compare it with + ``udf_def.registration_request.artifact.digest`` to check whether a local + [UdfDefinition][lancedb.functions.UdfDefinition] has the same source. + It is ``None`` when the server does not provide a source digest. """ name: str @@ -374,6 +380,7 @@ class FunctionVersion(_RemoteValue): location: str version: _ObjectVersion image: FunctionImage + source_digest: Optional[str] = None signature: FunctionSignature secret_bindings: tuple[SecretBinding, ...] = () created_at_millis: int diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 06730a5f1..64a610b53 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -146,6 +146,27 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"]) +def test_function_version_preserves_source_digest(source_digest): + value = job_result("remote_function_job.json") + legacy = FunctionVersion.from_json(json.dumps(value)) + assert legacy.source_digest is None + assert "source_digest" not in json.loads(legacy.to_canonical_json()) + + value["source_digest"] = source_digest + version = FunctionVersion.from_json(json.dumps(value)) + assert version.source_digest == source_digest + assert version.image == legacy.image + encoded = version.to_canonical_json() + if source_digest is None: + assert "source_digest" not in json.loads(encoded) + else: + assert json.loads(encoded)["source_digest"] == source_digest + assert FunctionVersion.from_json(encoded) == version + with pytest.raises((TypeError, ValueError)): + version.source_digest = "sha256:changed" + + def test_function_version_binds_named_columns_as_one_immutable_application(): version = FunctionVersion.from_json( json.dumps(job_result("remote_function_job.json")) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 392becf8c..58afa9c7c 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1651,6 +1651,7 @@ def _mock_remote_function_catalog(): ).read_text() )["image"], "signature": body["signature"], + "source_digest": body["artifact"]["digest"], "secret_bindings": body.get("secret_bindings", []), "created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z } @@ -1760,6 +1761,9 @@ def test_remote_registration_job_and_exact_version_reopen_round_trip(): assert created == reopened assert reopened.name == "normalize_score" assert reopened.version == FUNCTION_VERSION + assert ( + reopened.source_digest == normalize_score.registration_request.artifact.digest + ) create_request = state["requests"][0][1] expected_request = json.loads( normalize_score.registration_request.to_canonical_json() @@ -1866,6 +1870,7 @@ def test_blocking_remote_registration_returns_function_version(): assert created.name == "normalize_score" assert created.version == FUNCTION_VERSION + assert created.source_digest == normalize_score.registration_request.artifact.digest assert [path for path, _ in state["requests"]] == [ "/v1/function/normalize_score/create", "/v1/jobs/describe", @@ -1885,6 +1890,9 @@ def test_remote_list_functions_paginates_and_returns_typed_versions(): functions = list(db.list_functions()) assert functions == [created] + assert functions[0].source_digest == ( + normalize_score.registration_request.artifact.digest + ) assert state["requests"] == [ ("/v1/namespace/$/function/list", {"include_definition": "true"}), ( @@ -1909,6 +1917,9 @@ async def test_async_remote_list_functions_returns_typed_versions(): functions = [item async for item in db.list_functions()] assert functions == [created] + assert functions[0].source_digest == ( + normalize_score.registration_request.artifact.digest + ) assert [path for path, _ in state["requests"]] == [ "/v1/namespace/$/function/list", "/v1/namespace/$/function/list", diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index db3dc1c3b..db93f0071 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -459,6 +459,8 @@ pub struct FunctionVersion { #[serde(deserialize_with = "deserialize_object_version")] version: String, image: FunctionImage, + #[serde(default, skip_serializing_if = "Option::is_none")] + source_digest: Option, signature: FunctionSignature, #[serde(default, skip_serializing_if = "Vec::is_empty")] secret_bindings: Vec, @@ -503,6 +505,23 @@ impl FunctionVersion { pub fn image(&self) -> &FunctionImage { &self.image } + + /// Digest of the registered source artifact, when provided by the server. + /// + /// Compare this with [`FunctionArtifactRequest::digest`] to identify matching + /// source, independently of the built image's manifest digest. + /// + /// ``` + /// use lancedb::function::{FunctionArtifactRequest, FunctionVersion}; + /// + /// fn has_same_source(version: &FunctionVersion, artifact: &FunctionArtifactRequest) -> bool { + /// version.source_digest() == Some(artifact.digest.as_str()) + /// } + /// ``` + pub fn source_digest(&self) -> Option<&str> { + self.source_digest.as_deref() + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } @@ -965,6 +984,32 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn function_version_preserves_source_digest() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert_eq!(legacy.source_digest(), None); + assert_eq!(legacy.to_canonical_json().unwrap(), VERSION.trim_end()); + + for digest in [Value::Null, serde_json::json!("sha256:source-artifact")] { + document["source_digest"] = digest.clone(); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.source_digest(), digest.as_str()); + assert_eq!(version.image(), legacy.image()); + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + if digest.is_null() { + assert!(encoded_value.get("source_digest").is_none()); + } else { + assert_eq!(encoded_value["source_digest"], digest); + } + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + } + } + #[test] fn blob_reader_access_survives_signature_round_trip() { let parameter: FunctionParameter = serde_json::from_value(serde_json::json!({ From 741cb9ad4e7b15aaa611a6c64415bd67c9200e9d Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:08:43 -0700 Subject: [PATCH 155/180] fix(python): implement remote namespace and table existence checks (#4725) Remote Python connections inherited the unsupported-operation stubs for `namespace_exists` and `table_exists`, so both raised `NotImplementedError` even when namespace and table operations worked. Add the missing remote overrides, async methods, and PyO3 bindings using the existing namespace describe and table open paths. Only an explicit not-found result returns `False`; permission, transport, and server errors propagate. This preserves authentication, dynamic headers, retries, and nested namespace handling, and rechecks cached tables before reporting that they exist. The async namespace helper also recognizes native `NamespaceNotFound` errors so missing local namespaces return `False`. The table and namespace guides document Python remote support and distinguish it from the unsupported `exists` routes used by direct REST namespace clients. Validation: - All 40 focused regression cases pass, covering successful and missing lookups, local and remote namespaces, dynamic headers, permission/server errors, invalid table identifiers, and cached tables that disappear. - The original inherited stubs reproduce the reported `NotImplementedError`; the local namespace regression reproduced the native missing-namespace `RuntimeError` before its fix. - Full remote connection suite: 255 passed. Local namespace tests: 14 passed. - `cargo clippy --quiet -p lancedb-python --features remote --lib`, `cargo fmt --all`, Python Ruff lint, and Python formatting checks pass. - Root `ruff check .` reports 48 existing errors in documentation examples under `docs/web-tests`; the Python subtree passes and those unrelated files are unchanged. Fixes #4722 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- docs/web/management/namespace.mdx | 7 +- docs/web/management/table.mdx | 23 ++++--- python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 43 ++++++++++++ python/python/lancedb/remote/db.py | 30 ++++++++ python/python/tests/test_db.py | 18 +++++ python/python/tests/test_remote_db.py | 98 ++++++++++++++++++++++++++- python/src/connection.rs | 47 +++++++++++++ 8 files changed, 257 insertions(+), 11 deletions(-) diff --git a/docs/web/management/namespace.mdx b/docs/web/management/namespace.mdx index 0d80831c9..e5222ab84 100644 --- a/docs/web/management/namespace.mdx +++ b/docs/web/management/namespace.mdx @@ -243,8 +243,11 @@ let db = lancedb::connect_namespace("rest", properties) ``` [LanceDB Enterprise](/enterprise) operates a REST namespace server on top of the Lance format, so any REST client that can speak the REST namespace API -contract can be used to interact with it. It does not serve the contract's `exists` routes, so checks such as `namespace_exists` -fail against it. For authentication examples in LanceDB Enterprise, visit +contract can be used to interact with it. It does not serve the contract's `exists` routes, +so existence checks made through a direct REST namespace client fail against it. +Python remote connections created with `lancedb.connect("db://...")` or +`lancedb.connect_async("db://...")` support `namespace_exists` and `table_exists` +through the existing describe routes instead. For authentication examples in LanceDB Enterprise, visit the [Namespaces in SDKs](#namespaces-in-lancedb-enterprise) page. ## Best practices {#best-practices} diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index bf256ac97..a28f63d40 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -214,14 +214,21 @@ await db.tableNames(); Each accepts `namespace_path` to act inside a [namespace](/management/namespace) rather than at the database root. -To find out whether a table exists, open it and handle the error, or look for -its name in a listing. A missing table raises `ValueError` on a local directory -or a deployment, and `lance_namespace.TableNotFoundError` on a connection from -`connect_namespace`. A listing returns one page of names at a time, so check -every page. Python's `table_exists` is no substitute: a local directory or a -deployment raises `NotImplementedError` for it, and on a connection from -`connect_namespace("dir", ...)` or `connect_namespace("rest", ...)` it fails with -an `AttributeError`. TypeScript has no `tableExists`. +For Python remote connections created with `lancedb.connect("db://...")`, use +`db.table_exists(["documents"])` to check whether a table exists. For an async +remote connection, use `await db.table_exists(["documents"])`. Include namespace +segments before the table name, for example `["analytics", "documents"]`. These +checks return `False` when the table is missing and propagate other errors, +including permission errors. + +Local synchronous directory connections still raise `NotImplementedError` for +`table_exists`. On a connection from `connect_namespace("dir", ...)` or +`connect_namespace("rest", ...)`, it fails with an `AttributeError`. For these +connections, open the table and handle the error, or look for its name in a +listing. A missing table raises `ValueError` on a local directory and +`lance_namespace.TableNotFoundError` on a connection from `connect_namespace`. +A listing returns one page of names at a time, so check every page. TypeScript +has no `tableExists`. ## Rename and clone tables {#rename-clone} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 66fdd3a7c..2b8d1655a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -137,6 +137,8 @@ class Connection(object): self, namespace_path: List[str], ) -> DescribeNamespaceResponse: ... + async def namespace_exists(self, namespace_id: List[str]) -> bool: ... + async def table_exists(self, table_id: List[str]) -> bool: ... def list_tables( self, namespace_path: Optional[List[str]] = None, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 09e032607..32f7dc43c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -2436,6 +2436,49 @@ class AsyncConnection(object): result = await self._inner.describe_namespace(namespace_path) return DescribeNamespaceResponse(**result) + async def namespace_exists(self, namespace_id: List[str]) -> bool: + """Check if a namespace exists. + + Parameters + ---------- + namespace_id: List[str] + The namespace identifier to check. An empty list represents root. + + Returns + ------- + bool + True if the namespace exists, False if it is not found. + Other errors, including permission errors, are propagated. + + Examples + -------- + >>> async def check_namespace(conn): + ... return await conn.namespace_exists(["analytics"]) + """ + return await self._inner.namespace_exists(namespace_id) + + async def table_exists(self, table_id: List[str]) -> bool: + """Check if a table exists. + + Parameters + ---------- + table_id: List[str] + The full identifier, including namespace segments and table name. + Must contain at least the table name. + + Returns + ------- + bool + True if the table exists, False if it is not found. + Other errors, including permission errors, are propagated. + + Examples + -------- + >>> async def check_table(conn): + ... return await conn.table_exists(["analytics", "events"]) + """ + return await self._inner.table_exists(table_id) + def list_tables( self, namespace_path: Optional[List[str]] = None, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index e2defa216..d97e6526b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -390,6 +390,36 @@ class RemoteDBConnection(DBConnection): """ return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path)) + @override + def namespace_exists(self, namespace_id: List[str]) -> bool: + """Check if a namespace exists. + + ``namespace_id`` contains the namespace segments; an empty list represents + root. Returns False only if the namespace is not found. Other errors, + including permission errors, are propagated. + + Examples + -------- + >>> def check_namespace(conn): + ... return conn.namespace_exists(["analytics"]) + """ + return LOOP.run(self._conn.namespace_exists(namespace_id)) + + @override + def table_exists(self, table_id: List[str]) -> bool: + """Check if a table exists. + + ``table_id`` contains the namespace segments followed by the table name. + Returns False only if the table is not found. Other errors, including + permission errors, are propagated. + + Examples + -------- + >>> def check_table(conn): + ... return conn.table_exists(["analytics", "events"]) + """ + return LOOP.run(self._conn.table_exists(table_id)) + @override def list_tables( self, diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index af63987aa..64bf928c0 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -1149,6 +1149,24 @@ def test_local_namespace_operations(tmp_path): assert db.list_namespaces().namespaces == [] +@pytest.mark.asyncio +async def test_local_async_namespace_exists(tmp_path): + db = await lancedb.connect_async(tmp_path) + await db.create_namespace(["existing"]) + await db.create_namespace(["existing", "nested"]) + + assert await db.namespace_exists([]) is True + assert await db.namespace_exists(["existing"]) is True + assert await db.namespace_exists(["existing", "nested"]) is True + assert await db.namespace_exists(["missing"]) is False + assert await db.namespace_exists(["existing", "missing"]) is False + assert await db.namespace_exists(["missing", "nested"]) is False + + await db.drop_namespace(["existing", "nested"]) + assert await db.namespace_exists(["existing", "nested"]) is False + assert await db.namespace_exists(["existing"]) is True + + def test_local_sync_namespace_uses_rust_without_python_client(tmp_path, monkeypatch): """Sync local namespace operations should avoid the Python namespace client.""" db = lancedb.connect(tmp_path) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 32fec4b57..0b32376e8 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -54,7 +54,7 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name): @contextlib.contextmanager -def mock_lancedb_connection(handler): +def mock_lancedb_connection(handler, **client_config): with http.server.HTTPServer( ("localhost", 0), make_mock_http_handler(handler) ) as server: @@ -71,6 +71,7 @@ def mock_lancedb_connection(handler): "timeout_config": { "connect_timeout": 1, }, + **client_config, }, ) @@ -110,6 +111,101 @@ async def mock_lancedb_connection_async(handler, **client_config): handle.join() +@pytest.fixture +def existence_handler(method, identifier, status): + def handler(request): + resource = "namespace" if method == "namespace_exists" else "table" + resource_id = "$".join(identifier) or "$" + suffix = "/" if resource == "table" else "" + assert request.command == "POST" + assert request.path == f"/v1/{resource}/{resource_id}/describe{suffix}" + assert request.headers["x-api-key"] == "fake" + assert request.headers["X-Exists-Test"] == "present" + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}" if status == 200 else b"lookup failed") + + return handler + + +@pytest.mark.parametrize( + "method,identifier", + [ + ("namespace_exists", []), + ("namespace_exists", ["ns"]), + ("namespace_exists", ["parent", "ns"]), + ("table_exists", ["table"]), + ("table_exists", ["parent", "ns", "table"]), + ], +) +@pytest.mark.parametrize("status", [200, 404, 403, 507]) +def test_remote_exists(method, identifier, status, existence_handler): + from lancedb.remote.header import StaticHeaderProvider + + provider = StaticHeaderProvider({"X-Exists-Test": "present"}) + with mock_lancedb_connection(existence_handler, header_provider=provider) as db: + if status in (200, 404): + assert getattr(db, method)(identifier) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + getattr(db, method)(identifier) + assert exc_info.value.status_code == status + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "method,identifier", + [ + ("namespace_exists", []), + ("namespace_exists", ["parent", "ns"]), + ("table_exists", ["table"]), + ("table_exists", ["parent", "ns", "table"]), + ], +) +@pytest.mark.parametrize("status", [200, 404, 403, 507]) +async def test_async_remote_exists(method, identifier, status, existence_handler): + from lancedb.remote.header import StaticHeaderProvider + + provider = StaticHeaderProvider({"X-Exists-Test": "present"}) + async with mock_lancedb_connection_async( + existence_handler, header_provider=provider + ) as db: + if status in (200, 404): + assert await getattr(db, method)(identifier) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + await getattr(db, method)(identifier) + assert exc_info.value.status_code == status + + +@pytest.mark.parametrize("table_id", [[], ["invalid/name"]]) +def test_remote_table_exists_rejects_invalid_identifier(table_id): + requests = [] + with mock_lancedb_connection(lambda request: requests.append(request.path)) as db: + with pytest.raises(ValueError): + db.table_exists(table_id) + assert requests == [] + + +def test_remote_table_exists_rechecks_cached_table(): + requests = [] + + def handler(request): + requests.append(request.path) + request.send_response(200 if len(requests) == 1 else 404) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}") + + with mock_lancedb_connection(handler) as db: + table_id = ["ns", "table"] + assert db.table_exists(table_id) is True + assert db.table_exists(table_id) is False + assert table_id == ["ns", "table"] + assert requests == ["/v1/table/ns$table/describe/"] * 2 + + def paginated_table_listing_handler(request): url = urlparse(request.path) assert url.path in { diff --git a/python/src/connection.rs b/python/src/connection.rs index 2cdf71f4a..54ea615de 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -711,6 +711,53 @@ impl Connection { }) } + pub fn namespace_exists( + self_: PyRef<'_, Self>, + namespace_id: Vec, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let request = lance_namespace::models::DescribeNamespaceRequest { + id: Some(namespace_id), + ..Default::default() + }; + match inner.describe_namespace(request).await { + Ok(_) => Ok(true), + Err(lancedb::Error::Http { + status_code: Some(status), + .. + }) if status.as_u16() == 404 => Ok(false), + Err(lancedb::Error::Lance { + source: lance_core::Error::Namespace { ref source, .. }, + }) if matches!( + source.downcast_ref::(), + Some(lance_namespace::NamespaceError::NamespaceNotFound { .. }) + ) => + { + Ok(false) + } + Err(err) => Err(err).infer_error(), + } + }) + } + + pub fn table_exists( + self_: PyRef<'_, Self>, + mut table_id: Vec, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let name = table_id + .pop() + .ok_or_else(|| PyValueError::new_err("table_id must include a table name"))?; + future_into_py(self_.py(), async move { + match inner.open_table(name).namespace(table_id).execute().await { + Ok(_) => Ok(true), + Err(lancedb::Error::TableNotFound { .. }) => Ok(false), + Err(err) => Err(err).infer_error(), + } + }) + } + #[pyo3(signature = (namespace_path=None, page_token=None, limit=None))] pub fn list_tables( &self, From 04e509278e5039c686ff3dbe57ff62c8617edfb1 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:37:57 -0700 Subject: [PATCH 156/180] fix(python): clarify schemas for batch UDF annotations (#4727) `@udf` documented batch annotations without explaining that `pa.Array` and `pa.RecordBatch` do not specify concrete Arrow element types or field schemas. Document the requirement for both explicit schemas (including class `__call__` methods), add an array example, and make inference errors point callers to `input_schema` and `output_schema`. Fixes #4721 Validation: - Five new regression cases pass; all four diagnostic cases fail with the original implementation. - Function packaging, first-class Function slice 1/2 tests, and UDF doctests: 168 passed, 3 failed. This includes the upstream BlobReader annotation coverage. The three existing packaging tests fail while importing temporary modules, before UDF registration; all three failures also reproduce with the unchanged source and tests at `057a39a1`. - Rebuilt the native extension in the uv-managed tests/dev environment. - Python lint and formatting checks pass (`ruff check python`, `ruff format --check python`); `cargo fmt --all` also passes without changes. - Repository-wide `ruff check .` reports 48 existing errors under `docs/web-tests`. Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/functions.py | 27 ++++++++++-- .../python/tests/test_function_packaging.py | 41 +++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index a3e56247a..a7c85a984 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1000,6 +1000,11 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: if isinstance(annotation, pa.DataType): return annotation, nullable + if annotation is pa.Array or annotation is pa.RecordBatch: + raise TypeError( + f"cannot infer Arrow types from Function annotation {annotation!r}; " + "provide input_schema and output_schema together for batch callables" + ) if annotation is bool: return pa.bool_(), nullable if annotation is int: @@ -2064,8 +2069,11 @@ def udf( **Functions and classes.** A decorated function is called once per row, or once per batch when its parameters are annotated ``pyarrow.Array`` or - it takes one ``pyarrow.RecordBatch``. A decorated class is the same - callable with state: each remote instance calls ``__init__`` once, calls + it takes one ``pyarrow.RecordBatch``. These batch annotations require both + ``input_schema`` and ``output_schema`` explicitly: the annotations do not + specify Arrow element types or fields. This also applies to a class's + ``__call__`` method. A decorated class is the same callable with state: + each remote instance calls ``__init__`` once, calls ``__call__`` for every row or batch of every input it processes, and calls ``close()``, if defined, once when it retires. Load models, open clients, and build rate limiters in ``__init__``; every batch of the instance then @@ -2117,10 +2125,12 @@ def udf( letters, digits, and underscores. input_schema : pyarrow.Schema, optional Explicit input fields in the exact order of the callable parameters. - Must be provided together with ``output_schema``. + Required for batch annotations. Must be provided together with + ``output_schema``. output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional Explicit scalar or named-struct output. Scalar outputs must be - non-nullable. Must be provided together with ``input_schema``. + non-nullable. Required for batch annotations. Must be provided together + with ``input_schema``. pip : sequence of str, optional Pip requirements for the remote environment. conda : sequence of str, optional @@ -2158,6 +2168,15 @@ def udf( ... return value * 2 >>> score(1.5) 3.0 + >>> import pyarrow as pa + >>> @udf( + ... input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + ... output_schema=pa.int64(), + ... ) + ... def batch_identity(value: pa.Array) -> pa.Array: + ... return value + >>> batch_identity(pa.array([1, 2, 3])).to_pylist() + [1, 2, 3] >>> @udf(pip=["cupy-cuda12x"], gpu=True) ... def gpu_score(value: int) -> int: ... return value * 2 diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index fe86de14e..a61588777 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -127,6 +127,47 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.parametrize("annotation", ["Array", "RecordBatch"]) +@pytest.mark.parametrize("kind", ["function", "class"]) +def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package): + if kind == "class": + source = f""" + import pyarrow as pa + + class identity: + def __call__(self, value: pa.{annotation}) -> pa.{annotation}: + return value + """ + else: + source = f""" + import pyarrow as pa + + def identity(value: pa.{annotation}) -> pa.{annotation}: + return value + """ + module = helper_package("fx_batch_annotations", {"__init__.py": source}) + with pytest.raises(TypeError, match="input_schema and output_schema"): + udf(module.identity) + + +def test_array_batch_annotations_accept_explicit_schemas(): + @udf( + input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + output_schema=pa.int64(), + ) + def identity(value: pa.Array) -> pa.Array: + return value + + signature = identity.registration_request.signature + assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [ + ("value", "int64", False) + ] + assert signature.output.arrow_type == "int64" + assert signature.output.nullable is False + values = pa.array([1, 2, 3]) + assert identity(values).equals(values) + + @pytest.mark.parametrize("class_udf", [False, True]) @pytest.mark.parametrize("postponed", [False, True]) @pytest.mark.parametrize( From 5fbf9fd9f0702668d1f7ce9fbfc8d3248186e215 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Wed, 28 Oct 2026 17:01:12 -0700 Subject: [PATCH 157/180] docs(python): note that packaged Functions import lance_blob.BlobReader (#4730) Function authors annotate inputs with lancedb.BlobReader, but the packaged source binds that annotation to the worker's lance_blob.BlobReader, so grepping the artifact for the client class finds nothing. Say so on the class. --- python/python/lancedb/_blob_reader.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python/python/lancedb/_blob_reader.py b/python/python/lancedb/_blob_reader.py index 2fd0f00ca..c47f8074d 100644 --- a/python/python/lancedb/_blob_reader.py +++ b/python/python/lancedb/_blob_reader.py @@ -21,6 +21,9 @@ class BlobReader(io.RawIOBase): ``read_range`` does not change the sequential cursor. Readers are scoped to the invocation and must not be retained for a later call. + A packaged Function's source imports the worker's ``lance_blob.BlobReader`` + in place of this class. + For local calls, construct a reader from a range-reading callable and the blob's size. The callable accepts an offset and length and returns bytes. """ From 088f4d670ef5b5aa3fdcde9ecb7c262eece9b184 Mon Sep 17 00:00:00 2001 From: medimedi Date: Thu, 29 Oct 2026 08:44:10 +0800 Subject: [PATCH 158/180] docs(rust): use LanceDB Arrow re-exports (#3908) ## Summary - explain that Rust callers should use the Arrow crates re-exported by `lancedb::arrow` - update the crate quick-start doctests to build Arrow values from those re-exports - update the checked-in `simple` example so it cannot drift to an incompatible Arrow crate version Fixes #1207. ## Validation - `cargo fmt --all -- --check` - `cargo metadata --no-deps --format-version 1 --quiet` - static checks that the documented crates are publicly re-exported and both examples use them - `git diff --check` - attempted `cargo check --quiet -p lancedb --example simple`; dependency compilation stopped in the unmodified `lance-encoding` build script because `protoc` is not installed in this environment --- rust/lancedb/examples/simple.rs | 6 +++--- rust/lancedb/src/lib.rs | 21 +++++++++++++++------ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/rust/lancedb/examples/simple.rs b/rust/lancedb/examples/simple.rs index 14846e037..d4887224d 100644 --- a/rust/lancedb/examples/simple.rs +++ b/rust/lancedb/examples/simple.rs @@ -7,10 +7,10 @@ use std::sync::Arc; -use arrow_array::types::Float32Type; -use arrow_array::{FixedSizeListArray, Int32Array, RecordBatch}; -use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; +use lancedb::arrow::arrow_array::types::Float32Type; +use lancedb::arrow::arrow_array::{FixedSizeListArray, Int32Array, RecordBatch}; +use lancedb::arrow::arrow_schema::{DataType, Field, Schema}; use lancedb::connection::Connection; use lancedb::index::Index; use lancedb::query::{ExecutableQuery, QueryBase}; diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index e2d063c40..fa6850f14 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -23,6 +23,11 @@ //! cargo add lancedb //! ``` //! +//! Use the Arrow crates re-exported from [`arrow`] when building schemas, arrays, and +//! record batches for LanceDB. Arrow types from different crate versions are distinct +//! Rust types, so declaring independent `arrow-array` or `arrow-schema` dependencies +//! can cause type errors if their versions do not match LanceDB's dependencies. +//! //! ## Crate Features //! //! - `aws` - Enable AWS S3 object store support. @@ -91,9 +96,11 @@ //! //! ```rust //! # use std::sync::Arc; -//! use arrow_array::{RecordBatch, RecordBatchIterator}; -//! use arrow_schema::{DataType, Field, Schema}; -//! # use arrow_array::{FixedSizeListArray, Float32Array, Int32Array, types::Float32Type}; +//! use lancedb::arrow::arrow_array::{RecordBatch, RecordBatchIterator}; +//! use lancedb::arrow::arrow_schema::{DataType, Field, Schema}; +//! # use lancedb::arrow::arrow_array::{ +//! # FixedSizeListArray, Float32Array, Int32Array, types::Float32Type, +//! # }; //! //! # tokio::runtime::Runtime::new().unwrap().block_on(async { //! # let tmpdir = tempfile::tempdir().unwrap(); @@ -138,9 +145,11 @@ //! //! ```no_run //! # use std::sync::Arc; -//! # use arrow_array::{FixedSizeListArray, types::Float32Type, RecordBatch, -//! # RecordBatchIterator, Int32Array}; -//! # use arrow_schema::{Schema, Field, DataType}; +//! # use lancedb::arrow::arrow_array::{ +//! # FixedSizeListArray, Int32Array, RecordBatch, RecordBatchIterator, +//! # types::Float32Type, +//! # }; +//! # use lancedb::arrow::arrow_schema::{DataType, Field, Schema}; //! use lancedb::index::Index; //! # tokio::runtime::Runtime::new().unwrap().block_on(async { //! # let tmpdir = tempfile::tempdir().unwrap(); From 3506b43c0301613e3e5a52f6988f424b2c6f8ba7 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Wed, 28 Oct 2026 18:16:32 -0700 Subject: [PATCH 159/180] feat(python): accept input_schema or output_schema alone in @udf (#4731) Binding a nullable column needed an explicit input schema, and that forced spelling out the output schema too. Either schema can now be given alone; the other side is inferred from annotations. The udf docstring now says a bare annotation is non-nullable and `Optional[T]` binds a nullable column, and that a `bytes` input counts against the per-row input limit, with Blob V2 and `BlobReader` for large values. --- python/python/lancedb/functions.py | 63 +++++++++++-------- .../tests/test_first_class_function_slice2.py | 20 +++++- 2 files changed, 57 insertions(+), 26 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index a7c85a984..ae40b4e3f 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1109,8 +1109,6 @@ def _infer_signature( parameters = _callable_parameters(function) if method: parameters = parameters[1:] - if (input_schema is None) != (output_schema is None): - raise ValueError("input_schema and output_schema must be provided together") try: annotations = get_type_hints(function, include_extras=True) @@ -1164,14 +1162,26 @@ def _infer_signature( f"expected {expected!r}, got {actual!r}" ) inputs = tuple(input_parameter(field) for field in input_schema) - return FunctionSignature(inputs=inputs, output=_function_output(output_schema)) + else: + inputs = None + + missing = [] + if inputs is None: + missing += [p.name for p in parameters if p.name not in annotations] + if output_schema is None and "return" not in annotations: + missing.append("return") + if missing: + raise TypeError(f"missing Function annotations: {missing!r}") + if output_schema is not None: + output = _function_output(output_schema) + else: + output_type, output_nullable = _annotation_type(annotations["return"]) + if output_nullable: + raise ValueError("Function output must be non-nullable") + output = _function_output(pa.field("result", output_type, nullable=False)) + if inputs is not None: + return FunctionSignature(inputs=inputs, output=output) - missing = [ - parameter.name for parameter in parameters if parameter.name not in annotations - ] - if missing or "return" not in annotations: - names = missing + ([] if "return" in annotations else ["return"]) - raise TypeError(f"missing Function annotations: {names!r}") inputs = [] for parameter in parameters: annotation = annotations[parameter.name] @@ -1190,13 +1200,7 @@ def _infer_signature( inputs.append( input_parameter(pa.field(parameter.name, data_type, nullable=nullable)) ) - output_type, output_nullable = _annotation_type(annotations["return"]) - if output_nullable: - raise ValueError("Function output must be non-nullable") - return FunctionSignature( - inputs=tuple(inputs), - output=_function_output(pa.field("result", output_type, nullable=False)), - ) + return FunctionSignature(inputs=tuple(inputs), output=output) def _is_udf_decorator(node: ast.expr) -> bool: @@ -2061,11 +2065,20 @@ def udf( ): """Prepare a Python function or class for remote Function registration. - Input and output signatures are inferred from supported annotations. For - Arrow types annotations cannot express precisely, pass ``input_schema`` - and ``output_schema`` together. Scalar outputs must be non-nullable. Every - named-struct field may be nullable; Enterprise preserves the struct's - validity when the result is expanded into sibling columns. + Input and output signatures are inferred from supported annotations. A + parameter annotated ``T`` is non-nullable and binds only a non-nullable + column; annotate ``Optional[T]`` to bind a nullable one, and it receives + ``None`` for a null value. PyArrow fields are nullable unless declared + otherwise, so most columns need ``Optional``. For Arrow types annotations + cannot express precisely, pass ``input_schema``, ``output_schema``, or + both; the one omitted is inferred. Scalar outputs must be non-nullable. + Every named-struct field may be nullable; Enterprise preserves the + struct's validity when the result is expanded into sibling columns. + + **Large values.** A ``bytes`` parameter receives the whole value, which + is held in memory with its row and counts against the server's per-row + input limit. To pass large binary values, such as video, store them in a + Blob V2 column and annotate the parameter ``BlobReader``, which streams. **Functions and classes.** A decorated function is called once per row, or once per batch when its parameters are annotated ``pyarrow.Array`` or @@ -2125,12 +2138,12 @@ def udf( letters, digits, and underscores. input_schema : pyarrow.Schema, optional Explicit input fields in the exact order of the callable parameters. - Required for batch annotations. Must be provided together with - ``output_schema``. + Required for batch annotations. When omitted, inputs are inferred from + the parameter annotations. output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional Explicit scalar or named-struct output. Scalar outputs must be - non-nullable. Required for batch annotations. Must be provided together - with ``input_schema``. + non-nullable. Required for batch annotations. When omitted, the output + is inferred from the return annotation. pip : sequence of str, optional Pip requirements for the remote environment. conda : sequence of str, optional diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 58afa9c7c..47c021b15 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1495,7 +1495,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): def nullable_output(value: int) -> Optional[int]: return value - with pytest.raises(ValueError, match="provided together"): + with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"): @udf(input_schema=pa.schema([pa.field("value", pa.int64())])) def partial_schema(value): @@ -2062,3 +2062,21 @@ def test_a_function_namespace_path_must_be_a_list_of_segments(): list(db.list_functions(namespace_path="analytics")) assert state["requests"] == [] + + +def test_one_explicit_schema_infers_the_other_from_annotations(): + @udf(input_schema=pa.schema([pa.field("value", pa.int64())])) + def explicit_input(value) -> float: + return float(value or 0) + + @udf(output_schema=pa.field("result", pa.float32(), nullable=False)) + def explicit_output(value: Optional[int]): + return float(value or 0) + + for fn in (explicit_input, explicit_output): + signature = fn.registration_request.signature + assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [ + ("value", "int64", True) + ] + assert explicit_input.registration_request.signature.output.arrow_type == "float64" + assert explicit_output.registration_request.signature.output.arrow_type == "float32" From 65954bf9ccee3e1bedf7e1edbbe1f261c7de270f Mon Sep 17 00:00:00 2001 From: Bilal Atique <74999164+BilalAtique@users.noreply.github.com> Date: Thu, 29 Oct 2026 06:52:15 +0500 Subject: [PATCH 160/180] docs(python): document connection_factory on StreamingDataset Closes #3693. `columns` is documented on `StreamingDataset` now, but `connection_factory` still wasn't. This adds it to the parameter list, in signature order. The text follows `__getstate__` / `__setstate__`: with a factory, pickling the dataset replaces the table's reopen state with its name, and each DataLoader worker calls the factory to reopen the table. The factory is pickled along with the rest of the dataset, so it has to be picklable, and credentials stay out of the pickle only when the factory loads them in the worker instead of capturing them (the same guidance as `Permutation.with_connection_factory`). Without a factory, the table's own reopen state is pickled. This picks up #3697, which documented the same parameter and was closed by its author without a merge. --- python/python/lancedb/streaming.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 4a4ffd1f5..db71840c6 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -395,6 +395,16 @@ class StreamingDataset(IterableDataset): capping peak memory when the consumer (e.g. a GPU training step) is slower than the transform stage. Must be greater than zero. ``None`` (the default) imposes no limit. + connection_factory: + Optional picklable function that takes the table name and returns an + open LanceDB table. When set, pickling the dataset (as DataLoader + workers do under the ``spawn`` and ``forkserver`` start methods) + replaces the table's reopen state with its name, and each worker calls + the factory with that name to reopen the table. The factory itself is + pickled too, so credentials stay out of the pickle only if the factory + loads them in the worker, for example from the environment, instead of + capturing them. ``None`` (the default) pickles the table's own reopen + state instead. worker_info_override: If set, used in place of ``torch.utils.data.get_worker_info()`` to determine the DataLoader worker assignment. Intended for unit tests From 913ee160b067c23aee1260c5a6aa05f9cda0ba0e Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:45:34 +0800 Subject: [PATCH 161/180] test(python): cover vector index prewarming by name (#3859) ## Summary - cover vector-index prewarming through the Python API using the logical index name returned by list_indices - prevent regression to interpreting a vector index name as a schema column ## Root cause The Lance version used by the reported release opened a vector index by treating the prewarm argument as a column before resolving the index metadata. Current LanceDB dependencies contain the upstream metadata-based resolution, but LanceDB only exercised prewarming for FTS indexes, leaving the vector behavior unguarded. ## Validation - uv run --extra tests pytest python/tests/test_index.py::test_create_vector_index -q - python/.venv/bin/ruff format --check python/python/tests/test_index.py - python/.venv/bin/ruff check . Fixes #2897 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/tests/test_index.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 2ec14f6f8..a1ec1e04b 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -364,6 +364,8 @@ async def test_create_vector_index(some_table: AsyncTable): assert indices[0].columns == ["vector"] assert indices[0].name == "vector_idx" + await some_table.prewarm_index(indices[0].name) + stats = await some_table.index_stats("vector_idx") assert stats.index_type == "IVF_PQ" assert stats.distance_type == "l2" From 9ffd3d33e1f11c4f502b9f5d352747035bb0cd32 Mon Sep 17 00:00:00 2001 From: max <40643627+quotentiroler@users.noreply.github.com> Date: Thu, 29 Oct 2026 04:31:23 +0100 Subject: [PATCH 162/180] test(python): remove fixed per-test delays from mock HTTP servers The Python test jobs spend much of their pytest time waiting on the in-process mock HTTP servers. 1. Each server ran `serve_forever()` with the default 0.5 s poll interval, so every `server.shutdown()` blocked for up to 0.5 s. Around 300 tests use such a server (test_remote_db, test_authz/test_catalog, test_listing, the permutation helpers), about 150 s per test job on every platform. A shared `start_server_thread()` helper in `tests/utils.py` serves with a 0.01 s poll interval, so shutdown returns in about 10 ms. 2. The servers bind IPv4 only, but clients used `http://localhost:`. The client tries ::1 first and falls back after the happy-eyeballs delay, about 0.3 s per connection on Windows. The mock handlers close the connection after each response, so one listing test took 9.5 s on Windows CI versus 0.6 s on Linux. Clients now use 127.0.0.1, as test_catalog, test_listing and test_namespace already do. Measured on Windows with the 0.41.0b6 wheel and `-m "not slow and not s3_test"`: full suite 546.7 s to 212.3 s; test_remote_db.py, test_listing.py and test_catalog.py together 284 s to 14 s on current main. Collected test ids are identical (1898) and pass/fail/skip results match. No assertion, test or marker changed. --- python/python/tests/test_catalog.py | 5 +-- .../tests/test_first_class_function_slice2.py | 17 +++---- python/python/tests/test_listing.py | 5 +-- .../python/tests/test_materialized_views.py | 9 ++-- python/python/tests/test_namespace.py | 9 ++-- python/python/tests/test_remote_db.py | 45 +++++++++---------- python/python/tests/test_torch.py | 16 +++---- python/python/tests/utils.py | 16 +++++-- 8 files changed, 60 insertions(+), 62 deletions(-) diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py index b259778dd..95b03c6e7 100644 --- a/python/python/tests/test_catalog.py +++ b/python/python/tests/test_catalog.py @@ -3,13 +3,13 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json -from threading import Thread import pytest import lancedb from lancedb.db import AsyncConnection, DBConnection from lancedb.remote.errors import HttpError +from utils import start_server_thread @pytest.fixture @@ -38,8 +38,7 @@ def catalog_server(): do_POST = handle_request with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: - thread = Thread(target=server.serve_forever, daemon=True) - thread.start() + thread = start_server_thread(server, daemon=True) try: yield f"http://127.0.0.1:{server.server_port}", requests, responses finally: diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 47c021b15..0e8aca4e9 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -15,7 +15,6 @@ import os from pathlib import Path import subprocess import sys -import threading import urllib.parse from typing import Optional @@ -34,6 +33,7 @@ from lancedb.functions import ( udf, ) from lancedb.secrets import EnvVarSecret +from utils import start_server_thread THRESHOLD = 20 _CACHE = None @@ -295,13 +295,15 @@ class Handler(http.server.BaseHTTPRequestHandler): self.wfile.write(payload) -server = http.server.ThreadingHTTPServer(("localhost", 0), Handler) -threading.Thread(target=server.serve_forever, daemon=True).start() +server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) +threading.Thread( + target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True +).start() try: db = lancedb.connect( "db://dev", api_key="API_KEY_SENTINEL", - host_override="http://localhost:%d" % server.server_address[1], + host_override="http://127.0.0.1:%d" % server.server_address[1], client_config={"retry_config": {"retries": 0}}, ) db.create_secret("openai-prod", "SECRET_VALUE_SENTINEL") @@ -1731,11 +1733,10 @@ def _mock_remote_function_catalog(): response = {"functions": []} self._write_response(200, response) - with http.server.HTTPServer(("localhost", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() + with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) try: - yield f"http://localhost:{server.server_address[1]}", state + yield f"http://127.0.0.1:{server.server_address[1]}", state finally: server.shutdown() thread.join() diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index 2d1e6497a..4cf37b631 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -5,12 +5,12 @@ import asyncio from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json from pathlib import Path -from threading import Thread from urllib.parse import parse_qs, urlsplit import lancedb from lancedb.remote.errors import HttpError import pytest +from utils import start_server_thread @pytest.fixture @@ -31,8 +31,7 @@ def listing_server(): do_POST = handle_request with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: - thread = Thread(target=server.serve_forever, daemon=True) - thread.start() + thread = start_server_thread(server, daemon=True) try: yield f"http://127.0.0.1:{server.server_port}", requests, responses finally: diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 85c02ccc3..891b49164 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -5,7 +5,6 @@ import contextlib import http.server import json -import threading import lancedb import pytest @@ -13,6 +12,7 @@ import pyarrow as pa from lancedb.db import AsyncConnection from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection +from utils import start_server_thread STABLE_ROW_IDS = {"new_table_enable_stable_row_ids": "true"} @@ -50,11 +50,10 @@ def mock_remote_materialized_view_refresh(): self.end_headers() self.wfile.write(encoded) - with http.server.HTTPServer(("localhost", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() + with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) try: - yield f"http://localhost:{server.server_address[1]}", requests + yield f"http://127.0.0.1:{server.server_address[1]}", requests finally: server.shutdown() thread.join() diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index c70ba3d8e..663172e77 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -9,12 +9,12 @@ import importlib import warnings import http.server import json -import threading from urllib.parse import parse_qs, unquote, urlparse import pytest import pyarrow as pa import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError +from utils import start_server_thread from lancedb.listing import AsyncListing, Listing from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY from lancedb.namespace import _MAX_QUERY_K, _query_to_namespace_request @@ -267,8 +267,7 @@ def paginated_rest_namespace(): pass with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server: - thread = threading.Thread(target=server.serve_forever) - thread.start() + thread = start_server_thread(server) try: yield {"uri": f"http://127.0.0.1:{server.server_port}"}, requests finally: @@ -1205,7 +1204,7 @@ class TestPushdownOperations: Rust so reads carry the x-lancedb-min-timestamp read-freshness header.""" db = lancedb.connect_namespace( "rest", - {"uri": "http://localhost:12345"}, + {"uri": "http://127.0.0.1:12345"}, namespace_client_pushdown_operations=["QueryTable"], ) assert db._route_pushdown_to_rust is True @@ -1222,7 +1221,7 @@ class TestPushdownOperations: for the async path omitting the freshness header).""" db = lancedb.connect_namespace_async( "rest", - {"uri": "http://localhost:12345"}, + {"uri": "http://127.0.0.1:12345"}, namespace_client_pushdown_operations=["QueryTable"], ) assert db._route_pushdown_to_rust is True diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 0b32376e8..415f8be3c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -34,6 +34,7 @@ from lancedb.remote import ClientConfig from lancedb.remote.errors import HttpError, RetryError import pytest import pyarrow as pa +from utils import start_server_thread def make_mock_http_handler(handler): @@ -56,16 +57,15 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name): @contextlib.contextmanager def mock_lancedb_connection(handler, **client_config): with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 2}, "timeout_config": { @@ -85,16 +85,15 @@ def mock_lancedb_connection(handler, **client_config): @contextlib.asynccontextmanager async def mock_lancedb_connection_async(handler, **client_config): with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) db = await lancedb.connect_async( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 2}, "timeout_config": { @@ -660,16 +659,15 @@ def test_remote_table_open_does_not_require_picklable_client_config(): request.end_headers() with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -3249,17 +3247,16 @@ def test_header_provider_with_sync_connection(): # Create connection with custom client config with http.server.HTTPServer( - ("localhost", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 2}, "timeout_config": {"connect_timeout": 1}, @@ -3463,7 +3460,7 @@ def _remote_fork_child(port: int, queue) -> None: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -3497,17 +3494,16 @@ def test_remote_connection_after_fork(): request.end_headers() request.wfile.write(b'{"tables": []}') - server = http.server.HTTPServer(("localhost", 0), make_mock_http_handler(handler)) + server = http.server.HTTPServer(("127.0.0.1", 0), make_mock_http_handler(handler)) port = server.server_address[1] - server_thread = threading.Thread(target=server.serve_forever) - server_thread.start() + server_thread = start_server_thread(server) try: # Hit the server in the parent first so the runtime + LOOP are warm # before fork; a fresh child must still succeed. parent_db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -3563,15 +3559,14 @@ def test_inherited_remote_table_reopens_after_fork(): request.send_response(404) request.end_headers() - server = http.server.HTTPServer(("localhost", 0), make_mock_http_handler(handler)) + server = http.server.HTTPServer(("127.0.0.1", 0), make_mock_http_handler(handler)) port = server.server_address[1] - server_thread = threading.Thread(target=server.serve_forever) - server_thread.start() + server_thread = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index 38a367330..500378fef 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -9,13 +9,13 @@ import multiprocessing as mp import pickle import re import sys -import threading import lancedb import pyarrow as pa import pytest from lancedb.permutation import Permutation, Permutations, permutation_builder from lancedb.util import tbl_to_tensor +from utils import start_server_thread torch = pytest.importorskip("torch") @@ -100,16 +100,15 @@ def _remote_dataset_handler(request): @contextlib.contextmanager def _remote_dataset_table(): with http.server.ThreadingHTTPServer( - ("localhost", 0), _make_mock_http_handler(_remote_dataset_handler) + ("127.0.0.1", 0), _make_mock_http_handler(_remote_dataset_handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -349,7 +348,7 @@ def _remote_multiworker_dataloader_target(port: int, result_queue): db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{port}", + host_override=f"http://127.0.0.1:{port}", client_config={ "retry_config": {"retries": 0}, "timeout_config": {"connect_timeout": 2, "read_timeout": 2}, @@ -419,11 +418,10 @@ def test_permutation_dataloader_fork_workers(tmp_path): ) def test_remote_permutation_dataloader_fork_workers(): with http.server.ThreadingHTTPServer( - ("localhost", 0), _make_mock_http_handler(_remote_dataset_handler) + ("127.0.0.1", 0), _make_mock_http_handler(_remote_dataset_handler) ) as server: port = server.server_address[1] - handle = threading.Thread(target=server.serve_forever) - handle.start() + handle = start_server_thread(server) try: ctx = mp.get_context("spawn") queue = ctx.Queue() diff --git a/python/python/tests/utils.py b/python/python/tests/utils.py index ca72a4dfd..7c4c30b71 100644 --- a/python/python/tests/utils.py +++ b/python/python/tests/utils.py @@ -153,6 +153,15 @@ class MockPermutationServer: return self._arrow(request, pa.table({"id": pa.array([], pa.int64())})) +def start_server_thread(server, daemon=False) -> threading.Thread: + """Serve on a thread; a short poll interval lets ``shutdown()`` return promptly.""" + thread = threading.Thread( + target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=daemon + ) + thread.start() + return thread + + def _make_handler(serve): class MockLanceDBHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): @@ -175,15 +184,14 @@ def mock_remote_table(server): serialize, hiding the prefetch overlap under test. """ with http.server.ThreadingHTTPServer( - ("localhost", 0), _make_handler(server) + ("127.0.0.1", 0), _make_handler(server) ) as srv: - thread = threading.Thread(target=srv.serve_forever) - thread.start() + thread = start_server_thread(srv) try: db = lancedb.connect( "db://dev", api_key="fake", - host_override=f"http://localhost:{srv.server_address[1]}", + host_override=f"http://127.0.0.1:{srv.server_address[1]}", client_config={"timeout_config": {"connect_timeout": 5}}, ) yield db.open_table(server.name) From 03bd909dab8a81ba01d5acad2917d44a824594bd Mon Sep 17 00:00:00 2001 From: Lei Xu Date: Wed, 28 Oct 2026 21:19:44 -0700 Subject: [PATCH 163/180] test(python): resolve aliased projections in the torch remote mock server Map dynamic projections by output name to their source columns in the remote torch test mock so permutation take queries preserve the aliased ordering column. Run the regression in the embeddings-installed Python test job and require torch to import so a missing dependency cannot skip coverage. --- .github/workflows/python.yml | 4 ++++ python/python/tests/test_torch.py | 24 +++++++++++++++--------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index a18ae5ad9..fa6ac4741 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -122,6 +122,10 @@ jobs: run: | pip install --extra-index-url https://pypi.fury.io/lance-format/ --extra-index-url https://pypi.fury.io/lancedb/ -e .[tests,dev,embeddings] pip install mlx + - name: Test remote torch data loader + run: | + python -c "import torch" + pytest python/tests/test_torch.py::test_remote_permutation_dataloader_multiprocessing -q -rs - name: Doctest run: pytest --doctest-modules python/lancedb linux: diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index 500378fef..befa3c10f 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -74,17 +74,23 @@ def _remote_dataset_handler(request): body = json.loads(request.rfile.read(content_len)) offsets = _offsets_from_filter(body.get("filter")) requested_columns = body.get("columns") or ["a"] + # A dynamic projection is sent as {output name: source expression}; take + # queries use it to alias `_rowoffset` as `__lancedb_take_row_offset`. if isinstance(requested_columns, dict): - requested_columns = list(requested_columns) + projection = requested_columns + else: + projection = {column: column for column in requested_columns} - data = {} - for column in requested_columns: - if column == "a": - data[column] = [REMOTE_ROWS[offset] for offset in offsets] - elif column == "_rowoffset": - data[column] = offsets - elif column == "_rowid": - data[column] = offsets + sources = { + "a": [REMOTE_ROWS[offset] for offset in offsets], + "_rowoffset": offsets, + "_rowid": offsets, + } + data = { + name: sources[source] + for name, source in projection.items() + if source in sources + } table = pa.table(data) request.send_response(200) From 7ea10fa1e085085f2edc4039218e38fca4229bd7 Mon Sep 17 00:00:00 2001 From: geoffgscott <59206100+geoffgscott@users.noreply.github.com> Date: Thu, 29 Oct 2026 01:13:00 -0400 Subject: [PATCH 164/180] feat(node): expose targetPartitionSize on IVF index options (#4594) The Node SDK's vector index options only take `numPartitions`. The Rust index builders (`target_partition_size` in `rust/lancedb/src/index/vector.rs`) and the Python SDK already support a target partition size, so this adds `targetPartitionSize` to `IvfPqOptions`, `IvfRqOptions`, `IvfFlatOptions`, `HnswPqOptions` and `HnswSqOptions` and passes it to their builders. When both are set, `numPartitions` is used, as it is for Rust and Python callers. The reason to want it: an index built from a partition count records no target partition size, so `table.optimize()` splits and joins it against the index type's default and can merge small partitions down to one or two. Building with a target records it in the index details, and optimize keeps to it. https://github.com/lance-format/lance/pull/10154 fixes this on the Lance side for indexes built from a partition count; this lets Node users set the size directly. The new tests build IvfPq, IvfFlat, IvfRq, IvfHnswPq and IvfHnswSq indexes with `targetPartitionSize` and check the size recorded in the index details, and check that `numPartitions` wins when both are set. Each option's doc comment states that index type's default target. Docs regenerated with `pnpm run docs`. --- docs/src/js/classes/Table.md | 7 ++ docs/src/js/interfaces/HnswPqOptions.md | 22 ++++++ docs/src/js/interfaces/HnswSqOptions.md | 22 ++++++ docs/src/js/interfaces/IvfFlatOptions.md | 25 +++++- docs/src/js/interfaces/IvfPqOptions.md | 25 +++++- docs/src/js/interfaces/IvfRqOptions.md | 25 +++++- nodejs/__test__/table.test.ts | 32 ++++++++ nodejs/lancedb/indices.ts | 99 ++++++++++++++++++++++-- nodejs/lancedb/table.ts | 5 ++ nodejs/src/index.rs | 21 +++++ 10 files changed, 271 insertions(+), 12 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index b1929019c..4398ee3ad 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -385,6 +385,13 @@ await table.createIndex("vector", { }); ``` +```ts +// Or size the partitions by row count instead of choosing how many. +await table.createIndex("vector", { + config: lancedb.Index.ivfPq({ targetPartitionSize: 4096 }), +}); +``` + ```ts // Or create a Scalar index await table.createIndex("my_float_col"); diff --git a/docs/src/js/interfaces/HnswPqOptions.md b/docs/src/js/interfaces/HnswPqOptions.md index 6d42ed28f..f044e0e11 100644 --- a/docs/src/js/interfaces/HnswPqOptions.md +++ b/docs/src/js/interfaces/HnswPqOptions.md @@ -100,6 +100,8 @@ optional numPartitions: number; The number of IVF partitions to create. +When set, this takes precedence over `targetPartitionSize`. + For HNSW, we recommend a small number of partitions. Setting this to 1 works well for most tables. For very large tables, training just one HNSW graph will require too much memory. Each partition becomes its own HNSW graph, so @@ -147,3 +149,23 @@ number of vectors used to train the index is `sample_rate * num_partitions`. Increasing this value might improve the quality of the index but in most cases the default should be sufficient. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +1,048,576 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/HnswSqOptions.md b/docs/src/js/interfaces/HnswSqOptions.md index 585737a5a..332854490 100644 --- a/docs/src/js/interfaces/HnswSqOptions.md +++ b/docs/src/js/interfaces/HnswSqOptions.md @@ -100,6 +100,8 @@ optional numPartitions: number; The number of IVF partitions to create. +When set, this takes precedence over `targetPartitionSize`. + For HNSW, we recommend a small number of partitions. Setting this to 1 works well for most tables. For very large tables, training just one HNSW graph will require too much memory. Each partition becomes its own HNSW graph, so @@ -126,3 +128,23 @@ number of vectors used to train the index is `sample_rate * num_partitions`. Increasing this value might improve the quality of the index but in most cases the default should be sufficient. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +1,048,576 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/IvfFlatOptions.md b/docs/src/js/interfaces/IvfFlatOptions.md index 36da98907..5b8024bc3 100644 --- a/docs/src/js/interfaces/IvfFlatOptions.md +++ b/docs/src/js/interfaces/IvfFlatOptions.md @@ -82,8 +82,9 @@ optional numPartitions: number; The number of IVF partitions to create. This value should generally scale with the number of rows in the dataset. -By default the number of partitions is the square root of the number of -rows. +When set, this takes precedence over `targetPartitionSize`. When omitted, +the partition count is derived from `targetPartitionSize`, which defaults +to 4096 rows for this index type. If this value is too large then the first part of the search (picking the right partition) will be slow. If this value is too small then the second @@ -110,3 +111,23 @@ Increasing this value might improve the quality of the index but in most cases t default should be sufficient. The default value is 256. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +4096 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/IvfPqOptions.md b/docs/src/js/interfaces/IvfPqOptions.md index 7109e448c..f1dd47621 100644 --- a/docs/src/js/interfaces/IvfPqOptions.md +++ b/docs/src/js/interfaces/IvfPqOptions.md @@ -92,8 +92,9 @@ optional numPartitions: number; The number of IVF partitions to create. This value should generally scale with the number of rows in the dataset. -By default the number of partitions is the square root of the number of -rows. +When set, this takes precedence over `targetPartitionSize`. When omitted, +the partition count is derived from `targetPartitionSize`, which defaults +to 8192 rows for this index type. If this value is too large then the first part of the search (picking the right partition) will be slow. If this value is too small then the second @@ -141,3 +142,23 @@ Increasing this value might improve the quality of the index but in most cases t default should be sufficient. The default value is 256. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +8192 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/docs/src/js/interfaces/IvfRqOptions.md b/docs/src/js/interfaces/IvfRqOptions.md index 298565a62..eb2cfe0ac 100644 --- a/docs/src/js/interfaces/IvfRqOptions.md +++ b/docs/src/js/interfaces/IvfRqOptions.md @@ -72,8 +72,9 @@ optional numPartitions: number; The number of IVF partitions to create. This value should generally scale with the number of rows in the dataset. -By default the number of partitions is the square root of the number of -rows. +When set, this takes precedence over `targetPartitionSize`. When omitted, +the partition count is derived from `targetPartitionSize`, which defaults +to 4096 rows for this index type. If this value is too large then the first part of the search (picking the right partition) will be slow. If this value is too small then the second @@ -100,3 +101,23 @@ Increasing this value might improve the quality of the index but in most cases t default should be sufficient. The default value is 256. + +*** + +### targetPartitionSize? + +```ts +optional targetPartitionSize: number; +``` + +The target number of rows in each IVF partition. + +This is an alternative to `numPartitions`. When it is set and +`numPartitions` is not, the number of partitions is derived by dividing +the number of rows by this value. When both are set, `numPartitions` is +used and this value is ignored. When neither is set, the target is +4096 rows. + +Larger partitions mean fewer of them, which makes the first part of the +search (picking the right partitions) faster and the second part +(searching within a partition) slower. diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 6db5b2f4d..c98292fd4 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -1707,6 +1707,38 @@ describe("When creating an index", () => { }); }); + it.each([ + ["IvfPq", Index.ivfPq({ targetPartitionSize: 100 })], + ["IvfFlat", Index.ivfFlat({ targetPartitionSize: 100 })], + ["IvfRq", Index.ivfRq({ targetPartitionSize: 100 })], + ["IvfHnswPq", Index.hnswPq({ targetPartitionSize: 100 })], + ["IvfHnswSq", Index.hnswSq({ targetPartitionSize: 100 })], + ])("should create %s with targetPartitionSize", async (indexType, config) => { + await tbl.createIndex("vec", { config }); + + const indices = await tbl.listIndices(); + expect(indices).toHaveLength(1); + expect(indices[0].indexType).toBe(indexType); + expect( + (indices[0].indexDetails as Record)[ + "target_partition_size" + ], + ).toBe(100); + }); + + it("should prefer numPartitions over targetPartitionSize", async () => { + await tbl.createIndex("vec", { + config: Index.ivfFlat({ numPartitions: 2, targetPartitionSize: 100 }), + }); + + const indices = await tbl.listIndices(); + expect( + (indices[0].indexDetails as Record)[ + "target_partition_size" + ], + ).toBeUndefined(); + }); + it("should allow me to replace (or not) an existing index", async () => { await tbl.createIndex("id"); // Default is replace=true diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index 0e383e984..4b1b422bf 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -11,8 +11,9 @@ export interface IvfPqOptions { * The number of IVF partitions to create. * * This value should generally scale with the number of rows in the dataset. - * By default the number of partitions is the square root of the number of - * rows. + * When set, this takes precedence over `targetPartitionSize`. When omitted, + * the partition count is derived from `targetPartitionSize`, which defaults + * to 8192 rows for this index type. * * If this value is too large then the first part of the search (picking the * right partition) will be slow. If this value is too small then the second @@ -20,6 +21,21 @@ export interface IvfPqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 8192 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Number of sub-vectors of PQ. * @@ -117,8 +133,9 @@ export interface IvfRqOptions { * The number of IVF partitions to create. * * This value should generally scale with the number of rows in the dataset. - * By default the number of partitions is the square root of the number of - * rows. + * When set, this takes precedence over `targetPartitionSize`. When omitted, + * the partition count is derived from `targetPartitionSize`, which defaults + * to 4096 rows for this index type. * * If this value is too large then the first part of the search (picking the * right partition) will be slow. If this value is too small then the second @@ -126,6 +143,21 @@ export interface IvfRqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 4096 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Number of bits per dimension for residual quantization. * @@ -215,6 +247,8 @@ export interface HnswPqOptions { /** * The number of IVF partitions to create. * + * When set, this takes precedence over `targetPartitionSize`. + * * For HNSW, we recommend a small number of partitions. Setting this to 1 works * well for most tables. For very large tables, training just one HNSW graph * will require too much memory. Each partition becomes its own HNSW graph, so @@ -223,6 +257,21 @@ export interface HnswPqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 1,048,576 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Number of sub-vectors of PQ. * @@ -331,6 +380,8 @@ export interface HnswSqOptions { /** * The number of IVF partitions to create. * + * When set, this takes precedence over `targetPartitionSize`. + * * For HNSW, we recommend a small number of partitions. Setting this to 1 works * well for most tables. For very large tables, training just one HNSW graph * will require too much memory. Each partition becomes its own HNSW graph, so @@ -339,6 +390,21 @@ export interface HnswSqOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 1,048,576 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Max iterations to train kmeans. * @@ -407,8 +473,9 @@ export interface IvfFlatOptions { * The number of IVF partitions to create. * * This value should generally scale with the number of rows in the dataset. - * By default the number of partitions is the square root of the number of - * rows. + * When set, this takes precedence over `targetPartitionSize`. When omitted, + * the partition count is derived from `targetPartitionSize`, which defaults + * to 4096 rows for this index type. * * If this value is too large then the first part of the search (picking the * right partition) will be slow. If this value is too small then the second @@ -416,6 +483,21 @@ export interface IvfFlatOptions { */ numPartitions?: number; + /** + * The target number of rows in each IVF partition. + * + * This is an alternative to `numPartitions`. When it is set and + * `numPartitions` is not, the number of partitions is derived by dividing + * the number of rows by this value. When both are set, `numPartitions` is + * used and this value is ignored. When neither is set, the target is + * 4096 rows. + * + * Larger partitions mean fewer of them, which makes the first part of the + * search (picking the right partitions) faster and the second part + * (searching within a partition) slower. + */ + targetPartitionSize?: number; + /** * Distance type to use to build the index. * @@ -633,6 +715,7 @@ export class Index { options?.numBits, options?.maxIterations, options?.sampleRate, + options?.targetPartitionSize, ), ); } @@ -661,6 +744,7 @@ export class Index { options?.numBits, options?.maxIterations, options?.sampleRate, + options?.targetPartitionSize, ), ); } @@ -688,6 +772,7 @@ export class Index { options?.numPartitions, options?.maxIterations, options?.sampleRate, + options?.targetPartitionSize, ), ); } @@ -798,6 +883,7 @@ export class Index { options?.sampleRate, options?.m, options?.efConstruction, + options?.targetPartitionSize, ), ); } @@ -820,6 +906,7 @@ export class Index { options?.sampleRate, options?.m, options?.efConstruction, + options?.targetPartitionSize, ), ); } diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 8e7cd02a1..0806f7c6d 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -381,6 +381,11 @@ export abstract class Table { * }), * }); * @example + * // Or size the partitions by row count instead of choosing how many. + * await table.createIndex("vector", { + * config: lancedb.Index.ivfPq({ targetPartitionSize: 4096 }), + * }); + * @example * // Or create a Scalar index * await table.createIndex("my_float_col"); */ diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs index e5884aa4d..39aa6f8b8 100644 --- a/nodejs/src/index.rs +++ b/nodejs/src/index.rs @@ -104,6 +104,7 @@ impl Index { num_bits: Option, max_iterations: Option, sample_rate: Option, + target_partition_size: Option, ) -> napi::Result { let mut ivf_pq_builder = IvfPqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -113,6 +114,9 @@ impl Index { if let Some(num_partitions) = num_partitions { ivf_pq_builder = ivf_pq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + ivf_pq_builder = ivf_pq_builder.target_partition_size(target_partition_size); + } if let Some(num_sub_vectors) = num_sub_vectors { ivf_pq_builder = ivf_pq_builder.num_sub_vectors(num_sub_vectors); } @@ -137,6 +141,7 @@ impl Index { num_bits: Option, max_iterations: Option, sample_rate: Option, + target_partition_size: Option, ) -> napi::Result { let mut ivf_rq_builder = IvfRqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -146,6 +151,9 @@ impl Index { if let Some(num_partitions) = num_partitions { ivf_rq_builder = ivf_rq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + ivf_rq_builder = ivf_rq_builder.target_partition_size(target_partition_size); + } if let Some(num_bits) = num_bits { ivf_rq_builder = ivf_rq_builder.num_bits(num_bits); } @@ -166,6 +174,7 @@ impl Index { num_partitions: Option, max_iterations: Option, sample_rate: Option, + target_partition_size: Option, ) -> napi::Result { let mut ivf_flat_builder = IvfFlatIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -175,6 +184,9 @@ impl Index { if let Some(num_partitions) = num_partitions { ivf_flat_builder = ivf_flat_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + ivf_flat_builder = ivf_flat_builder.target_partition_size(target_partition_size); + } if let Some(max_iterations) = max_iterations { ivf_flat_builder = ivf_flat_builder.max_iterations(max_iterations); } @@ -283,6 +295,7 @@ impl Index { } #[napi(factory)] + #[allow(clippy::too_many_arguments)] pub fn hnsw_pq( distance_type: Option, num_partitions: Option, @@ -291,6 +304,7 @@ impl Index { sample_rate: Option, m: Option, ef_construction: Option, + target_partition_size: Option, ) -> napi::Result { let mut hnsw_pq_builder = IvfHnswPqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -300,6 +314,9 @@ impl Index { if let Some(num_partitions) = num_partitions { hnsw_pq_builder = hnsw_pq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + hnsw_pq_builder = hnsw_pq_builder.target_partition_size(target_partition_size); + } if let Some(num_sub_vectors) = num_sub_vectors { hnsw_pq_builder = hnsw_pq_builder.num_sub_vectors(num_sub_vectors); } @@ -328,6 +345,7 @@ impl Index { sample_rate: Option, m: Option, ef_construction: Option, + target_partition_size: Option, ) -> napi::Result { let mut hnsw_sq_builder = IvfHnswSqIndexBuilder::default(); if let Some(distance_type) = distance_type { @@ -337,6 +355,9 @@ impl Index { if let Some(num_partitions) = num_partitions { hnsw_sq_builder = hnsw_sq_builder.num_partitions(num_partitions); } + if let Some(target_partition_size) = target_partition_size { + hnsw_sq_builder = hnsw_sq_builder.target_partition_size(target_partition_size); + } if let Some(max_iterations) = max_iterations { hnsw_sq_builder = hnsw_sq_builder.max_iterations(max_iterations); } From 079711d4ad6670be4aa00cbc6e16d561e4e96872 Mon Sep 17 00:00:00 2001 From: Ishita Singh Date: Thu, 29 Oct 2026 11:26:27 +0530 Subject: [PATCH 165/180] feat(python): list registered embedding functions Closes #1605. Adds `EmbeddingFunctionRegistry.list_functions()` to expose registered lookup names in registration order without accessing `_functions`. The method returns an independent snapshot, and every returned name can be passed to `get()`. Tests cover empty registries, aliases and class names, registration order, snapshot isolation, and reset. --- python/python/lancedb/embeddings/registry.py | 19 +++++++ .../tests/test_embedding_registry_listing.py | 55 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 python/python/tests/test_embedding_registry_listing.py diff --git a/python/python/lancedb/embeddings/registry.py b/python/python/lancedb/embeddings/registry.py index 728ff36da..a7093094d 100644 --- a/python/python/lancedb/embeddings/registry.py +++ b/python/python/lancedb/embeddings/registry.py @@ -101,6 +101,25 @@ class EmbeddingFunctionRegistry: """ return self._functions[name] + def list_functions(self) -> list[str]: + """List the names of registered embedding functions. + + Returns + ------- + list[str] + Registered aliases, or class names for functions registered without + an alias, in registration order. Each name can be passed to + :meth:`get`. The returned list is a copy; changing it does not + change the registry. + + Examples + -------- + >>> registry = get_registry() + >>> "openai" in registry.list_functions() + True + """ + return list(self._functions) + def parse_functions( self, metadata: Optional[Dict[bytes, bytes]] ) -> Dict[str, "EmbeddingFunctionConfig"]: diff --git a/python/python/tests/test_embedding_registry_listing.py b/python/python/tests/test_embedding_registry_listing.py new file mode 100644 index 000000000..4f7189a7b --- /dev/null +++ b/python/python/tests/test_embedding_registry_listing.py @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from lancedb.embeddings import EmbeddingFunctionRegistry, TextEmbeddingFunction + + +class ExampleEmbedding(TextEmbeddingFunction): + def ndims(self): + return 2 + + def generate_embeddings(self, texts): + return [[1.0, 0.0] for _ in texts] + + +class OtherEmbedding(ExampleEmbedding): + pass + + +def test_list_functions_empty_registry(): + registry = EmbeddingFunctionRegistry() + assert registry.list_functions() == [] + + +def test_list_functions_names_and_registration_order(): + registry = EmbeddingFunctionRegistry() + registry.register("custom-embedding")(ExampleEmbedding) + registry.register()(OtherEmbedding) + + assert registry.list_functions() == ["custom-embedding", "OtherEmbedding"] + assert [registry.get(name) for name in registry.list_functions()] == [ + ExampleEmbedding, + OtherEmbedding, + ] + + +def test_list_functions_returns_independent_snapshot(): + registry = EmbeddingFunctionRegistry() + registry.register("first")(ExampleEmbedding) + names = registry.list_functions() + names.append("not-registered") + assert registry.list_functions() == ["first"] + + registry.register("second")(OtherEmbedding) + assert names == ["first", "not-registered"] + assert registry.list_functions() == ["first", "second"] + + +def test_list_functions_after_reset(): + registry = EmbeddingFunctionRegistry() + registry.register("custom-embedding")(ExampleEmbedding) + names = registry.list_functions() + registry.reset() + + assert registry.list_functions() == [] + assert names == ["custom-embedding"] From 41c1a2a8b19274e540245b0831bd3471a51d4c2a Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Thu, 29 Oct 2026 00:28:36 -0700 Subject: [PATCH 166/180] feat(python): declare Debian system packages on a Function Adds `apt` to `@udf` and `system_packages` to the Rust `PythonEnvironmentSpec`. The server adds the packages to the Function's image before installing its Python environment, for shared libraries that pip and conda cannot provide, such as FFmpeg's for torchcodec. The field is omitted when empty, so existing Function identities are unchanged. --- python/python/lancedb/functions.py | 26 ++++++++++++++++--- .../tests/test_first_class_function_slice2.py | 24 +++++++++++++++++ rust/lancedb/src/function.rs | 26 +++++++++++++++++++ 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index ae40b4e3f..2125542af 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -283,6 +283,7 @@ class PythonEnvironmentSpec(_RemoteValue): path: Optional[str] = None modules: tuple[str, ...] = () image: Optional[str] = None + system_packages: tuple[str, ...] = () class PythonRuntimeSpec(_RemoteValue): @@ -1854,6 +1855,7 @@ class UdfDefinition: gpu: bool = False, conda: tuple[str, ...] = (), conda_channels: tuple[str, ...] = (), + apt: tuple[str, ...] = (), code: tuple[types.ModuleType, ...] = (), ): is_class = inspect.isclass(function) @@ -1869,14 +1871,23 @@ class UdfDefinition: if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") packages = tuple(sorted(set(conda if conda else pip))) - if any(not package or package != package.strip() for package in packages): + system_packages = tuple(sorted(set(apt))) + if any( + not package or package != package.strip() + for package in packages + system_packages + ): raise ValueError("package requirements must be non-empty and trimmed") if conda: environment_spec = PythonEnvironmentSpec( - kind="conda", packages=packages, channels=tuple(conda_channels) + kind="conda", + packages=packages, + channels=tuple(conda_channels), + system_packages=system_packages, ) else: - environment_spec = PythonEnvironmentSpec(kind="pip", packages=packages) + environment_spec = PythonEnvironmentSpec( + kind="pip", packages=packages, system_packages=system_packages + ) environment = dict(env) if any( not isinstance(key, str) or not isinstance(value, str) @@ -2045,6 +2056,7 @@ def udf( gpu: bool = False, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), + apt: tuple[str, ...] | list[str] = (), code: Sequence[types.ModuleType] = (), ) -> Callable[[Callable[..., Any]], UdfDefinition]: ... @@ -2061,6 +2073,7 @@ def udf( gpu: bool = False, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), + apt: tuple[str, ...] | list[str] = (), code: Sequence[types.ModuleType] = (), ): """Prepare a Python function or class for remote Function registration. @@ -2150,6 +2163,12 @@ def udf( Conda packages for the remote environment, instead of ``pip``. conda_channels : sequence of str, optional Conda channels in priority order; requires ``conda``. + apt : sequence of str, optional + Debian packages (``"name"`` or ``"name=version"``) added to the remote + image before the Python environment, for shared libraries pip and + conda cannot provide, such as FFmpeg's for ``torchcodec``. Packages + are unpacked without running their maintainer scripts. Works with + ``pip`` or ``conda``; requires image execution. env : mapping of str to str, optional Environment variables included in the Function definition. Not for credentials -- these are ordinary configuration, stored with the @@ -2219,6 +2238,7 @@ def udf( gpu=gpu, conda=tuple(conda), conda_channels=tuple(conda_channels), + apt=tuple(apt), code=tuple(code), ) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 0e8aca4e9..562a90eb4 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -494,6 +494,30 @@ def test_udf_conda_environment(): udf(name="channels", conda_channels=["conda-forge"])(lambda value: value) +def test_udf_apt_system_packages(): + @udf(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"]) + def decode(value: float) -> float: + return value + + request = json.loads(decode.registration_request.to_canonical_json()) + assert request["runtime"]["environment"] == { + "kind": "pip", + "packages": ["torchcodec"], + "system_packages": ["libavcodec60", "libavutil58"], + } + + @udf(conda=["numpy"], apt=["libsndfile1"]) + def conda_decode(value: float) -> float: + return value + + request = json.loads(conda_decode.registration_request.to_canonical_json()) + assert request["runtime"]["environment"]["system_packages"] == ["libsndfile1"] + pip_request = json.loads(normalize_score.registration_request.to_canonical_json()) + assert "system_packages" not in pip_request["runtime"]["environment"] + with pytest.raises(ValueError, match="trimmed"): + udf(name="padded", apt=[" libsndfile1"])(lambda value: value) + + def test_udf_gpu_marker_uses_gpu_runtime(): @udf(pip=["cupy-cuda12x"], gpu=True) def double_on_gpu(value: int) -> int: diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index db93f0071..128a7efdf 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -224,6 +224,10 @@ pub struct PythonEnvironmentSpec { pub modules: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub image: Option, + /// Debian packages (`name` or `name=version`) added to the Function's + /// image before its Python environment is installed. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub system_packages: Vec, } /// Reproducible Python runtime definition understood by Sophon. @@ -253,6 +257,7 @@ pub enum PythonRuntimeSpec { /// path: None, /// modules: Vec::new(), /// image: None, + /// system_packages: Vec::new(), /// }, /// env: BTreeMap::new(), /// }; @@ -938,6 +943,27 @@ mod conda_environment_tests { assert!(!serde_json::to_string(&pip).unwrap().contains("channels")); } + #[test] + fn system_packages_round_trip_and_stay_absent_when_empty() { + let apt: PythonEnvironmentSpec = serde_json::from_str( + r#"{"kind":"pip","packages":["torchcodec"],"system_packages":["libavutil58"]}"#, + ) + .unwrap(); + assert_eq!(apt.system_packages, ["libavutil58"]); + assert!( + serde_json::to_string(&apt) + .unwrap() + .contains(r#""system_packages":["libavutil58"]"#) + ); + let pip: PythonEnvironmentSpec = + serde_json::from_str(r#"{"kind":"pip","packages":["numpy"]}"#).unwrap(); + assert!( + !serde_json::to_string(&pip) + .unwrap() + .contains("system_packages") + ); + } + #[test] fn gpu_python_runtime_marker_round_trips_and_validates() { let runtime: PythonRuntimeSpec = serde_json::from_str( From 280ca410616285a51fe98122254218eddcd95d9e Mon Sep 17 00:00:00 2001 From: Jay Pokale Date: Thu, 29 Oct 2026 13:38:20 +0530 Subject: [PATCH 167/180] feat(python): support time and timedelta values in table.update Support `time` and `timedelta` values in `table.update` by generating explicit Arrow casts. - Preserve Arrow duration/time units and pandas nanosecond precision. - Reject timezone-aware `time` values before data can be changed. - Cover time64 us/ns, duration s/us/ns, negative timedeltas, filters, and nanosecond round trips. --- python/python/lancedb/util.py | 44 +++++++++++++- python/python/tests/test_util.py | 101 +++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index 36536f499..c37edcc6a 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -9,7 +9,7 @@ import math import os import pathlib import warnings -from datetime import date, datetime +from datetime import date, datetime, time, timedelta from decimal import Decimal from functools import singledispatch from typing import Tuple, Union, Optional, Any, List @@ -425,6 +425,28 @@ def _(value: date): return f"'{value.isoformat()}'" +@value_to_sql.register(time) +def _(value: time): + if value.utcoffset() is not None: + raise ValueError( + "time values with a timezone cannot be converted to SQL, " + "because Arrow time columns do not store one" + ) + # A plain string literal can be assigned to a time column but not compared with one. + return f"arrow_cast('{value.isoformat()}', 'Time64(Microsecond)')" + + +@value_to_sql.register(timedelta) +def _(value: timedelta): + # Lance does not accept INTERVAL literals, so cast the exact count of the + # smallest unit. pandas.Timedelta, a timedelta subclass, keeps nanoseconds. + nanoseconds = getattr(value, "value", None) + if isinstance(nanoseconds, int): + return f"arrow_cast({nanoseconds}, 'Duration(Nanosecond)')" + microseconds = value // timedelta(microseconds=1) + return f"arrow_cast({microseconds}, 'Duration(Microsecond)')" + + @value_to_sql.register(list) @value_to_sql.register(tuple) def _(value: Union[list, tuple]): @@ -452,6 +474,26 @@ def _(value: pa.Scalar): return value_to_sql(value.as_py()) +_ARROW_TIME_UNITS = { + "s": "Second", + "ms": "Millisecond", + "us": "Microsecond", + "ns": "Nanosecond", +} + + +@value_to_sql.register(pa.DurationScalar) +@value_to_sql.register(pa.Time64Scalar) +def _(value: Union[pa.DurationScalar, pa.Time64Scalar]): + # Cast the raw count in the scalar's own unit: as_py() would round a + # nanosecond value to the microseconds of a Python timedelta or time. + if not value.is_valid: + return value_to_sql(None) + kind = "Duration" if pa.types.is_duration(value.type) else "Time64" + unit = _ARROW_TIME_UNITS[value.type.unit] + return f"arrow_cast({value.value}, '{kind}({unit})')" + + @value_to_sql.register(pa.MapScalar) def _(value: pa.MapScalar): if not value.is_valid: diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index e85afb5bc..1e470e3be 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -4,6 +4,7 @@ import os import pathlib +from datetime import time, timedelta, timezone from decimal import Decimal, localcontext from typing import Optional @@ -217,6 +218,106 @@ def test_value_to_sql_decimal_non_finite(value): value_to_sql(Decimal(value)) +def test_value_to_sql_time_and_timedelta(tmp_path): + assert ( + value_to_sql(time(9, 30, 0, 250)) + == "arrow_cast('09:30:00.000250', 'Time64(Microsecond)')" + ) + assert ( + value_to_sql(timedelta(days=1, microseconds=5)) + == "arrow_cast(86400000005, 'Duration(Microsecond)')" + ) + assert ( + value_to_sql(timedelta(seconds=-1)) + == "arrow_cast(-1000000, 'Duration(Microsecond)')" + ) + + # Round trip through update and a filter, including columns whose unit is not + # microseconds. + db = lancedb.connect(tmp_path) + table = db.create_table( + "test", + pa.table( + { + "id": [1, 2], + "starts": pa.array([time(1, 2, 3), time(4, 5, 6)], pa.time64("us")), + "starts_ns": pa.array([time(1, 2, 3), time(4, 5, 6)], pa.time64("ns")), + "duration": pa.array([timedelta(0), timedelta(0)], pa.duration("us")), + "duration_s": pa.array([timedelta(0), timedelta(0)], pa.duration("s")), + } + ), + ) + table.update( + where="id = 1", + values={ + "starts": time(9, 30, 0, 250), + "starts_ns": time(9, 30, 0, 250), + "duration": timedelta(minutes=45, microseconds=5), + "duration_s": timedelta(hours=2), + }, + ) + assert table.to_arrow().sort_by("id").slice(0, 1).to_pylist() == [ + { + "id": 1, + "starts": time(9, 30, 0, 250), + "starts_ns": time(9, 30, 0, 250), + "duration": timedelta(minutes=45, microseconds=5), + "duration_s": timedelta(hours=2), + } + ] + for where in ( + f"starts = {value_to_sql(time(9, 30, 0, 250))}", + f"duration = {value_to_sql(timedelta(minutes=45, microseconds=5))}", + ): + assert table.search().where(where).to_arrow()["id"].to_pylist() == [1] + + +def test_value_to_sql_keeps_nanoseconds(tmp_path): + # Arrow scalars and pandas.Timedelta values can hold nanoseconds, which a + # Python timedelta or time would round to microseconds. + assert ( + value_to_sql(pd.Timedelta(1001, "ns")) + == "arrow_cast(1001, 'Duration(Nanosecond)')" + ) + assert value_to_sql(pa.scalar(None, pa.duration("ns"))) == "NULL" + + db = lancedb.connect(tmp_path) + table = db.create_table( + "test", + pa.table( + { + "id": [1, 2], + "duration": pa.array([0, 1001], pa.duration("ns")), + "starts": pa.array([0, 34_200_000_000_250], pa.time64("ns")), + } + ), + ) + source = table.to_arrow().sort_by("id") + table.update( + where="id = 1", + values={"duration": source["duration"][1], "starts": source["starts"][1]}, + ) + updated = table.to_arrow().sort_by("id") + assert updated["duration"].cast(pa.int64()).to_pylist() == [1001, 1001] + assert updated["starts"].cast(pa.int64()).to_pylist() == [ + 34_200_000_000_250, + 34_200_000_000_250, + ] + + +def test_value_to_sql_keeps_duration_units(): + for unit, sql_unit in [("s", "Second"), ("ms", "Millisecond")]: + assert ( + value_to_sql(pa.scalar(1500, pa.duration(unit))) + == f"arrow_cast(1500, 'Duration({sql_unit})')" + ) + + +def test_value_to_sql_rejects_time_with_timezone(): + with pytest.raises(ValueError, match="time values with a timezone"): + value_to_sql(time(9, 30, tzinfo=timezone.utc)) + + def test_value_to_sql_dict(): # Simple flat struct assert value_to_sql({"a": 1, "b": "hello"}) == "named_struct('a', 1, 'b', 'hello')" From 06b6625a94ca63c726e8c45cd04cc492b9f3d194 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 29 Oct 2026 17:06:55 +0800 Subject: [PATCH 168/180] docs: validate release branches before Lance stable approval (#4711) Freeze the SDK product baseline on a release branch before validating a Lance RC, so later main commits do not change the candidate. Require the RC pin PR's CI and applicable reviews to complete with no blocking findings before Lance stable publication. Draft-skipped reviews are missing evidence, and green CI does not clear a request-changes recommendation. After the upstream release, update only the validated dependency references, rerun checks and refresh review, then publish from the verified release branch. Document Cargo override boundaries, exact commit/artifact evidence, and the workflow's actual stable input (`type=stable`). Validation: Markdown fences, public-scope and diff checks passed; the documented workflow inputs were checked against the repository workflow. --- release_process.md | 74 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/release_process.md b/release_process.md index f223504a7..a1130fdf7 100644 --- a/release_process.md +++ b/release_process.md @@ -24,6 +24,68 @@ from the packaging index after a while. Once your application is stable, we recommend switching to full releases, which will never be removed from package indexes. +## Prepare a stable release + +### Select the release baseline + +Choose the SDK product commit for the planned release and record its SHA. Include +all fixes required for that release, including security fixes. Create and push a +release branch such as `release/v0.41` from that commit before opening the Lance RC +upgrade PR. For a patch to an existing stable line, reuse its release branch and +backport the required fixes. + +Keep the selected product baseline while main continues development. If main +already tracks a newer Lance development version, retain that dependency on main +and prepare the stable Lance dependency on the SDK release branch. Any additional +fixes should arrive through reviewed PRs into the release branch and be validated. + +### Validate the Lance RC + +1. Open a **draft PR targeting the SDK release branch** to consume the exact Lance + RC. Check both the PR base and dependency references when using automation. + Update the Rust declarations and lockfile, Python dependency declarations and + lockfile, and Java Maven version consistently. +2. Wait for the RC artifacts needed by each SDK to be available, then run the + relevant Rust, Python, Node.js, Java, and packaging checks. Resolve compatibility + failures and rerun CI after changes to the PR or its release-branch base. +3. Complete code and compatibility review on the RC pin PR. If draft status + skips Gatekeeper or another applicable review, mark the PR ready for review or + explicitly run the review. Read the recommendation and inline findings even + when GitHub records them as comments. Passing CI or a skipped review does not + clear an unresolved blocking finding. +4. Before the Lance vote is closed and Lance stable is published, the pin PR + must be **ready to merge**: all relevant CI and reviews are complete, with no + unresolved blocking findings at its current head and release-branch base. + Refresh reviews and comments immediately before reporting readiness. +5. Report the exact Lance tag and peeled SHA, + SDK release-branch base and PR head SHAs (and tested merge commit, when + applicable), full CI results and review outcomes to the release manager. + Label local source checks separately from checks consuming the published RC + artifacts. + +Keep the RC validation PR unmerged until Lance is approved, while completing all +substantive compatibility and review work before Lance stable publication. Once +the official stable Lance artifacts are available, only the mechanical +RC-to-stable dependency update and validation of those packages should remain. +Update the PR, rerun the relevant checks and refresh reviews. In particular, +verify that the Rust package resolves +published dependencies: Cargo only reads [`[patch]` settings at the workspace root](https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html#the-patch-section), +so package consumers do not inherit a dependency's workspace override. Merge the +validated stable update into the SDK release branch. + +### Publish the validated candidate + +Run **Create Release Commit** from the verified SDK release-branch head. Do not +switch to a later main snapshot after validation. Start with a dry run, review the +expected version and lockfile updates, and use the same branch and release inputs +for the real run. + +The workflow creates a new version commit and tag. Compare that tag with the +validated candidate and check that only the expected mechanical version and +lockfile updates were introduced. Code or dependency changes require renewed +validation. Verify all four SDK publishing workflows and the exact registry +artifacts before reporting the stable release as complete. + ## Making releases The release process uses a handful of GitHub actions to automate the process. @@ -54,7 +116,17 @@ To start a release, trigger a `Create Release Commit` action from (Click on "Run workflow"). * **For a preview release**, leave the default parameters. -* **For a stable release**, set the `release_type` input to `stable`. +* **For a stable release**, select the verified release branch and set the `type` input to `stable`. + +For example, dry-run a stable release from the selected branch: + +```bash +gh workflow run make-release-commit.yml --repo lancedb/lancedb \ + --ref release/v0.41 -f type=stable -f dry_run=true -f bump-minor=false +``` + +After reviewing the dry run, use the same branch and inputs with `dry_run=false`. +Select `bump-minor` according to the version and breaking-change check below. > [!IMPORTANT] > If there was a breaking change since the last stable release, and we haven't From 891774343e203bb883983863fd0124eabac27590 Mon Sep 17 00:00:00 2001 From: BHAWESHBHASKAR <90614484+BHAWESHBHASKAR@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:59:22 +0530 Subject: [PATCH 169/180] feat(python): add CombinedFieldsQuery for BM25F full text search Add a typed Python `CombinedFieldsQuery` for BM25F search across multiple columns. The query mirrors Lance's combined-fields semantics with ordered per-column boosts and AND/OR term matching. Convert it in both directions at the PyO3 boundary, including nested Boolean queries, and document the Python typed convenience entry. Closes #4652. --- docs/src/python/python.md | 2 + docs/web/search/full-text-search.mdx | 44 +++++++++++ python/python/lancedb/query.py | 37 +++++++++ python/python/tests/test_fts.py | 110 +++++++++++++++++++++++++++ python/src/query.rs | 39 ++++++++-- 5 files changed, 227 insertions(+), 5 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 84188aecb..af3f9d598 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -508,6 +508,8 @@ and combined with [BooleanQuery][lancedb.query.BooleanQuery]. ::: lancedb.query.MultiMatchQuery +::: lancedb.query.CombinedFieldsQuery + ::: lancedb.query.BooleanQuery ::: lancedb.query.FullTextOperator diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 5e0d7d8d7..858492576 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -748,6 +748,50 @@ const multiMatchBoostingResults = await table.query() ``` +### Search Columns as One Field {#combined-fields-search} + +`MultiMatchQuery` scores each column on its own and keeps the best match. +`CombinedFieldsQuery` treats the columns as one field (BM25F), so with the `AND` +operator a row matches when every term appears in at least one of the columns. +The query below finds `car` in `text` and `merrily` in `text2`, returning rows 1 +and 3. The same query with `MultiMatchQuery` returns no rows, because neither +column contains both words on its own. + +Every column must use the same tokenizer configuration. The two indexes in this +example are built with the same `FTS` settings. Boosts work as they do for +`MultiMatchQuery`: one weight per column, each at least 1. + + +```python Python icon="python" +from lancedb.query import CombinedFieldsQuery, FullTextOperator + +# Every term must appear in at least one of the two columns +combined_results = ( + table.search( + CombinedFieldsQuery("car merrily", ["text", "text2"], operator=FullTextOperator.AND), + ) + .select(["id", "text", "text2", "_score"]) + .limit(100) + .to_arrow().to_pandas() +) + +# Weight matches in text2 twice as much as matches in text +combined_boosting_results = ( + table.search( + CombinedFieldsQuery("car merrily", ["text", "text2"], boosts=[1.0, 2.0]), + ) + .select(["id", "text", "text2", "_score"]) + .limit(100) + .to_arrow().to_pandas() +) +``` + + +The typed `CombinedFieldsQuery` convenience class and this example are specific +to the Python SDK. Rust applications can construct the core query type exposed +by `lancedb::index::scalar`. TypeScript and Java do not yet provide typed +convenience entry points for this query. + ### Boolean Queries {#boolean-queries} LanceDB supports boolean logic in full-text search, allowing you to combine multiple queries using `and` and `or` operators. This is useful when you want to match documents that satisfy multiple conditions (intersection) or at least one of several conditions (union). diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 625a17524..c9ca258e7 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -445,6 +445,7 @@ class FullTextQueryType(str, Enum): MATCH_PHRASE = "match_phrase" BOOST = "boost" MULTI_MATCH = "multi_match" + COMBINED_FIELDS = "combined_fields" BOOLEAN = "boolean" @@ -669,6 +670,42 @@ class MultiMatchQuery(FullTextQuery): return FullTextQueryType.MULTI_MATCH +@pydantic.dataclasses.dataclass +class CombinedFieldsQuery(FullTextQuery): + """ + Combined-fields (BM25F) query for full-text search. + + Unlike `MultiMatchQuery`, which scores each column on its own and keeps + the best one, this query treats the columns as a single virtual field, so + term statistics are blended across them. A query term can then match in + any of the columns, e.g. a first name in one column and a last name in + another. + + Parameters + ---------- + query : str + The query string to match against. + columns : list[str] + The columns combined into the virtual field. Every column must have the + same tokenizer configuration, and at least one must have an FTS index. + boosts : list[float], optional + The weight of each column, aligned with `columns`. Each weight must be + at least 1. If not provided, every column has a weight of 1. + operator : FullTextOperator, default OR + The operator to use for combining the query terms. + If `AND`, every term must appear in at least one of the columns. + If `OR`, at least one term must match. + """ + + query: str + columns: list[str] + boosts: Optional[list[float]] = pydantic.Field(None, kw_only=True) + operator: FullTextOperator = pydantic.Field(FullTextOperator.OR, kw_only=True) + + def query_type(self) -> FullTextQueryType: + return FullTextQueryType.COMBINED_FIELDS + + @pydantic.dataclasses.dataclass class BooleanQuery(FullTextQuery): """ diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index a02c4db28..486c1ce62 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -26,7 +26,9 @@ from lancedb.db import DBConnection from lancedb.index import FTS from lancedb.query import ( BoostQuery, + CombinedFieldsQuery, DocumentGranularity, + FullTextOperator, MatchQuery, MultiMatchQuery, PhraseQuery, @@ -1367,6 +1369,103 @@ def test_match_query_fuzziness_search(tmp_db, options, expected): assert sorted(row["text"] for row in results) == sorted(expected) +@pytest.mark.parametrize( + "operator,combined_ids,multi_match_ids", + [ + # Combined fields treat the columns as one field, so AND also matches + # row 0, where "john" is in the title and "smith" is in the body. + (FullTextOperator.AND, {0, 1}, {1}), + (FullTextOperator.OR, {0, 1, 2}, {0, 1, 2}), + ], +) +def test_combined_fields_query(mem_db, operator, combined_ids, multi_match_ids): + table = mem_db.create_table( + "people", + pa.table( + { + "id": [0, 1, 2], + "title": ["john", "john smith", "john"], + "body": ["smith", "foo", "alice"], + } + ), + ) + table.create_index("title", config=FTS()) + table.create_index("body", config=FTS()) + + def ids(query): + return {row["id"] for row in table.search(query).select(["id"]).to_list()} + + combined = CombinedFieldsQuery("john smith", ["title", "body"], operator=operator) + multi_match = MultiMatchQuery("john smith", ["title", "body"], operator=operator) + assert ids(combined) == combined_ids + assert ids(multi_match) == multi_match_ids + + +def test_combined_fields_query_boosts(mem_db): + table = mem_db.create_table( + "docs", pa.table({"title": ["hello"], "body": ["world"]}) + ) + table.create_index("title", config=FTS()) + table.create_index("body", config=FTS()) + + results = table.search( + CombinedFieldsQuery("hello", ["title", "body"], boosts=[1.5, 1.0]) + ).to_list() + assert len(results) == 1 + + # Each weight must be at least 1, and there must be one per column. + with pytest.raises(ValueError, match="boost"): + table.search( + CombinedFieldsQuery("hello", ["title", "body"], boosts=[0.5, 1.0]) + ).to_list() + with pytest.raises(ValueError, match="boosts"): + table.search( + CombinedFieldsQuery("hello", ["title", "body"], boosts=[1.0]) + ).to_list() + + +@pytest.mark.asyncio +async def test_combined_fields_query_round_trip(mem_db_async): + table = await mem_db_async.create_table( + "docs", pa.table({"title": ["hello"], "body": ["world"]}) + ) + query = CombinedFieldsQuery( + "hello world", + ["title", "body"], + boosts=[2.0, 1.0], + operator=FullTextOperator.AND, + ) + + query_obj = table.query().nearest_to_text(query).to_query_object() + + assert query_obj.full_text_query.query == query + + +@pytest.mark.asyncio +async def test_combined_fields_query_nested_round_trip(mem_db_async): + table = await mem_db_async.create_table( + "docs", pa.table({"title": ["hello"], "body": ["world"]}) + ) + query = BooleanQuery( + [ + ( + Occur.MUST, + CombinedFieldsQuery( + "hello world", + ["title", "body"], + boosts=[2.0, 1.0], + operator=FullTextOperator.AND, + ), + ), + (Occur.MUST_NOT, MatchQuery("draft", "body")), + ] + ) + + query_obj = table.query().nearest_to_text(query).to_query_object() + + assert query_obj.full_text_query.query == query + + def test_fts_query_to_json(): """Test that FTS query to_json() produces valid JSON strings with exact format.""" @@ -1504,6 +1603,17 @@ def test_fts_query_to_json(): ) assert json_str == expected + # Test CombinedFieldsQuery + combined_fields = CombinedFieldsQuery( + "python", ["tags", "title"], boosts=[2.0, 1.0], operator=FullTextOperator.AND + ) + json_str = combined_fields.to_json() + expected = ( + '{"combined_fields":{"query":"python","columns":["tags","title"],' + '"boost":[2.0,1.0],"operator":"And"}}' + ) + assert json_str == expected + # Test complex nested BooleanQuery inner1 = BooleanQuery( [ diff --git a/python/src/query.rs b/python/src/query.rs index c2bd6afb3..8687b3756 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -17,8 +17,8 @@ use arrow::pyarrow::FromPyArrow; use arrow::pyarrow::IntoPyArrow; use arrow::pyarrow::ToPyArrow; use lancedb::index::scalar::{ - BooleanQuery, BoostQuery, DocumentGranularity, FtsQuery, FullTextSearchQuery, MatchQuery, - MultiMatchQuery, Occur, Operator, PhraseQuery, + BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery, + FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery, }; use lancedb::query::AnalyzePlanDistributedMetrics; use lancedb::query::QueryBase; @@ -148,6 +148,26 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { Ok(Self(q.with_operator(op).into())) } + "CombinedFieldsQuery" => { + let query = ob.getattr("query")?.extract()?; + let columns = ob.getattr("columns")?.extract()?; + let boosts: Option> = ob.getattr("boosts")?.extract()?; + let operator: String = ob.getattr("operator")?.extract()?; + + let q = CombinedFieldsQuery::try_new(query, columns) + .map_err(|e| PyValueError::new_err(format!("Invalid query: {}", e)))?; + let q = if let Some(boosts) = boosts { + q.try_with_boosts(boosts) + .map_err(|e| PyValueError::new_err(format!("Invalid boosts: {}", e)))? + } else { + q + }; + + let op = Operator::try_from(operator.as_str()) + .map_err(|e| PyValueError::new_err(format!("Invalid operator: {}", e)))?; + + Ok(Self(q.with_operator(op).into())) + } "BooleanQuery" => { let queries: Vec<(String, Self)> = ob.getattr("queries")?.extract()?; let mut sub_queries = Vec::with_capacity(queries.len()); @@ -178,9 +198,6 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { .expect("Failed to import namespace"); match self.0 { - FtsQuery::CombinedFields(_) => Err(PyValueError::new_err( - "Combined-fields FTS queries are not yet supported in Python", - )), FtsQuery::Match(query) => { let kwargs = PyDict::new(py); kwargs.set_item("boost", query.boost)?; @@ -236,6 +253,18 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { .getattr(intern!(py, "MultiMatchQuery"))? .call((first.terms.clone(), columns), Some(&kwargs)) } + FtsQuery::CombinedFields(query) => { + let (columns, boosts): (Vec<_>, Vec<_>) = query + .weighted_columns() + .map(|(column, boost)| (column.to_string(), boost)) + .unzip(); + let kwargs = PyDict::new(py); + kwargs.set_item("boosts", boosts)?; + kwargs.set_item::<_, &str>("operator", query.operator().into())?; + namespace + .getattr(intern!(py, "CombinedFieldsQuery"))? + .call((query.terms(), columns), Some(&kwargs)) + } FtsQuery::Boolean(query) => { let mut queries: Vec<(&str, Bound<'py, PyAny>)> = Vec::with_capacity( query.should.len() + query.must.len() + query.must_not.len(), From a065b4b9c658206f175e00b28462f946088ebfdc Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:10:50 -0700 Subject: [PATCH 170/180] feat(python): add NVIDIA Nemotron embedding provider Adds a Python `nvidia` embedding provider for Nemotron 3.5 Embed 1B and 8B. It works with NVIDIA's hosted API and self-hosted NIM `/v1` endpoints, and uses the existing `openai` client. The OpenAI provider can't send NVIDIA's passage/query input types or pick Nemotron's dimensions. - Documents are embedded as `passage`, searches as `query`. - Default dimensions are 2048 (1B) and 4096 (8B), and `dim` is checked against each model's supported range. Self-hosted model IDs need an explicit `dim`. - Response count, order, 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. Invalid input or responses fail immediately. - `NVIDIA_API_KEY` is only sent to the hosted API. Custom endpoints need an explicit `api_key` (a `$var:` reference), and endpoints restored from table metadata must be allowed with `allow_endpoint`. - Request dimensions are sent through `extra_body`, preserving the NVIDIA wire contract while supporting the declared minimum `openai==1.6.1`. Python and text only. Docs are in `integrations/embedding/nvidia`. Originally authored by Taylor (@tsmithv11). ### Testing - `test_nvidia_embeddings.py`: 45 passed, 2 deselected with both the locked `openai==2.44.0` and minimum `openai==1.6.1`. These use the real OpenAI client with mock HTTP transport and real local tables. - Embedding, registry, field-metadata and trust suites: 163 passed, 4 skipped, 10 deselected. - Historical live experiments: hosted 8B passed a five-request smoke test; hosted 1B returned HTTP 500. No live request was made in this stage, so current hosted 1B availability was not verified. Enterprise coverage uses the repository mock HTTP server, not a live deployment. --- docs/web/docs.json | 1 + docs/web/integrations/embedding/nvidia.mdx | 107 ++++ python/python/lancedb/embeddings/__init__.py | 2 + python/python/lancedb/embeddings/nvidia.py | 194 +++++++ python/python/tests/test_nvidia_embeddings.py | 522 ++++++++++++++++++ 5 files changed, 826 insertions(+) create mode 100644 docs/web/integrations/embedding/nvidia.mdx create mode 100644 python/python/lancedb/embeddings/nvidia.py create mode 100644 python/python/tests/test_nvidia_embeddings.py diff --git a/docs/web/docs.json b/docs/web/docs.json index 66ce3acd3..917eb6406 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -446,6 +446,7 @@ "integrations/embedding/imagebind", "integrations/embedding/instructor", "integrations/embedding/jina", + "integrations/embedding/nvidia", "integrations/embedding/ollama", "integrations/embedding/openai", "integrations/embedding/openclip", diff --git a/docs/web/integrations/embedding/nvidia.mdx b/docs/web/integrations/embedding/nvidia.mdx new file mode 100644 index 000000000..c0664684a --- /dev/null +++ b/docs/web/integrations/embedding/nvidia.mdx @@ -0,0 +1,107 @@ +--- +title: NVIDIA Nemotron +sidebarTitle: NVIDIA +description: Text embeddings with Nemotron 3.5 Embed 1B and 8B in the Python SDK. +--- + +The Python SDK registers `nvidia` for client-side text embedding with NVIDIA-hosted +and self-hosted NIM endpoints. Documents use `input_type="passage"`; searches use +`input_type="query"`. This provider supports text only, with floating-point output. +Null and empty text values get a null vector without a request; pass +`on_bad_vectors="null"` or `"drop"` to `add` to keep or skip those rows. +Image and combined text/image inputs are not supported by this integration. + +Install the optional client and set your NVIDIA API key: + +```shell +pip install openai +export NVIDIA_API_KEY="your-api-key" +``` + +```python +import lancedb +from lancedb.embeddings import get_registry +from lancedb.pydantic import LanceModel, Vector + +func = get_registry().get("nvidia").create( + name="nvidia/nemotron-3.5-embed-1b", +) + +class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + +db = lancedb.connect("./nemotron-db") +table = db.create_table("documents", schema=Document) +table.add([{"text": "Paris is the capital of France."}]) +results = table.search("What is the capital of France?").limit(3).to_list() +``` + +For a LanceDB Enterprise table, connect as usual, for example +`lancedb.connect("db://my-database", api_key=..., region=...)`. The same schema, +`add`, and `search` calls compute embeddings in the Python client. The NVIDIA key +is separate from the LanceDB database key. Use a fresh table name when creating a +table; reopening an existing table restores its embedding configuration. + +## Models and configuration + +The hosted API documents these exact IDs and dimensions: + +| Model ID | Default dimensions | Supported `dim` | +|---|---:|---:| +| `nvidia/nemotron-3.5-embed-1b` | 2048 | 128–2048 | +| `nvidia/nemotron-3.5-embed-8b` | 4096 | 1–4096 | + +| Parameter | Default | Description | +|---|---|---| +| `name` | `nvidia/nemotron-3.5-embed-1b` | Model ID sent to the endpoint. | +| `dim` | Model default above | Output dimensions; required for other served model IDs. | +| `base_url` | `https://integrate.api.nvidia.com/v1` | API base including `/v1`. | +| `api_key` | `NVIDIA_API_KEY` for the hosted API | Alternatively, a registry reference such as `$var:nvidia-key`. | +| `batch_size` | `32` | Maximum inputs per request. Reduce for your deployment's limits. | +| `truncate` | `END` | Truncate overlong text at the end, or use `NONE` to reject it. | +| `max_retries` | `7` | LanceDB's retry policy, applied to each request during automatic document/query embedding. | + +Requests specify `modality="text"` and `encoding_format="float"`. Returned vectors +are checked for count, input indices, dimensions, and finite numeric values. +The hosted input limit is 10,240 tokens per item; self-hosted limits depend on the +served profile. This provider batches by item count, not token count. + +## Self-hosted NIM + +Set `name` to the exact ID returned by your deployment's `GET /v1/models` and +`dim` to an output dimension that deployment supports: + +```python +func = get_registry().get("nvidia").create( + name="nvidia/Nemotron-3.5-Embed-1B-BF16", + base_url="http://localhost:8000/v1", + dim=2048, +) +``` + +Custom endpoints may run without a key. `NVIDIA_API_KEY` is only sent to the +hosted API, so for authenticated endpoints use +`get_registry().set_var("nvidia-key", key)` with `api_key="$var:nvidia-key"`. Registry references, rather than secret values, are +stored in the schema. Restore registry variables in each process. Before using +a custom endpoint restored from table metadata in a new process, call +`get_registry().allow_endpoint("http://localhost:8000/v1")`. + +The NIM 2.4 support matrix lists `nvidia/Nemotron-3.5-Embed-8B-BF16` at 2048 +dimensions, whereas the hosted 8B reference specifies 4096. For self-hosted model +IDs, this provider requires an explicit `dim` and checks the response instead of +assuming the hosted defaults. + +SDK coverage: Python. TypeScript, Rust, and Java do not gain a NVIDIA provider +from this integration. Automated tests use mocked NVIDIA and Enterprise HTTP +responses plus real local tables. The opt-in hosted smoke test runs with +`NVIDIA_API_KEY` and `pytest python/tests/test_nvidia_embeddings.py -m slow -k nvidia_live` +from the repository's Python environment. It sends five small requests per model +(ten total), with retries disabled, to check local ingestion, reopening, search, +and reduced-dimensional embeddings. + +NVIDIA references (checked October 23, 2026): +[hosted 1B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-1b-infer), +[hosted 8B API](https://docs.api.nvidia.com/nim/reference/nvidia-nemotron-3_5-embed-8b-infer), +[NIM request/response format](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/use-the-api-openai.html), +[NIM support matrix](https://docs.nvidia.com/nim/nemo-retriever/embedding/2.4/support-matrix.html). diff --git a/python/python/lancedb/embeddings/__init__.py b/python/python/lancedb/embeddings/__init__.py index 636502c9e..20e8c331b 100644 --- a/python/python/lancedb/embeddings/__init__.py +++ b/python/python/lancedb/embeddings/__init__.py @@ -16,6 +16,7 @@ from .instructor import InstructorEmbeddingFunction from .ollama import OllamaEmbeddings from .open_clip import OpenClipEmbeddings from .openai import OpenAIEmbeddings +from .nvidia import NvidiaEmbeddings from .registry import EmbeddingFunctionRegistry, get_registry, register from .sentence_transformers import SentenceTransformerEmbeddings from .gte import GteEmbeddings @@ -40,6 +41,7 @@ __all__ = [ "register", "SentenceTransformerEmbeddings", "OpenAIEmbeddings", + "NvidiaEmbeddings", "OpenClipEmbeddings", "BedRockText", "CohereEmbeddingFunction", diff --git a/python/python/lancedb/embeddings/nvidia.py b/python/python/lancedb/embeddings/nvidia.py new file mode 100644 index 000000000..11fae0d34 --- /dev/null +++ b/python/python/lancedb/embeddings/nvidia.py @@ -0,0 +1,194 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import math +import os +from functools import cached_property +from typing import List, Literal, Optional + +from pydantic import Field, model_validator + +from ..util import attempt_import_or_raise +from .base import TextEmbeddingFunction +from .registry import register +from .utils import TEXT, MissingApiKeyError, retry_with_exponential_backoff + + +NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1" +# Hosted model ID -> (default dimensions, minimum dimensions) +MODEL_DIMENSIONS = { + "nvidia/nemotron-3.5-embed-1b": (2048, 128), + "nvidia/nemotron-3.5-embed-8b": (4096, 1), +} + + +@register("nvidia") +class NvidiaEmbeddings(TextEmbeddingFunction): + """Text embeddings using NVIDIA Nemotron 3.5 Embed 1B or 8B. + + Uses the optional ``openai`` package for NVIDIA-hosted and self-hosted NIM + ``/v1/embeddings`` endpoints. Documents use ``input_type="passage"`` and + queries use ``input_type="query"``. Null and empty strings get a null + embedding. Image inputs are not supported. + + Parameters + ---------- + name : str + Hosted model ID, or the served model ID from a NIM ``/v1/models`` response. + dim : int, optional + Requested output dimensions. Defaults to 2048 for the hosted 1B model + and 4096 for the hosted 8B model. Required for other served model IDs; + use a dimension supported by your deployment. + base_url : str + API base URL including ``/v1``. Defaults to NVIDIA's hosted API. + api_key : str, optional + Registry variable reference, such as ``$var:nvidia-key``. Otherwise the + hosted API uses ``NVIDIA_API_KEY``. Custom endpoints only receive an + explicit ``api_key`` and can run without authentication. + batch_size : int + Maximum inputs per request (default 32). Reduce for deployment limits. + truncate : str + ``END`` (default) truncates overlong text; ``NONE`` rejects it. + max_retries : int + Inherited LanceDB retry limit, applied to each request. The OpenAI + client's own retries are disabled. + + Examples + -------- + Set ``NVIDIA_API_KEY`` before using the hosted API: + + >>> from lancedb.embeddings import get_registry + >>> from lancedb.pydantic import LanceModel, Vector + >>> func = get_registry().get("nvidia").create() + >>> class Document(LanceModel): + ... text: str = func.SourceField() + ... vector: Vector(func.ndims()) = func.VectorField() + + Embedding runs client-side for both local and remote tables. For a custom + endpoint restored from table metadata in a new process, first call + [allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint]. + """ + + name: str = "nvidia/nemotron-3.5-embed-1b" + dim: Optional[int] = Field(default=None, gt=0) + base_url: str = NVIDIA_BASE_URL + api_key: Optional[str] = Field(default=None, repr=False) + batch_size: int = Field(default=32, gt=0) + truncate: Literal["END", "NONE"] = "END" + + @model_validator(mode="after") + def _validate_dimensions(self): + dimensions = MODEL_DIMENSIONS.get(self.name) + if dimensions is None and self.dim is None: + raise ValueError("Set dim explicitly for self-hosted NIM model IDs") + if dimensions is not None and self.dim is not None: + native_dim, minimum = dimensions + if not minimum <= self.dim <= native_dim: + raise ValueError( + f"{self.name} supports dimensions from {minimum} to {native_dim}" + ) + return self + + @staticmethod + def sensitive_keys(): + return ["api_key"] + + def endpoints(self) -> List[str]: + return [] if self.base_url.rstrip("/") == NVIDIA_BASE_URL else [self.base_url] + + def ndims(self) -> int: + return self.dim if self.dim is not None else MODEL_DIMENSIONS[self.name][0] + + def compute_query_embeddings( + self, query: str, *args, **kwargs + ) -> List[Optional[List[float]]]: + return self._embed(query, input_type="query") + + def generate_embeddings(self, texts: TEXT) -> List[Optional[List[float]]]: + return self._embed(texts, input_type="passage") + + # Retry each request rather than the whole call, so a transient failure does + # not resend batches that already succeeded, and invalid inputs or responses + # fail at once instead of being retried. + def compute_query_embeddings_with_retry( + self, query: str, *args, **kwargs + ) -> List[Optional[List[float]]]: + return self._embed(query, input_type="query", max_retries=self.max_retries) + + def compute_source_embeddings_with_retry( + self, texts: TEXT, *args, **kwargs + ) -> List[Optional[List[float]]]: + return self._embed(texts, input_type="passage", max_retries=self.max_retries) + + def _embed( + self, + texts: TEXT, + *, + input_type: Literal["passage", "query"], + max_retries: int = 0, + ) -> List[Optional[List[float]]]: + texts = list(self.sanitize_input(texts)) + if any(text is not None and not isinstance(text, str) for text in texts): + raise ValueError("NVIDIA embeddings support text strings only") + request = self._request + if max_retries > 0: + request = retry_with_exponential_backoff(request, max_retries=max_retries) + embeddings = [None] * len(texts) + valid = [index for index, text in enumerate(texts) if text] + for start in range(0, len(valid), self.batch_size): + rows = valid[start : start + self.batch_size] + data = request([texts[row] for row in rows], input_type) + if not isinstance(data, list) or len(data) != len(rows): + raise ValueError("NVIDIA returned an unexpected number of embeddings") + indices = [getattr(item, "index", None) for item in data] + if any(type(index) is not int for index in indices) or sorted( + indices + ) != list(range(len(rows))): + raise ValueError("NVIDIA returned invalid embedding indices") + for row, item in zip(rows, sorted(data, key=lambda item: item.index)): + vector = getattr(item, "embedding", None) + if ( + not isinstance(vector, list) + or len(vector) != self.ndims() + or any( + type(value) not in (int, float) or not math.isfinite(value) + for value in vector + ) + ): + raise ValueError( + "NVIDIA returned an invalid embedding: expected " + f"{self.ndims()} finite numeric values" + ) + embeddings[row] = vector + return embeddings + + def _request(self, batch: List[str], input_type: str): + response = self._client.embeddings.create( + model=self.name, + input=batch, + encoding_format="float", + # The typed dimensions parameter is unavailable in openai 1.6.1. + extra_body={ + "dimensions": self.ndims(), + "input_type": input_type, + "modality": "text", + "truncate": self.truncate, + }, + ) + return getattr(response, "data", None) + + @cached_property + def _client(self): + openai = attempt_import_or_raise("openai") + hosted = not self.endpoints() + # Never send the hosted API key from the environment to a custom endpoint + api_key = self.api_key or (os.environ.get("NVIDIA_API_KEY") if hosted else None) + if not api_key and hosted: + raise MissingApiKeyError( + "Set NVIDIA_API_KEY or provide api_key via a registry variable" + ) + return openai.OpenAI( + base_url=self.base_url, + api_key=api_key or "not-required", + max_retries=0, + ) diff --git a/python/python/tests/test_nvidia_embeddings.py b/python/python/tests/test_nvidia_embeddings.py new file mode 100644 index 000000000..3ae07c330 --- /dev/null +++ b/python/python/tests/test_nvidia_embeddings.py @@ -0,0 +1,522 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +import os +from typing import Optional + +import lancedb +import numpy as np +import pyarrow as pa +import pytest + +from lancedb.embeddings import ( + EmbeddingFunctionConfig, + NvidiaEmbeddings, + UntrustedEmbeddingConfigError, + get_registry, +) +from lancedb.embeddings.nvidia import MODEL_DIMENSIONS, NVIDIA_BASE_URL +from lancedb.pydantic import LanceModel, Vector + + +@pytest.fixture +def nvidia_api(monkeypatch): + """Exercise the real OpenAI client against a deterministic NVIDIA endpoint.""" + httpx = pytest.importorskip("httpx") + openai = pytest.importorskip("openai") + requests, responses, clients = [], [], [] + original_client = openai.OpenAI + monkeypatch.setenv("NVIDIA_API_KEY", "test-nvidia-key") + registry = get_registry() + monkeypatch.setattr(registry, "_variables", {}) + monkeypatch.setattr(registry, "_allowed_endpoints", set()) + + def respond(request): + requests.append(request) + if responses: + return responses.pop(0) + body = json.loads(request.content) + data = [] + for index, text in enumerate(body["input"]): + vector = [0.0] * body["dimensions"] + vector[0 if text == "alpha" else 1] = 1.0 + data.append({"index": index, "embedding": vector, "object": "embedding"}) + return httpx.Response( + 200, + json={ + "object": "list", + "model": body["model"], + # The API's index, not response order, determines the input row. + "data": data[::-1], + "usage": {"prompt_tokens": len(data), "total_tokens": len(data)}, + }, + ) + + def client(**kwargs): + assert kwargs["max_retries"] == 0 + instance = original_client( + **kwargs, + http_client=httpx.Client( + transport=httpx.MockTransport(respond), trust_env=False + ), + ) + clients.append(instance) + return instance + + monkeypatch.setattr(openai, "OpenAI", client) + yield requests, responses + for client in clients: + client.close() + + +@pytest.mark.parametrize( + "name,dimensions", [(name, dims[0]) for name, dims in MODEL_DIMENSIONS.items()] +) +def test_hosted_models(nvidia_api, name, dimensions): + requests, _ = nvidia_api + func = get_registry().get("nvidia").create(name=name) + assert isinstance(func, NvidiaEmbeddings) + assert func.ndims() == dimensions + assert len(func.compute_source_embeddings(["alpha"])[0]) == dimensions + assert len(func.compute_query_embeddings("alpha")[0]) == dimensions + for request, input_type in zip(requests, ["passage", "query"]): + assert str(request.url) == f"{NVIDIA_BASE_URL}/embeddings" + assert request.headers["authorization"] == "Bearer test-nvidia-key" + assert json.loads(request.content) == { + "model": name, + "input": ["alpha"], + "dimensions": dimensions, + "encoding_format": "float", + "input_type": input_type, + "modality": "text", + "truncate": "END", + } + + +@pytest.mark.parametrize( + "texts", + [ + ["alpha", "beta", "gamma"], + np.array(["alpha", "beta", "gamma"]), + pa.array(["alpha", "beta", "gamma"]), + pa.chunked_array([["alpha"], ["beta", "gamma"]]), + ], +) +def test_batching_and_response_order(nvidia_api, texts): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(dim=128, batch_size=2, truncate="NONE") + result = func.compute_source_embeddings(texts) + assert [vector[:2] for vector in result] == [[1, 0], [0, 1], [0, 1]] + assert [json.loads(request.content)["input"] for request in requests] == [ + ["alpha", "beta"], + ["gamma"], + ] + assert all(json.loads(r.content)["truncate"] == "NONE" for r in requests) + assert func.compute_source_embeddings([]) == [] + assert len(requests) == 2 + + +@pytest.mark.parametrize( + "texts", + [ + ["alpha", None, "", "beta"], + pa.array(["alpha", None, "", "beta"]), + ], +) +def test_null_and_empty_inputs(nvidia_api, texts): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(dim=128) + result = func.compute_source_embeddings(texts) + assert [vector and vector[:2] for vector in result] == [[1, 0], None, None, [0, 1]] + assert [json.loads(r.content)["input"] for r in requests] == [["alpha", "beta"]] + assert func.compute_source_embeddings([None, ""]) == [None, None] + assert len(requests) == 1 + + +def test_table_with_null_text(nvidia_api, tmp_path): + func = NvidiaEmbeddings.create(dim=128) + + class Document(LanceModel): + text: Optional[str] = func.SourceField() + vector: Optional[Vector(func.ndims())] = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("docs", schema=Document) + table.add([{"text": "alpha"}, {"text": None}], on_bad_vectors="null") + rows = table.to_arrow().to_pylist() + assert rows[0]["vector"][:2] == [1, 0] + assert rows[1]["vector"] is None + + +@pytest.mark.parametrize("texts", [[b"image"], [["nested"]], [123]]) +def test_rejects_non_text(nvidia_api, monkeypatch, texts): + requests, _ = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail) + func = NvidiaEmbeddings.create() + with pytest.raises(ValueError, match="text strings only"): + func.compute_source_embeddings(texts) + with pytest.raises(ValueError, match="text strings only"): + func.compute_source_embeddings_with_retry(texts) + assert requests == [] + + +@pytest.mark.parametrize( + "options", + [ + {"batch_size": 0}, + {"dim": 0}, + {"dim": 127}, + {"dim": 2049}, + {"name": "nvidia/nemotron-3.5-embed-8b", "dim": 4097}, + {"name": "nvidia/Nemotron-3.5-Embed-8B-BF16"}, + {"truncate": "START"}, + ], +) +def test_invalid_configuration(options): + with pytest.raises(ValueError): + NvidiaEmbeddings.create(**options) + + +@pytest.mark.parametrize( + "data,error", + [ + ([], "number of embeddings"), + (None, "number of embeddings"), + ([{"index": 1, "embedding": [0.0] * 128}], "indices"), + ([{"embedding": [0.0] * 128}], "indices"), + ([{"index": 0, "embedding": [0.0]}], "finite numeric"), + ([{"index": 0, "embedding": "base64"}], "finite numeric"), + ([{"index": 0, "embedding": ["bad"] * 128}], "finite numeric"), + ([{"index": 0}], "finite numeric"), + ], +) +def test_invalid_response(nvidia_api, data, error): + import httpx + + _, responses = nvidia_api + responses.append(httpx.Response(200, json={"data": data})) + with pytest.raises(ValueError, match=error): + NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha"]) + + +def test_invalid_response_is_not_retried(nvidia_api, monkeypatch): + import httpx + + requests, responses = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail) + responses.append(httpx.Response(200, json={"data": []})) + func = NvidiaEmbeddings.create(dim=128) + with pytest.raises(ValueError, match="number of embeddings"): + func.compute_source_embeddings_with_retry(["alpha"]) + assert len(requests) == 1 + + +def test_missing_response_data(nvidia_api): + import httpx + + _, responses = nvidia_api + responses.append(httpx.Response(200, json={})) + with pytest.raises(ValueError, match="number of embeddings"): + NvidiaEmbeddings.create().compute_query_embeddings("alpha") + + +@pytest.mark.parametrize("bad_value", ["NaN", "Infinity", "-Infinity"]) +def test_nonfinite_response(nvidia_api, bad_value): + import httpx + + _, responses = nvidia_api + # Raw JSON is needed because httpx refuses to encode non-finite numbers. + vector = ",".join([bad_value] + ["0"] * 127) + responses.append( + httpx.Response(200, text='{"data":[{"index":0,"embedding":[' + vector + "]}]}") + ) + with pytest.raises(ValueError, match="finite numeric"): + NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha"]) + + +def test_duplicate_indices(nvidia_api): + import httpx + + _, responses = nvidia_api + responses.append( + httpx.Response(200, json={"data": [{"index": 0, "embedding": [0.0] * 128}] * 2}) + ) + with pytest.raises(ValueError, match="indices"): + NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha", "beta"]) + + +@pytest.mark.parametrize( + "status,expected_calls", [(429, 2), (503, 2), (401, 1), (400, 1)] +) +def test_retry_policy(nvidia_api, monkeypatch, status, expected_calls): + import httpx + import openai + + requests, responses = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", lambda _: None) + responses.append(httpx.Response(status, json={"error": {"message": "test error"}})) + func = NvidiaEmbeddings.create(dim=128, max_retries=1) + if expected_calls == 2: + assert len(func.compute_query_embeddings_with_retry("alpha")[0]) == 128 + else: + with pytest.raises(openai.APIStatusError) as error: + func.compute_query_embeddings_with_retry("alpha") + assert error.value.status_code == status + assert len(requests) == expected_calls + + +def test_retry_resends_only_failed_batch(nvidia_api, monkeypatch): + import httpx + + requests, responses = nvidia_api + monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", lambda _: None) + vector = [1.0] + [0.0] * 127 + responses.append( + httpx.Response(200, json={"data": [{"index": 0, "embedding": vector}]}) + ) + responses.append(httpx.Response(429, json={"error": {"message": "slow down"}})) + func = NvidiaEmbeddings.create(dim=128, batch_size=1, max_retries=1) + result = func.compute_source_embeddings_with_retry(["alpha", "beta"]) + assert [v[:2] for v in result] == [[1, 0], [0, 1]] + assert [json.loads(r.content)["input"] for r in requests] == [ + ["alpha"], + ["beta"], + ["beta"], + ] + + +def test_credentials_and_metadata(nvidia_api, monkeypatch): + requests, _ = nvidia_api + registry = get_registry() + registry.set_var("nvidia-key", "secret-from-registry") + options = { + "name": "nvidia/Nemotron-3.5-Embed-8B-BF16", + "base_url": "http://localhost:8000/v1", + "dim": 2048, + "api_key": "$var:nvidia-key", + "batch_size": 2, + "truncate": "NONE", + } + func = NvidiaEmbeddings.create(**options) + config = EmbeddingFunctionConfig( + source_column="text", vector_column="vector", function=func + ) + schema = pa.schema([], metadata=registry.get_table_metadata([config])) + # Round-trip the configuration through Arrow, as table schemas do. + restored_schema = pa.ipc.read_schema(pa.BufferReader(schema.serialize())) + metadata = restored_schema.metadata + assert b"secret-from-registry" not in metadata[b"embedding_functions"] + restored = registry.parse_functions(metadata)["vector"].function + assert restored.safe_model_dump() == options + restored.compute_source_embeddings(["alpha"]) + restored.compute_query_embeddings("alpha") + assert str(requests[0].url) == "http://localhost:8000/v1/embeddings" + assert requests[0].headers["authorization"] == "Bearer secret-from-registry" + assert json.loads(requests[0].content)["model"] == options["name"] + assert [json.loads(r.content)["input_type"] for r in requests] == [ + "passage", + "query", + ] + + monkeypatch.setattr(registry, "_allowed_endpoints", set()) + blocked = registry.parse_functions(metadata)["vector"].function + with pytest.raises(UntrustedEmbeddingConfigError): + blocked.compute_query_embeddings("alpha") + registry.allow_endpoint(options["base_url"]) + assert isinstance( + registry.parse_functions(metadata)["vector"].function, NvidiaEmbeddings + ) + with pytest.raises(ValueError, match="Sensitive key"): + NvidiaEmbeddings.create(api_key="hardcoded-secret") + + +def test_missing_key_and_unauthenticated_nim(nvidia_api, monkeypatch): + from lancedb.embeddings.utils import MissingApiKeyError + + requests, _ = nvidia_api + # The hosted key in NVIDIA_API_KEY is not sent to custom endpoints. + func = NvidiaEmbeddings.create( + name="nvidia/Nemotron-3.5-Embed-1B-BF16", + base_url="http://localhost:8000/v1", + dim=128, + ) + func.compute_query_embeddings("alpha") + assert requests[0].headers["authorization"] == "Bearer not-required" + monkeypatch.delenv("NVIDIA_API_KEY") + with pytest.raises(MissingApiKeyError, match="NVIDIA_API_KEY"): + NvidiaEmbeddings.create().compute_query_embeddings_with_retry("alpha") + assert len(requests) == 1 + + +@pytest.mark.parametrize("name", MODEL_DIMENSIONS) +def test_local_table_document_query_and_reopen(nvidia_api, tmp_path, name): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(name=name, dim=128) + + class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("docs", schema=Document, data=[{"text": "alpha"}]) + table.add([{"text": "beta"}]) + reopened = lancedb.connect(tmp_path).open_table("docs") + assert reopened.schema.metadata == table.schema.metadata + assert isinstance(reopened.embedding_functions["vector"].function, NvidiaEmbeddings) + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + assert [json.loads(request.content)["input_type"] for request in requests] == [ + "passage", + "passage", + "query", + ] + + +@pytest.mark.parametrize("name", MODEL_DIMENSIONS) +def test_remote_table_document_query_and_reopen(nvidia_api, name): + from test_remote_db import mock_lancedb_connection, read_json_body, send_json + + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(name=name, dim=128) + config = EmbeddingFunctionConfig( + source_column="text", vector_column="vector", function=func + ) + writes, queries = [], [] + + def handler(request): + if "/create/" in request.path or "/insert/" in request.path: + if request.headers.get("Transfer-Encoding") == "chunked": + body = bytearray() + while True: + size = int(request.rfile.readline(), 16) + if size == 0: + request.rfile.readline() + break + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body = request.rfile.read(int(request.headers["Content-Length"])) + writes.append(pa.ipc.open_stream(body).read_all()) + send_json(request, {}) + elif "/describe/" in request.path: + send_json( + request, + { + "version": 1, + "schema": { + "fields": [ + { + "name": "text", + "type": {"type": "string"}, + "nullable": True, + }, + { + "name": "vector", + "nullable": True, + "type": { + "type": "fixed_size_list", + "length": 128, + "fields": [ + { + "name": "item", + "type": {"type": "float"}, + "nullable": True, + } + ], + }, + }, + ], + "metadata": { + k.decode(): v.decode() + for k, v in writes[0].schema.metadata.items() + }, + }, + }, + ) + elif "/query/" in request.path: + queries.append(read_json_body(request)) + result = pa.table({"text": ["alpha"], "_distance": [0.0]}) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.file") + request.end_headers() + with pa.ipc.new_file(request.wfile, result.schema) as writer: + writer.write_table(result) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.create_table( + "docs", data=[{"text": "alpha"}], embedding_functions=[config] + ) + table.add([{"text": "beta"}]) + reopened = db.open_table("docs") + assert reopened.schema.metadata == writes[0].schema.metadata + assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha" + assert len(writes) == 2 + assert writes[0]["vector"].to_pylist()[0] == [1.0] + [0.0] * 127 + assert writes[1]["vector"].to_pylist()[0] == [0.0, 1.0] + [0.0] * 126 + assert queries[0]["vector"] == [1.0] + [0.0] * 127 + assert [json.loads(r.content)["input_type"] for r in requests] == [ + "passage", + "passage", + "query", + ] + + +@pytest.mark.asyncio +async def test_async_local_table(nvidia_api, tmp_path): + requests, _ = nvidia_api + func = NvidiaEmbeddings.create(dim=128) + + class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + with await lancedb.connect_async(tmp_path) as db: + table = await db.create_table("docs", schema=Document) + await table.add([{"text": "alpha"}, {"text": "beta"}]) + reopened = await db.open_table("docs") + results = await (await reopened.search("alpha")).limit(1).to_list() + assert results[0]["text"] == "alpha" + assert [json.loads(r.content)["input_type"] for r in requests] == [ + "passage", + "query", + ] + + +@pytest.mark.slow +@pytest.mark.skipif( + not os.environ.get("NVIDIA_API_KEY"), reason="NVIDIA_API_KEY not set" +) +@pytest.mark.parametrize("name", MODEL_DIMENSIONS) +def test_nvidia_live(name, tmp_path): + """Five small requests per model, with retries disabled for free-tier tests.""" + pytest.importorskip("openai") + func = NvidiaEmbeddings.create(name=name, max_retries=0) + passages = ["Paris is the capital of France.", "Bananas are yellow fruit."] + question = "What is the capital of France?" + + class Document(LanceModel): + text: str = func.SourceField() + vector: Vector(func.ndims()) = func.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table( + "docs", schema=Document, data=[{"text": text} for text in passages] + ) + table.add([{"text": "Saturn is a planet with rings."}]) + reopened = lancedb.connect(tmp_path).open_table("docs") + assert reopened.schema.metadata == table.schema.metadata + assert reopened.schema.field("vector").type.list_size == func.ndims() + result = reopened.search(question).limit(1).to_list()[0] + assert result["text"] == passages[0] + assert len(result["vector"]) == func.ndims() + assert np.isfinite(result["vector"]).all() + + reduced = NvidiaEmbeddings.create(name=name, dim=128, max_retries=0) + vectors = reduced.compute_source_embeddings_with_retry(passages) + query = reduced.compute_query_embeddings_with_retry(question)[0] + assert np.shape(vectors) == (2, 128) + assert np.shape(query) == (128,) + assert np.dot(query, vectors[0]) > np.dot(query, vectors[1]) From 005a9a353a04874c95586c7c734871d8955b1bfd Mon Sep 17 00:00:00 2001 From: Divyanshu Singh Date: Thu, 29 Oct 2026 16:03:13 +0530 Subject: [PATCH 171/180] ci(java): run Java 11 and 17 builds in parallel with matrix strategy Split the Java 17 workflow into a matrix for Java 11 and Java 17. Run Checkstyle once in a dedicated Java 17 job and skip the lifecycle-bound Checkstyle execution in the matrix builds to avoid redundant work. Closes #1331. --- .github/workflows/java.yml | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index 7739489cb..6140afbc5 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -28,9 +28,9 @@ permissions: contents: read jobs: - build-java: + style-check: runs-on: ubuntu-24.04 - name: Build + name: Style Check defaults: run: working-directory: ./java @@ -45,5 +45,24 @@ jobs: cache: "maven" - name: Java Style Check run: ./mvnw checkstyle:check + + build-java: + runs-on: ubuntu-24.04 + name: Build (Java ${{ matrix.java-version }}) + strategy: + matrix: + java-version: [11, 17] + defaults: + run: + working-directory: ./java + steps: + - name: Checkout repository + uses: actions/checkout@v6 + - name: Set up Java ${{ matrix.java-version }} + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java-version }} + cache: "maven" - name: Build and install - run: ./mvnw clean install + run: ./mvnw clean install -Dcheckstyle.skip=true From ddb318567a11211a9b75aca6dcf2902ff615f7d8 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 29 Oct 2026 10:16:03 -0700 Subject: [PATCH 172/180] docs: complete SQL reference, enrich Functions drafts, rename OSS to Embedded (#4732) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Complete the SQL reference: `ATTACH DATABASE`, the `CHANGES` clause, and `dedupe()`/`duplicate_pairs()` (verified against current sophon source; these were recently renamed from `vector_dedup`/`vector_duplicate_pairs`). Fix the blob-column default-projection claim and add the previously undocumented `blob_descriptor()`. - Enrich the gated Functions draft (still `.mintignore`'d, pre-release): chained Functions over blob outputs, GPU-produced blobs, Secrets, multi-input/output binding, `code=[module]` packaging. - Upgrade the materialized-view and computed-column auto-refresh drafts with precise, verified catch-up semantics, and add the missing `ALTER MATERIALIZED VIEW` / `CREATE ... WITH(...)` sections (also gated — the automatic-refresh scheduler is still dev/staging-only). - Thread one running example (video frames → GPU extract/caption → dedup → auto-refreshing materialized view) through Functions, materialized views, and the LeRobotDataset integration guide instead of a separate tutorial. - Rename "LanceDB OSS"/"OSS" to "LanceDB Embedded"/"Embedded" throughout (52 files); activate the existing availability-comparison mechanism on `basics/offerings.mdx` for a full feature-by-feature comparison table. --- docs/web-tests/py/test_quickstart.py | 151 +++--- docs/web-tests/rs/quickstart.rs | 240 +++++----- docs/web-tests/ts/quickstart.test.ts | 98 ++-- docs/web/.mintignore | 22 +- docs/web/architecture.mdx | 128 ------ docs/web/basics/agentic-skills.mdx | 2 +- docs/web/basics/catalog.mdx | 124 ++++- docs/web/basics/connect.mdx | 135 ------ docs/web/basics/guarantees.mdx | 4 +- docs/web/basics/jobs.mdx | 49 +- docs/web/basics/lakehouse.mdx | 75 --- docs/web/basics/lance.mdx | 4 +- docs/web/basics/limits.mdx | 6 +- docs/web/basics/offerings.mdx | 73 --- docs/web/basics/query.mdx | 55 --- docs/web/basics/sdk.mdx | 109 ++--- docs/web/basics/sql.mdx | 148 ++++-- docs/web/curation/aggregate.mdx | 4 +- docs/web/curation/changes.mdx | 93 ++++ docs/web/curation/chunking.mdx | 210 +++++++++ docs/web/curation/create-function.mdx | 213 +++++++++ docs/web/curation/dedupe.mdx | 142 ++++++ docs/web/curation/index.mdx | 6 +- docs/web/curation/join.mdx | 36 +- docs/web/curation/sampling.mdx | 10 +- docs/web/curation/windowing.mdx | 4 +- docs/web/deployment/storage.mdx | 17 +- docs/web/docs.json | 105 +++-- docs/web/embedding/index.mdx | 6 +- docs/web/enterprise/architecture.mdx | 23 - docs/web/enterprise/authentication.mdx | 6 +- docs/web/enterprise/benchmarks.mdx | 2 +- docs/web/enterprise/deployment/azure.mdx | 17 - docs/web/enterprise/deployment/index.mdx | 20 - docs/web/enterprise/deployment/kubernetes.mdx | 17 + docs/web/enterprise/distributed-search.mdx | 9 +- docs/web/enterprise/index.mdx | 13 +- docs/web/enterprise/security.mdx | 2 +- .../add-computed-column.mdx | 117 ++++- .../feature-engineering/data-evolution.mdx | 134 ------ docs/web/feature-engineering/index.mdx | 39 +- .../materialized-views.mdx | 151 +++--- .../feature-engineering/refresh-column.mdx | 57 ++- .../refresh-materialized-view.mdx | 88 ++++ docs/web/feature-engineering/view.mdx | 73 +++ docs/web/governance/authorization.mdx | 4 +- docs/web/index.mdx | 218 +++++---- docs/web/indexing/fts-index.mdx | 6 +- docs/web/indexing/index.mdx | 5 +- docs/web/indexing/reindexing.mdx | 7 +- docs/web/indexing/scalar-index.mdx | 6 +- docs/web/indexing/vector-index.mdx | 7 +- docs/web/ingestion/create-table.mdx | 4 +- docs/web/ingestion/delete.mdx | 4 +- docs/web/ingestion/index.mdx | 6 +- docs/web/ingestion/insert.mdx | 4 +- docs/web/ingestion/merge-insert.mdx | 4 +- docs/web/ingestion/realtime-write.mdx | 196 ++++++++ docs/web/ingestion/update.mdx | 6 +- docs/web/integrations/ai/huggingface.mdx | 7 +- .../integrations/data/pandas_and_pyarrow.mdx | 6 +- docs/web/integrations/data/polars_arrow.mdx | 7 +- docs/web/integrations/data/pydantic.mdx | 7 +- docs/web/integrations/lerobotdataset.mdx | 19 + docs/web/maintenance/background-jobs.mdx | 9 +- docs/web/maintenance/cleanup.mdx | 4 +- docs/web/maintenance/compaction.mdx | 8 +- docs/web/management/database.mdx | 15 +- docs/web/management/function.mdx | 327 ++++++++++--- docs/web/management/index.mdx | 2 +- docs/web/management/materialized-view.mdx | 64 ++- docs/web/management/namespace.mdx | 5 +- docs/web/management/table.mdx | 10 +- docs/web/management/view.mdx | 6 +- docs/web/quickstart.mdx | 187 ++++---- docs/web/reranking/index.mdx | 4 +- docs/web/search/explain.mdx | 4 +- docs/web/search/filtering.mdx | 4 +- docs/web/search/full-text-search.mdx | 4 +- docs/web/search/hybrid-search.mdx | 4 +- docs/web/search/index.mdx | 6 +- docs/web/search/realtime-read.mdx | 74 +++ docs/web/search/vector-search.mdx | 4 +- docs/web/snippets/quickstart.mdx | 62 +-- docs/web/sql/data-types.mdx | 5 +- docs/web/sql/ddl/database.mdx | 50 ++ docs/web/sql/ddl/function.mdx | 23 + docs/web/sql/ddl/grant.mdx | 77 ++++ docs/web/sql/ddl/index.mdx | 5 +- docs/web/sql/ddl/job.mdx | 7 +- docs/web/sql/ddl/materialized-view.mdx | 67 ++- docs/web/sql/ddl/namespace.mdx | 8 +- docs/web/sql/ddl/table.mdx | 37 +- docs/web/sql/ddl/view.mdx | 5 +- docs/web/sql/dml/delete.mdx | 5 +- docs/web/sql/dml/insert.mdx | 5 +- .../dml/{refresh.mdx => refresh-column.mdx} | 46 +- .../web/sql/dml/refresh-materialized-view.mdx | 50 ++ docs/web/sql/dml/update.mdx | 5 +- docs/web/sql/dql/aggregation.mdx | 5 +- docs/web/sql/dql/changes.mdx | 76 +++ docs/web/sql/dql/dedupe.mdx | 99 ++++ docs/web/sql/dql/duplicate-pairs.mdx | 97 ++++ docs/web/sql/dql/explain.mdx | 5 +- docs/web/sql/dql/fts.mdx | 5 +- docs/web/sql/dql/join.mdx | 31 +- docs/web/sql/dql/sampling.mdx | 5 +- docs/web/sql/dql/select.mdx | 5 +- docs/web/sql/dql/subqueries.mdx | 5 +- docs/web/sql/dql/window.mdx | 5 +- docs/web/sql/functions.mdx | 28 +- docs/web/sql/index.mdx | 7 +- docs/web/sql/operators.mdx | 5 +- docs/web/sql/prepared-statements.mdx | 12 +- docs/web/sql/scalar-functions.mdx | 58 ++- .../assets/images/enterprise/architecture.png | Bin 99871 -> 0 bytes .../images/overview/lancedb-architecture.svg | 60 --- .../assets/images/overview/lancedb-suite.svg | 92 ---- .../overview/training-data-lifecycle.svg | 49 -- .../static/assets/logo/lance-logo-gray.png | Bin 0 -> 57024 bytes .../static/assets/logo/lance-logo-gray.svg | 5 - .../static/assets/logo/light-lancedb-logo.svg | 17 +- docs/web/tables/branching.mdx | 6 +- docs/web/tables/consistency.mdx | 8 +- docs/web/tables/realtime-engine.mdx | 219 +-------- docs/web/training/data-loading.mdx | 435 +++++++----------- docs/web/training/distributed-training.mdx | 216 +++++++++ docs/web/training/object-detection.mdx | 4 +- docs/web/training/permutation.mdx | 123 +++++ docs/web/training/torch.mdx | 334 -------------- docs/web/training/why-lancedb.mdx | 119 ----- .../feature-engineering-101.mdx | 1 - .../materialized-views.mdx | 2 +- 133 files changed, 3978 insertions(+), 2918 deletions(-) delete mode 100644 docs/web/architecture.mdx delete mode 100644 docs/web/basics/connect.mdx delete mode 100644 docs/web/basics/lakehouse.mdx delete mode 100644 docs/web/basics/offerings.mdx delete mode 100644 docs/web/basics/query.mdx create mode 100644 docs/web/curation/changes.mdx create mode 100644 docs/web/curation/chunking.mdx create mode 100644 docs/web/curation/create-function.mdx create mode 100644 docs/web/curation/dedupe.mdx delete mode 100644 docs/web/enterprise/architecture.mdx delete mode 100644 docs/web/enterprise/deployment/azure.mdx delete mode 100644 docs/web/enterprise/deployment/index.mdx create mode 100644 docs/web/enterprise/deployment/kubernetes.mdx delete mode 100644 docs/web/feature-engineering/data-evolution.mdx create mode 100644 docs/web/feature-engineering/refresh-materialized-view.mdx create mode 100644 docs/web/feature-engineering/view.mdx create mode 100644 docs/web/ingestion/realtime-write.mdx create mode 100644 docs/web/search/realtime-read.mdx create mode 100644 docs/web/sql/ddl/database.mdx create mode 100644 docs/web/sql/ddl/grant.mdx rename docs/web/sql/dml/{refresh.mdx => refresh-column.mdx} (63%) create mode 100644 docs/web/sql/dml/refresh-materialized-view.mdx create mode 100644 docs/web/sql/dql/changes.mdx create mode 100644 docs/web/sql/dql/dedupe.mdx create mode 100644 docs/web/sql/dql/duplicate-pairs.mdx delete mode 100644 docs/web/static/assets/images/enterprise/architecture.png delete mode 100644 docs/web/static/assets/images/overview/lancedb-architecture.svg delete mode 100644 docs/web/static/assets/images/overview/lancedb-suite.svg delete mode 100644 docs/web/static/assets/images/overview/training-data-lifecycle.svg create mode 100644 docs/web/static/assets/logo/lance-logo-gray.png delete mode 100644 docs/web/static/assets/logo/lance-logo-gray.svg create mode 100644 docs/web/training/distributed-training.mdx create mode 100644 docs/web/training/permutation.mdx delete mode 100644 docs/web/training/torch.mdx delete mode 100644 docs/web/training/why-lancedb.mdx diff --git a/docs/web-tests/py/test_quickstart.py b/docs/web-tests/py/test_quickstart.py index 779a268d4..bdcb8abff 100644 --- a/docs/web-tests/py/test_quickstart.py +++ b/docs/web-tests/py/test_quickstart.py @@ -119,38 +119,35 @@ async def async_db(request, db_path_factory): await owned.drop_claimed() -def create_characters(db): +def create_frames(db): # --8<-- [start:quickstart_data] data = [ { - "id": "1", - "name": "King Arthur", - "role": "King", - "description": "Leader of Camelot and wielder of Excalibur.", - "stats": {"strength": 4, "magic": 1, "leadership": 5, "wisdom": 4}, - "vector": [0.7, 0.1, 0.9, 0.7], + "frame_id": "1", + "video_id": "clip-1", + "caption": "a robot arm reaching toward a cup", + "stats": {"motion": 3, "sharpness": 4, "exposure": 4, "framing": 3}, + "embedding": [0.7, 0.1, 0.9, 0.7], }, { - "id": "2", - "name": "Merlin", - "role": "Wizard", - "description": "Advisor and prophet with deep magical knowledge.", - "stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 5}, - "vector": [0.2, 0.9, 0.4, 0.9], + "frame_id": "2", + "video_id": "clip-1", + "caption": "a two-finger gripper closing on a cup", + "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, + "embedding": [0.2, 0.9, 0.4, 0.9], }, { - "id": "3", - "name": "Sir Lancelot", - "role": "Knight", - "description": "Legendary knight known for courage and combat skill.", - "stats": {"strength": 5, "magic": 1, "leadership": 3, "wisdom": 3}, - "vector": [0.9, 0.1, 0.5, 0.4], + "frame_id": "3", + "video_id": "clip-2", + "caption": "a robot arm holding a cup steady", + "stats": {"motion": 2, "sharpness": 3, "exposure": 3, "framing": 4}, + "embedding": [0.9, 0.1, 0.5, 0.4], }, ] # --8<-- [end:quickstart_data] # --8<-- [start:quickstart_create_table] - table = db.create_table("characters", data=data, mode="overwrite") + table = db.create_table("frames", data=data, mode="overwrite") # --8<-- [end:quickstart_create_table] assert table.count_rows() == 3 @@ -158,12 +155,11 @@ def create_characters(db): table.add( [ { - "id": "4", - "name": "Morgana", - "role": "Sorceress", - "description": "Powerful sorceress of Avalon.", - "stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 4}, - "vector": [0.3, 0.9, 0.6, 0.8], + "frame_id": "4", + "video_id": "clip-2", + "caption": "a gripper lowering a cup onto the table", + "stats": {"motion": 5, "sharpness": 4, "exposure": 4, "framing": 2}, + "embedding": [0.3, 0.9, 0.6, 0.8], } ] ) @@ -173,153 +169,152 @@ def create_characters(db): def test_quickstart(db): - table = create_characters(db) + table = create_frames(db) # --8<-- [start:quickstart_vector_search_1] - # Search for examples similar to a "wise magical advisor" + # Search for frames similar to "a gripper closing on an object" query_vector = [0.2, 0.8, 0.4, 0.9] # Ensure you run `pip install polars` beforehand result = ( table.search(query_vector) - .select(["name", "role", "description", "_distance"]) + .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .to_polars() ) print(result) # --8<-- [end:quickstart_vector_search_1] - assert result["name"].to_list() == ["Merlin", "Morgana"] + assert result["frame_id"].to_list() == ["2", "4"] # --8<-- [start:quickstart_output_pandas] # Ensure you run `pip install pandas` beforehand result = table.search(query_vector).limit(2).to_pandas() print(result) # --8<-- [end:quickstart_output_pandas] - assert result["name"].to_list() == ["Merlin", "Morgana"] + assert result["frame_id"].to_list() == ["2", "4"] # --8<-- [start:quickstart_curate_with_metadata] curated = ( table.search(query_vector) - .where("stats.magic >= 4") - .select(["name", "role", "description", "_distance"]) + .where("stats.motion >= 4") + .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .to_polars() ) print(curated) # --8<-- [end:quickstart_curate_with_metadata] - assert curated["name"].to_list() == ["Merlin", "Morgana"] + assert curated["frame_id"].to_list() == ["2", "4"] - curated = table.search(query_vector).where("stats.magic < 4").limit(2).to_list() - assert [row["name"] for row in curated] == ["King Arthur", "Sir Lancelot"] + curated = table.search(query_vector).where("stats.motion < 4").limit(2).to_list() + assert [row["frame_id"] for row in curated] == ["1", "3"] @pytest.mark.asyncio async def test_quickstart_async_api(async_db): data = [ { - "id": "2", - "name": "Merlin", - "role": "Wizard", - "description": "Advisor and prophet with deep magical knowledge.", - "stats": {"strength": 2, "magic": 5, "leadership": 4, "wisdom": 5}, - "vector": [0.2, 0.9, 0.4, 0.9], + "frame_id": "2", + "video_id": "clip-1", + "caption": "a two-finger gripper closing on a cup", + "stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2}, + "embedding": [0.2, 0.9, 0.4, 0.9], } ] # --8<-- [start:quickstart_create_table_async] async_table = await async_db.create_table( - "characters", + "frames", data=data, mode="overwrite", ) # --8<-- [end:quickstart_create_table_async] # --8<-- [start:quickstart_vector_search_1_async] - # Search for examples similar to a "wise magical advisor" + # Search for frames similar to "a gripper closing on an object" query_vector = [0.2, 0.8, 0.4, 0.9] # Ensure you run `pip install polars` beforehand async_result = await ( await async_table.search(query_vector) - ).select(["name", "role", "description", "_distance"]).limit(2).to_polars() + ).select(["frame_id", "video_id", "caption", "_distance"]).limit(2).to_polars() print(async_result) # --8<-- [end:quickstart_vector_search_1_async] - assert async_result["name"].to_list() == ["Merlin"] + assert async_result["frame_id"].to_list() == ["2"] def test_quickstart_derived_feature(db): - table = create_characters(db) + table = create_frames(db) # --8<-- [start:quickstart_add_feature] table.add_columns( { - "power_score": "cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)" + "quality_score": "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)" } ) # --8<-- [end:quickstart_add_feature] # --8<-- [start:quickstart_query_feature] - features = table.search().select(["name", "role", "power_score"]).to_polars() + features = table.search().select(["frame_id", "video_id", "quality_score"]).to_polars() print(features) # --8<-- [end:quickstart_query_feature] - assert sorted(zip(features["name"], features["power_score"])) == [ - ("King Arthur", 3.5), - ("Merlin", 4.0), - ("Morgana", 3.75), - ("Sir Lancelot", 3.0), + assert sorted(zip(features["frame_id"], features["quality_score"])) == [ + ("1", 3.5), + ("2", 4.0), + ("3", 3.0), + ("4", 3.75), ] -def description_lengths(table): - rows = table.search().select(["description", "description_length"]).to_list() - return {row["description"]: row["description_length"] for row in rows} +def caption_lengths(table): + rows = table.search().select(["caption", "caption_length"]).to_list() + return {row["caption"]: row["caption_length"] for row in rows} def test_quickstart_computed_column(db_path_factory): - table = create_characters(lancedb.connect(db_path_factory("computed"))) + table = create_frames(lancedb.connect(db_path_factory("computed"))) # --8<-- [start:quickstart_computed_feature] - table.add_columns(computed={"description_length": "length(description)"}) - table.refresh_column("description_length") + table.add_columns(computed={"caption_length": "length(caption)"}) + table.refresh_column("caption_length") # --8<-- [end:quickstart_computed_feature] - lengths = description_lengths(table) + lengths = caption_lengths(table) assert lengths == {text: len(text) for text in lengths} def test_quickstart_computed_column_on_a_deployment(deployment): - table = create_characters(deployment) + table = create_frames(deployment) # --8<-- [start:quickstart_computed_feature_enterprise] - table.add_columns(computed={"description_length": "length(description)"}) - job = table.refresh_column_async("description_length") + table.add_columns(computed={"caption_length": "length(caption)"}) + job = table.refresh_column_async("caption_length") job.wait() # --8<-- [end:quickstart_computed_feature_enterprise] - lengths = description_lengths(table) + lengths = caption_lengths(table) assert len(lengths) == 4 assert lengths == {text: len(text) for text in lengths} with pytest.raises(Exception): - table.refresh_column("description_length") + table.refresh_column("caption_length") def test_quickstart_multimodal(db, tmp_path, monkeypatch): app = tmp_path / "app" (app / "data").mkdir(parents=True) - shutil.copy(IMAGE, app / "data/sir-lancelot.jpg") + shutil.copy(IMAGE, app / "data/sample-frame.jpg") monkeypatch.chdir(app) # --8<-- [start:quickstart_multimodal_bytes] from pathlib import Path - image_bytes = Path("data/sir-lancelot.jpg").read_bytes() + image_bytes = Path("data/sample-frame.jpg").read_bytes() multimodal_table = db.create_table( - "character_images", + "frame_images", data=[ { - "id": "lancelot", - "description": "Portrait of Sir Lancelot", + "frame_id": "thumb-1", + "caption": "Sample frame thumbnail", "image": image_bytes, - "vector": [0.9, 0.1, 0.5, 0.4], + "embedding": [0.9, 0.1, 0.5, 0.4], } ], mode="overwrite", @@ -331,7 +326,7 @@ def test_quickstart_multimodal(db, tmp_path, monkeypatch): def test_quickstart_training(db): - table = create_characters(db) + table = create_frames(db) # --8<-- [start:quickstart_training] import torch @@ -339,15 +334,15 @@ def test_quickstart_training(db): table.add_columns( { - "magic": "cast(stats.magic as float)", - "strength": "cast(stats.strength as float)", + "motion": "cast(stats.motion as float)", + "sharpness": "cast(stats.sharpness as float)", } ) - dataset = Permutation.identity(table).select_columns(["magic", "strength"]) + dataset = Permutation.identity(table).select_columns(["motion", "sharpness"]) dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True) # --8<-- [end:quickstart_training] batches = list(dataloader) assert len(batches) == 1 - assert set(batches[0]) == {"magic", "strength"} + assert set(batches[0]) == {"motion", "sharpness"} assert all(isinstance(value, torch.Tensor) for value in batches[0].values()) - assert sorted(batches[0]["magic"].tolist()) == [1.0, 1.0, 5.0, 5.0] + assert sorted(batches[0]["motion"].tolist()) == [2.0, 3.0, 5.0, 5.0] diff --git a/docs/web-tests/rs/quickstart.rs b/docs/web-tests/rs/quickstart.rs index f6ea7e0f9..b0df4daba 100644 --- a/docs/web-tests/rs/quickstart.rs +++ b/docs/web-tests/rs/quickstart.rs @@ -16,92 +16,88 @@ use lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema}; // Define structs representing the data schema #[derive(Debug, Clone)] struct Stats { - strength: i8, - magic: i8, - leadership: i8, - wisdom: i8, + motion: i8, + sharpness: i8, + exposure: i8, + framing: i8, } #[derive(Debug, Clone)] -struct Character { - id: String, - name: String, - role: String, - description: String, +struct Frame { + frame_id: String, + video_id: String, + caption: String, stats: Stats, - vector: [f32; 4], + embedding: [f32; 4], } -fn characters_schema() -> Arc { +fn frames_schema() -> Arc { Arc::new(Schema::new(vec![ - Field::new("id", DataType::LargeUtf8, false), - Field::new("name", DataType::LargeUtf8, false), - Field::new("role", DataType::LargeUtf8, false), - Field::new("description", DataType::LargeUtf8, false), + Field::new("frame_id", DataType::LargeUtf8, false), + Field::new("video_id", DataType::LargeUtf8, false), + Field::new("caption", DataType::LargeUtf8, false), Field::new( "stats", DataType::Struct(Fields::from(vec![ - Arc::new(Field::new("strength", DataType::Int8, false)), - Arc::new(Field::new("magic", DataType::Int8, false)), - Arc::new(Field::new("leadership", DataType::Int8, false)), - Arc::new(Field::new("wisdom", DataType::Int8, false)), + Arc::new(Field::new("motion", DataType::Int8, false)), + Arc::new(Field::new("sharpness", DataType::Int8, false)), + Arc::new(Field::new("exposure", DataType::Int8, false)), + Arc::new(Field::new("framing", DataType::Int8, false)), ])), false, ), Field::new( - "vector", + "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), ])) } -fn characters_to_reader( +fn frames_to_reader( schema: Arc, - rows: &[Character], + rows: &[Frame], ) -> Box { - let ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.id.as_str())); - let names = LargeStringArray::from_iter_values(rows.iter().map(|row| row.name.as_str())); - let roles = LargeStringArray::from_iter_values(rows.iter().map(|row| row.role.as_str())); - let descriptions = - LargeStringArray::from_iter_values(rows.iter().map(|row| row.description.as_str())); + let frame_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str())); + let video_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str())); + let captions = + LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str())); - let strength = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.strength)); - let magic = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.magic)); - let leadership = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.leadership)); - let wisdom = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.wisdom)); + let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion)); + let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness)); + let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure)); + let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing)); let stats_fields: Vec = vec![ - Arc::new(Field::new("strength", DataType::Int8, false)), - Arc::new(Field::new("magic", DataType::Int8, false)), - Arc::new(Field::new("leadership", DataType::Int8, false)), - Arc::new(Field::new("wisdom", DataType::Int8, false)), + Arc::new(Field::new("motion", DataType::Int8, false)), + Arc::new(Field::new("sharpness", DataType::Int8, false)), + Arc::new(Field::new("exposure", DataType::Int8, false)), + Arc::new(Field::new("framing", DataType::Int8, false)), ]; let stats = StructArray::new( stats_fields.into(), vec![ - Arc::new(strength), - Arc::new(magic), - Arc::new(leadership), - Arc::new(wisdom), + Arc::new(motion), + Arc::new(sharpness), + Arc::new(exposure), + Arc::new(framing), ], None, ); - let vectors = FixedSizeListArray::from_iter_primitive::( + let embeddings = FixedSizeListArray::from_iter_primitive::( rows.iter() - .map(|row| Some(row.vector.iter().copied().map(Some).collect::>())), + .map(|row| Some(row.embedding.iter().copied().map(Some).collect::>())), 4, ); let batch = RecordBatch::try_new( schema.clone(), vec![ - Arc::new(ids), - Arc::new(names), - Arc::new(roles), - Arc::new(descriptions), + Arc::new(frame_ids), + Arc::new(video_ids), + Arc::new(captions), Arc::new(stats), - Arc::new(vectors), + Arc::new(embeddings), ], ) .unwrap(); @@ -121,44 +117,41 @@ async fn main() { // --8<-- [start:quickstart_data] let data = vec![ - Character { - id: "1".to_string(), - name: "King Arthur".to_string(), - role: "King".to_string(), - description: "Leader of Camelot and wielder of Excalibur.".to_string(), + Frame { + frame_id: "1".to_string(), + video_id: "clip-1".to_string(), + caption: "a robot arm reaching toward a cup".to_string(), stats: Stats { - strength: 4, - magic: 1, - leadership: 5, - wisdom: 4, + motion: 3, + sharpness: 4, + exposure: 4, + framing: 3, }, - vector: [0.7, 0.1, 0.9, 0.7], + embedding: [0.7, 0.1, 0.9, 0.7], }, - Character { - id: "2".to_string(), - name: "Merlin".to_string(), - role: "Wizard".to_string(), - description: "Advisor and prophet with deep magical knowledge.".to_string(), + Frame { + frame_id: "2".to_string(), + video_id: "clip-1".to_string(), + caption: "a two-finger gripper closing on a cup".to_string(), stats: Stats { - strength: 2, - magic: 5, - leadership: 4, - wisdom: 5, + motion: 5, + sharpness: 4, + exposure: 5, + framing: 2, }, - vector: [0.2, 0.9, 0.4, 0.9], + embedding: [0.2, 0.9, 0.4, 0.9], }, - Character { - id: "3".to_string(), - name: "Sir Lancelot".to_string(), - role: "Knight".to_string(), - description: "Legendary knight known for courage and combat skill.".to_string(), + Frame { + frame_id: "3".to_string(), + video_id: "clip-2".to_string(), + caption: "a robot arm holding a cup steady".to_string(), stats: Stats { - strength: 5, - magic: 1, - leadership: 3, - wisdom: 3, + motion: 2, + sharpness: 3, + exposure: 3, + framing: 4, }, - vector: [0.9, 0.1, 0.5, 0.4], + embedding: [0.9, 0.1, 0.5, 0.4], }, ]; // --8<-- [end:quickstart_data] @@ -166,9 +159,9 @@ async fn main() { // --8<-- [start:quickstart_create_table] use lancedb::database::CreateTableMode; - let schema = characters_schema(); + let schema = frames_schema(); let table = db - .create_table("characters", characters_to_reader(schema.clone(), &data)) + .create_table("frames", frames_to_reader(schema.clone(), &data)) .mode(CreateTableMode::Overwrite) .execute() .await @@ -177,21 +170,20 @@ async fn main() { assert_eq!(table.count_rows(None).await.unwrap(), 3); // --8<-- [start:quickstart_add_data] - let more_data = vec![Character { - id: "4".to_string(), - name: "Morgana".to_string(), - role: "Sorceress".to_string(), - description: "Powerful sorceress of Avalon.".to_string(), + let more_data = vec![Frame { + frame_id: "4".to_string(), + video_id: "clip-2".to_string(), + caption: "a gripper lowering a cup onto the table".to_string(), stats: Stats { - strength: 2, - magic: 5, - leadership: 4, - wisdom: 4, + motion: 5, + sharpness: 4, + exposure: 4, + framing: 2, }, - vector: [0.3, 0.9, 0.6, 0.8], + embedding: [0.3, 0.9, 0.6, 0.8], }]; table - .add(characters_to_reader(schema.clone(), &more_data)) + .add(frames_to_reader(schema.clone(), &more_data)) .execute() .await .unwrap(); @@ -202,7 +194,7 @@ async fn main() { use lancedb::arrow::IntoPolars; use lancedb::query::{ExecutableQuery, QueryBase, Select}; - // Search for examples similar to a "wise magical advisor" + // Search for frames similar to "a gripper closing on an object" let query_vector = [0.2, 0.8, 0.4, 0.9]; let result = table @@ -210,9 +202,9 @@ async fn main() { .nearest_to(&query_vector) .unwrap() .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "description".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "caption".to_string(), "_distance".to_string(), ])) .limit(2) @@ -224,20 +216,20 @@ async fn main() { .unwrap(); println!("{result:?}"); // --8<-- [end:quickstart_vector_search_1] - let name_col = result.column("name").unwrap().str().unwrap(); - assert_eq!(name_col.get(0).unwrap(), "Merlin"); - assert_eq!(name_col.get(1).unwrap(), "Morgana"); + let frame_id_col = result.column("frame_id").unwrap().str().unwrap(); + assert_eq!(frame_id_col.get(0).unwrap(), "2"); + assert_eq!(frame_id_col.get(1).unwrap(), "4"); // --8<-- [start:quickstart_curate_with_metadata] let curated = table .query() .nearest_to(&query_vector) .unwrap() - .only_if("stats.magic >= 4") + .only_if("stats.motion >= 4") .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "description".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "caption".to_string(), "_distance".to_string(), ])) .limit(2) @@ -249,9 +241,9 @@ async fn main() { .unwrap(); println!("{curated:?}"); // --8<-- [end:quickstart_curate_with_metadata] - let curated_name_col = curated.column("name").unwrap().str().unwrap(); - assert_eq!(curated_name_col.get(0).unwrap(), "Merlin"); - assert_eq!(curated_name_col.get(1).unwrap(), "Morgana"); + let curated_frame_id_col = curated.column("frame_id").unwrap().str().unwrap(); + assert_eq!(curated_frame_id_col.get(0).unwrap(), "2"); + assert_eq!(curated_frame_id_col.get(1).unwrap(), "4"); // --8<-- [start:quickstart_output_array] let result = table @@ -259,9 +251,9 @@ async fn main() { .nearest_to(&query_vector) .unwrap() .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "description".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "caption".to_string(), "_distance".to_string(), ])) .limit(2) @@ -273,15 +265,15 @@ async fn main() { .unwrap(); println!("{result:?}"); // --8<-- [end:quickstart_output_array] - let name_col = result.column("name").unwrap().str().unwrap(); - assert_eq!(name_col.get(0).unwrap(), "Merlin"); + let frame_id_col = result.column("frame_id").unwrap().str().unwrap(); + assert_eq!(frame_id_col.get(0).unwrap(), "2"); // --8<-- [start:quickstart_add_feature] table .add_columns( NewColumnTransform::SqlExpressions(vec![( - "power_score".to_string(), - "cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)" + "quality_score".to_string(), + "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)" .to_string(), )]), None, @@ -294,9 +286,9 @@ async fn main() { let features = table .query() .select(Select::Columns(vec![ - "name".to_string(), - "role".to_string(), - "power_score".to_string(), + "frame_id".to_string(), + "video_id".to_string(), + "quality_score".to_string(), ])) .execute() .await @@ -306,7 +298,7 @@ async fn main() { .unwrap(); println!("{features:?}"); // --8<-- [end:quickstart_query_feature] - assert_eq!(features.column("power_score").unwrap().len(), 4); + assert_eq!(features.column("quality_score").unwrap().len(), 4); // What the quickstart's download step leaves in an application's directory. let app = tempfile::tempdir().unwrap(); @@ -314,7 +306,7 @@ async fn main() { std::fs::copy( std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../web/static/assets/images/quickstart/sir-lancelot.jpg"), - app.path().join("data/sir-lancelot.jpg"), + app.path().join("data/sample-frame.jpg"), ) .unwrap(); std::env::set_current_dir(app.path()).unwrap(); @@ -322,30 +314,30 @@ async fn main() { // --8<-- [start:quickstart_multimodal_bytes] use lancedb::arrow::arrow_array::BinaryArray; - let image_bytes = std::fs::read("data/sir-lancelot.jpg").unwrap(); + let image_bytes = std::fs::read("data/sample-frame.jpg").unwrap(); let image_schema = Arc::new(Schema::new(vec![ - Field::new("id", DataType::LargeUtf8, false), - Field::new("description", DataType::LargeUtf8, false), + Field::new("frame_id", DataType::LargeUtf8, false), + Field::new("caption", DataType::LargeUtf8, false), Field::new("image", DataType::Binary, false), Field::new( - "vector", + "embedding", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4), false, ), ])); - let image_vectors = [[0.9_f32, 0.1, 0.5, 0.4]]; + let image_embeddings = [[0.9_f32, 0.1, 0.5, 0.4]]; let image_batch = RecordBatch::try_new( image_schema.clone(), vec![ - Arc::new(LargeStringArray::from_iter_values(["lancelot"])), + Arc::new(LargeStringArray::from_iter_values(["thumb-1"])), Arc::new(LargeStringArray::from_iter_values([ - "Portrait of Sir Lancelot", + "Sample frame thumbnail", ])), Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])), Arc::new( FixedSizeListArray::from_iter_primitive::( - image_vectors + image_embeddings .iter() .map(|vector| Some(vector.iter().copied().map(Some).collect::>())), 4, @@ -359,7 +351,7 @@ async fn main() { image_schema, )); let multimodal_table = db - .create_table("character_images", image_reader) + .create_table("frame_images", image_reader) .mode(CreateTableMode::Overwrite) .execute() .await diff --git a/docs/web-tests/ts/quickstart.test.ts b/docs/web-tests/ts/quickstart.test.ts index 2c3ee8252..6796e0613 100644 --- a/docs/web-tests/ts/quickstart.test.ts +++ b/docs/web-tests/ts/quickstart.test.ts @@ -90,50 +90,46 @@ async function withDatabase( }); } -async function createCharacters(db: lancedb.Connection) { +async function createFrames(db: lancedb.Connection) { // --8<-- [start:quickstart_data] const data = [ { - id: "1", - name: "King Arthur", - role: "King", - description: "Leader of Camelot and wielder of Excalibur.", - stats: { strength: 4, magic: 1, leadership: 5, wisdom: 4 }, - vector: [0.7, 0.1, 0.9, 0.7], + frame_id: "1", + video_id: "clip-1", + caption: "a robot arm reaching toward a cup", + stats: { motion: 3, sharpness: 4, exposure: 4, framing: 3 }, + embedding: [0.7, 0.1, 0.9, 0.7], }, { - id: "2", - name: "Merlin", - role: "Wizard", - description: "Advisor and prophet with deep magical knowledge.", - stats: { strength: 2, magic: 5, leadership: 4, wisdom: 5 }, - vector: [0.2, 0.9, 0.4, 0.9], + frame_id: "2", + video_id: "clip-1", + caption: "a two-finger gripper closing on a cup", + stats: { motion: 5, sharpness: 4, exposure: 5, framing: 2 }, + embedding: [0.2, 0.9, 0.4, 0.9], }, { - id: "3", - name: "Sir Lancelot", - role: "Knight", - description: "Legendary knight known for courage and combat skill.", - stats: { strength: 5, magic: 1, leadership: 3, wisdom: 3 }, - vector: [0.9, 0.1, 0.5, 0.4], + frame_id: "3", + video_id: "clip-2", + caption: "a robot arm holding a cup steady", + stats: { motion: 2, sharpness: 3, exposure: 3, framing: 4 }, + embedding: [0.9, 0.1, 0.5, 0.4], }, ]; // --8<-- [end:quickstart_data] // --8<-- [start:quickstart_create_table] - const table = await db.createTable("characters", data, { mode: "overwrite" }); + const table = await db.createTable("frames", data, { mode: "overwrite" }); // --8<-- [end:quickstart_create_table] expect(await table.countRows()).toBe(3); // --8<-- [start:quickstart_add_data] await table.add([ { - id: "4", - name: "Morgana", - role: "Sorceress", - description: "Powerful sorceress of Avalon.", - stats: { strength: 2, magic: 5, leadership: 4, wisdom: 4 }, - vector: [0.3, 0.9, 0.6, 0.8], + frame_id: "4", + video_id: "clip-2", + caption: "a gripper lowering a cup onto the table", + stats: { motion: 5, sharpness: 4, exposure: 4, framing: 2 }, + embedding: [0.3, 0.9, 0.6, 0.8], }, ]); // --8<-- [end:quickstart_add_data] @@ -144,44 +140,44 @@ async function createCharacters(db: lancedb.Connection) { describe.each(connections)("quickstart (%s)", (connection) => { test("create, add and search", async () => { await withDatabase(connection, async (db) => { - const table = await createCharacters(db); + const table = await createFrames(db); // --8<-- [start:quickstart_vector_search_1] - // Search for examples similar to a "wise magical advisor" + // Search for frames similar to "a gripper closing on an object" const queryVector = [0.2, 0.8, 0.4, 0.9]; const result = await table .search(queryVector) - .select(["name", "role", "description", "_distance"]) + .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .toArray(); console.table(result); // --8<-- [end:quickstart_vector_search_1] - expect(result.map((row) => row.name)).toEqual(["Merlin", "Morgana"]); + expect(result.map((row) => row.frame_id)).toEqual(["2", "4"]); // --8<-- [start:quickstart_curate_with_metadata] const curated = await table .search(queryVector) - .where("stats.magic >= 4") - .select(["name", "role", "description", "_distance"]) + .where("stats.motion >= 4") + .select(["frame_id", "video_id", "caption", "_distance"]) .limit(2) .toArray(); console.table(curated); // --8<-- [end:quickstart_curate_with_metadata] - expect(curated.map((row) => row.name)).toEqual(["Merlin", "Morgana"]); + expect(curated.map((row) => row.frame_id)).toEqual(["2", "4"]); }); }); test("a derived feature", async () => { await withDatabase(connection, async (db) => { - const table = await createCharacters(db); + const table = await createFrames(db); // --8<-- [start:quickstart_add_feature] await table.addColumns([ { - name: "power_score", + name: "quality_score", valueSql: - "cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)", + "cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)", }, ]); // --8<-- [end:quickstart_add_feature] @@ -189,17 +185,17 @@ describe.each(connections)("quickstart (%s)", (connection) => { // --8<-- [start:quickstart_query_feature] const features = await table .query() - .select(["name", "role", "power_score"]) + .select(["frame_id", "video_id", "quality_score"]) .toArray(); console.table(features); // --8<-- [end:quickstart_query_feature] expect( - features.map((row) => [row.name, row.power_score]).sort(), + features.map((row) => [row.frame_id, row.quality_score]).sort(), ).toEqual([ - ["King Arthur", 3.5], - ["Merlin", 4], - ["Morgana", 3.75], - ["Sir Lancelot", 3], + ["1", 3.5], + ["2", 4], + ["3", 3], + ["4", 3.75], ]); }); }); @@ -208,7 +204,7 @@ describe.each(connections)("quickstart (%s)", (connection) => { await withDatabase(connection, async (db) => { await withTempDirectory(async (app) => { fs.mkdirSync(path.join(app, "data")); - fs.copyFileSync(IMAGE, path.join(app, "data/sir-lancelot.jpg")); + fs.copyFileSync(IMAGE, path.join(app, "data/sample-frame.jpg")); const cwd = process.cwd(); process.chdir(app); try { @@ -216,13 +212,13 @@ describe.each(connections)("quickstart (%s)", (connection) => { const arrow = await import("apache-arrow"); const { readFile } = await import("node:fs/promises"); - const imageBytes = await readFile("data/sir-lancelot.jpg"); + const imageBytes = await readFile("data/sample-frame.jpg"); const imageSchema = new arrow.Schema([ - new arrow.Field("id", new arrow.Utf8()), - new arrow.Field("description", new arrow.Utf8()), + new arrow.Field("frame_id", new arrow.Utf8()), + new arrow.Field("caption", new arrow.Utf8()), new arrow.Field("image", new arrow.Binary()), new arrow.Field( - "vector", + "embedding", new arrow.FixedSizeList( 4, new arrow.Field("item", new arrow.Float32(), true), @@ -232,16 +228,16 @@ describe.each(connections)("quickstart (%s)", (connection) => { const imageData = lancedb.makeArrowTable( [ { - id: "lancelot", - description: "Portrait of Sir Lancelot", + frame_id: "thumb-1", + caption: "Sample frame thumbnail", image: imageBytes, - vector: [0.9, 0.1, 0.5, 0.4], + embedding: [0.9, 0.1, 0.5, 0.4], }, ], { schema: imageSchema }, ); const multimodalTable = await db.createTable( - "character_images", + "frame_images", imageData, { mode: "overwrite" }, ); diff --git a/docs/web/.mintignore b/docs/web/.mintignore index b8da6c17a..79cce2724 100644 --- a/docs/web/.mintignore +++ b/docs/web/.mintignore @@ -1,6 +1,22 @@ # Functions are documented before their release. At release, remove these -# entries, add the pages back to the navigation in docs.json, restore the -# /feature-engineering/functions redirect to /management/function, and publish -# the drafts marked "Draft for the Functions release". +# entries, restore the /feature-engineering/functions redirect to +# /management/function, publish the drafts marked "Draft for the Functions +# release", restore `availability` frontmatter (removed while gated, since +# the comparison table on index.mdx links every page that declares one, +# draft or not) to management/function.mdx and sql/ddl/function.mdx -- each +# currently carries a plain `Enterprise` instead +# -- and re-link curation/chunking.mdx's plain-text `CREATE FUNCTION`/ +# `add_columns` mentions to /management/function and /sql/ddl/function#create +# now that those pages have a route. Chunking stays published ahead of +# Functions shipping, so its examples intentionally do not link to either +# gated page -- only an unrouted page would break. management/function.mdx sql/ddl/function.mdx + +# GRANT/REVOKE currently only covers privileges on Secrets and Functions +# (CREATE SECRET, CREATE FUNCTION, USAGE on a secret or function), which are +# themselves part of the Functions release: see the "Draft for the Functions +# release" block in governance/authorization.mdx#privileges. At release, +# remove this entry, add the page to the navigation in docs.json, and give it +# `availability` frontmatter like the rest of the SQL reference. +sql/ddl/grant.mdx diff --git a/docs/web/architecture.mdx b/docs/web/architecture.mdx deleted file mode 100644 index be6cc84af..000000000 --- a/docs/web/architecture.mdx +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: "Architecture" -sidebarTitle: "Architecture" -description: "How LanceDB Enterprise separates query serving, background work, and storage, and how it compares with LanceDB Embedded." -icon: cubes -keywords: ["architecture", "embedded", "distributed", "object storage", "compute", "deployment"] ---- - -LanceDB Embedded is an open-source library for working with Lance tables. It runs -in your application's process; your data can live on local disk or in object -storage. LanceDB Enterprise is a multimodal lakehouse for data curation, feature -engineering, search, and training data access. LanceDB Enterprise runs LanceDB -Distributed: query execution, indexing and maintenance run on the Enterprise -service, outside your application. Its architecture separates query serving, -read execution, caching, and background work. Both use the open -[Lance](/basics/lance) format. - -Teams can curate datasets, derive features, search multimodal records, and -read the resulting tables into training frameworks. Enterprise separates the -resources that serve shared data from those that build indexes and run -background work, so teams can size them for these different workloads. - -![LanceDB Embedded runs the application and embedded library in one process, using local disk or object storage. Enterprise applications connect to query serving, with separate read execution and caching, indexing and background workers, and durable object storage. Both use the Lance format, but they do not share a storage location automatically.](/static/assets/images/overview/lancedb-architecture.svg) - -The diagram shows the main compute and storage boundaries, not every request -path. The control plane governs the Enterprise service. - -## A shared format, different storage choices {#storage} - -Lance stores table data, versions, and indexes. LanceDB Embedded can read and write tables on -local disk or in object storage. Enterprise keeps durable table data and index -artifacts in object storage, independently of the machines serving requests. -Its caches accelerate reads; they are not the durable source of truth. - -Sharing a format does not mean that an Enterprise deployment automatically -opens an existing LanceDB Embedded database. Plan how to move or connect your data and -configure access for your deployment. - -## LanceDB Embedded: a library inside your application {#embedded} - -With an embedded connection, the LanceDB library plans and executes queries, -builds indexes, and updates tables inside your process. There is no separate -database server to deploy. - -This fits local retrieval applications, notebooks, development, and -single-node data pipelines. Your application controls the compute resources and -when to run [table maintenance](/maintenance/compaction). You also manage access -to the local files or object storage that hold your tables. - -## LanceDB Enterprise: distributed execution for shared workloads {#distributed} - -A LanceDB SDK connects to LanceDB Enterprise, and the service runs operations -with LanceDB Distributed. The service handles -requests across a fleet, with components sized for different kinds of work: - -- **Query serving** receives requests, resolves tables, and plans operations. - Add serving capacity as more applications and users depend on your data. -- **Read execution and caching** use separately provisioned resources. Executors - cache table data to reduce repeated reads from object storage. -- **Indexing and background workers** build indexes and perform maintenance - outside the query request path. Size this work separately from query serving - as your data grows. - -The control plane manages configuration, identity, policy, and cluster -lifecycle. It governs the service rather than executing table queries. -[Authorization](/governance/authorization) lets teams control access to catalog -objects when enabled and configured by the administrator. Deployment settings govern background -[compaction](/maintenance/compaction) and -[cleanup](/maintenance/cleanup), including retention. - -These boundaries support different parts of an AI data workflow. -[SQL curation](/curation) requires a deployment with SQL enabled. -[Feature engineering](/feature-engineering) can produce derived columns and -tables; computed columns and materialized views require a deployment that -enables them. [Geneva](/geneva) runs distributed Python feature backfills while -its capabilities continue to transition to LanceDB APIs. -[Training data loaders](/training/data-loading) read tables into model training -frameworks in both offerings. LanceDB provides data access for training; the -training framework runs the model. - -Size and monitor each tier for your workload. Read the -[Enterprise architecture](/enterprise/architecture) for the component details -and request flows. - -## Application changes for Enterprise {#differences} - -Core operations remain familiar: create a table, add data, and run a search. -With LanceDB Embedded, the application executes those operations. With Enterprise, the SDK -sends requests to the service, and the service manages execution and configured -background maintenance. - -To use Enterprise, configure the cluster endpoint, database URI and credentials, -and make your data available in the Enterprise database. Review SDK methods -that behave differently with LanceDB Distributed, including result retrieval and -background jobs. [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise) -describes these application changes. If you plan to use materialized views, check the -[stable row ID requirements](/basics/limits#schema) before creating source tables. - -## Choose for the workload you need to run {#choosing} - -Choose LanceDB Embedded when you want an embedded library and can manage its resources and -maintenance in your application. - -Choose Enterprise when multiple applications or teams need a shared multimodal -lakehouse for curation, feature engineering, search, and training data access. -It also fits workloads whose query and indexing demand grow at different rates, -or that need configured service-level access controls and background operations. -You can begin with Enterprise. - -[Talk to us about your workload](https://www.lancedb.com/contact) to plan capacity, -deployment options, and the path from your existing data to Enterprise. - -## Where to go next {#next} - - - - Query serving, execution, and background work in detail. - - - Connect an application to your deployment. - - - What a write promises, and what a reader sees. - - - The open format underneath both offerings. - - diff --git a/docs/web/basics/agentic-skills.mdx b/docs/web/basics/agentic-skills.mdx index 96222e27a..b87574dff 100644 --- a/docs/web/basics/agentic-skills.mdx +++ b/docs/web/basics/agentic-skills.mdx @@ -273,7 +273,7 @@ private deployment, or platform-managed operations. The data format and the core table API stay the same, so the pipeline's table and search code carries over: the agent connects to an Enterprise `db://` table, leaves maintenance to the deployment instead of calling `optimize()`, and submits long-running work as -jobs. See [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise). +[jobs](/basics/jobs). ## What agents are good at here {#workflows} diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index c6950b9de..976aac300 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -1,16 +1,128 @@ --- -title: "Lance Catalog" -sidebarTitle: "Lance Catalog" -description: "Organize, find and control access to your data in LanceDB." +title: "LanceDB Catalog" +sidebarTitle: "LanceDB Catalog" +description: "LanceDB Lakehouse objects are organized into a catalog of databases, namespaces and tables -- connect to a database to work with them." icon: sitemap -keywords: ["catalog", "namespace", "hierarchy", "governance", "database", "table", "view"] +keywords: ["catalog", "namespace", "hierarchy", "governance", "database", "table", "view", "connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"] --- +import { + PyConnect, + PyConnectAsync, + PyConnectEnterprisePlaceholders, + PyConnectObjectStorage, + PyConnectObjectStorageAsync, + RsConnect, + TsConnect, + TsConnectEnterprisePlaceholders, + TsConnectObjectStorage, +} from '/snippets/connection.mdx'; + ## Catalog overview {#catalog} A catalog keeps track of named data objects, such as tables and views, so applications can discover and access them. In LanceDB, it organizes those -objects into databases and namespaces. +objects into databases and namespaces -- similar to a catalog in Postgres, +Snowflake, or other database systems. + +## Connecting {#connecting} + +You always run table and query operations within a **database**; cross-database +operations go through SQL instead. The same Python, TypeScript and Rust SDKs +reach a database two ways: + +- **Directly, the common case.** `lancedb.connect(uri)` opens one database in a + single call -- a local directory, an object-storage path, or (with a `db://` + URI) a specific Enterprise database. +- **Through the catalog, for admin and cross-database work.** `connect_catalog(endpoint)` + connects to Enterprise's root catalog, which can list, create and drop + databases across the whole deployment. Its `connect_database(name)` and + `create_database(name)` then return the same kind of database connection + `lancedb.connect()` does. Local filesystem and object-store deployments have + no catalog to connect to -- each is already scoped to one database. + +The table below shows which URI reaches which kind of database directly. + +| URI | Where queries run | +| --- | --- | +| A local path, such as `./data` | Embedded: in your process | +| `s3://`, `gs://` or `az://` | Embedded: in your process, reading object storage | +| `db://` | LanceDB Enterprise: queries run on your cluster | + +### A local directory {#local} + +Embedded in your application, LanceDB reads and writes the tables in a +directory on disk. + + + + {PyConnect} + + + + {PyConnectAsync} + + + + { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } + {TsConnect} + + + + { "use lancedb::connect;\n" } + { "\n" } + {RsConnect} + + + +### Object storage {#object-storage} + +With an object storage URI the library is still embedded: your process runs +every query and reads and writes the bucket directly, with the credentials from +its environment or its storage options. [Configuring storage](/deployment/storage) +covers credentials, endpoints and provider options. + + + + {PyConnectObjectStorage} + + + + {PyConnectObjectStorageAsync} + + + + { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } + {TsConnectObjectStorage} + + + +In Rust, pass the same URI to `connect`. + +### LanceDB Enterprise {#enterprise} + +A `db://` URI connects directly to one database in LanceDB Enterprise, where +your cluster runs queries and background work. Get the database URI, API key, +region and endpoint from your administrator, then replace the placeholders +below. Use your cluster's region in place of `us-east-1`. In application code, +load credentials from environment variables or a secrets manager. + + + + {PyConnectEnterprisePlaceholders} + + + + { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } + {TsConnectEnterprisePlaceholders} + + + +In Rust, enable the crate's `remote` feature; the connection builder then takes +the same settings through `api_key`, `region` and `host_override`. To use OAuth +instead of an API key, see +[Authentication](/enterprise/authentication); for every connection option, see +[Database](/management/database#deployment). ## Databases, namespaces and tables {#objects} @@ -37,7 +149,7 @@ flowchart TD | [Namespace](/management/namespace) | A named group of tables, views or nested namespaces. | | [Table](/management/table) | Data stored as rows and columns. | | [View](/management/view) | A saved query, evaluated when read. Available in Enterprise. | -| [Materialized view](/management/materialized-view) | The stored results of a query, updated by a refresh. | +| [Materialized view](/management/materialized-view) | The stored results of a query, updated by a refresh. Available in Enterprise. | {/* Draft for the Functions release. Add this row to the table above: diff --git a/docs/web/basics/connect.mdx b/docs/web/basics/connect.mdx deleted file mode 100644 index d576b62d8..000000000 --- a/docs/web/basics/connect.mdx +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: "Connect to LanceDB" -sidebarTitle: "Connect" -description: "Use LanceDB Embedded with tables in a local directory or object storage, or connect to LanceDB Enterprise." -icon: plug -keywords: ["connect", "uri", "embedded", "object storage", "s3", "enterprise", "db://"] ---- - -import { - PyConnect, - PyConnectAsync, - PyConnectEnterprisePlaceholders, - PyConnectEnterpriseQuickstart, - PyConnectObjectStorage, - PyConnectObjectStorageAsync, - RsConnect, - TsConnect, - TsConnectEnterprisePlaceholders, - TsConnectEnterpriseQuickstart, - TsConnectObjectStorage, -} from '/snippets/connection.mdx'; - -The URI you pass to `connect` decides where the work runs. LanceDB Embedded -runs in your application's process; your data can live on local disk or in -object storage. LanceDB Enterprise runs LanceDB Distributed: query execution, -indexing and maintenance run on the Enterprise service, outside your -application. The same Python, TypeScript and Rust SDKs open all three kinds; -[Embedded and Enterprise](/basics/offerings) describes how the two offerings differ. - -| URI | Where queries run | -| --- | --- | -| A local path, such as `./data` | LanceDB Embedded: in your process | -| `s3://`, `gs://` or `az://` | LanceDB Embedded: in your process, reading object storage | -| `db://` | LanceDB Enterprise: LanceDB Distributed runs queries on your cluster | - -## A local directory {#local} - -Embedded in your application, LanceDB reads and writes the tables in a -directory on disk. - - - - {PyConnect} - - - - {PyConnectAsync} - - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnect} - - - - { "use lancedb::connect;\n" } - { "\n" } - {RsConnect} - - - -## Object storage {#object-storage} - -With an object storage URI the library is still embedded: your process runs -every query and reads and writes the bucket directly, with the credentials from -its environment or its storage options. [Configuring storage](/deployment/storage) -covers credentials, endpoints and provider options. - - - - {PyConnectObjectStorage} - - - - {PyConnectObjectStorageAsync} - - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnectObjectStorage} - - - -In Rust, pass the same URI to `connect`. - -## LanceDB Enterprise {#enterprise} - -A `db://` URI connects to LanceDB Enterprise, where your cluster runs queries -and background work. Get the database URI, API key, region and endpoint from -your administrator, then replace the placeholders below. Use your cluster's region -in place of `us-east-1`. In application code, load credentials from environment -variables or a secrets manager. - - - - {PyConnectEnterprisePlaceholders} - - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnectEnterprisePlaceholders} - - - -In Rust, enable the crate's `remote` feature; the connection builder then takes -the same settings through `api_key`, `region` and `host_override`. To use OAuth -instead of an API key, see -[Authentication](/enterprise/authentication); for every connection option, see -[Database](/management/database#deployment). - - - - -Set these values in the shell that starts your application. Replace the URI, API -key, region and endpoint with your Enterprise connection settings. In production, a secrets -manager can supply these environment variables for you. - -```shell -export LANCEDB_URI="db://your-database" -export LANCEDB_API_KEY="your-api-key" -export LANCEDB_REGION="us-east-1" -export LANCEDB_HOST_OVERRIDE="https://your-endpoint" -``` - - - - {PyConnectEnterpriseQuickstart} - - - { "import * as lancedb from \"@lancedb/lancedb\";\n\n" } - {TsConnectEnterpriseQuickstart} - - - - diff --git a/docs/web/basics/guarantees.mdx b/docs/web/basics/guarantees.mdx index 2774d749b..42392c5ba 100644 --- a/docs/web/basics/guarantees.mdx +++ b/docs/web/basics/guarantees.mdx @@ -87,5 +87,5 @@ cannot undo `drop_table`. - [Table versioning](/management/table#versioning): inspect and restore history. - [Cleanup](/maintenance/cleanup): configure retention and understand protected versions. - [Jobs](/basics/jobs): distinguish submission, completion and cancellation. -- [Column refresh](/feature-engineering/refresh-column): understand partial progress. -- [Architecture](/architecture): understand storage and background maintenance. +- [Refresh a computed column](/feature-engineering/refresh-column): understand partial progress. +- [Architecture](/#architecture): understand storage and background maintenance. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 20445843e..a15f10fee 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -5,11 +5,8 @@ description: "Track background work from submission to completion." icon: hourglass-half keywords: ["job", "background", "progress", "events", "cancel"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Job handles track operations in LanceDB Embedded and LanceDB Enterprise. Enterprise also - supports listing server jobs, reopening them by ID and reading their events. --- ## Job handles {#convention} @@ -26,6 +23,14 @@ so check its status before waiting or requesting cancellation. See the operation's API reference for when the method returns. +```python +job = tbl.create_index_async("vector", replace=True) + +print(job.id) +print(job.job_type) +print(job.status()) +``` + ## Submit and wait for a job {#waiting} 1. **Submit the operation.** Keep the returned job handle. For an Enterprise @@ -39,6 +44,22 @@ In Python, `job.status()` reports the current state and `job.wait()` waits for completion, raising if the job fails or is cancelled. If `job.wait()` times out, the client stops waiting. The timeout does not cancel the server job. +```python +from datetime import timedelta +from lancedb.exceptions import JobFailedError, JobCancelledError + +job = tbl.create_index_async("vector", replace=True) + +try: + result = job.wait(timeout=timedelta(minutes=10)) +except JobFailedError: + print(f"job failed: {job.failure}") +except JobCancelledError: + print("job was cancelled") +except TimeoutError: + print(f"still running: {job.status()}") +``` + @@ -54,6 +75,24 @@ The timeout does not cancel the server job. Reopening a job retrieves the existing operation; it does not restart failed work. Treat the ID as an opaque identifier and pass it unchanged to the jobs API. +```python +job = db.open_job(job_id) # raises JobNotFoundError if unknown +job.refresh() # pull the latest status from the server +print(job.status()) + +events = job.events(limit=100) +print(events.to_pylist()) + +job.cancel() +``` + +List jobs on a connection, paging through the results: + +```python +for info in db.list_jobs(page_limit=50): + print(info.job_id, info.job_type, info.state) +``` + Event responses have [row limits](/basics/limits#jobs). An explicit limit can request more than the default, but it does not guarantee a complete event history. @@ -97,7 +136,7 @@ workers. That placement does not change the handle's query-backed identity. ## Learn more {#next} - [Build and repair indexes](/indexing/reindexing): submit index work. -- [Column refresh](/feature-engineering/refresh-column): populate derived values. +- [Refresh a computed column](/feature-engineering/refresh-column): populate derived values. - [Background jobs](/maintenance/background-jobs): understand Enterprise maintenance. - [SQL job commands](/sql/ddl/job): list jobs and inspect errors. - [SDKs](/basics/sdk): find the job API for your client. diff --git a/docs/web/basics/lakehouse.mdx b/docs/web/basics/lakehouse.mdx deleted file mode 100644 index 9ecf6800a..000000000 --- a/docs/web/basics/lakehouse.mdx +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: "LanceDB Lakehouse" -sidebarTitle: "LanceDB Lakehouse" -description: "Bring multimodal data, search and feature engineering together for AI workloads." -icon: layer-group -keywords: ["lakehouse", "multimodal", "search", "compute", "training", "feature engineering"] ---- - -## Multimodal storage and processing {#multimodal} - -LanceDB brings storage, search and data processing together for AI workloads. -You can store multimodal data, derive features, search your records and prepare -training datasets using tables built on the open [Lance format](/basics/lance). - -The format provides the storage foundation. The [catalog](/basics/catalog) -organizes your tables. LanceDB provides the tools to work with that data. - -## Example: a video search workflow {#capabilities} - -Consider a team building a video search application: - - - - - -1. **Ingest the clips.** Store video clips with metadata such as timestamps, - source and labels. -2. **Add features.** Generate captions and embeddings with your models, and - store them alongside each clip. -3. **Use the dataset.** Search for relevant clips using embeddings and metadata - filters, or select a dataset to read into a training framework. - -```mermaid -flowchart TD - clips["Video clips and metadata"] --> table["Store in a Lance table"] - table --> features["Add captions and embeddings"] - features --> search["Search for relevant clips"] - features --> training["Select data for training"] -``` - -The clips, metadata and derived features stay associated in the same table, -so retrieval and training workflows can use the same dataset. Your training -framework runs the model; LanceDB provides access to the training data. - -## Shared compute and maintenance in Enterprise {#where} - -LanceDB Embedded runs as an embedded library in your application. LanceDB Enterprise -provides shared infrastructure for applications and teams working with larger -multimodal workloads. - - - -- **Scale resources for different workloads.** Provision query serving and - background workers independently as search traffic and indexing demand grow. -- **Share data across teams.** Give applications access to shared tables, with - Enterprise permissions controlling who can read or change them. -- **Manage ongoing maintenance.** Configure background indexing, compaction - and cleanup as your datasets grow. - -See [Architecture](/architecture) for how Enterprise separates storage, query -serving and background work. - -## Learn more {#next} - -- [Data ingestion](/ingestion): load and update your data. -- [Search](/search): retrieve records with vector, full-text and hybrid search. -- [Feature engineering](/feature-engineering): derive columns and datasets. -- [Training data access](/training/data-loading): read datasets into training workflows. -- [Enterprise](/enterprise): explore deployment options for shared workloads. - -{/* -Draft for the Functions release. Add this item to the list above, after -Feature engineering: -- [Functions](/management/function): run Python to compute column values. -*/} diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 13b7755be..883992afd 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -2,7 +2,7 @@ title: "Lance format" sidebarTitle: "Lance Format" description: "The open format for multimodal data behind LanceDB." -icon: "/static/assets/logo/lance-logo-gray.svg" +icon: "/static/assets/logo/lance-logo-gray.png" keywords: ["lance", "format", "multimodal", "versioning", "column evolution"] --- @@ -42,4 +42,4 @@ those fields together. - [Lance format specification](https://lance.org/format): how the format works. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. -- [Architecture](/architecture): how LanceDB Embedded and LanceDB Enterprise build on Lance. +- [Architecture](/#architecture): how LanceDB Embedded and Enterprise build on Lance. diff --git a/docs/web/basics/limits.mdx b/docs/web/basics/limits.mdx index 0d4f1b028..c4af28c45 100644 --- a/docs/web/basics/limits.mdx +++ b/docs/web/basics/limits.mdx @@ -38,9 +38,9 @@ See [SQL job commands](/sql/ddl/job#errors) and Data-type and index constraints belong to the operation you choose. Check [Data types](/sql/data-types) and [Vector indexes](/indexing/vector-index) -before choosing a schema or index. For materialized views, check -[stable row ID requirements](/feature-engineering/materialized-views#stable-row-ids) -before creating source tables. +before choosing a schema or index. For materialized views, confirm your +source table meets your deployment's requirements with your administrator +before creating one over it. ## Configurable limits {#not-quotas} diff --git a/docs/web/basics/offerings.mdx b/docs/web/basics/offerings.mdx deleted file mode 100644 index a2df61b21..000000000 --- a/docs/web/basics/offerings.mdx +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: "LanceDB Embedded or Enterprise?" -sidebarTitle: "Embedded and Enterprise" -description: "Start with an embedded library, or use the LanceDB Enterprise multimodal lakehouse for shared AI workloads." -icon: compass -keywords: ["oss", "enterprise", "embedded", "deployment", "availability", "comparison"] ---- - -LanceDB gives you two ways to work with multimodal data, both built on the open -[Lance](/basics/lance) format. - -**LanceDB Embedded (open source)** is a library that runs in your -application's process; your data can live on local disk or in object storage. -You control the application, -its resources, and table maintenance, without a separate database service. -[Try the quickstart](/quickstart) to create a table and run your first search. - -**LanceDB Enterprise** is a multimodal lakehouse for data curation, feature -engineering, search, and training data access. It adds query-serving capacity, -data caching, and background operations for teams working with shared -multimodal datasets. LanceDB Enterprise runs LanceDB Distributed: query -execution, indexing and maintenance run on the Enterprise service, outside your -application. -[Connect to Enterprise](/basics/connect#enterprise) when your cluster is ready. - - - - -## Why choose Enterprise? {#why-enterprise} - -### Serve growing workloads {#serving} - -Add query-serving capacity as more applications and users depend on your data. -Enterprise spreads query traffic across a fleet and caches frequently read -table data near compute, reducing repeated reads from object storage. Query -serving and background work use separate resources, so you can size each for -your workload. See [Enterprise architecture](/enterprise/architecture). - -### Reduce operational work {#operations} - -Let the service handle routine table maintenance instead of scheduling it in -application code. Enterprise handles background [compaction](/maintenance/compaction) and can -[clean up old table versions](/maintenance/cleanup) according to your retention -policy. Configure these maintenance tasks for your Enterprise cluster so each -application does not have to schedule them. - -### Fit your deployment requirements {#deployment} - -Choose a managed deployment or bring LanceDB into your own cloud account. -Enterprise integrates with OpenTelemetry for metrics and traces, helping your -team monitor the service alongside your applications. Talk to us about your -cloud, networking, and operational requirements to plan the right deployment. -The [Enterprise overview](/enterprise) explains the available options. - -### Connect your data workflows {#workflows} - -Use the same tables for retrieval, dataset preparation, and training data access. -With its [SQL endpoint](/basics/sql) enabled, Enterprise supports analytical -[curation](/curation), including joins, grouping, and sampling. -[Feature engineering](/feature-engineering) adds derived columns and tables; -computed columns and materialized views require the corresponding features to -be enabled for your Enterprise cluster. -[Geneva](/geneva) runs Python feature backfills as distributed jobs. -[Training data loaders](/training/data-loading), available in both offerings, -read the resulting datasets for model training. - -## Plan your Enterprise deployment {#get-started} - -[Talk to us about your workload](https://www.lancedb.com/contact) to discuss your -data, query traffic, pipelines, and deployment requirements. - -For a closer look at how the service runs, read the -[Enterprise architecture](/enterprise/architecture). diff --git a/docs/web/basics/query.mdx b/docs/web/basics/query.mdx deleted file mode 100644 index aa8e9b9df..000000000 --- a/docs/web/basics/query.mdx +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: "Queries" -sidebarTitle: "Query" -description: "Choose how to query your data and read the results." -icon: magnifying-glass -keywords: ["query", "search", "SQL", "async", "streaming", "results"] ---- - -## Querying tables {#queries} - -A query selects data from your tables. You can filter rows, choose columns, -search for similar content or combine those operations. For example, a video -application might find clips similar to a sample and return only those recorded -in the last month. - -## SDK searches and SQL queries {#searches} - -| Interface | When to use it | -| --- | --- | -| **SDK query builders** | Build vector, full-text and hybrid searches, apply filters and choose the fields to return. Available in LanceDB Embedded and LanceDB Enterprise. | -| **Enterprise SQL** | Write SQL queries for filtering, aggregation, joins and other data curation tasks. Connect through Python or a Flight SQL client. | - -Both interfaces work with LanceDB tables. Choose the one that supports your -operation and fits your application. See [SQL](/basics/sql) for connection -instructions and SQL search support, and [Search](/search) for the query builders. - -## Collect or stream results {#results} - -- **Collect the results** when you want a list, Arrow table or DataFrame that - fits in memory. Use a result limit and select only the columns you need. -- **Read batches** when you want to process a large result incrementally. - Reading batches avoids loading the entire result into application memory. - It does not guarantee that the query can return its first batch immediately. - -### Asynchronous clients {#async-client} - -An async client lets your application do other work while a request is waiting. -That is separate from whether you collect results or read them in batches. -Python offers synchronous and asynchronous clients; TypeScript uses async APIs. -Check the SDK reference for the methods available in your client. - -### Query handles and background jobs {#jobs} - -An Enterprise SQL query handle lets you inspect query execution and request -cancellation. Background operations such as index builds return a -[job](/basics/jobs) handle instead. Use the API for the returned handle to -check status and retrieve results. - -## Learn more {#next} - -- [Quickstart](/quickstart): run a complete create, insert and search example. -- [Search](/search): choose vector, full-text or hybrid retrieval. -- [Filtering](/search/filtering): narrow results with predicates. -- [SQL](/basics/sql): connect a client and run SQL queries. -- [SDKs](/basics/sdk): choose a language and find its API reference. diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index 3144c11cf..1d9312f77 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -4,12 +4,6 @@ sidebarTitle: "SDKs" description: "Choose a LanceDB SDK and find the API reference for your language." icon: code-compare keywords: ["python", "typescript", "rust", "java", "sdk", "rest", "api reference"] -availability: - oss: available - enterprise: available - summary: >- - Python, TypeScript and Rust support both LanceDB Embedded and LanceDB Enterprise. - Java provides a client for the Enterprise REST API. --- Use a LanceDB SDK to create tables, add data, build indexes and run searches @@ -21,16 +15,15 @@ run on the Enterprise service, outside your application. The [quickstart](/quickstart) includes installation instructions and complete examples in all three languages. For connection settings, see -[Connect to LanceDB](/basics/connect). +[Connect to LanceDB](/basics/catalog). ## Official SDKs {#supported-sdks} -| SDK | Use it with | API reference | -| --- | --- | --- | -| Python | Python applications, notebooks, pandas and PyArrow | [Python reference](https://lancedb.github.io/lancedb/python/python/) | -| TypeScript | Node.js and TypeScript applications | [TypeScript reference](https://lancedb.github.io/lancedb/js/) | -| Rust | Rust applications using the native library | [Rust reference](https://docs.rs/lancedb/latest/lancedb/index.html) | -| Java | Applications using the Enterprise REST API | [Java reference](https://lancedb.github.io/lancedb/java/java/) | +| SDK | API reference | +| --- | --- | +| Python | [Python reference](https://lancedb.github.io/lancedb/python/python/) | +| TypeScript | [TypeScript reference](https://lancedb.github.io/lancedb/js/) | +| Rust | [Rust reference](https://docs.rs/lancedb/latest/lancedb/index.html) | Guides show the available language examples together. Use the API reference for method signatures and options; SDKs do not expose every feature through the same @@ -41,12 +34,35 @@ For SQL joins, aggregations and window functions, use languages can use a Flight SQL client. TypeScript's table query API does not provide a SQL execution method. -## REST API {#rest} +## Lance Namespace SDKs {#lance-namespace-sdks} -LanceDB Enterprise also exposes an HTTP API for catalog and table operations. -Use it when integrating a language or tool without a LanceDB SDK. The -[REST API reference](/api-reference/rest) describes its endpoints and request -formats. For SQL queries, connect through [Flight SQL](/basics/sql). +LanceDB Enterprise's catalog and table operations follow +[Lance Namespace](https://lance.org/format/namespace), an open specification +for describing access to tables in a multimodal lakehouse, including its REST +Namespace Spec. LanceDB Enterprise exposes this as an HTTP API for catalog and +table operations -- the [REST API reference](/api-reference/rest) describes +its endpoints and request formats. Use it when integrating a language or tool +without a LanceDB SDK; for SQL queries, connect through +[Flight SQL](/basics/sql) instead. Any client that implements a Lance +Namespace REST client can integrate with LanceDB this way, not only the +official SDKs above. + +| Language | Package | Used by | +| --- | --- | --- | +| Java | `org.lance:lance-namespace-core` | Spark, Flink, Kafka, Trino, Presto; also LanceDB's Java client | +| Python | `lance-namespace` | Core interface and connect functionality | +| Rust | `lance-namespace` | Core interface, in [lance-format/lance](https://github.com/lance-format/lance) | + +LanceDB's Java client builds on this Lance Namespace Java core: table creation, +listing and most other catalog operations go through the generated +`LanceNamespace` interface talking to Enterprise's REST Namespace endpoint. +The [real time engine](/tables/realtime-engine) is the one area with its own, +LanceDB-specific Java client on top, since RTE's LSM write path is not part of +the Lance Namespace specification. + +See [lance.org/format/namespace](https://lance.org/format/namespace) for the +full spec and its other catalog implementations (Directory, Apache Polaris, +Unity Catalog, Apache Hive Metastore, Apache Iceberg REST Catalog, and more). ## Community SDKs {#community-sdks} @@ -61,66 +77,15 @@ features, installation instructions and releases before choosing one. | R | [lancedb](https://github.com/CathalByrneGit/lancedb) | | Flutter | [flutter_lancedb](https://github.com/Alexcn/flutter_lancedb) | -## Python multiprocessing {#multiprocessing} - - -Use `spawn` when starting Python worker processes with `multiprocessing`. -LanceDB uses threads internally, and forking a process with active threads can -cause deadlocks. Create a connection inside each worker instead of sharing an -open connection from the parent process. - - -For PyTorch worker setup and connection factories, see -[PyTorch integration](/training/torch). - -## Moving to LanceDB Enterprise {#moving-to-enterprise} - -The core table workflow stays familiar: connect, create or open a table, write -records, and query them. Enterprise runs those operations with LanceDB -Distributed and manages background maintenance. - -- **Configure the connection.** Replace the local path with your database URI, - and supply the endpoint, region and credentials provided by your administrator. - [Connect to Enterprise](/basics/connect#enterprise) shows these settings. -- **Retrieve query results.** Python tables on Enterprise do not support whole-table - `to_arrow()` or `to_pandas()` calls. Use a query and select the columns and - number of rows you need, for example `table.search().limit(10).to_arrow()`. -- **Handle table listings and namespaces.** Enterprise table listings are paginated. - Use the namespace and pagination options described in - [Namespaces](/management/namespace). -- **Use server-side jobs.** Index builds and feature refreshes can run as - [jobs](/basics/jobs). Each operation's guide explains how to submit work and - track completion. -- **Let Enterprise manage maintenance.** Use - [background maintenance](/maintenance/background-jobs) rather than calling - the embedded table's `optimize()` method. - -{/* Draft for the remote option validation release. -- **Remove local storage and cache settings.** `db://` connections reject local - sessions, table cache settings, and per-table storage and write options. Omit - these options so Enterprise manages storage and caching. Connection-level - storage options supported by your Enterprise deployment remain available. -*/} - -For SQL connection details, see [SQL](/basics/sql). For the operating model and -deployment options, see [LanceDB Enterprise](/enterprise). - -## Shared data across languages {#invariants} - -LanceDB uses Arrow schemas across its SDKs. A fixed-size vector column stores -vectors of a consistent dimension; the [data types reference](/sql/data-types) -describes the supported element types and other column types. - -Applications in different languages can work with the same tables. Connect to -the same database and namespace, use the appropriate credentials, and account -for [read consistency](/tables/consistency) when another process writes data. - ## Related guides {#next} Query Enterprise tables with SQL from Python or a Flight SQL client. + + Use LanceDB tables in a DataLoader, including multiple worker processes. + Use the LanceDB plugin to help a coding agent work with your data. diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index ce34237b5..590e3989e 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -4,11 +4,6 @@ sidebarTitle: "SQL" description: "Query LanceDB Enterprise with SQL from Python or an Arrow Flight SQL client." icon: table-list keywords: ["sql", "flight sql", "datafusion", "reference", "dialect"] -availability: - oss: unavailable - enterprise: available - summary: >- - Enterprise supports SQL through Arrow Flight SQL. Use the SDK table APIs for LanceDB Embedded tables. See [Connection settings](#sql-is-remote) to connect. --- Use SQL in LanceDB Enterprise to filter records, join tables, calculate @@ -16,26 +11,42 @@ aggregates, and prepare datasets. SQL queries work with the same Lance tables you create and update through the SDKs, without exporting the data to another system. -You can run SQL through the Python SDK or an Arrow Flight SQL client. This -guide covers connection settings, a first query, and how SQL fits alongside -the SDK table APIs. +This guide covers the two ways to run SQL, connection settings, a first query, +parameterized queries, and how to read and manage the results. -## Connect a SQL client {#flight-sql} +## Access LanceDB with SQL {#access} -Enterprise exposes an -[Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) -endpoint. A compatible client sends SQL statements to this endpoint and -receives results as Arrow record batches. +There are two ways to run SQL against LanceDB Enterprise, both against the +same [Arrow Flight SQL](https://arrow.apache.org/docs/format/FlightSql.html) +endpoint, returning results as Arrow record batches: -- **Python:** use `execute_query()` on an Enterprise connection, as shown below. -- **TypeScript:** use a separate Flight SQL client. The LanceDB TypeScript SDK - does not expose a SQL execution method. -- **Other languages and tools:** use a Flight SQL client or a tool with Flight - SQL integration. A LanceDB-specific SDK is not required to submit SQL. +1. **`db.execute_query()`** on the Python SDK's Enterprise connection, shown + below. This is LanceDB's native SQL execution method, and we recommend it + for the best performance -- see [Adaptive query execution](#adaptive). +2. **An Arrow Flight SQL client.** Use this from TypeScript and other + languages, whose LanceDB SDKs do not expose a SQL execution method, or from + any tool with its own Flight SQL integration. A LanceDB-specific SDK is not + required to submit SQL. The [SQL reference](/sql#connecting) shows a query from Python. See [SDKs](/basics/sdk) for the LanceDB language clients. +### Adaptive query execution {#adaptive} + +A standard Flight SQL client calls `GetFlightInfo` to plan a query and then +`DoGet` to fetch rows -- two round trips every time, even when the server +could stream results back immediately. + +`execute_query()` skips that extra round trip when it can. It calls `DoGet` +directly for a query with no parameters, or `DoExchange` when +[binding parameters](#parameters), and sends a +`lancedb-sql-protocol: adaptive-v1` header. The server decides per query +whether to stream results on that same call or defer execution and return a +poll ticket; when it defers, `execute_query()` follows up with +`PollFlightInfo` automatically, with no extra code on your side. A generic +Flight SQL client does not send that header, so it always takes the slower +`GetFlightInfo` path. + ### Connection settings {#sql-is-remote} Get the following values from your Enterprise administrator: @@ -49,7 +60,7 @@ The Flight SQL endpoint must be enabled and reachable from your client. Pass it explicitly as `sql_host_override` in Python, as in the example below. The API and SQL endpoints may use different hosts or ports. -See [Connect to Enterprise](/basics/connect#enterprise) for other connection options. +See [Connect to Enterprise](/basics/catalog#enterprise) for other connection options. SQL runs in Enterprise. Connections to a local directory or an object-storage bucket use LanceDB Embedded and cannot execute SQL statements. Use @@ -59,10 +70,11 @@ SDK table operations to query those tables. Install the SDK with `pip install lancedb`. Replace the connection placeholders with your Enterprise settings, including the region and both endpoint URLs. -This example reads an existing table named `my_docs` with `id` and `text` -columns. Change the query to match your table. +This example reads an existing `frames` table, with a `video_id` and a +`caption` column describing each frame. Change the query to match your table. -```python + +```python Python icon="python" import lancedb db = lancedb.connect( @@ -73,21 +85,77 @@ db = lancedb.connect( sql_host_override="https://your-sql-endpoint:443", ) -reader = db.execute_query("SELECT id, text FROM my_docs LIMIT 10") +reader = db.execute_query("SELECT frame_id, video_id, caption FROM frames LIMIT 10") table = reader.read_all() print(table.to_pylist()) ``` + In application code, load credentials from environment variables or a secrets -manager. The [connection guide](/basics/connect#enterprise) shows that setup. +manager. The [connection guide](/basics/catalog#enterprise) shows that setup. -`execute_query()` returns a blocking Arrow reader when results start arriving. -The server can stream rows on the first call or return result tickets that the -SDK follows automatically, with the same behavior for parameterized queries. -The example uses `read_all()` to collect the small result in memory. For larger -results, consume the reader in batches. To submit a query and check its status -separately, use `execute_query_async()`. See [Queries](/basics/query) for query -handles, streaming, and cancellation. +`execute_query()` returns a blocking Arrow reader; see +[Adaptive query execution](#adaptive) for how it starts streaming. The example +above uses `read_all()` to collect the small result in memory. For larger +results, or to track and cancel a running query, see +[Read and manage results](#results). To submit a query and check its status +separately, use `execute_query_async()`. + +## Parameters in SQL queries {#parameters} + +Pass a `parameters` argument to bind values into a query, instead of +formatting them into the SQL string: + +```python +import numpy as np + +reader = db.execute_query( + "SELECT id FROM docs ORDER BY distance(vector, $1) LIMIT $2", + parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10], +) +``` + +Values travel as Arrow, not interpolated SQL text, so a vector binds as a +fixed-size list with no manual formatting and no injection risk. Reference a +parameter with `$1`, `$2`, ... for positional binding, or `$name` for named +binding: + +- A list or tuple binds positionally, in order, to `$1`, `$2`, ... +- A dict binds by key to `$name`. +- A one-row `pyarrow.RecordBatch` or `Table` binds its columns, by name and by + position. +- A 1-D NumPy or Arrow array becomes a single fixed-size-list value -- use + this form for a vector argument, as shown above. + + +`parameters` is a LanceDB-specific mechanism, separate from the Flight SQL +protocol's `PREPARE`/bind step, which +[a deployment does not implement](/sql/prepared-statements#parameters). Bind +values with `parameters` from the Python SDK; a generic Flight SQL client has +no equivalent. + + +## Read and manage results {#results} + +- **Collect the results** when you want a list, Arrow table or DataFrame that + fits in memory. Use a result limit and select only the columns you need. +- **Read batches** when you want to process a large result incrementally. + Reading batches avoids loading the entire result into application memory. + It does not guarantee that the query can return its first batch immediately. + +### Asynchronous clients {#async-client} + +An async client lets your application do other work while a request is +waiting. That is separate from whether you collect results or read them in +batches. Python offers synchronous and asynchronous clients; TypeScript uses +async APIs. Check the SDK reference for the methods available in your client. + +### Query handles and background jobs {#jobs} + +An Enterprise SQL query handle lets you inspect query execution and request +cancellation. Background operations such as index builds return a +[job](/basics/jobs) handle instead. Use the API for the returned handle to +check status and retrieve results. ## Choose SQL or SDK table operations {#choosing} @@ -100,6 +168,14 @@ You can combine them. For example, create and populate a table with an SDK, then query it with SQL to prepare a training dataset. In Python, both workflows can use the same Enterprise connection. +Both interfaces work with the same Lance tables, through the same Arrow +schema. Applications in different languages can work with the same tables: +connect to the same database and namespace, use the appropriate credentials, +and account for [read consistency](/tables/consistency) when another process +writes data. A fixed-size vector column stores vectors of a consistent +dimension; see the [data types reference](/sql/data-types) for the supported +element types and other column types. + ### Common SQL operations {#sdk-parity} Several tasks are available through both interfaces, but the methods and SQL @@ -152,8 +228,14 @@ and data types. For SDK methods and their arguments, use the ## Next steps {#next} - - Read results, track long-running queries, and cancel work. + + Run a complete create, insert and search example. + + + Choose vector, full-text or hybrid retrieval. + + + Narrow results with predicates. Compare language clients and find their API references. diff --git a/docs/web/curation/aggregate.mdx b/docs/web/curation/aggregate.mdx index b6d02d7fb..4fbca58f4 100644 --- a/docs/web/curation/aggregate.mdx +++ b/docs/web/curation/aggregate.mdx @@ -5,10 +5,8 @@ description: "Measure coverage, missing values and class balance before selectin icon: chart-column keywords: ["aggregate", "group by", "class balance", "count", "profiling", "distinct"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL aggregation. --- Use SQL aggregates to summarize a dataset: count records, find missing values, diff --git a/docs/web/curation/changes.mdx b/docs/web/curation/changes.mdx new file mode 100644 index 000000000..28f98f784 --- /dev/null +++ b/docs/web/curation/changes.mdx @@ -0,0 +1,93 @@ +--- +title: "Scope curation to what changed" +sidebarTitle: "Changes" +description: "Process only the rows added since your last curation run, instead of rescanning the whole table." +icon: clock-rotate-left +keywords: ["changes", "incremental", "cdc", "version", "append-only"] +availability: + embedded: unavailable + enterprise: available +--- + +A curation task you run repeatedly -- chunking, deduplication, profiling -- +does not need to rescan rows it already processed. `CHANGES` reads only the +rows appended to a table since an earlier +[version](/management/table#versioning), so a recurring job can scope itself +to what is new. + +## Example data {#example-data} + +`curation_batches` gets a batch of new documents appended periodically, with +no updates or deletes between appends: + +```sql +CREATE TABLE curation_batches (doc_id BIGINT, source VARCHAR, text VARCHAR); +INSERT INTO curation_batches VALUES + (1, 'web', 'A cat on a chair'), + (2, 'web', 'A dog in a field'); +-- note the version after this insert, for example 5 +INSERT INTO curation_batches VALUES + (3, 'books', 'A bird in a tree'), + (4, 'books', 'A cat by a window'); +-- the table is now at a later version, for example 7 +``` + +## Read only what is new {#read-new} + +`CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5)` reads the rows +appended after version 5 -- documents 3 and 4 -- without rescanning 1 and 2: + +```sql +SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) +``` + +Record the table's version after each curation run, then start the next +run's `CHANGES` from it. See [Versioning](/management/table#versioning) for +the APIs that read a table's current version. + +## Chain it into a curation task {#chain} + +`CHANGES` is a relation, like any other table reference, so it composes with +the rest of this page: chunk, dedupe, or join only the new rows, instead of +the whole table. Materializing the result keeps a running, append-only table +of work already done: + +```sql +INSERT INTO curated_batches +SELECT doc_id, source, text +FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) +WHERE source = 'books' +``` + +A [chunker Function](/curation/chunking) or a [`dedupe`](/sql/dql/dedupe) +call works the same way: put the `CHANGES` relation where the source table +would otherwise go, and only the new rows flow through it. + +## Strictly append-only {#strict} + +The clause is named for what it requires, not just what it does. If anything +other than a pure append happened to the table between the starting version +and the current one -- an update, a delete, a merge -- the query is refused +rather than silently returning an incomplete or wrong result: + +```sql +-- refused if any row in curation_batches was updated or deleted after version 5 +SELECT * FROM curation_batches CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 5) +``` + +When that happens, either re-run from a later starting version that is +itself after the non-append write, or read the table in full instead of +incrementally for that run. See +[Changes since a version](/sql/dql/changes#strict) for the complete set of +refused forms. + +## What to read next {#next} + + + + The full SQL syntax, placement rules, and unsupported forms. + + + How table versions work, and how to find one to start from. + + diff --git a/docs/web/curation/chunking.mdx b/docs/web/curation/chunking.mdx new file mode 100644 index 000000000..f4c0197b7 --- /dev/null +++ b/docs/web/curation/chunking.mdx @@ -0,0 +1,210 @@ +--- +title: "Chunk records into multiple rows" +sidebarTitle: "Chunking" +description: "Expand one source row into many derived rows -- documents into passages, videos into clips, images into tiles." +icon: diagram-subtask +keywords: ["chunking", "function", "udf", "lateral", "unnest", "1:N", "passages", "clips", "video", "frames"] +availability: + embedded: unavailable + enterprise: available +--- + +Every other curation task on this page keeps the row count the same or +smaller: profiling, sampling, joining, deduplicating. Chunking goes the other +way -- one source row becomes many derived rows, each carrying its parent's +columns along with it. Use it to split a document into passages for +embedding, a video into clips, or an image into tiles. + +## Define a chunking Function {#function} + +A Function that returns a `list` produces more than one value per input row. +A chunker is a Function whose output is a list -- of structs, of strings, of +anything -- registered like any other Function. See +[Create a Function](/curation/create-function) for CPU, GPU and remote-service +Functions, and scalar versus batch calling, if you have not registered one +before. + +A function that splits text into fixed-size passages turns a `documents` +table into one row per passage: + +**Source: `documents`** + +| doc_id | title | text | +| --- | --- | --- | +| 1 | "Intro to AI" | "Machine learning is a method of..." (long text) | + + +```python Python icon="python" +import pyarrow as pa +from lancedb.functions import udf + +@udf( + output_schema=pa.list_( + pa.struct([ + pa.field("chunk_index", pa.int64(), nullable=False), + pa.field("chunk_text", pa.utf8(), nullable=False), + ]) + ), +) +def split_into_passages(text: str) -> list[dict]: + size = 200 + return [ + {"chunk_index": i, "chunk_text": text[i : i + size]} + for i in range(0, len(text), size) + ] + +version = db.create_function_async(split_into_passages).wait() +``` + + +Registration details, environment and dependency declarations, and how a +version stays immutable once rows are filled from it, are the same for a +chunker as for any other Function. The same function can be registered from +SQL with `CREATE FUNCTION`: + + +```sql SQL +CREATE FUNCTION split_into_passages(text utf8) +RETURNS list> +LANGUAGE python +AS 'def split_into_passages(text): size = 200; return [{"chunk_index": i, "chunk_text": text[i:i+size]} for i in range(0, len(text), size)]' +``` + + +## Explode it in a query {#explode} + +Call the function in the `FROM` clause, after the source table, with an +alias: a Function there yields one row per element of the list it returns, +with every other column repeated. Reference the function's output fields +through the alias: + + +```python Python icon="python" +reader = db.execute_query(""" + SELECT doc_id, title, p.chunk_index, p.chunk_text + FROM documents, split_into_passages(text) AS p +""") +print(reader.read_all().to_pylist()) +``` + + +A document with five 200-character passages becomes five output rows, each +carrying `doc_id` and `title` from its parent. This is the fastest way to +check a chunker before committing to a materialized view: run it over a few +rows and inspect the output shape. + +## Video into frames {#video} + +Chunking a blob column is the same shape, with the chunker producing +timestamps rather than text spans, and a second Function pulling the actual +frame for each one. `videos` holds raw clips in a +[Blob v2](/management/table#managed-blobs) column, with each row's duration +already known: + +**Source: `videos`** + +| video_id | video | duration_seconds | +| --- | --- | --- | +| "clip-1" | (Blob v2 bytes) | 12.0 | + +A chunker that samples one timestamp per second needs no blob access at all +-- it only looks at `duration_seconds`: + + +```python Python icon="python" +@udf( + output_schema=pa.list_( + pa.struct([ + pa.field("frame_index", pa.int64(), nullable=False), + pa.field("ts", pa.float64(), nullable=False), + ]) + ), +) +def sample_frame_timestamps(duration_seconds: float) -> list[dict]: + every = 1.0 # one frame per second + count = int(duration_seconds // every) + return [{"frame_index": i, "ts": i * every} for i in range(count)] + +version = db.create_function_async(sample_frame_timestamps).wait() +``` + + +A second Function reads the blob -- incrementally, through a `BlobReader`, +rather than loading the whole clip -- and returns one JPEG per call: + + +```python Python icon="python" +import lancedb +from datetime import timedelta +from lancedb import BlobReader + +@udf( + name="extract_frame", + gpu=True, + pip=["av==13.1.0", "pillow==11.0.0"], + input_schema=pa.schema([ + lancedb.blob("video"), + pa.field("ts", pa.float64(), nullable=False), + ]), + output_schema=lancedb.blob("jpeg", nullable=False), +) +def extract_frame(video: BlobReader, ts: float) -> bytes: + ... # decode the frame at ts, encode as JPEG, return its bytes + +extract_version = db.create_function_async(extract_frame).wait(timeout=timedelta(minutes=15)) +``` + + +Compose both in one query: explode `videos` into one row per sampled +timestamp, then call `extract_frame` on each row to produce its image: + + +```python Python icon="python" +reader = db.execute_query(""" + SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg + FROM videos, sample_frame_timestamps(duration_seconds) AS f +""") +``` + + +A 12-second clip becomes 12 output rows, each with its own extracted JPEG. A +Function in `FROM` position yields one row per list element the same way +regardless of what the list holds; whether the second step produces a blob, +a plain value, or another struct does not change the explosion. + +## Persist it as a materialized view {#persist} + +Wrap either query in [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view) +to keep a real table that stays current as the source changes, instead of +recomputing the explosion on every query: + + +```sql SQL +CREATE MATERIALIZED VIEW chunks AS +SELECT doc_id, title, p.chunk_index, p.chunk_text +FROM documents, split_into_passages(text) AS p +``` + + +**Derived: `chunks`** (1:N expansion) + +| doc_id | title | chunk_index | chunk_text | +| --- | --- | --- | --- | +| 1 | "Intro to AI" | 0 | "Machine learning is a method..." | +| 1 | "Intro to AI" | 1 | "...of teaching computers..." | + +The view refreshes like any other materialized view: new source rows are +chunked and inserted, deleted source rows drop their children, and an +updated row's old children are replaced by freshly chunked ones on the next +[refresh](/feature-engineering/refresh-column). A single Function call or +`UNNEST(column)` is the only lateral source a materialized view can carry -- +not both, and not combined with `GROUP BY` -- so keep aggregation or further +curation in a second step over the chunked table. + +## Chunk, then curate {#next} + +A freshly chunked table is a normal table: [dedupe](/curation/dedupe) it to +collapse near-identical chunks, [sample](/curation/sampling) it for a quick +look, or [profile it](/curation/aggregate) to check how many chunks each +source row produced. Continue with +[choosing a curation task](/curation#questions). diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx new file mode 100644 index 000000000..2d161e84b --- /dev/null +++ b/docs/web/curation/create-function.mdx @@ -0,0 +1,213 @@ +--- +title: "Create a Function" +sidebarTitle: "Create Function" +description: "Register Python as a column: CPU, GPU, and remote-service Functions, called once per row or once per batch." +icon: code +keywords: ["function", "udf", "cpu", "gpu", "batch", "scalar", "blob", "remote api", "embedding", "rate limiter"] +availability: + embedded: unavailable + enterprise: available +--- + +Some curation steps cannot be written as a SQL expression: an embedding +model, an image decode, a call to an external service. A Function is a +Python callable registered with the database, versioned, and then applied as +a column or called in a query -- the code runs where the data is, not pulled +into your process first. This page covers how to shape one; later curation +tasks such as [Chunking](/curation/chunking) assume you have read it. + +## Scalar: once per row {#scalar} + +The plain form takes one row's values and returns one result. Types are +inferred from the annotations: + + +```python Python icon="python" +from lancedb import udf + +@udf(pip=["numpy==2.2.0"]) +def score(value: float) -> float: + return value * 2 + +version = db.create_function_async(score).wait() +table.add_columns({"doubled": version(value=col("value"))}) +``` + + +`pip` declares the worker's dependencies; they are part of the function's +immutable version, so changing one produces a new version rather than +altering rows a previous version already filled. + +## Batch: once per call, many rows at a time {#batch} + +A function is called once per batch instead of once per row when its +parameters are annotated `pyarrow.Array`, or when it takes a single +`pyarrow.RecordBatch` parameter to read more than one column together. The +same doubling logic, vectorized over a whole batch at once: + + +```python Python icon="python" +import pyarrow as pa +import pyarrow.compute as pc +from lancedb import udf + +@udf(pip=["numpy==2.2.0"]) +def score_batch(value: pa.Array) -> pa.Array: + return pc.multiply(value, 2) +``` + + +Batching amortizes per-call overhead across many rows, which matters most +once a function also does something with real fixed cost per call -- loading +a model, opening a connection, making a network round trip. + +## Stateful Functions: load once, call many times {#stateful} + +A `@udf`-decorated **class** is the same callable with state. Each remote +instance calls `__init__` once, calls `__call__` for every row or batch it +processes, and calls `close()`, if defined, once when it retires: + + +```python Python icon="python" +from lancedb import udf + +@udf +class scale: + def __init__(self, factor: float, offset: float = 0.0): + self.factor = factor + self.offset = offset + + def __call__(self, value: float) -> float: + return value * self.factor + self.offset +``` + + +Constructor parameters are **initialization fields**, bound once per binding +rather than read per row -- mixed with per-row columns in the same call: +`version(value=col("value"), factor=2.0)`. Load models, open clients, and +build rate limiters in `__init__`; every batch the instance serves then +reuses them, since an instance's state is shared across its own batches but +never across other instances or workers. This is the pattern GPU inference +and remote-API Functions both build on below. + +## GPU: batch inference, loaded once {#gpu} + +`gpu=True` requires a GPU-capable worker for every execution. Combined with +the batch and stateful forms above, a realistic embedding model loads once +in `__init__` and runs one forward pass per batch, not one per row: + + +```python Python icon="python" +import pyarrow as pa +from lancedb import udf + +@udf(gpu=True, pip=["torch==2.12.0", "sentence-transformers==5.7.0"]) +class embed_text: + def __init__(self, model_name: str = "all-MiniLM-L6-v2"): + import torch + from sentence_transformers import SentenceTransformer + + device = "cuda" if torch.cuda.is_available() else "cpu" + self.model = SentenceTransformer(model_name, device=device) + + def __call__(self, text: pa.Array) -> pa.Array: + texts = [t or "" for t in text.to_pylist()] + embeddings = self.model.encode(texts) + return pa.array(embeddings.tolist(), type=pa.list_(pa.float32(), list_size=384)) + +version = db.create_function_async(embed_text).wait() +table.add_columns({"embedding": version(text=col("caption"))}) +``` + + +The model loads once per worker instance, in `__init__`; `__call__` only +encodes the batch it was handed. Registering the same logic as a plain +function instead would reload the model on every single row. + +## Calling a remote service {#remote} + +A function that calls an external API needs a credential without putting it +in the function's source. A Secret is a database-scoped named credential: +`db.create_secret` stores the value once, and binding it at registration time +puts it in the environment variable the function reads, without ever +returning it from any API or recording it in the function's own definition. +Combine it with the stateful form so the HTTP client -- and any rate limiter +around it -- is built once, not reopened on every row: + + +```python Python icon="python" +import os +from lancedb import EnvVarSecret, udf + +db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"]) + +@udf +class embed_remote: + def __init__(self, model: str = "text-embedding-3-small"): + import os + from openai import OpenAI + + self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) + self.model = model + + def __call__(self, text: str) -> list[float]: + response = self.client.embeddings.create(input=text, model=self.model) + return response.data[0].embedding + +version = db.create_function_async( + embed_remote, + secrets=[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")], +).wait() +``` + + +A mistyped Secret name is caught at registration; a mistyped environment +variable name only surfaces on the first rows, since nothing records which +variables a function reads. There is no built-in retry or per-row +error-skip policy -- a function that calls a flaky service should handle +timeouts and retries itself, inside `__call__`. + +## Blob v2 input and output {#blob} + +A Function can bind a [Blob v2 column](/management/table#managed-blobs) and +return another one, including a blob nested inside a struct field, not only +at the top level. In row mode, a blob parameter arrives as Python `bytes` +(or a `BlobReader` for incremental, seekable access, so a function never +has to materialize a payload it only partially needs): + + +```python Python icon="python" +import pyarrow as pa +import lancedb +from lancedb import BlobReader, udf + +@udf( + gpu=True, + pip=["av==13.1.0", "pillow==11.0.0"], + input_schema=pa.schema([ + lancedb.blob("video"), + pa.field("ts", pa.float64(), nullable=False), + ]), + output_schema=lancedb.blob("jpeg", nullable=False), +) +def extract_frame(video: BlobReader, ts: float) -> bytes: + ... # decode the frame at ts, encode as JPEG, return its bytes +``` + + +`output_schema=lancedb.blob(...)` is what makes the result Blob v2 rather +than plain Arrow `binary` -- returning `bytes` with no explicit blob output +schema still holds the right bytes, but skips the Managed storage path and +`fetch_blobs`. Declare it explicitly on every function whose output should +be a blob. + +## What to read next {#next} + + + + A Function whose output is a list, exploded into one row per element. + + + Filling the column a Function is bound to, and re-filling it as inputs change. + + diff --git a/docs/web/curation/dedupe.mdx b/docs/web/curation/dedupe.mdx new file mode 100644 index 000000000..bdcf0b4b2 --- /dev/null +++ b/docs/web/curation/dedupe.mdx @@ -0,0 +1,142 @@ +--- +title: "Deduplicate near-duplicate records" +sidebarTitle: "Dedupe" +description: "Collapse records that are only approximately alike, judged by embedding distance, without a pairwise scan." +icon: clone +keywords: ["dedupe", "duplicate_pairs", "deduplication", "near-duplicate", "embedding", "distance_threshold"] +availability: + embedded: unavailable + enterprise: available +--- + +[Ranking and deduplication](/curation/windowing#dedup) removes records by an +explicit rule, such as keeping the latest version of a known key. This page +covers the other kind of duplicate: records with no shared key that are still +nearly identical, judged by distance between their embeddings -- a stopped +camera holding one pose for a few seconds, or two scraped pages with the same +paragraph reworded. `dedupe` and `duplicate_pairs` find these directly over a +vector index, without a pairwise scan. + +## Example data {#example-data} + +Connect with an [Enterprise connection](/basics/catalog#enterprise). A small +fixture keeps the distances easy to check by hand. + + + +`curation_embeddings` has eight records. Rows 10 and 20 are near-identical; +rows 30, 40 and 50 form one looser cluster; the rest are distinct. + + +```python Python icon="python" +import pyarrow as pa +from lancedb.index import IvfFlat + +schema = pa.schema([ + pa.field("id", pa.int64(), nullable=False), + pa.field("caption", pa.utf8()), + pa.field("embedding", pa.list_(pa.float32(), 2)), +]) +table = db.create_table("curation_embeddings", [ + {"id": 10, "caption": "a cat on a chair", "embedding": [0.0, 0.0]}, + {"id": 20, "caption": "a cat on the chair", "embedding": [0.0, 0.03]}, + {"id": 30, "caption": "a dog in a field", "embedding": [5.0, 5.0]}, + {"id": 40, "caption": "a dog in the field", "embedding": [5.0, 5.05]}, + {"id": 50, "caption": "a dog out in a field", "embedding": [5.0, 5.10]}, + {"id": 60, "caption": "a bird in a tree", "embedding": [10.0, 10.0]}, + {"id": 70, "caption": "a boat on the water", "embedding": [20.0, 20.0]}, + {"id": 80, "caption": "a car on the road", "embedding": [30.0, 30.0]}, +], schema=schema) + +table.create_index("embedding", config=IvfFlat(num_partitions=1, distance_type="l2")) +table.wait_for_index(["embedding_idx"]) +``` + + +`dedupe` and `duplicate_pairs` read the vector index, so the column needs one +before either function runs; a query against unindexed fragments is rejected +rather than silently returning stale or wrong results. + + + +## Collapse near-duplicates {#dedupe} + +`dedupe` returns one representative row per cluster of records within +`distance_threshold` of each other -- rows 10/20 collapse to one, 30/40/50 +collapse to one, and the four distinct rows pass through unchanged: + + +```python Python icon="python" +reader = db.execute_query(""" + SELECT id, caption FROM dedupe('curation_embeddings', 'embedding', distance_threshold => 0.06) + ORDER BY id +""") +print(reader.read_all().to_pylist()) +# [{'id': 10, 'caption': 'a cat on a chair'}, {'id': 30, 'caption': 'a dog in a field'}, +# {'id': 60, ...}, {'id': 70, ...}, {'id': 80, ...}] +``` + + +Every other column survives unchanged, since `dedupe` returns full rows, not +just which ones matched. Clustering is transitive: 30 and 40 are within +`distance_threshold` of each other, and so are 40 and 50, so all three +collapse into one representative even though 30 and 50 alone sit outside the +threshold. Pass `resolution => 'direct_representative'` +for a simpler, non-transitive selection instead, if a chained cluster like that +should not merge into one representative. + +Which row survives as the representative is not guaranteed to stay the same +across appends: a later row that bridges two previously separate clusters can +change which id represents the merged cluster. Do not treat a representative's +id as a stable identifier for its cluster. + +## Inspect the pairs instead {#pairs} + +`duplicate_pairs` returns the matching edges themselves, without collapsing +anything -- useful for review, or for a threshold that is still being tuned: + + +```python Python icon="python" +db.execute_query(""" + SELECT id_a, id_b, distance FROM duplicate_pairs( + 'curation_embeddings', 'embedding', distance_threshold => 0.06, id_column => 'id' + ) + ORDER BY id_a +""") +``` + + +This returns the pairs `(10, 20)`, `(30, 40)` and `(40, 50)` -- note 30 and 50 +are not a direct pair here (they sit `0.10` apart, outside the threshold), +even though `dedupe` merges all three transitively above. + +## Keep it current with a materialized view {#materialized} + +Wrap either call in a [materialized view](/management/materialized-view) so +the deduplicated set stays current as new records arrive, instead of +recomputing it from scratch on every curation pass: + + +```python Python icon="python" +db.execute_query(""" + CREATE MATERIALIZED VIEW curation_embeddings_deduped AS + SELECT * FROM dedupe('curation_embeddings', 'embedding', distance_threshold => 0.06) +""") +``` + + +See [Refresh a materialized view](/feature-engineering/refresh-materialized-view) +for manual and automatic refresh options to keep it current as new records land. + +## At production scale {#production} + +[LeRobotDataset](/integrations/lerobotdataset) runs the same `dedupe` +call over 27.6 million real embedding rows to remove near-static frames from a +robotics training set in under 30 seconds -- the mechanism does not change +with scale, only the table it runs against. + +## Continue with the curated data {#next} + +[Profile the result](/curation/aggregate) to check how much a threshold +removes before committing to it, or go back to +[choosing a curation task](/curation#questions). diff --git a/docs/web/curation/index.mdx b/docs/web/curation/index.mdx index 191ff2fd1..c4d6a48e5 100644 --- a/docs/web/curation/index.mdx +++ b/docs/web/curation/index.mdx @@ -17,10 +17,14 @@ records belong, and save the selected data or the rules used to produce it. | Task | What it helps you decide | | --- | --- | +| [Create a Function](/curation/create-function) | How to run your own Python -- on CPU, on GPU, or against a remote service -- as part of SQL. | +| [Chunk records](/curation/chunking) | How to split one record into several -- passages, clips, or tiles. | +| [Scope to what changed](/curation/changes) | How to process only the rows added since your last run. | | [Profile a dataset](/curation/aggregate) | Whether coverage, missing values and class balance suit the task. | | [Sample records](/curation/sampling) | Which subset to inspect or use for an experiment. | | [Join datasets](/curation/join) | How to attach labels, metadata or scores stored elsewhere. | -| [Rank and deduplicate](/curation/windowing) | Which records to keep when several describe the same item. | +| [Rank and deduplicate](/curation/windowing) | Which records to keep when several share an explicit key. | +| [Deduplicate near-duplicates](/curation/dedupe) | Which records to collapse when they only look alike, with no shared key. | The analytical examples in this section use **Enterprise SQL**. Connect with the [SQL guide](/basics/sql). For sampling through the Python SDK in LanceDB Embedded or diff --git a/docs/web/curation/join.mdx b/docs/web/curation/join.mdx index 03a45326e..3306ca511 100644 --- a/docs/web/curation/join.mdx +++ b/docs/web/curation/join.mdx @@ -5,10 +5,8 @@ description: "Combine records with labels or metadata, and check for missing or icon: link keywords: ["join", "labels", "metadata", "enrichment", "namespace"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL joins. --- A SQL join combines records from two tables using a shared key. Use joins to @@ -127,6 +125,38 @@ Use [Explain a query plan](/search/explain) to see how the query reads and combines data. Check the plan to see whether the query uses indexes and how it performs the join. An index on a key does not guarantee that the join will use it. +### Defer wide columns until after the join {#late-materialization} + +When one side of a join carries a BlobV2 column, an embedding, or both, join +on a narrow key first -- `row_id`, `_rowid`, or another selective column -- +and project the wide columns only in the final select list, rather than +selecting them alongside the join condition. The planner can then defer +reading those columns until after the join has already narrowed down which +rows survive, instead of reading them for every candidate row. + +`frames` is wide: a BlobV2 `image` and a vector `embedding` alongside its +key. `selected` is narrow: the frame IDs an earlier curation step already +kept, such as a sample or a dedupe result. Join on the key, project the wide +columns last: + +```sql +SELECT s.frame_id, f.image, f.embedding +FROM selected AS s +JOIN frames AS f ON f.frame_id = s.frame_id +``` + +`selected` narrows the row set before `image` or `embedding` is ever touched +on the `frames` side, rather than reading every row's blob and vector just +to discard most of them after the join. + +This is query planning the optimizer may or may not apply to a given query, +not a guarantee from writing the join this way. Confirm it per query with +[`EXPLAIN`](/search/explain): a plan containing `RemoteTake` deferred the +wide read; a plan without it read the wide columns eagerly, even for a query +shaped exactly like the one above. See +[Late materialization for wide columns](/sql/dql/join#late-materialization) +in the SQL reference for the underlying mechanism. + ## Save the result or continue curating {#reference} Keep the query for reuse or [save the selected data](/curation#next). diff --git a/docs/web/curation/sampling.mdx b/docs/web/curation/sampling.mdx index 1289275a1..82f1c1ecb 100644 --- a/docs/web/curation/sampling.mdx +++ b/docs/web/curation/sampling.mdx @@ -1,14 +1,12 @@ --- -title: "SQL sampling" -sidebarTitle: "SQL Sampling" +title: "Sampling" +sidebarTitle: "Sampling" description: "Choose a sample for exploration or evaluation and preserve the selected records when reproducibility matters." icon: dice keywords: ["sampling", "tablesample", "subset", "eval set", "reproducible", "shuffle"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL `TABLESAMPLE`. For sampling in LanceDB Embedded and LanceDB Enterprise through the Python SDK, see [Sample without SQL](#training). --- import { PySampleDataset } from '/snippets/curation_sampling.mdx'; @@ -163,7 +161,7 @@ promise the same IDs across SDK versions or changes to the source dataset. For shuffled training reads, worker configuration and data loaders, see -[Loading data for model training](/training/data-loading). +[PyTorch Data Loader](/training/data-loading). ## Related guides {#reference} diff --git a/docs/web/curation/windowing.mdx b/docs/web/curation/windowing.mdx index fa84ed5fe..6cb5322d6 100644 --- a/docs/web/curation/windowing.mdx +++ b/docs/web/curation/windowing.mdx @@ -5,10 +5,8 @@ description: "Choose records with explicit ranking rules and deterministic tie h icon: chart-simple keywords: ["window", "deduplication", "row_number", "rank", "train test split", "per class"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports SQL window functions. --- Window functions calculate values across related rows while keeping each row diff --git a/docs/web/deployment/storage.mdx b/docs/web/deployment/storage.mdx index dd370846b..50746d778 100644 --- a/docs/web/deployment/storage.mdx +++ b/docs/web/deployment/storage.mdx @@ -1,23 +1,16 @@ --- -title: "Embedded storage configuration" -sidebarTitle: "Embedded Storage" -description: "Choose and configure local disk or object storage for tables accessed by LanceDB Embedded." +title: "Storage configuration" +sidebarTitle: "Storage Configuration" +description: "Choose and configure local disk or object storage for your tables." icon: database keywords: ["storage", "s3", "gcs", "azure", "object store", "configuration", "deploy"] -availability: - oss: available - enterprise: unavailable - summary: >- - The embedded library chooses and configures its storage backend from the - connection URI and `storage_options`. In LanceDB Enterprise, storage is part of - the deployment's own configuration instead. --- This page is about LanceDB Embedded, where your connection chooses and configures the storage backend. A LanceDB Enterprise deployment sets up its own storage when it is deployed, so a `db://` connection passes none of these options except an Azure storage account name. See -[Deployment](/enterprise/deployment) for how a deployment is set up. +[LanceDB Enterprise](/enterprise) for how a deployment is set up. LanceDB's storage layer is built on modular, disk-first components. That design makes it flexible enough to run across local NVMe, EBS, EFS, and any object store that exposes an S3-compatible API. It also supports region-specific backends such as [Tencent COS](/storage/configuration#tencent-cos) and cache-acceleration layers such as [GooseFS](/storage/configuration#goosefs). @@ -124,7 +117,7 @@ import { **LanceDB Enterprise storage configuration** -In LanceDB Enterprise, you connect with `db://...` and the cluster owns the storage credentials, so `storage_options` are not passed at runtime. Cloud auth is set at deployment time. For federated databases, the namespace service vends per-request credentials automatically. See the [quickstart](/quickstart), [Enterprise overview](/enterprise/), and [Azure deployment guide](/enterprise/deployment/azure) for the Enterprise flow. +In LanceDB Enterprise, you connect with `db://...` and the cluster owns the storage credentials, so `storage_options` are not passed at runtime. Cloud auth is set at deployment time. For federated databases, the namespace service vends per-request credentials automatically. See the [quickstart](/quickstart), [Enterprise overview](/enterprise/), and [Kubernetes deployment guide](/enterprise/deployment/kubernetes) for the Enterprise flow. ### Object stores {#object-stores} diff --git a/docs/web/docs.json b/docs/web/docs.json index 917eb6406..5729dd8eb 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -27,6 +27,42 @@ }, "favicon": "/static/favicon.ico", "redirects": [ + { + "source": "/architecture", + "destination": "/#architecture" + }, + { + "source": "/enterprise/architecture", + "destination": "/#architecture" + }, + { + "source": "/enterprise/deployment/azure", + "destination": "/enterprise/deployment/kubernetes" + }, + { + "source": "/basics/query", + "destination": "/basics/sql#results" + }, + { + "source": "/basics/offerings", + "destination": "/#embedded-and-enterprise" + }, + { + "source": "/enterprise/deployment", + "destination": "/enterprise#deployment" + }, + { + "source": "/feature-engineering/data-evolution", + "destination": "/feature-engineering/add-computed-column" + }, + { + "source": "/training/torch", + "destination": "/training/data-loading" + }, + { + "source": "/basics/lakehouse", + "destination": "/" + }, { "source": "/tables/update", "destination": "/ingestion/update" @@ -209,7 +245,7 @@ }, { "source": "/sql/refresh", - "destination": "/sql/dml/refresh" + "destination": "/sql/dml/refresh-column" }, { "source": "/sql/show", @@ -245,13 +281,11 @@ "group": "Getting Started", "pages": [ "index", - "basics/offerings", - "basics/connect", "quickstart", - "architecture", "basics/sdk", "basics/sql", - "basics/agentic-skills" + "basics/agentic-skills", + "deployment/support" ] }, { @@ -259,9 +293,8 @@ "pages": [ "basics/lance", "basics/catalog", - "basics/lakehouse", - "basics/query", "basics/jobs", + "tables/realtime-engine", "tables/consistency", "basics/guarantees", "basics/limits", @@ -276,7 +309,8 @@ "ingestion/insert", "ingestion/merge-insert", "ingestion/update", - "ingestion/delete" + "ingestion/delete", + "ingestion/realtime-write" ] }, { @@ -288,35 +322,42 @@ "search/hybrid-search", "search/filtering", "reranking/index", - "search/explain" + "search/explain", + "search/realtime-read", + "enterprise/distributed-search" ] }, { "group": "Data Curation", "pages": [ "curation/index", + "curation/create-function", + "curation/chunking", + "curation/changes", "curation/aggregate", "curation/sampling", "curation/join", - "curation/windowing" + "curation/windowing", + "curation/dedupe" ] }, { "group": "Feature Engineering", "pages": [ "feature-engineering/index", - "feature-engineering/data-evolution", "feature-engineering/add-computed-column", "feature-engineering/refresh-column", - "feature-engineering/materialized-views" + "feature-engineering/view", + "feature-engineering/materialized-views", + "feature-engineering/refresh-materialized-view" ] }, { "group": "Training", "pages": [ - "training/why-lancedb", + "training/permutation", "training/data-loading", - "training/torch" + "training/distributed-training" ] }, { @@ -327,19 +368,24 @@ "management/namespace", "management/table", "tables/branching", - "tables/realtime-engine", - "management/materialized-view", - "management/view" + "management/view", + "management/materialized-view" ] }, { "group": "Maintenance", "pages": [ - "indexing/index", - "indexing/vector-index", - "indexing/fts-index", - "indexing/scalar-index", - "indexing/reindexing", + { + "group": "Indexing", + "icon": "layer-group", + "pages": [ + "indexing/index", + "indexing/vector-index", + "indexing/fts-index", + "indexing/scalar-index", + "indexing/reindexing" + ] + }, "maintenance/compaction", "maintenance/cleanup", "maintenance/background-jobs" @@ -349,14 +395,10 @@ "group": "Deployment", "pages": [ "enterprise/index", - "enterprise/architecture", - "enterprise/distributed-search", - "enterprise/deployment/index", "deployment/storage", "deployment/monitoring", - "enterprise/deployment/azure", - "enterprise/benchmarks", - "deployment/support" + "enterprise/deployment/kubernetes", + "enterprise/benchmarks" ] }, { @@ -375,6 +417,7 @@ { "group": "DDL", "pages": [ + "sql/ddl/database", "sql/ddl/namespace", "sql/ddl/table", "sql/ddl/view", @@ -391,7 +434,8 @@ "sql/dml/update", "sql/dml/delete", "sql/dml/copy", - "sql/dml/refresh" + "sql/dml/refresh-column", + "sql/dml/refresh-materialized-view" ], "icon": "database" }, @@ -404,7 +448,10 @@ "sql/dql/aggregation", "sql/dql/window", "sql/dql/sampling", + "sql/dql/changes", "sql/dql/fts", + "sql/dql/dedupe", + "sql/dql/duplicate-pairs", "sql/dql/explain" ], "icon": "filter" diff --git a/docs/web/embedding/index.mdx b/docs/web/embedding/index.mdx index c35074b20..91efcc566 100644 --- a/docs/web/embedding/index.mdx +++ b/docs/web/embedding/index.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Managing Embeddings" description: "Use the embedding API in LanceDB: registry, functions, schemas, and multi-language SDK support." icon: "bars" availability: - oss: available + embedded: available enterprise: available - summary: >- - Embedding functions run in your process, whether the table is local or on a - deployment, which stores their configuration but never runs them. Python - and TypeScript also embed query text; in Rust you embed queries yourself. --- import { diff --git a/docs/web/enterprise/architecture.mdx b/docs/web/enterprise/architecture.mdx deleted file mode 100644 index 8f887c142..000000000 --- a/docs/web/enterprise/architecture.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: "Enterprise architecture" -sidebarTitle: "Architecture" -description: "The tiers a deployment runs, and how they scale independently." -icon: cubes -keywords: ["architecture", "control plane", "data plane", "indexer"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. - -A deployment separates compute from storage so each scales on its own: table -data and indexes live in object storage, while query serving and background work -run on machines that can be replaced without any of them owning the data. - -[Architecture](/architecture) covers this alongside the embedded form, which is -the comparison most readers want first. - -See [Distributed search](/enterprise/distributed-search) for how Enterprise -distributes index execution and table-data reads. diff --git a/docs/web/enterprise/authentication.mdx b/docs/web/enterprise/authentication.mdx index 74d68ecae..920275d16 100644 --- a/docs/web/enterprise/authentication.mdx +++ b/docs/web/enterprise/authentication.mdx @@ -5,12 +5,8 @@ description: "Authentication modes for LanceDB Enterprise: API keys and OAuth cr icon: key keywords: ["authentication", "oauth", "api key", "authorization code", "device code", "azure managed identity", "client credentials"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Requests to a deployment carry an API key or an OAuth token, whichever it is - configured to accept. LanceDB Embedded has no server to sign in to; see - [Architecture](/architecture). --- A deployment authenticates each request over a `db://` connection before diff --git a/docs/web/enterprise/benchmarks.mdx b/docs/web/enterprise/benchmarks.mdx index feec4dfc4..b733aef78 100644 --- a/docs/web/enterprise/benchmarks.mdx +++ b/docs/web/enterprise/benchmarks.mdx @@ -10,7 +10,7 @@ keywords: ["benchmarks", "performance", "throughput", "latency"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. +[Architecture](/#architecture) for what differs between the two. Benchmark results are specific to a deployment's shape (cluster size, storage class, dataset), so they are published with LanceDB Enterprise. diff --git a/docs/web/enterprise/deployment/azure.mdx b/docs/web/enterprise/deployment/azure.mdx deleted file mode 100644 index 702c6a2eb..000000000 --- a/docs/web/enterprise/deployment/azure.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: "Azure deployment guide" -sidebarTitle: "Azure" -description: "Deploying LanceDB Enterprise on Azure." -icon: cloud -keywords: ["azure", "deployment", "aks"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. - -The Azure deployment procedure is published with LanceDB Enterprise. See -[Deployment](/enterprise/deployment) for the general shape, and -[contact us](https://www.lancedb.com/contact) to get started. diff --git a/docs/web/enterprise/deployment/index.mdx b/docs/web/enterprise/deployment/index.mdx deleted file mode 100644 index 38e854282..000000000 --- a/docs/web/enterprise/deployment/index.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: "Deployment guide" -sidebarTitle: "Deployment Models" -description: "Standing up a LanceDB Enterprise deployment." -icon: server -keywords: ["deployment", "install", "cluster", "kubernetes"] ---- - -Enterprise - -This page describes a LanceDB Enterprise capability. The embedded form -of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. - -Deployment is specific to your cloud and account, so the procedure is published -with LanceDB Enterprise. [Contact us](https://www.lancedb.com/contact) to get -started. - -LanceDB Embedded has nothing to deploy: it is a library your process links -against. See [Architecture](/architecture#embedded). diff --git a/docs/web/enterprise/deployment/kubernetes.mdx b/docs/web/enterprise/deployment/kubernetes.mdx new file mode 100644 index 000000000..3b1f4dea9 --- /dev/null +++ b/docs/web/enterprise/deployment/kubernetes.mdx @@ -0,0 +1,17 @@ +--- +title: "Kubernetes deployment guide" +sidebarTitle: "Kubernetes" +description: "Deploying LanceDB Enterprise on Kubernetes." +icon: cloud +keywords: ["kubernetes", "k8s", "aks", "deployment", "helm"] +--- + +Enterprise + +This page describes a LanceDB Enterprise capability. The embedded form +of LanceDB has no server to provide it. See +[Architecture](/#architecture) for what differs between the two. + +The Kubernetes deployment procedure is published with LanceDB Enterprise. See +[LanceDB Enterprise](/enterprise#deployment) for the general shape, and +[contact us](https://www.lancedb.com/contact) to get started. diff --git a/docs/web/enterprise/distributed-search.mdx b/docs/web/enterprise/distributed-search.mdx index 86837e157..f7c6001a5 100644 --- a/docs/web/enterprise/distributed-search.mdx +++ b/docs/web/enterprise/distributed-search.mdx @@ -4,17 +4,14 @@ sidebarTitle: "Distributed search" description: "How LanceDB Enterprise distributes index execution and table-data reads." icon: "network-wired" availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - LanceDB Enterprise distributes index execution and table-data reads across - executors. LanceDB Embedded executes searches in the application process. --- Distributed search spreads index execution, table-data reads, and caching across multiple serving machines in LanceDB Enterprise. Query nodes plan queries and -combine results. Executors cache index structures and table data and execute -the distributed work. See [Enterprise architecture](/enterprise/architecture). +combine results. Plan executors cache index structures and table data and execute +the remote work. See [Architecture](/#architecture). ## Embedded search {#embedded-search} diff --git a/docs/web/enterprise/index.mdx b/docs/web/enterprise/index.mdx index 888804756..59ab7e3a0 100644 --- a/docs/web/enterprise/index.mdx +++ b/docs/web/enterprise/index.mdx @@ -10,7 +10,7 @@ keywords: ["enterprise", "deployment", "cluster"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. +[Architecture](/#architecture) for what differs between the two. LanceDB Enterprise runs the lakehouse as a service: a control plane for configuration, identity and policy; a data plane serving reads and writes; and @@ -30,4 +30,13 @@ Draft for the Functions release. Add this row to the table above, after SQL: | [Functions](/management/function) | Python running on workers | */} -See [Architecture](/architecture) for the two shapes side by side. +See [Architecture](/#architecture) for the two shapes side by side. + +## Getting a deployment {#deployment} + +Deployment is specific to your cloud and account, so the procedure is +published with LanceDB Enterprise rather than here. +[Contact us](https://www.lancedb.com/contact) to get started; see the +[Kubernetes deployment guide](/enterprise/deployment/kubernetes) for a worked example. +Embedded LanceDB has nothing to deploy: it is a library your process links +against -- see [LanceDB Embedded](/#1-lancedb-oss). diff --git a/docs/web/enterprise/security.mdx b/docs/web/enterprise/security.mdx index c848be23f..b8d9d72c5 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -10,7 +10,7 @@ keywords: ["compliance", "security", "soc2", "encryption", "audit"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/architecture) for what differs between the two. +[Architecture](/#architecture) for what differs between the two. Compliance posture (certifications, data residency, encryption at rest and in transit, audit logging) is a property of a deployment, so it is documented diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 49820a454..aecb0acf0 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -1,18 +1,33 @@ --- -title: "Add a computed column" -sidebarTitle: "Computed Columns" +title: "Create a computed column" +sidebarTitle: "Create Computed Column" description: "Declare a column from a SQL expression. Nothing is evaluated until you refresh it." icon: table-columns keywords: ["computed columns", "add_columns", "transforms", "schema"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Local computed columns require a source build with the experimental-functions Cargo feature. Enterprise requires the deployment to enable them. --- -A computed column is declared with an expression and starts with no values. -Declaring it is cheap on any table size, because nothing is evaluated until +import { + PySchemaAddSetup, + TsSchemaAddSetup, + RsSchemaAddSetup, + PyAddColumnsCalculated, + TsAddColumnsCalculated, + RsAddColumnsCalculated, +} from '/snippets/tables.mdx'; + +Lance can write a new column without rewriting the columns already in the +table. That matters most on a table that also holds large images, video or +embeddings, where rewriting everything just to add one small derived field +would be wasteful. See [Lance format](/basics/lance) for the storage model +this relies on. + +A computed column is how LanceDB formalizes that capability for feature +engineering specifically: instead of writing the derived values immediately, +it is declared with an expression and starts with no values. Declaring it is +cheap on any table size, because nothing is evaluated until [a refresh](/feature-engineering/refresh-column) asks for it. @@ -56,6 +71,69 @@ including that you can travel back to before the column existed. `computed` and `transforms` cannot be combined in one call. Reach for `computed` when the table is large enough that you would rather control when the work happens. +Pass `auto_refresh_enabled` and `auto_refresh_interval_seconds` alongside +`computed` to have the server keep the column refreshed instead of calling +[`refresh_column`](/feature-engineering/refresh-column) yourself: + +```python +table.add_columns( + computed={"doubled": "x * 2"}, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=300, +) +``` + +A local table stores these settings but does not act on them -- automatic +scheduling runs on LanceDB Cloud or Enterprise. See +[Automatic refresh](/feature-engineering/refresh-column#automatic) for the +full behavior, including how to change the setting later. + +An eager `transforms` call looks like this, starting from a small product +table: + + + + {PySchemaAddSetup} + + + + {TsSchemaAddSetup} + + + + {RsSchemaAddSetup} + + + + + + {PyAddColumnsCalculated} + + + + {TsAddColumnsCalculated} + + + + {RsAddColumnsCalculated} + + + +For feature engineering on large existing tables, group related derived +features into one `add_columns` call instead of running many separate +writes: this creates one new table version for the schema change and +computes every new column from the existing rows in it, rather than growing +the table's version history with many small updates. + + +`add_columns` does not accept Python callables, batch UDFs, or PyArrow +`RecordBatch` iterators for populating new columns, whether through +`transforms` or `computed`. New column values must be defined with SQL +expressions, or added as NULL columns from an Arrow field or schema. If your +transformation cannot be expressed in SQL, compute the values outside +`add_columns` before writing them back through another workflow. + + ## The expression {#expressions} The expression is SQL, evaluated over the row. It can reference any column in @@ -111,12 +189,35 @@ image decode -- the column is filled by a registered [function](/management/function) instead of an expression. Declaring it looks the same; what differs is what fills it. It needs a deployment with Functions enabled. + +The call passed to `add_columns` is the tell: a SQL expression in `computed` +is a string, keyed by the column name -- + + +```python Python icon="python" +table.add_columns(computed={"caption_length": "length(caption)"}) +``` + + +-- while a Function application is the registered version itself, called with +its parameters bound to source columns through `col(...)`, keyed the same way +but passed positionally rather than through `computed`: + + +```python Python icon="python" +table.add_columns({"caption": caption_version(jpeg=col("jpeg"))}) +``` + + +Both accept the same `auto_refresh_enabled` and `auto_refresh_interval_seconds` +options, and both refresh and toggle the same way; see +[Refresh a computed column](/feature-engineering/refresh-column#automatic). */} ## Related guides {#next} - + Fill the rows that lack values. diff --git a/docs/web/feature-engineering/data-evolution.mdx b/docs/web/feature-engineering/data-evolution.mdx deleted file mode 100644 index 37e396b8b..000000000 --- a/docs/web/feature-engineering/data-evolution.mdx +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: "Data evolution" -sidebarTitle: "Data Evolution" -description: "Derive new columns from data already in the table, without rewriting what is already there." -icon: wand-magic-sparkles -keywords: ["data evolution", "derived columns", "add_columns", "zero copy", "feature engineering"] -availability: - oss: available - enterprise: available - summary: >- - Adding columns computed from SQL expressions works in the embedded library - and in LanceDB Enterprise. ---- - -import { - PySchemaAddSetup, - TsSchemaAddSetup as TsSchemaAddSetup, - RsSchemaAddSetup as RsSchemaAddSetup, - PyAddColumnsCalculated as AddColumnsCalculated, - TsAddColumnsCalculated as TsAddColumnsCalculated, - RsAddColumnsCalculated as RsAddColumnsCalculated, - PyAddFeatureColumnsSql as AddFeatureColumnsSql, - TsAddFeatureColumnsSql as TsAddFeatureColumnsSql, - RsAddFeatureColumnsSql as RsAddFeatureColumnsSql, -} from '/snippets/tables.mdx'; - -Add derived columns to calculate features from data already in a table. -For example, compute a product score from existing fields without reading -and rewriting the table in your application. - -Lance can write the new columns without rewriting the existing columns. -This is useful when the table also contains large images, video or embeddings. -See [Lance format](/basics/lance) for the storage model. - - -In SQL, on an Enterprise cluster that enables computed columns, this is [`ALTER TABLE ... ADD COLUMN ... AS`](/sql/ddl/table#computed-column). - - -## Set up the example table {#set-up-the-example-table} - -The examples use `db`, a connection opened as in -[Connect to LanceDB](/basics/connect), and create a small product table in it: - - - - {PySchemaAddSetup} - - - - {TsSchemaAddSetup} - - - - {RsSchemaAddSetup} - - - -## Add derived columns {#add-derived-columns} - -You can add new columns that are derived from existing data using SQL expressions. -For feature engineering on large existing tables, group related derived features into -one `add_columns` operation instead of running many separate writes. This creates one -new table version for the schema change and computes the new columns from the existing -rows, which avoids growing the table's version history with many small updates. - - - - {AddColumnsCalculated} - - - - {TsAddColumnsCalculated} - - - - {RsAddColumnsCalculated} - - - -The same call can add multiple derived columns at once. For example, if you are -building several lightweight features from existing product fields, pass all of the -new column expressions together: - - - - {AddFeatureColumnsSql} - - - - {TsAddFeatureColumnsSql} - - - - {RsAddFeatureColumnsSql} - - - - -LanceDB `add_columns` does not currently accept Python callables, batch UDFs, or -PyArrow `RecordBatch` iterators for populating new columns. New column values must be -defined with SQL expressions, or added as NULL columns from an Arrow field or schema. -If your transformation cannot be expressed in SQL, compute the values outside -`add_columns` before writing them back through another workflow. - - -## When SQL is not enough {#beyond-sql} - -The expressions above are evaluated once, as part of the call. For other workflows: - -- A [computed column](/feature-engineering/add-computed-column) declares the - expression and leaves the column empty, so you choose when the work happens. - Use it when you want to schedule the computation separately. -- On LanceDB Enterprise, [Geneva](/geneva) fills a column with Python, for - values SQL cannot express: an embedding, a model call, an image decode. - -{/* -Draft for the Functions release. Replaces the Geneva item in the list above: -- A [function](/management/function) fills a column with Python, for values SQL - cannot express -- an embedding, a model call, an image decode. -*/} - -A deployment has to enable computed columns before you use them. -{/* Draft for the Functions release: Functions need enabling there too. */} - -## Related guides {#next} - - - - Declare now, fill later. - - - Change the table's shape instead of its contents. - - diff --git a/docs/web/feature-engineering/index.mdx b/docs/web/feature-engineering/index.mdx index 30a165af4..6807998ec 100644 --- a/docs/web/feature-engineering/index.mdx +++ b/docs/web/feature-engineering/index.mdx @@ -24,7 +24,7 @@ then refresh the derived data when its inputs change. */} -In LanceDB Enterprise, every operation here also has a SQL form. See [DDL](/sql/ddl/table#alter) to declare a column and [REFRESH](/sql/dml/refresh) to fill it. +In LanceDB Enterprise, every operation here also has a SQL form. See [DDL](/sql/ddl/table#alter) to declare a column and [REFRESH COLUMN](/sql/dml/refresh-column) to fill it. ## Computed columns and materialized views {#the-shape} @@ -36,8 +36,8 @@ refresh costs: | | Computed column | Materialized view | | --- | --- | --- | | Declaring or creating it | records the expression; no values are written | runs the query and stores its rows, unless created empty | -| A refresh | fills rows with no value and recomputes rows whose inputs changed | applies source changes or rebuilds the view, depending on the query and SDK version | -| A refresh when nothing changed | fills nothing | can be a no-op when incremental refresh is supported | +| A refresh | fills rows with no value and recomputes rows whose inputs changed | rebuilds the view completely from its source query | +| A refresh when nothing changed | fills nothing | still rebuilds the view and commits a new version | | In LanceDB Enterprise | runs as a [job](/basics/jobs) | runs as a server-side materialization job | ### Computed columns fill incrementally {#incremental} @@ -65,21 +65,19 @@ up-to-date features. A [materialized view](/feature-engineering/materialized-views) has no separate declaration step: creating one runs its query and stores the result, so the view -is ready to read. A refresh updates those stored results. Python SDK 0.40.0 can apply -changes incrementally for supported queries; other queries require a full rebuild. -See [refresh behavior](/feature-engineering/materialized-views#incremental) for -version-specific details. +is ready to read. A refresh rebuilds the stored result completely from the +source query; see [Refresh a materialized view](/feature-engineering/refresh-materialized-view) +for the full behavior, including automatic refresh. -Enterprise runs materialization on the Enterprise service. Use the SDK and refresh -options supported by your server version; see -[Enterprise refreshes](/feature-engineering/materialized-views#availability). +Enterprise runs materialization on remote compute, as a server-side job. ## Choose a feature engineering workflow {#which-one} | | What it produces | Filled by | Available | | --- | --- | --- | --- | +| [View](/feature-engineering/view) | a saved query, no stored rows of its own | nothing -- it runs on every read | Enterprise | | [Computed column](/feature-engineering/add-computed-column) | a new column on an existing table | a SQL expression | Embedded and Enterprise | -| [Materialized view](/feature-engineering/materialized-views) | a new table derived by a query | a refresh | Embedded and Enterprise | +| [Materialized view](/feature-engineering/materialized-views) | a new table derived by a query | a refresh | Enterprise | | [Geneva](/geneva) | columns filled by Python | the `geneva` package | Enterprise | {/* @@ -88,6 +86,11 @@ Draft for the Functions release. Replace the Geneva row of the table above with: | [Geneva](/geneva) | columns filled by Python, for existing pipelines | the `geneva` package | Enterprise | */} +**A view** has no refresh and no staleness window, because it stores the +query rather than its result. Reach for one first, before a computed column +or a materialized view, when the query is cheap enough to simply re-run on +every read. + **Computed columns** are the common case: a column declared with a SQL expression, filled by [a refresh](/feature-engineering/refresh-column). @@ -147,20 +150,26 @@ should handle that itself, inside the function body. When a refresh fails, fix the cause and run the refresh again. The new refresh fills what is still empty or stale. How much of the failed run was kept depends on where it ran (see -[Refresh a column](/feature-engineering/refresh-column#failures)), and a retry +[Refresh a computed column](/feature-engineering/refresh-column#failures)), and a retry can recompute values that were already written, so do not count on it costing only the rows that did not complete. ## Related guides {#next} - + + A saved query, with no storage or refresh of its own. + + Declare a column from a SQL expression. - + Fill the rows that lack values, locally or as a job. - + + Store a query's result as a table. + + Bring a derived table up to date with its source. {/* diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index e90f3233c..86a3667f3 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -1,122 +1,95 @@ --- -title: "Refresh a materialized view" -sidebarTitle: "Materialized View Refresh" -description: "Create a materialized view and refresh it when the source data changes." +title: "Create a materialized view" +sidebarTitle: "Create Materialized View" +description: "Store the result of a query as a table, ready to query, index and search." icon: table -keywords: ["materialized view", "create_materialized_view", "refresh", "full refresh"] +keywords: ["materialized view", "create_materialized_view"] availability: - oss: available + embedded: unavailable enterprise: available - summary: >- - Creation and refresh in LanceDB Embedded require a source build with the experimental-functions Cargo feature. Enterprise runs the work on the Enterprise service. See [Enterprise refreshes](#availability) for server compatibility requirements. --- -import { - PyMaterializedViewCreate as MaterializedViewCreate, - PyMaterializedViewRefresh as MaterializedViewRefresh, -} from '/snippets/materialized_view.mdx'; - A materialized view stores the result of a query as a table. Use it to keep a -filtered or transformed dataset that you can query, index and search repeatedly. -Refresh the view after its source data changes. +filtered or transformed dataset that you can query, index and search +repeatedly, instead of recomputing the query every time you read it. -In the 0.41 SDK release, materialized-view creation and refresh in LanceDB Embedded require a -source build with the `experimental-functions` Cargo feature. Published Python -and TypeScript packages leave it disabled. Opening, reading, listing and dropping -existing views remain available, as do LanceDB Enterprise operations. +In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create). - -In SQL this is [`REFRESH MATERIALIZED VIEW`](/sql/refresh#refresh-materialized-view). - +## Create a view {#create} -## Create and refresh {#create-and-refresh} + +```python Python icon="python" +view = db.create_materialized_view( + "frames_captioned", + source="frames", + select=["frame_id", "video_id", "ts", "caption"], + where="selected = true", +) +``` - -{MaterializedViewCreate} - +```typescript TypeScript icon="square-js" +const view = await db.createMaterializedView("frames_captioned", "frames", { + select: ["frame_id", "video_id", "ts", "caption"], + where: "selected = true", +}); +``` + + +`source` names the table the view reads. `select` takes column names, +`(alias, expression)` pairs, or a dict of the same; omitting it selects every +source column, expanded against the schema as it was at creation time. +`where` filters source rows, and `limit` caps the view. Creating the view computes its rows, so it is ready to read. Pass -`with_no_data=True` to create it empty instead. Later changes to the source -reach the view through a refresh: +`with_no_data=True` to create it empty instead; a later +[refresh](/feature-engineering/refresh-materialized-view) populates it. - -{MaterializedViewRefresh} - +Your administrator manages stable row IDs and other source-table +requirements for materialized views on the server; confirm support for your +source table's shape before creating a view over it. -The example works with Python SDK 0.40.0. It creates the source with stable -row IDs, which that release requires for ordinary materialized-view sources. +## Automatic refresh at creation {#auto-refresh} -`select` takes column names, `(alias, expression)` pairs, or a dict of the same. -Omitting it selects every source column, expanded against the schema as it was -at creation time. `where` filters source rows; `limit` caps the view. +Pass `auto_refresh_enabled` and `auto_refresh_interval_seconds` to schedule +refreshes instead of calling +[`refresh`](/feature-engineering/refresh-materialized-view) yourself: -## Prepare the source table {#stable-row-ids} +```python +view = db.create_materialized_view( + "frames_captioned", + source="frames", + select=["frame_id", "video_id", "ts", "caption"], + where="selected = true", + auto_refresh_enabled=True, + auto_refresh_interval_seconds=300, +) +``` -In Python SDK 0.40.0, create the source with -`storage_options={"new_table_enable_stable_row_ids": "true"}`, as the example -above does. Stable row IDs let the view track source rows across updates and -compaction. Set this option when creating the table; it cannot be added later. - -A source with the [realtime engine](/tables/realtime-engine) enabled or retained, uncompacted write-ahead-log -rows is not accepted by the local materialized-view implementation. - -## Refresh behavior {#incremental} - -With Python SDK 0.40.0, a refresh applies source changes incrementally when the -query supports it, and rebuilds the view otherwise. In the example, adding Bea -writes one new view row. Refreshing again without source changes writes none. -Use `refresh(full=True)` to force a rebuild. - -`rows_written` counts rows written by that refresh, not all rows in the view. -Use `view.table.count_rows()` to get the total. Pass `source_version=N` to -refresh against a particular source version instead of the latest. - - -Refresh behavior has changed between SDK versions. The earlier 0.40.0b13 -development build rebuilt every local view on refresh and did not accept -`full`; 0.39.0 created views empty. Use the reference for your installed SDK -when maintaining an existing pipeline. - - -## Enterprise refreshes {#availability} - -Enterprise - -Enterprise runs materialized-view creation and refresh on the Enterprise service. -For SQL, see [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view) and -[`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh#refresh-materialized-view). - -Use an SDK version supported by your Enterprise deployment. Materialized-view -APIs and stored definitions have changed across releases; a local SDK example -alone does not establish compatibility with an older server. Before upgrading -an existing pipeline, confirm the supported refresh options and whether its -views need to be recreated with your administrator. - -Stable row IDs and feature configuration for Enterprise sources are managed on -the server. The source-table storage option in the local example does not -configure the Enterprise deployment, and Python SDK 0.40.0's `create_table` on a -`db://` connection does not accept `storage_options`: leave it out, and confirm -with your administrator that the deployment gives new tables stable row IDs. - -`list_materialized_views` requests the server's view listing. On a local -database it reads table schemas to find views. +Omit `auto_refresh_enabled` to let the server decide whether to enable it, +and omit `auto_refresh_interval_seconds` to let the server decide the +pacing. See +[Automatic refresh](/feature-engineering/refresh-materialized-view#auto-refresh) +for how scheduling behaves once the view exists. ## Working with the view {#working-with-the-view} `view.table` is the underlying table, for querying, indexing, or search. `view.definition` is the recorded query: the select list, predicate, and -limit. Use it to inspect the query without inferring it from the rows. Both are properties; on an async view, the definition is read -with `await view.definition()`. +limit. Use it to inspect the query without inferring it from the rows. Both +are properties; on an async view, the definition is read with +`await view.definition()`. -An existing view is reopened with `db.open_materialized_view(name)`. +An existing view is reopened with `db.open_materialized_view(name)`. Creation, +refresh and drop also have async, job-returning SDK methods; see +[Materialized view](/management/materialized-view#manage). ## Related guides {#next} - - Derive a column instead of a whole table. + + Bring the view up to date with its source. Inspect the table history and read a particular version. diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 10ab9fdc8..ba3934f1e 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -1,14 +1,12 @@ --- -title: "Refresh a column" -sidebarTitle: "Column Refresh" +title: "Refresh a computed column" +sidebarTitle: "Refresh Computed Column" description: "Populate a computed column and update it when its inputs change." icon: arrows-rotate keywords: ["refresh_column", "backfill", "job", "idempotent", "REFRESH COLUMN"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Local column refresh requires a source build with the experimental-functions Cargo feature. Enterprise runs it as a server job that must be enabled for your Enterprise cluster. --- Refresh a [computed column](/feature-engineering/add-computed-column) to fill @@ -64,10 +62,6 @@ That is what makes the call idempotent and safe to retry. However, unlike a spreadsheet formula, nothing is recomputed until you refresh, so a derived column is stale between an update and the next refresh. -{/* -Draft for automatic computed-column refresh. Keep the released manual-refresh -instructions above until the server feature is available. - ## Automatic refresh {#automatic} Set scheduling options when declaring a computed column: @@ -80,17 +74,17 @@ table.add_columns( ) ``` -Both options apply to every computed output declared in that call, including -registered Function outputs. Automatic refresh is enabled by default. When -the interval is omitted, the server determines when to refresh. LanceDB Embedded -tables persist only an explicitly configured interval; automatic execution requires a -LanceDB Enterprise deployment with its separate `column_refresh.enabled` switch -turned on. That server switch is disabled in the base configuration. +These options apply to every computed output declared in that call. Automatic +refresh is enabled by default. When the interval is omitted, the server +determines when to refresh. Local tables store the setting, but automatic +execution requires a Cloud or Enterprise server with its separate +`column_refresh.enabled` switch turned on. That server switch is disabled in +the base configuration. The interval is a positive minimum delay after the last successful refresh of that output. A first refresh is immediately eligible. The scheduler still checks input freshness and waits for computed ancestors to settle; the timer -does not make unchanged inputs require recomputation. Each Function output's +does not make unchanged inputs require recomputation. Each declared output's interval is independent, so refreshing a sibling does not postpone it. Pacing uses retained live Job Registry history. If completed jobs are archived @@ -107,10 +101,31 @@ ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_interval_seconds = 60 ALTER TABLE my_table ALTER COLUMN doubled SET auto_refresh_enabled = true; ``` -Disabling automatic refresh prevents new automatic jobs. Inflight jobs may -finish, and manual refresh remains available. Re-enabling wakes maintenance -to consider accumulated changes under the interval and dependency rules. -*/} + +The current setting is in the column's own field metadata, +`computed_column.auto_refresh_enabled`, readable from `table.schema` without +submitting a job to ask. + + +Setting the flag is a metadata-only change and always succeeds, independent of +whether the scheduler can actually refresh the column -- a deployment issue +that keeps the background job from running (for example, a worker that cannot +reach object storage) does not stop the `ALTER` from committing. Check the +column's job history, not just its metadata, if values stop appearing after +re-enabling. + +**Disabling does not skip or drop writes.** Rows written while disabled +commit with no computed value, the same as a row written before the column +existed; they do not queue anywhere separate. Inflight jobs may finish, and +manual refresh remains available throughout. + +**Re-enabling catches up the entire backlog in one pass**, not just rows +written after that point: the next scheduler tick processes every row left +unfilled since the column was disabled, in a single refresh, with no +further write required to trigger it. This is "catch up," not "resume +cadence" -- a column disabled for an hour and re-enabled fills everything +that accumulated during that hour, immediately, rather than only picking up +new rows from the moment it is re-enabled. ## Refreshing part of a table {#partial} @@ -196,7 +211,7 @@ symptoms, which rarely name their cause. Waiting on, inspecting, and cancelling server-side work. - + The same idea, for a whole derived table. diff --git a/docs/web/feature-engineering/refresh-materialized-view.mdx b/docs/web/feature-engineering/refresh-materialized-view.mdx new file mode 100644 index 000000000..05ebff109 --- /dev/null +++ b/docs/web/feature-engineering/refresh-materialized-view.mdx @@ -0,0 +1,88 @@ +--- +title: "Refresh a materialized view" +sidebarTitle: "Refresh Materialized View" +description: "Bring a materialized view up to date after its source data changes." +icon: arrows-rotate +keywords: ["materialized view", "refresh", "auto_refresh_enabled", "auto_refresh_interval_seconds"] +availability: + embedded: unavailable + enterprise: available +--- + +Refresh a [materialized view](/feature-engineering/materialized-views) to +bring its stored rows up to date after the source table changes. + + +In SQL this is [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh-materialized-view). + + +## Refresh a view {#refresh} + +```python +view.refresh() +``` + +Every refresh rebuilds the view completely from its source query -- there is +no incremental refresh. Calling it again with no source changes still +rebuilds and commits a new table version. + +The result reports what the refresh did: + +```python +result = view.refresh() +result.rows_written # rows in the rebuilt view +result.source_version # the source table version the view now reflects +result.version # the view's own new table version +``` + +Pass `source_version=N` to refresh against a particular source version +instead of the latest: + +```python +view.refresh(source_version=12) +``` + +Use `view.table.count_rows()` for the view's row count at any time; it +always matches `rows_written` from the most recent refresh. + +## Automatic refresh {#auto-refresh} + +Set scheduling options when [creating the view](/feature-engineering/materialized-views#auto-refresh): + +```python +view = db.create_materialized_view( + "frames_captioned", + source="frames", + select=["frame_id", "video_id", "ts", "caption"], + where="selected = true", + auto_refresh_enabled=True, + auto_refresh_interval_seconds=300, +) +``` + +`auto_refresh_interval_seconds` is a positive minimum delay after the last +successful refresh before the next automatic one is eligible; omit it to let +the server decide. The whole view toggles together -- there is no +per-column granularity the way a computed column has one setting per output. + +The view's *initial* population, at creation or when the server first runs +it, happens regardless of these settings; only refreshes after that are +gated. Manual `view.refresh()` keeps working whether or not automatic +refresh is enabled. + +## When a refresh fails {#failures} + +A refresh replaces the view's stored rows in one commit, so a failure leaves +the view as it was after its last successful refresh. Fix the cause and +refresh again. + +## Related guides {#next} + + + + Define the query a view stores. + + + The same idea, for a single derived column. + + diff --git a/docs/web/feature-engineering/view.mdx b/docs/web/feature-engineering/view.mdx new file mode 100644 index 000000000..e61b2118a --- /dev/null +++ b/docs/web/feature-engineering/view.mdx @@ -0,0 +1,73 @@ +--- +title: "Create a view" +sidebarTitle: "Create View" +description: "Define a derived dataset as a saved query, with no storage or refresh of its own." +icon: eye +keywords: ["view", "create view", "feature engineering", "saved query"] +availability: + embedded: unavailable + enterprise: available +--- + +A view is the lightest way to derive a feature-engineered dataset: it stores +a **query**, not rows, so there is nothing to refresh and nothing that can +fall out of date. Reach for one before +[a computed column](/feature-engineering/add-computed-column) or +[a materialized view](/feature-engineering/materialized-views) when the +underlying query is cheap enough to simply re-run on every read. + +## Define a view {#create} + +A view over a products table, selecting and deriving a few columns: + +```sql +CREATE VIEW "discounted_products" AS +SELECT id, name, price, price * 0.9 AS sale_price +FROM "products" +WHERE in_stock = true +``` + +The statement resolves the view's schema from the query at creation time. +Anything the [SQL dialect](/sql/functions) supports can define one: joins, +predicates, aggregates, window functions -- the same expressiveness as +[a computed column's](/feature-engineering/add-computed-column#expressions) +SQL expression, just over a whole derived table instead of one column. + +## Read it like a table {#reading} + +```sql +SELECT * FROM "discounted_products" WHERE sale_price < 20 +``` + +Every read runs the saved query against current data, so `sale_price` +reflects whatever `price` is right now -- there is no staleness window to +reason about, unlike a materialized view between refreshes. A predicate +applied when reading the view composes with the query inside it, rather than +filtering the view's output afterward, so a selective filter does not pay +for rows the view would have produced and then discarded. + +## When to use a view instead {#choosing} + +| | View | Computed column / materialized view | +| --- | --- | --- | +| Stores | the query | derived values | +| Freshness | always current | as of the last refresh | +| Read cost | the full query, every read | a column or table scan | +| Write cost | none | a refresh | + +Reach for a view when the query is cheap, or when reading a stale value would +be wrong for the workload. Reach for a computed column or a materialized view +when the query is expensive and the data changes less often than it is read. +See [View](/sql/ddl/view#choosing) for the full SQL reference comparison, +including the separate privileges each one needs. + +## What to read next {#next} + + + + CREATE VIEW, DROP VIEW, and listing views alongside tables. + + + The stored-rows counterpart, and when a refresh is worth paying for. + + diff --git a/docs/web/governance/authorization.mdx b/docs/web/governance/authorization.mdx index 72e4e9534..c7831590b 100644 --- a/docs/web/governance/authorization.mdx +++ b/docs/web/governance/authorization.mdx @@ -5,10 +5,8 @@ description: "Who may do what: privileges granted on catalog objects to principa icon: shield-halved keywords: ["authorization", "authz", "privileges", "rbac", "access control"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports catalog privileges when its administrator configures enforcement. LanceDB Embedded has no catalog authorization layer: access is whatever the object store allows. --- [Authentication](/enterprise/authentication) establishes who is calling. diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 11b72505d..3cd157897 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -19,29 +19,6 @@ Training data and experimentation slow down when raw data, metadata, embeddings, artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed. -![Training data lifecycle: Curation, Feature Engineering, Search and Retrieval, Training](/static/assets/images/overview/training-data-lifecycle.svg) - -Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs. -Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble -GPU-ready batches from a tagged dataset version. - -For a deeper look at how this works in training pipelines, start with [Why LanceDB for training](/training/why-lancedb). - -## LanceDB suite {#lancedb-suite} - -The LanceDB suite includes LanceDB Embedded (open source), a retrieval library, and LanceDB Enterprise, -a multimodal lakehouse platform for the full AI data lifecycle. -LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. -It is easy to set up on a local machine for search and regular-scale workflows. LanceDB Enterprise is built -for teams that need scale without building bespoke infrastructure for curation, -feature engineering, search and retrieval, and efficient training data access. -LanceDB Enterprise runs LanceDB Distributed: query execution, indexing and maintenance -run on the Enterprise service, outside your application. - -![LanceDB suite: LanceDB Embedded search and Enterprise multimodal lakehouse on Lance format](/static/assets/images/overview/lancedb-suite.svg) - -## Why teams use LanceDB {#why-teams-use-lancedb} - Store images, video, audio, text, annotations, embeddings, and model-generated features together in one schema-enforced table. @@ -58,70 +35,149 @@ run on the Enterprise service, outside your application. +Use the same table to curate training data, add derived features, retrieve examples, and feed training jobs that rely on expensive GPUs. +Training workloads can sample, shuffle, and scan projected columns from local storage or object storage, then assemble +GPU-ready batches from a tagged dataset version. Training pipelines need curation, derived features, reproducible +splits, fast random access, and a clean path into frameworks such as PyTorch -- LanceDB keeps all of it connected +through the same table model, whether a workflow uses one table or several related ones. + +## Architecture {#architecture} + +LanceDB Embedded and Enterprise are both built on [Lance](/basics/lance), which stores table data, versions, and +indexes in open, columnar files. The format and table model are the same across both offerings -- what changes is +how storage and compute are organized around them. + +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 45, "rankSpacing": 55, "padding": 12}}}%% +flowchart TB + subgraph Embedded["LanceDB Embedded"] + EmbApp(["Your application
+ LanceDB SDK"]) + end + + subgraph Enterprise["LanceDB Enterprise"] + EntSdk(["LanceDB SDK"]) --> EntEngine{{"Enterprise Distributed Engine"}} + end + + Lance[("Lance format
table data, versions, indexes")] + + Embedded --> Lance + Enterprise --> Lance +``` + +Embedded reads and writes tables on local disk or in object storage from inside your application process. +Enterprise keeps durable table data and index artifacts in object storage, independently of the machines serving +requests, and separates query serving, read execution and caching, and indexing and background work into their +own independently sized components. Caches accelerate reads; they are never the durable source of truth. With +multiple serving replicas, Enterprise routes traffic to surviving nodes when one fails; losing a cache node +temporarily raises latency while its replacement warms, rather than causing an outage. + +Sharing a format does not mean an Enterprise deployment automatically opens an existing Embedded database -- +plan how to move or connect your data and configure access for your deployment. + +## Embedded and Enterprise {#embedded-and-enterprise} + +LanceDB ships as two offerings on the same Lance format and table model. Start locally with Embedded, then move to +Enterprise when your team needs distributed scale, managed infrastructure, private deployment, or higher-throughput +curation, feature engineering, search and retrieval, and training workflows. + +### 1\. LanceDB Embedded {#1-lancedb-oss} + +**LanceDB Embedded** is an open-source, embedded retrieval library, with client SDKs in Python, TypeScript and +Rust -- the application itself plans queries, builds indexes, and runs background work, with no separate database +server to deploy. This fits local retrieval applications, notebooks, development, and single-node data pipelines, +where your application controls its own compute resources and [table maintenance](/maintenance/compaction). + +### 2\. LanceDB Enterprise {#2-lancedb-enterprise} + +[LanceDB Enterprise](/enterprise) is a petabyte-scale (and beyond), distributed **multimodal lakehouse** platform +built for search, curation, feature engineering, and high-throughput training data access workflows on top of the +same core table abstraction, without building bespoke infrastructure. Applications connect through a LanceDB SDK +while the service handles requests across a fleet, with query serving, read execution and caching, and indexing +and background work sized and scaled as separate components. A control plane governs configuration, identity +and cluster lifecycle, separately from the data-plane components in the diagram below. See +[Distributed search](/enterprise/distributed-search) for how query nodes and plan executors divide a request. + +```mermaid +%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 45, "rankSpacing": 55, "padding": 12}}}%% +flowchart TB + Clients(["Clients"]) + QueryFleet{{"Query Fleet
query serving"}} + ExecutorRing{{"Executor Ring
read execution + cache"}} + MonitoringFleet{{"Monitoring Fleet"}} + JobWorkerFleet{{"Job Worker Fleet
indexing, column + MV refresh, compaction"}} + Storage[("Cloud Object Storage")] + + Clients --> QueryFleet + QueryFleet -- reads --> ExecutorRing + QueryFleet -- writes --> Storage + QueryFleet -- notifies --> MonitoringFleet + MonitoringFleet -- creates jobs --> JobWorkerFleet + ExecutorRing -- reads --> Storage + JobWorkerFleet -- writes --> Storage +``` + +Teams choose Enterprise to: + +- **Serve growing workloads** -- add query-serving capacity and let Enterprise cache frequently read table data near + compute as traffic grows. +- **Reduce operational work** -- let the service handle background [compaction](/maintenance/compaction) and + [cleanup](/maintenance/cleanup) instead of scheduling them in application code. +- **Fit deployment requirements** -- run a managed deployment or bring LanceDB into your own cloud account, with + OpenTelemetry metrics and traces. +- **Connect data workflows** -- use the same tables for retrieval, curation, and training data access, with + [SQL](/basics/sql), [feature engineering](/feature-engineering), and [Geneva](/geneva) feature backfills. + +To set up LanceDB Enterprise in your organization, [reach out to us](https://www.lancedb.com/contact). + +### Compare features {#compare} + +{/* availability-comparison */} + +## Projects using LanceDB {#projects-using-lancedb} + +### Training {#training} + +- [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) -- a platform for reproducible world-model + research built on a LanceDB data layer, reporting 3-4x faster data loading on Push-T versus HDF5 / MP4 at a + fraction of the disk footprint. +- [le-wm](https://github.com/lucas-maes/le-wm) -- a joint-embedding predictive world model from pixels, trained on + the stable-worldmodel platform and its LanceDB data layer. +- [lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb) -- a drop-in LanceDB backend for Hugging Face + LeRobot datasets with faster loading across robotics datasets. + +### Agentic applications {#agentic-applications} + +- [OpenClaw LanceDB Plugin](https://docs.openclaw.ai/plugins/memory-lancedb) -- stores an agent's long-term memory + in LanceDB, automatically recalling relevant memories before a model turn and capturing new facts afterward. +- [Cognee](https://github.com/topoteretes/cognee) -- an open-source AI memory platform that gives agents persistent + memory across sessions, using LanceDB as one of its vector store backends. +- [CrewAI](https://github.com/crewAIInc/crewAI) -- a multi-agent framework that + [rebuilt its agent memory on LanceDB](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb). + +Across these projects, LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, +features, and training or memory access patterns in one format instead of scattering them across task-specific +stores. + ## Start with your workload {#start-with-your-workload} - - Learn why LanceDB works well as the data layer for training workloads. - - - Use LanceDB tables and permutations for projected, shuffled, random-access training reads. - - - Explore Lance-formatted multimodal datasets with raw bytes, metadata, embeddings, and indices. + + Create tables, append records, and update or delete rows as your data changes. Use vector search, full-text search, hybrid search, reranking, filtering, and SQL. + + Profile, sample, chunk, join, and deduplicate records before training on them. + + + Derive computed columns and materialized views without moving data elsewhere. + + + Use LanceDB tables and permutations for projected, shuffled, random-access training reads. + + + Create, list, and drop tables, namespaces, and views from Python, TypeScript, or SQL. + -## From local development to production scale {#from-local-development-to-production-scale} - -LanceDB Embedded and LanceDB Enterprise share the same Lance format and table model. Start locally with -LanceDB Embedded, then move to Enterprise when your team needs distributed scale, managed infrastructure, private deployment, -or higher-throughput curation, feature engineering, search and retrieval, and training workflows. - -### 1\. LanceDB Embedded {#1-lancedb-oss} -The fastest way to get started is the open-source embedded library, with client SDKs in Python, TypeScript -and Rust. Run it locally in just a few steps, which lets you explore datasets, curate data, and run search and retrieval workloads -for agents. Start here: - - - - Get started with LanceDB in minutes. - - - Create tables, evolve schemas, version data, and modify rows in LanceDB. - - - -### 2\. LanceDB Enterprise {#2-lancedb-enterprise} - -[LanceDB Enterprise](/enterprise) is a petabyte-scale (and beyond), distributed **multimodal lakehouse** platform built for -search, curation, feature engineering, and high-throughput training data access workflows on top of the same core table -abstraction. This eliminates the need for teams to build bespoke infrastructure to manage large multimodal datasets. -To set up LanceDB Enterprise in your organization, -[reach out to us](https://www.lancedb.com/contact). - - -**Built with scale, performance, and security in mind.** - -LanceDB Enterprise is designed for very large-scale, high-performance, distributed workloads in -private deployments, and can operate under strict [security requirements](/enterprise/security). - - - - Get started with LanceDB in minutes, including Enterprise `db://` connections. - diff --git a/docs/web/indexing/fts-index.mdx b/docs/web/indexing/fts-index.mdx index f112c996f..ac3ff36e5 100644 --- a/docs/web/indexing/fts-index.mdx +++ b/docs/web/indexing/fts-index.mdx @@ -4,12 +4,8 @@ sidebarTitle: "FTS Index" description: "Create and tune BM25-based full-text search indexes in LanceDB." icon: "book" availability: - oss: available + embedded: available enterprise: available - summary: >- - Full-text indexes are built in the embedded library and in LanceDB Enterprise. - The embedded library builds the index before the call returns; a - deployment builds it in the background. --- import { PyFtsIndexAsync as FtsIndexAsync, PyFtsIndexCreate as FtsIndexCreate, PyFtsIndexNested as FtsIndexNested, PyFtsIndexWait as FtsIndexWait } from '/snippets/indexing.mdx'; diff --git a/docs/web/indexing/index.mdx b/docs/web/indexing/index.mdx index 78844527f..e408acb78 100644 --- a/docs/web/indexing/index.mdx +++ b/docs/web/indexing/index.mdx @@ -4,11 +4,8 @@ sidebarTitle: "Overview" description: "Optimize search performance with LanceDB using vector indexes, full-text search, scalar indexes, and more." icon: "list" availability: - oss: available + embedded: available enterprise: available - summary: >- - Indexes are built in the embedded library and in LanceDB Enterprise. Enterprise builds them in the background, and builds fewer vector index types than the - embedded library. --- Indexes speed up searches and filters by organizing data for specific query diff --git a/docs/web/indexing/reindexing.mdx b/docs/web/indexing/reindexing.mdx index 27a51a3d3..68d0f5d73 100644 --- a/docs/web/indexing/reindexing.mdx +++ b/docs/web/indexing/reindexing.mdx @@ -5,13 +5,8 @@ description: "Learn how to keep your indexes up-to-date in LanceDB using increme icon: "refresh" keywords: ["reindexing", "re-index", "incremental indexing", "reindex"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Indexes are kept up to date in the embedded library and in LanceDB Enterprise. In - the embedded library you add new rows to them with `optimize()`; a - deployment does it in the background, and `optimize()` is not available - there. --- import { diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index 9f1f9a176..d99bb6003 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Scalar Index" description: "Learn how to use scalar indexes in LanceDB for efficient metadata filtering and query optimization." icon: "tree" availability: - oss: available + embedded: available enterprise: available - summary: >- - Scalar indexes are built in the embedded library and in LanceDB Enterprise. A - deployment builds them in the background and keeps most of them up to date - itself; in the embedded library you update them with `optimize()`. --- import { diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 33d6a8575..3e2b7d6f0 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -4,13 +4,8 @@ sidebarTitle: "Vector Index" description: "Build and manage LanceDB vector indexes." icon: "arrow-up-right-dots" availability: - oss: available + embedded: available enterprise: available - summary: >- - Vector indexes are built in the embedded library and in LanceDB Enterprise. The - embedded library builds an index before `create_index()` returns; a - deployment builds it in the background, keeps it up to date, and builds - only `IVF_FLAT`, `IVF_PQ`, `IVF_RQ` and `IVF_HNSW_SQ`. --- import { diff --git a/docs/web/ingestion/create-table.mdx b/docs/web/ingestion/create-table.mdx index 00425a1f9..ec13c02b7 100644 --- a/docs/web/ingestion/create-table.mdx +++ b/docs/web/ingestion/create-table.mdx @@ -5,10 +5,8 @@ description: "Create a table from records or a schema and choose input formats." icon: table keywords: ["create table", "ingest", "arrow", "pandas", "polars", "pydantic", "schema"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Create and open tables in LanceDB Embedded and LanceDB Enterprise. --- import { diff --git a/docs/web/ingestion/delete.mdx b/docs/web/ingestion/delete.mdx index f02320733..2b961fc4b 100644 --- a/docs/web/ingestion/delete.mdx +++ b/docs/web/ingestion/delete.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Delete" description: "Select and delete records, verify the remaining rows, and understand storage retention." icon: trash availability: - oss: available + embedded: available enterprise: available - summary: >- - Delete rows through the SDKs in LanceDB Embedded and LanceDB Enterprise. Storage reclamation follows compaction and retention policy. --- import { RsExample as RsDeleteRows } from '/snippets/ingestion_delete.mdx'; diff --git a/docs/web/ingestion/index.mdx b/docs/web/ingestion/index.mdx index 9eb453cd6..28cfce650 100644 --- a/docs/web/ingestion/index.mdx +++ b/docs/web/ingestion/index.mdx @@ -5,10 +5,8 @@ description: "Choose how to create a table, append records or change existing da icon: inbox keywords: ["ingest", "create table", "add", "insert", "arrow", "pandas", "polars", "pydantic"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Create tables and write records through the SDKs in LanceDB Embedded and LanceDB Enterprise. Enterprise also provides SQL write statements. --- import { PyWriteWorkflow, TsWriteWorkflowBody, TsWriteWorkflowTail, RsWriteWorkflow } from '/snippets/ingestion_examples.mdx'; @@ -32,7 +30,7 @@ with a stable key when the incoming data should update existing records. ## Connect and prepare the data {#connect-to-lancedb} -Use the [connection guide](/basics/connect) to connect to LanceDB Embedded or LanceDB Enterprise. +Use the [connection guide](/basics/catalog) to connect to Embedded or Enterprise. The SDK write operations in this section work with both. Enterprise also supports [SQL write statements](/sql#dml); an SDK filter expression does not require a separate SQL connection. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index 2c5823f4e..cd15bc65b 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Insert" description: "Append records, load file-backed data or batches, and verify ingestion." icon: plus availability: - oss: available + embedded: available enterprise: available - summary: >- - Append records through the SDKs in LanceDB Embedded and LanceDB Enterprise. For large Enterprise writes, see [large upload settings](#bulk-ingests-into-a-remote-table). --- import { diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index 74b161c29..a9ad3071c 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Merge Insert" description: "Match incoming records by key and choose which rows to update, insert or remove." icon: code-merge availability: - oss: available + embedded: available enterprise: available - summary: >- - Merge insert is available through the SDKs in LanceDB Embedded and LanceDB Enterprise. Use it for key-based updates and inserts. --- import { diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx new file mode 100644 index 000000000..bed77eed5 --- /dev/null +++ b/docs/web/ingestion/realtime-write.mdx @@ -0,0 +1,196 @@ +--- +title: "Real Time writes" +sidebarTitle: "Real Time Write" +description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." +icon: "bolt" +keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +availability: + embedded: unavailable + enterprise: available +--- + +The [real time engine](/tables/realtime-engine) puts an LSM-style write tier in +front of a table, turning many small writes into a few large commits. This +page covers enabling it and writing to a table; for querying an RTE table, see +[Real Time reads](/search/realtime-read). + +## Getting started {#getting-started} + +### 1. Create a table with a primary key {#primary-key} + +RTE deduplicates writes by primary key. Create the table with a non-nullable +key column, then declare it with `set_unenforced_primary_key`. The key is a +single `int32`, `int64`, string, or binary column, and cannot be changed once +set. + +The table below holds frames captioned and embedded as they stream in from a +live camera feed, such as a robot recording episodes into a dataset shaped +like [LeRobotDataset](/integrations/lerobotdataset)'s `frames` table — +`frame_id` is the primary key so a re-captioned frame upserts in place: + + +```python Python icon="python" +from datetime import timedelta + +import lancedb +import numpy as np +import pyarrow as pa +from lancedb import RTEWriteSpec +from lancedb.index import FTS, BTree, IvfPq + +db = lancedb.connect("db://my_db", api_key="...", host_override="https://...") + +dim = 768 +schema = pa.schema([ + pa.field("frame_id", pa.int64(), nullable=False), + pa.field("video_id", pa.utf8(), nullable=False), + pa.field("embedding", pa.list_(pa.float32(), dim)), + pa.field("caption", pa.utf8()), +]) +frames = db.create_table("frames", schema=schema) +frames.set_unenforced_primary_key("frame_id") +``` + + +Or in SQL: + + +```sql SQL +ALTER TABLE frames SET UNENFORCED PRIMARY KEY (frame_id) +``` + + +### 2. Create indexes {#indexes} + +By default, RTE maintains every supported index on the table, including +indexes created after it is enabled. A scalar index on the primary key is +required for partial updates and deletes. + + +```python Python icon="python" +frames.create_index("embedding", config=IvfPq()) +frames.create_index("caption", config=FTS()) +frames.create_index("frame_id", config=BTree()) +frames.wait_for_index(["embedding_idx", "caption_idx", "frame_id_idx"], timeout=timedelta(minutes=5)) +``` + + +### 3. Enable RTE {#enable} + + +```python Python icon="python" +frames.enable_rte(RTEWriteSpec.unsharded()) +``` + + +Or in SQL: + + +```sql SQL +ALTER TABLE frames SET RTE +``` + + +### 4. Write {#write} + + +On an RTE table, an upsert through `merge_insert` is the only way to write +rows. Use the form below exactly: `when_matched_update_all()` with no filter, +plus `when_not_matched_insert_all()`. Other `merge_insert` forms, such as +conditional updates or deleting rows missing from the source, are rejected. + + +Writes go through `merge_insert` on the primary key, and are visible to queries +immediately — see [Real Time reads](/search/realtime-read) for querying them +back: + + +```python Python icon="python" +new_frames = pa.table({ + "frame_id": pa.array([2000, 2001], pa.int64()), + "video_id": pa.array(["clip-9", "clip-9"]), + "embedding": pa.FixedSizeListArray.from_arrays( + pa.array(np.random.rand(2 * dim).astype("float32")), dim), + "caption": pa.array(["a gripper closing on a cup", "a cup set down on the table"]), +}, schema=schema) + +frames.merge_insert("frame_id") \ + .when_matched_update_all() \ + .when_not_matched_insert_all() \ + .execute(new_frames) +``` + + +**Partial updates.** Send the primary key plus only the columns you want to +change; omitted columns keep their current values. This requires a scalar +index on the primary key. A re-captioning job, for example, only touches +`caption`: + + +```python Python icon="python" +patch = pa.table( + {"frame_id": [2000, 2001], "caption": ["a two-finger gripper closing on a cup", "the cup resting upright"]}, + schema=pa.schema([schema.field("frame_id"), schema.field("caption")]), +) +frames.merge_insert("frame_id").when_matched_update_all().when_not_matched_insert_all().execute(patch) +``` + + +**Deletes.** The predicate must bind the primary key to literal values. Ranges, +`OR`, and filters on other columns are rejected. Deletes require a scalar index +on the primary key. + + +```python Python icon="python" +frames.delete("frame_id IN (2000, 2001)") +``` + + +### Disabling RTE {#disable} + +Stop writes and wait for in-flight writes to finish, then flush pending writes +into the base table and disable. `checkpoint_rte()` only drains writes that +existed when it started, so anything written during the checkpoint can be left +behind. `disable_rte()` is rejected while the write-ahead log still holds rows, +so run `checkpoint_rte()` first. + + +```python Python icon="python" +frames.checkpoint_rte() +frames.disable_rte() +``` + + +## Write performance {#write-performance} + +RTE acknowledges a write as soon as it is durable in the write-ahead log, so +ingest is no longer limited by how fast the table can commit. + +**Compared with writing directly to the table.** On tables ranging from +hundreds of thousands to tens of millions of rows, RTE delivered 4–12× the +write throughput and 24–52× lower p99 write latency, depending on the mix of +inserts, updates, and deletes. + +**Scaling with shards.** An RTE table can be split into +[shards](/sql/ddl/table#properties) that write independently, and a single +table's ingest grows with its shard count. In our testing on AWS, with every +index on the table (vector, full-text, and BTree) kept current, a single table +reached these peak rates: + +| Shards | Peak ingest | +| --: | --: | +| 1 | 90 MB/s | +| 2 | 170 MB/s | +| 4 | 340 MB/s | +| 8 | 625 MB/s | +| 16 | 690 MB/s | +| 32 | 885 MB/s | + +Adding shards scales a table's ingest nearly linearly. + +## Next steps {#next-steps} + +- [Real Time reads](/search/realtime-read) — query an RTE table +- [How the real time engine works](/tables/realtime-engine#how-it-works) +- [Merge insert](/ingestion/merge-insert) +- [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/ingestion/update.mdx b/docs/web/ingestion/update.mdx index 4a5fdaa24..ad4ae23b2 100644 --- a/docs/web/ingestion/update.mdx +++ b/docs/web/ingestion/update.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Update" description: "Select existing rows, change values or expressions, and verify the changes." icon: pen availability: - oss: available + embedded: available enterprise: available - summary: >- - Update rows through the SDKs in LanceDB Embedded and LanceDB Enterprise. Enterprise also supports the SQL UPDATE statement. --- import { @@ -83,7 +81,7 @@ connection or table handle, account for its Nested-field updates are not supported by these operations. For schema changes, see [schema evolution](/management/table#schema). Treat derived values separately: changing an input field is not a guarantee that every stored feature has been -recomputed. See [Refresh a column](/feature-engineering/refresh-column). +recomputed. See [Refresh a computed column](/feature-engineering/refresh-column). Updates can change index coverage and query cost. After a large update, inspect the workload and follow [index maintenance](/indexing/reindexing) diff --git a/docs/web/integrations/ai/huggingface.mdx b/docs/web/integrations/ai/huggingface.mdx index 0a38c208b..b284d38a2 100644 --- a/docs/web/integrations/ai/huggingface.mdx +++ b/docs/web/integrations/ai/huggingface.mdx @@ -3,11 +3,8 @@ title: "Hugging Face Hub" sidebarTitle: "Hugging Face" description: "Use LanceDB directly on Lance datasets hosted on the Hugging Face Hub for multimodal search and retrieval." availability: - oss: available - enterprise: unavailable - summary: >- - The embedded library opens Lance datasets on the Hugging Face Hub in place - through `hf://` URIs. A deployment does not read `hf://` datasets. + embedded: available + enterprise: available --- [Hugging Face Hub](https://huggingface.co/datasets?format=format:lance&sort=trending) is a popular platform for sharing machine learning datasets, models, and other resources. diff --git a/docs/web/integrations/data/pandas_and_pyarrow.mdx b/docs/web/integrations/data/pandas_and_pyarrow.mdx index c646e7f3b..810536587 100644 --- a/docs/web/integrations/data/pandas_and_pyarrow.mdx +++ b/docs/web/integrations/data/pandas_and_pyarrow.mdx @@ -2,12 +2,8 @@ title: "Pandas and PyArrow" sidebarTitle: "Pandas & PyArrow" availability: - oss: available + embedded: available enterprise: available - summary: >- - DataFrames go into `create_table` and come back from query results the same - way for local and deployment tables. - --- import { diff --git a/docs/web/integrations/data/polars_arrow.mdx b/docs/web/integrations/data/polars_arrow.mdx index 8eaaa6440..4ff759211 100644 --- a/docs/web/integrations/data/polars_arrow.mdx +++ b/docs/web/integrations/data/polars_arrow.mdx @@ -2,13 +2,8 @@ title: "Polars" sidebarTitle: "Polars & Arrow" availability: - oss: available + embedded: available enterprise: available - summary: >- - Polars data goes into `create_table`, and query results come back as Polars - DataFrames, for local and deployment tables alike; a LazyFrame over a whole - table is local only. - --- import { diff --git a/docs/web/integrations/data/pydantic.mdx b/docs/web/integrations/data/pydantic.mdx index 3ac660774..132ce7801 100644 --- a/docs/web/integrations/data/pydantic.mdx +++ b/docs/web/integrations/data/pydantic.mdx @@ -2,13 +2,8 @@ title: "Pydantic" sidebarTitle: "Pydantic" availability: - oss: available + embedded: available enterprise: available - summary: >- - The SDK converts `LanceModel` schemas to Arrow, and query rows back to - models, in your process, so they work the same with local and deployment - tables. - --- import { diff --git a/docs/web/integrations/lerobotdataset.mdx b/docs/web/integrations/lerobotdataset.mdx index cfb66b69b..260921034 100644 --- a/docs/web/integrations/lerobotdataset.mdx +++ b/docs/web/integrations/lerobotdataset.mdx @@ -138,6 +138,25 @@ class EmbedFromBlob: # SigLIP2 loads once per worker ... ``` +**Deduplication** removes near-static runs before they skew curation or +training. A stopped gripper holding one pose for a few seconds produces many +frames whose `emb_siglip2` vectors are nearly identical; LanceDB Enterprise's +native [`dedupe`](/sql/dql/dedupe) collapses them into one +representative per cluster, directly over the index, without a pairwise scan: + +```python +db.execute_query(""" + CREATE MATERIALIZED VIEW frames_deduped AS + SELECT * FROM dedupe('frames', 'emb_siglip2', distance_threshold => 0.01) +""") +``` + +Every column survives the dedup unchanged -- `jerk_score`, the episode and +camera metadata, the video blob reference -- since `dedupe` returns full +rows, not just which ones matched. Wrap it in a materialized view, as above, +to keep the deduplicated set current as new episodes land; see +[Materialized views](/feature-engineering/materialized-views). + **Search** is an index on those columns: a vector index over the embeddings built in 29.7 s across 27.6M rows, a full-text index over the instructions in 7.0 s, queries in 10 to 54 ms. **Curation** is one query across all of it. Semantic search with a predicate on the derived score, no join, no second system: diff --git a/docs/web/maintenance/background-jobs.mdx b/docs/web/maintenance/background-jobs.mdx index cfeab74df..3c2718cfe 100644 --- a/docs/web/maintenance/background-jobs.mdx +++ b/docs/web/maintenance/background-jobs.mdx @@ -5,16 +5,13 @@ description: "Understand the Enterprise background jobs that maintain tables, in icon: gears keywords: ["background jobs", "job type", "wal", "spfresh", "prewarm", "archive"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - LanceDB Enterprise schedules background maintenance jobs according to your - cluster configuration. --- The jobs documented elsewhere in these docs ([Build & Repair](/indexing/reindexing), [Compaction](/maintenance/compaction), [Cleanup](/maintenance/cleanup), -[Column Refresh](/feature-engineering/refresh-column)) start from a call you +[Refresh Computed Column](/feature-engineering/refresh-column)) start from a call you make or, for compaction, cleanup and index updates, from the deployment's own maintenance. This page is the rest: jobs the deployment runs to keep itself correct and fast, which you may see named in [`SHOW JOBS`](/sql/ddl/job#show) @@ -27,7 +24,7 @@ also start cache-warming jobs through the admin API. ## Write-ahead log maintenance {#wal} -For a table with the [realtime engine](/tables/realtime-engine) enabled, two jobs keep the +For a table with the [real time engine](/tables/realtime-engine) enabled, two jobs keep the log from growing without bound: | Job type | What it does | diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 4b9e24796..365eb66e8 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -5,10 +5,8 @@ description: "Pruning old versions and the files only they referenced." icon: broom keywords: ["cleanup", "retention", "prune", "delete_unverified", "vacuum"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Both offerings support cleanup. Embedded `optimize()` uses a retention window of 7 days by default; Enterprise uses configured background cleanup and retention, and does not support `optimize()`. --- Every write keeps the version before it, which is what makes diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index be6685d9c..64f18b095 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Compaction" description: "Merge small files, prune old versions, and fold new rows into existing indexes." icon: broom availability: - oss: available + embedded: available enterprise: available - summary: >- - Tables are compacted in the embedded library and in LanceDB Enterprise. In the - embedded library you call `optimize()`; a deployment compacts tables in the - background, and `optimize()` is not available there. --- import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompactionTuning } from '/snippets/doc_storage_examples.mdx'; @@ -98,7 +94,7 @@ continuous small writes needs it on a schedule. Compaction rewrites files, which conflicts with a concurrent [computed-column refresh](/feature-engineering/add-computed-column) or -[view refresh](/feature-engineering/materialized-views) planned against the +[view refresh](/feature-engineering/refresh-materialized-view) planned against the version it replaces. Sequence them rather than running both at once. diff --git a/docs/web/management/database.mdx b/docs/web/management/database.mdx index 35b63c308..6651d6409 100644 --- a/docs/web/management/database.mdx +++ b/docs/web/management/database.mdx @@ -5,12 +5,8 @@ description: "Connect to LanceDB and configure storage, credentials and read con icon: database keywords: ["connect", "database", "uri", "api key", "storage options", "consistency"] availability: - oss: available + embedded: available enterprise: available - summary: >- - LanceDB Embedded opens tables in a local directory or object storage. - LanceDB Enterprise connects with a database URI and credentials and runs - operations with LanceDB Distributed. --- import { PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; @@ -27,11 +23,10 @@ objects, and configure how your application reaches the data. | `s3://bucket/path`, `gs://bucket/path`, `az://container/path` | LanceDB Embedded, with object storage | In your application | | `db://my-database` | LanceDB Enterprise | On the Enterprise service (LanceDB Distributed) | -[Connect to LanceDB](/basics/connect) has examples for each connection type. -A connection to object storage still uses LanceDB Embedded: your process -reads and writes the bucket directly. LanceDB Enterprise runs LanceDB -Distributed: query execution, indexing and maintenance run on the Enterprise -service, outside your application. +[Connect to LanceDB](/basics/catalog) has examples for each connection type. +A connection to object storage still uses the embedded library: your process +reads and writes the bucket directly. Enterprise runs operations remotely and +manages the supporting compute and maintenance. ## Connect to Enterprise {#deployment} diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 7825b0bf6..415de7613 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -4,11 +4,6 @@ sidebarTitle: "Function" description: "Register a Python function once and apply it as a column, for work SQL cannot express." icon: code keywords: ["udf", "functions", "create_function", "embedding", "feature engineering"] -availability: - oss: unavailable - enterprise: available - summary: >- - Enterprise supports Functions when enabled for your Enterprise cluster; LanceDB Embedded cannot register or run them. --- import { @@ -110,6 +105,26 @@ with `db.get_function(name, version=...)`. the function is baked into an image before the version becomes usable.
+## Try it in SQL {#try-sql} + +A registered function is callable in SQL by its name, the same as any other +scalar function. Before applying it as a column, call it directly over the +table to check the registration succeeded, without committing a schema +change: + + +```python Python icon="python" +reader = db.execute_query("SELECT value, double(value) AS doubled FROM function_demo") +print(reader.read_all().to_pylist()) +# [{'value': 1.0, 'doubled': 2.0}, {'value': 2.0, 'doubled': 4.0}, {'value': 3.0, 'doubled': 6.0}] +``` + + + +Equivalent SQL: `SELECT value, double(value) AS doubled FROM function_demo`. +See [Querying with SQL](/basics/sql) for `execute_query` and other languages. + + ## Apply it as a column {#apply} Calling the registered version binds each parameter, by name, to a column with @@ -124,6 +139,51 @@ function application keeps its scalar or named-struct result in the named column. A bare named-struct application expands its result fields as one atomic binding, with aliases from `rename(columns=...)`. +### Bind more than one input, or fill more than one column {#multi} + +Parameters bind by name, so a function that takes several arguments binds +several columns in one call: + + +```python Python icon="python" +@udf +def ratio(numerator: float, denominator: float) -> float: + return numerator / denominator + +version = db.create_function_async(ratio).wait() +table.add_columns({"ratio": version(numerator=col("value"), denominator=col("count"))}) +``` + + +A named-struct output fills more than one column from a single application. +Declare the fields with `output_schema`, then alias each field to the column +it fills with `rename(columns=...)` and pass the application itself, not a +mapping, so both columns come from one atomic binding: + + +```python Python icon="python" +import pyarrow as pa + +@udf( + output_schema=pa.schema([ + pa.field("half", pa.float64(), nullable=False), + pa.field("double", pa.float64(), nullable=False), + ]), +) +def scale(value: float): + return {"half": value / 2, "double": value * 2} + +version = db.create_function_async(scale).wait() +application = version(value=col("value")).rename( + columns={"half": "value_half", "double": "value_double"} +) +table.add_columns(application) +``` + + +A single refresh fills `value_half` and `value_double` together: there is no +state where one is filled and the other is still empty. + ## Fill the column {#refresh} A refresh runs the function on the cluster as a [job](/basics/jobs). `wait()` @@ -188,46 +248,61 @@ undecorated class, so local tests can create an instance and call it directly. A Function can bind a [Blob v2 column](/management/table#managed-blobs) and return another blob. In row mode, a top-level blob parameter arrives as Python -`bytes`, or `None` for a nullable input. The worker reads the payload before -calling your function. Return bytes and let the destination table store the -Managed payload and descriptor. +`bytes`, or `None` for a nullable input, after the worker has read the +payload. Return bytes and let the destination table store the Managed +payload and descriptor. -Declare blob inputs and outputs explicitly. This example reverses the bytes -to demonstrate the round trip without requiring an image library. Here `db` -is an Enterprise database and `table` contains an `image` Blob v2 column -with table schema metadata `lance.blob.managed=true`, as in the -[table creation example](/management/table#managed-blobs-read-write): - -```python -from datetime import timedelta +The rest of this section extracts a frame from a stored video and captions +it, continuing as one example across chaining, persisting and incremental +reads below. `videos` holds raw clips in a `video` Blob v2 column; `frames` +names one timestamp per clip to extract, with a `selected` flag to skip some: + +```python Python icon="python" import lancedb -from lancedb import col -from lancedb.functions import udf import pyarrow as pa -@udf( - name="reverse_image", - python_version="3.12", - pip=["pyarrow==26.0.0"], - input_schema=pa.schema([lancedb.blob("image")]), - output_schema=lancedb.blob("reversed", nullable=False), -) -def reverse_image(image): - return b"missing" if image is None else image[::-1] - -function = db.create_function_async(reverse_image).wait( - timeout=timedelta(minutes=15) -) -table.add_columns({"reversed": function(image=col("image"))}) -result = table.refresh_column_async("reversed").wait( - timeout=timedelta(minutes=15) -) -assert result.rows_failed == 0 - -hits = table.search().select(["id", "reversed"]).with_row_id(True).to_arrow() -values = table.fetch_blobs("reversed", hits).to_pylist() +videos = db.create_table("videos", schema=pa.schema([ + pa.field("id", pa.utf8(), nullable=False), + lancedb.blob("video", nullable=False), +])) +frames = db.create_table("frames", [ + {"frame_id": 1, "video_id": "clip-1", "ts": 0.5, "selected": True}, + {"frame_id": 2, "video_id": "clip-1", "ts": 1.5, "selected": True}, +]) ``` + + +### Produce a blob {#produce-blobs} + +Declare blob inputs and outputs explicitly. `extract_frame` reads one frame +out of a video at a timestamp and returns it as a JPEG, without loading the +whole clip first -- see [Read a blob incrementally](#incremental) below for +how the `video: BlobReader` parameter does that: + + +```python Python icon="python" +from datetime import timedelta + +from lancedb import BlobReader, col +from lancedb.functions import udf + +@udf( + name="extract_frame", + gpu=True, + pip=["av==13.1.0", "pillow==11.0.0"], + input_schema=pa.schema([ + lancedb.blob("video"), + pa.field("ts", pa.float64(), nullable=False), + ]), + output_schema=lancedb.blob("jpeg", nullable=False), +) +def extract_frame(video: BlobReader, ts: float) -> bytes: + ... # decode the frame at ts, encode as JPEG, return its bytes + +version = db.create_function_async(extract_frame).wait(timeout=timedelta(minutes=15)) +``` + An empty byte string is a filled result. A scalar output cannot be nullable, because a physical NULL marks an unfilled computed row. To return a nullable @@ -235,29 +310,93 @@ blob as a value, use a named-struct output schema with a nullable blob field; the struct itself records whether the result has been filled. Read a nested blob with `table.fetch_blobs("payload.image", hits)`. -On deployments that support computed-column inputs, another Function can bind -to `col("reversed")`. Refresh the producer first, then the consumer. Once -outputs are current, a later refresh fills appended rows. A filtered refresh -preserves payload references for unselected Managed outputs. An unfiltered -refresh can recompute a whole fragment when it cannot establish that the -fragment's outputs are current. + +`output_schema=lancedb.blob(...)` is what makes a persisted result Blob v2 +rather than plain Arrow `binary`. Returning `bytes` from a function whose +output type is inferred from a bare annotation, with no explicit +`lancedb.blob(...)` output schema, persists as ordinary `binary`: the column +still holds the right bytes, but it skips the Managed storage path, descriptor +reads, and `fetch_blobs`. Declare it explicitly on every function whose output +should be a blob, not just the first one in a chain. + + +### Chain a Function on its output {#chain} + +A second Function can bind a blob another Function produced. Register +`caption` the same way, consuming a blob instead of producing one: + + +```python Python icon="python" +@udf(gpu=True, pip=["transformers==4.47.0"]) +def caption(jpeg: bytes) -> str: + ... # run a vision-language model over the JPEG, return one sentence + +caption_version = db.create_function_async(caption).wait(timeout=timedelta(minutes=15)) +``` + + +Compose both in one SQL statement over a join, instead of applying each as +its own column. The join supplies `video` and `ts` from two different +tables, and `caption` reads `extract_frame`'s result as it is computed, +before anything is written: + + +```sql SQL +SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, + caption(extract_frame(v.video, f.ts)) AS caption +FROM videos v JOIN frames f ON v.id = f.video_id +WHERE f.selected = true +``` + + +[`EXPLAIN`](/sql/dql/explain) on a query like this shows `RemoteTake`: the +blob is read once, where the worker runs, and never pulled into the query +node first. + +### Persist it as a column, or a materialized view {#persist} + +Apply the same chained expression with `add_columns` to persist it as an +ordinary table column: + + +```python Python icon="python" +table.add_columns({"jpeg": extract_frame(video=col("video"), ts=col("ts"))}) +result = table.refresh_column_async("jpeg").wait(timeout=timedelta(minutes=15)) +assert result.rows_failed == 0 + +hits = table.search().select(["frame_id", "jpeg"]).with_row_id(True).to_arrow() +values = table.fetch_blobs("jpeg", hits).to_pylist() +``` + + +Or wrap the join and both Functions in a +[materialized view](/sql/ddl/materialized-view) instead, so the extracted +frame and its caption stay current as new videos and frames arrive. See +[Automatic refresh](/feature-engineering/refresh-column#automatic) for +keeping either one fresh without calling refresh yourself. + +On deployments that support computed-column inputs, another Function can +bind to `col("jpeg")` directly, the same as the SQL join above does through +its own expression. Refresh the producer first, then the consumer. Once +outputs are current, a later refresh fills appended rows. A filtered +refresh preserves payload references for unselected Managed outputs. An +unfiltered refresh can recompute a whole fragment when it cannot establish +that the fragment's outputs are current. Function output blobs follow the same compaction and cleanup lifecycle as ingested Managed blobs. Retained versions continue to own their payloads; cleanup reclaims an object only after its retained references are gone. -### Draft: incremental blob inputs (upcoming) - -This feature requires an SDK that exports `BlobReader` and a compatible -Enterprise runtime with reader input support enabled. Coordinate the runtime -upgrade before registering or executing reader Functions. +### Read a blob incrementally {#incremental} Annotate a row Function parameter with `BlobReader` to read a Blob v2 input -incrementally. The signature selects the access mode without another -registration option. For example, read the first MP4 box type without loading -the whole video: +incrementally, the way `extract_frame` above does, instead of materializing +the whole payload first. The signature selects the access mode without +another registration option. A minimal example, reading only the first MP4 +box type without loading the rest of the video: -```python + +```python Python icon="python" from lancedb import BlobReader, udf @@ -266,12 +405,15 @@ def first_box_type(video: BlobReader) -> bytes: video.seek(4) return video.read(4) ``` + -The worker passes a seekable reader backed by the stored blob. `read(size)` -reads from the current cursor; `read_range(offset, length)` reads a byte range -without moving it. `size()` returns the payload size without reading it. -Each row call receives its own reader, which closes when the call returns or -raises. Do not retain it for another invocation. +The worker passes a seekable reader backed by the stored blob -- +`video.seekable()` is `True`. `read(size)` reads from the current cursor; +`read_range(offset, length)` reads a byte range without moving it, the same +bytes a `seek(offset)` followed by `read(length)` would read. `size()` +returns the payload size without reading it. Each row call receives its own +reader, which closes when the call returns or raises. Do not retain it for +another invocation. Use `video: bytes` when the Function needs the complete payload. Bytes inputs materialize before invocation and remain subject to eager input limits. @@ -293,6 +435,14 @@ dependencies are part of its definition: | `python_version` | Python major/minor for the execution environment, defaulting to yours | | `gpu` | whether every execution requires a GPU | + +```python Python icon="python" +@udf(gpu=True) +def extract_frame(video: BlobReader, ts: float) -> bytes: + ... # runs only on a GPU-capable worker +``` + + These are part of the **immutable function version**. Changing a dependency produces a new version rather than altering the one already registered, so a column filled by version 1 is unaffected by version 2. @@ -322,6 +472,46 @@ The client version defaults `python_version`, so a function registered from a right and occasionally surprising. Pin it when the function is sensitive to it. +## Remote calls and credentials {#secrets} + +A function that calls an external API needs a credential without putting it +in the function's source or its `env` map in plain text. A Secret is a +database-scoped named credential; `db.create_secret` stores the value once, +and an `EnvVarSecret` binds it to the environment variable the function +reads. Binding is a registration-time decision, passed to +`create_function_async`, not to `@udf`: + + +```python Python icon="python" +import os + +from lancedb import EnvVarSecret + +db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"]) + +@udf +def embed(text: str) -> list[float]: + import os + + from openai import OpenAI + + client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) + response = client.embeddings.create(input=text, model="text-embedding-3-small") + return response.data[0].embedding + +version = db.create_function_async( + embed, + secrets=[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")], +).wait() +``` + + +No API returns a Secret's value, and it never appears in the function's +registration: `embed` reads `OPENAI_API_KEY` the way it always did, and the +binding is what puts a value there. A mistyped Secret name is caught at +registration; a mistyped environment variable name surfaces only on the +first rows, since nothing records which variables a function reads. + ## Failure handling {#failures} A function that raises fails the job. There is no per-row retry or skip policy @@ -350,6 +540,25 @@ In practice this means a function should be self-contained: take its inputs as arguments, import what it needs at module level, and avoid capturing state from the surrounding scope. +Pass `code=[module, ...]` to ship additional helper modules into the same +image, for logic the function imports but that does not belong inlined into +it -- a model-loading helper shared by several Functions, for example. +Continuing `caption` from [above](#chain), with its model-loading code +factored into a sibling module instead of inlined: + + +```python Python icon="python" +import caption_worker # a sibling module with the model-loading logic + +@udf(gpu=True, code=[caption_worker]) +def caption(jpeg: bytes) -> str: + return caption_worker.run(jpeg) +``` + + +Each module in `code` is captured and shipped the same way the function +itself is: as source, snapshotted at registration. + ## Drop it {#drop} `db.drop_function(name, version=...)` drops the function's name and the object diff --git a/docs/web/management/index.mdx b/docs/web/management/index.mdx index 21222f418..9fc02ad6b 100644 --- a/docs/web/management/index.mdx +++ b/docs/web/management/index.mdx @@ -64,7 +64,7 @@ Enterprise, it requests the server's view listing. See [Materialized views](/management/materialized-view) for creating one, and -[Refresh a materialized view](/feature-engineering/materialized-views) for keeping +[Refresh a materialized view](/feature-engineering/refresh-materialized-view) for keeping it current. ### Views {#views} diff --git a/docs/web/management/materialized-view.mdx b/docs/web/management/materialized-view.mdx index 42245a51a..90283e198 100644 --- a/docs/web/management/materialized-view.mdx +++ b/docs/web/management/materialized-view.mdx @@ -5,10 +5,8 @@ description: "Create, open, list and drop a table whose contents are defined by icon: table keywords: ["materialized view", "create_materialized_view", "catalog", "ddl"] availability: - oss: available + embedded: unavailable enterprise: available - summary: >- - Both offerings support materialized views. See [Enterprise compatibility](#deployment) for connection and server requirements. --- A materialized view is a table whose contents are defined by a query over @@ -19,10 +17,10 @@ The result is an ordinary table: queryable, indexable, searchable, and present in `table_names()`. Nothing about reading it is special. This page covers creating and managing one. Keeping it current is -[Refresh a materialized view](/feature-engineering/materialized-views). +[Refresh a materialized view](/feature-engineering/refresh-materialized-view). -In SQL, see [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh#refresh-materialized-view) and [`SHOW MATERIALIZED VIEWS`](/sql/ddl/materialized-view#show). +In SQL, see [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh-materialized-view) and [`SHOW MATERIALIZED VIEWS`](/sql/ddl/materialized-view#show). ## Create a materialized view {#create} @@ -30,25 +28,25 @@ In SQL, see [`REFRESH MATERIALIZED VIEW`](/sql/dml/refresh#refresh-materialized- ```python Python icon="python" view = db.create_materialized_view( - "recent_docs", - source="documents", - select=["id", "title", "embedding"], - where="created_at > TIMESTAMP '2026-01-01 00:00:00'", + "frames_captioned", + source="frames", + select=["frame_id", "video_id", "ts", "caption"], + where="selected = true", ) ``` ```typescript TypeScript icon="square-js" -const view = await db.createMaterializedView("recent_docs", "documents", { - select: ["id", "title", "embedding"], - where: "created_at > TIMESTAMP '2026-01-01 00:00:00'", +const view = await db.createMaterializedView("frames_captioned", "frames", { + select: ["frame_id", "video_id", "ts", "caption"], + where: "selected = true", }); ``` -`source` names the table the view reads. With Python SDK 0.40.0, create that -table with stable row IDs before creating the view. The -[complete example](/feature-engineering/materialized-views#create-and-refresh) -shows the setup. `select`, `where` and `limit` define the query. +`source` names the table the view reads — here, a `frames` table with a +`caption` column, filtered to the frames selected for captioning. See +[Create a materialized view](/feature-engineering/materialized-views#create) +for the full walkthrough. `select`, `where` and `limit` define the query. ## Open, list and drop views {#manage} @@ -60,6 +58,30 @@ shows the setup. `select`, `where` and `limit` define the query. | refresh | `refresh` | `refresh` | `REFRESH MATERIALIZED VIEW` | | drop | `drop_table` | `dropTable` | `DROP TABLE` | +Enterprise Creating, refreshing and dropping a +materialized view each have an async, job-returning counterpart -- +`create_materialized_view_async`, `view.refresh_async()`, +`drop_materialized_view_async` -- the same pattern as +[`refresh_column_async`](/feature-engineering/refresh-column#async): each +returns a [job](/basics/jobs) you `wait()` on instead of blocking. The async +counterpart of the example [above](#create): + + +```python Python icon="python" +from datetime import timedelta + +job = db.create_materialized_view_async( + "frames_captioned", source="frames", + select=["frame_id", "video_id", "ts", "caption"], where="selected = true", +) +view = job.wait(timeout=timedelta(minutes=15)) +``` + + +`create_materialized_view_async` also accepts `auto_refresh_enabled` and +`auto_refresh_interval_seconds`; see +[Automatic refresh](/feature-engineering/refresh-materialized-view#auto-refresh). + On a local database, `list_materialized_views` reads table schemas to find views. On Enterprise, it asks the server for the view listing, as @@ -78,16 +100,14 @@ That also means dropping one removes stored rows, unlike dropping a ## Enterprise compatibility {#deployment} -Enterprise supports creating and refreshing materialized views on the -Enterprise service. Use the SDK version supported by your deployment, or the -[SQL interface](/sql/ddl/materialized-view). See -[Enterprise refreshes](/feature-engineering/materialized-views#availability) -for compatibility considerations when upgrading an existing pipeline. +Enterprise supports creating and refreshing materialized views on remote +compute. Use the SDK version supported by your deployment, or the +[SQL interface](/sql/ddl/materialized-view). ## Related guides {#next} - + How a refresh works, and what it writes. diff --git a/docs/web/management/namespace.mdx b/docs/web/management/namespace.mdx index e5222ab84..99e53d793 100644 --- a/docs/web/management/namespace.mdx +++ b/docs/web/management/namespace.mdx @@ -5,11 +5,8 @@ description: "Grouping tables into a hierarchy, and addressing them through it." icon: folder-tree keywords: ["namespace", "catalog", "hierarchy", "directory namespace", "rest namespace"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Namespaces work in the embedded library, through directory or REST - catalogs, and in LanceDB Enterprise. --- import { diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index a28f63d40..0b71fb315 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -5,12 +5,8 @@ description: "The object most operations act on: creating, opening, renaming, cl icon: table keywords: ["table", "create_table", "open_table", "clone", "rename", "drop"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Tables are created, evolved, versioned and dropped in the embedded library - and in LanceDB Enterprise. Renaming, cloning, dropping every table and pruning old - versions differ between the two. --- import { @@ -953,8 +949,8 @@ First, let's create a sample table with product data to demonstrate schema evolu Columns derived from existing data (SQL expressions over other columns) are -covered in [Data evolution](/feature-engineering/data-evolution), because -deriving values is a feature-engineering job rather than a schema one. +covered in [Create a computed column](/feature-engineering/add-computed-column), +because deriving values is a feature-engineering job rather than a schema one. #### Add columns with default values {#schema-add-columns-with-default-values} diff --git a/docs/web/management/view.mdx b/docs/web/management/view.mdx index de6cd38a5..e01120034 100644 --- a/docs/web/management/view.mdx +++ b/docs/web/management/view.mdx @@ -1,14 +1,12 @@ --- title: "Views" sidebarTitle: "View" -description: "A saved query, evaluated when read. The non-materialized counterpart to a materialized view." +description: "A saved query, evaluated when read." icon: eye keywords: ["view", "create view", "sql", "catalog"] availability: - oss: unavailable + embedded: unavailable enterprise: available - summary: >- - Enterprise supports views when enabled for your Enterprise cluster; the embedded library cannot create them. --- A view saves a query that you can refer to by name. Reading the view executes diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 645e0565e..c84ae191a 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -4,26 +4,24 @@ sidebarTitle: "Quickstart" description: "Install LanceDB, create a table, and run your first vector search." icon: rocket --- -import { PyConnect, TsConnect, RsConnect, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; -import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartVectorSearch1, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1 } from '/snippets/quickstart.mdx'; +import { PyConnect, TsConnect, RsConnect, PyConnectObjectStorage, TsConnectObjectStorage, RsConnectObjectStorage, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; +import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartAddFeature, PyQuickstartComputedFeature, PyQuickstartComputedFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartCurateWithMetadata, TsQuickstartAddFeature, TsQuickstartQueryFeature, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartCurateWithMetadata, RsQuickstartAddFeature, RsQuickstartQueryFeature, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx'; This quickstart uses LanceDB Embedded with a local database and works without an account or API key. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. -Follow the steps below, or jump to the [complete examples](#code) to copy a runnable program. - ## 1\. Install LanceDB {#1-install-lancedb} -Choose your language. Python uses Polars to display the search results. TypeScript needs Node.js 22.18 or later to run the `.mts` example directly. +Choose your language. Python uses Pandas to display the search results. TypeScript needs Node.js 22.18 or later to run the `.mts` example directly. ```bash Python (pip) icon="python" -pip install lancedb polars +pip install lancedb pandas ``` ```bash Python (uv) icon="python" uv venv -uv pip install lancedb polars +uv pip install lancedb pandas ``` ```bash TypeScript icon="square-js" @@ -112,7 +110,7 @@ uninstall the other first (`pip uninstall lancedb && pip install lancedb-compat` ## 2\. Connect to a database {#2-connect-to-a-lancedb-database} -### Use a local directory {#connect-via-local-directory-path} +### Local directory {#connect-via-local-directory-path} LanceDB creates an `ex_lancedb` directory to store your tables. No server is needed. @@ -130,10 +128,27 @@ LanceDB creates an `ex_lancedb` directory to store your tables. No server is nee -The [complete examples](#code) include the imports and entry points for each language. For Python's async API, see [Connecting to a database](/basics/connect). +For Python's async API, see [Connecting to a database](/basics/catalog). - -### Connect to LanceDB Enterprise {#connect-to-lancedb-enterprise} +### Object storage {#connect-via-object-storage-uris} + +Use an `s3://`, `gs://`, or `az://` URI in place of the local path. See [Configuring storage](/deployment/storage) for credentials and provider-specific options. + + + + {PyConnectObjectStorage} + + + {"import * as lancedb from \"@lancedb/lancedb\";\n\n"} + {TsConnectObjectStorage} + + + {"use lancedb::connect;\n\n"} + {RsConnectObjectStorage} + + + +### Enterprise {#connect-to-lancedb-enterprise} Use the database URI, API key, and endpoint provided by your administrator or the LanceDB team. Replace the placeholders below with those details. Use the deployment's region if provided; otherwise keep `us-east-1`. @@ -152,27 +167,20 @@ Use the database URI, API key, and endpoint provided by your administrator or th -In application code, load credentials from environment variables or a secrets manager. See [connection settings](/basics/connect#enterprise) for an example. +In application code, load credentials from environment variables or a secrets manager. See [connection settings](/basics/catalog#enterprise) for an example. -Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between Embedded and Distributed execution, see [Moving to LanceDB Enterprise](/basics/sdk#moving-to-enterprise). - - - -### Connect via object storage URIs {#connect-via-object-storage-uris} - -Use an `s3://`, `gs://`, or `az://` URI in place of the local path. See [Configuring storage](/deployment/storage) for credentials and provider-specific options. - +Need a deployment? [Contact the LanceDB team](https://www.lancedb.com/contact). For differences between local and server execution, see [LanceDB Enterprise](/enterprise). ## 3\. Create a table and add data {#3-create-a-new-table} -Each row describes a character and stores a vector alongside their name, description, and stats. +Each row describes a frame from a robot video clip and stores an embedding alongside its video, caption, and quality stats. -These vectors are made up for this example. In your application, use an embedding model to generate vectors from your data. +These embeddings are made up for this example. In your application, use an embedding model to generate them from your data. - + {PyQuickstartData} @@ -187,7 +195,7 @@ These vectors are made up for this example. In your application, use an embeddin -Create a `characters` table from those records: +Create a `frames` table from those records: @@ -201,9 +209,9 @@ Create a `characters` table from those records: -This example uses overwrite mode so you can run it again. It replaces any existing `characters` table in the database you connect to. +This example uses overwrite mode so you can run it again. It replaces any existing `frames` table in the database you connect to. -Add one more character: +Add one more frame: @@ -219,11 +227,11 @@ Add one more character: ## 4\. Search the table {#4-semantic-search} -Find the two vectors closest to the query vector. This example uses a fixed vector; it does not call an embedding model. +Find the two embeddings closest to the query embedding. This example uses a fixed embedding; it does not call an embedding model. - {PyQuickstartVectorSearch1} + {"# Search for frames similar to \"a gripper closing on an object\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install pandas` beforehand\nresult = (\n table.search(query_vector)\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_pandas()\n)\nprint(result)\n"} {TsQuickstartVectorSearch1} @@ -233,84 +241,109 @@ Find the two vectors closest to the query vector. This example uses a fixed vect -Merlin and Morgana come back first. Python and Rust display a Polars DataFrame; TypeScript displays an array of results. The `_distance` column measures how far each result is from your query vector, with smaller values indicating a closer match. +Frames 2 and 4 come back first -- the gripper closing on the cup, then lowering it. Python displays a Pandas DataFrame, Rust displays a Polars DataFrame, and TypeScript displays an array of results. The `_distance` column measures how far each result is from your query embedding, with smaller values indicating a closer match. -## Complete examples {#code} +## 5\. Filter results {#5-curation} -Each example below creates the local database, adds four characters, and prints the two closest matches. Use the dependencies from step 1. - - -Save this as `quickstart.py` and run `python quickstart.py`. If you installed with uv, run `uv run quickstart.py`. +Combine vector search with a metadata filter, such as `stats.motion >= 4`, to curate results instead of just ranking them: - - {PyConnect} - {PyQuickstartData} - {PyQuickstartCreateTable} - {PyQuickstartAddData} - {PyQuickstartVectorSearch1} + + {"curated = (\n table.search(query_vector)\n .where(\"stats.motion >= 4\")\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_pandas()\n)\nprint(curated)\n"} + + + {TsQuickstartCurateWithMetadata} + + + {RsQuickstartCurateWithMetadata} - - -Save this as `quickstart.mts` and run `node quickstart.mts` from the directory where you installed LanceDB. +Frames 2 and 4 come back again here, since both already have `motion >= 4`; frames 1 and 3 are excluded from ranking entirely, rather than ranked and then dropped. See [SQL filtering](/search/filtering) for the full predicate syntax. + +## 6\. Add a derived feature {#6-add-a-derived-feature} + +Add a column calculated from existing fields with a SQL expression. This fills every existing row once, immediately: - - {"import * as lancedb from \"@lancedb/lancedb\";\n\n"} - {TsConnect} - {TsQuickstartData} - {TsQuickstartCreateTable} - {TsQuickstartAddData} - {TsQuickstartVectorSearch1} + + {PyQuickstartAddFeature} + + + {TsQuickstartAddFeature} + + + {RsQuickstartAddFeature} - - -Replace `src/main.rs` with this program, then run `cargo run` from your project directory. The schema and Arrow conversion helpers are included. +Read it back like any other column: - - {"use lancedb::connect;\n\n"} - {RsQuickstartDefineStruct} - {"\n#[tokio::main]\nasync fn main() -> Result<(), Box> {\n"} - {RsConnect} - {RsQuickstartData} - {RsQuickstartCreateTable} - {RsQuickstartAddData} - {RsQuickstartVectorSearch1} - {"\nOk(())\n}\n"} + + {"features = table.search().select([\"frame_id\", \"video_id\", \"quality_score\"]).limit(10).to_pandas()\nprint(features)\n"} + + + {TsQuickstartQueryFeature} + + + {RsQuickstartQueryFeature} - -## Next steps {#next-steps} +See [Adding columns](/management/table#schema-add-new-columns) for more on this form. -You've created a table, added rows, and searched it. Continue with the guides below. +## 7\. Set up computed columns {#7-computed-columns} -### Filter results {#5-curation} +A computed column is declared up front and filled -- or refilled -- on demand, instead of being calculated once like step 6's. Declare `caption_length`, then fill it explicitly: -Combine vector search with metadata filters, such as `stats.magic >= 4`. See [SQL filtering](/search/filtering). + + + {PyQuickstartComputedFeature} + + -### Extend your table {#extensions} +A later `refresh_column` call fills only rows added since the last refresh and recomputes rows whose inputs changed, leaving unchanged rows alone. On LanceDB Enterprise, the equivalent refresh runs as a background job instead of blocking: -#### Add a derived feature {#6-add-a-derived-feature} + + + {PyQuickstartComputedFeatureEnterprise} + + -Add columns calculated from existing fields. See [Adding columns](/management/table#schema-add-new-columns). +TypeScript and Rust declare and refresh computed columns the same way, through the same `add_columns`/`refresh_column` calls. See [Computed columns](/feature-engineering/add-computed-column) for the full refresh semantics and the automatic-refresh option. -#### Computed columns {#computed-columns} +## 8\. Store multimodal data {#8-store-multimodal-data} -Declare a column and choose when to fill or refresh it. See [Computed columns](/feature-engineering/add-computed-column). +Store images, audio, or other binary data alongside vectors and metadata, in a column of raw bytes. This creates a new table from one image file -- replace the path with one of your own: -#### Store multimodal data {#7-store-multimodal-data} + + + {PyQuickstartMultimodalBytes} + + + {TsQuickstartMultimodalBytes} + + + {RsQuickstartMultimodalBytes} + + -Store images, audio, and other binary data alongside vectors and metadata. See [Multimodal data types](/management/table#multimodal). +See [Multimodal data types](/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan. -#### Train on your data {#8-train} +## 9\. Train on your data {#9-train} -Read table data into PyTorch for training. See [Data loading](/training/data-loading). +Read table data into PyTorch, projecting and shuffling only the columns a training step needs: + + + + {PyQuickstartTraining} + + + +`Permutation` is LanceDB's row-ordering primitive for training reads; `select_columns` projects before reading, so a training step touches only the columns it selects, not unused ones such as `caption` or `embedding`. See [Data loading](/training/data-loading) for the full `StreamingDataset` API, including resuming and multi-worker loading. + +## Where to go next {#next-steps} diff --git a/docs/web/reranking/index.mdx b/docs/web/reranking/index.mdx index ccaa70e9b..1de69a2a8 100644 --- a/docs/web/reranking/index.mdx +++ b/docs/web/reranking/index.mdx @@ -5,10 +5,8 @@ description: "Choose a reranker, apply it to search candidates and evaluate rele icon: "sort-amount-down" keywords: ["re-ranking", "reranker", "rerank"] availability: - oss: available + embedded: available enterprise: available - summary: >- - Reranking is available with LanceDB Embedded and LanceDB Enterprise. --- import { diff --git a/docs/web/search/explain.mdx b/docs/web/search/explain.mdx index 1a1fa3330..653eecb52 100644 --- a/docs/web/search/explain.mdx +++ b/docs/web/search/explain.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Query Plans" description: "Inspect query execution, identify expensive work and compare changes." icon: "map" availability: - oss: available + embedded: available enterprise: available - summary: >- - Query plans are available in LanceDB Embedded and LanceDB Enterprise. --- import { PyQueryPlan, TsQueryPlanBody, TsQueryPlanTail } from '/snippets/search_examples.mdx'; diff --git a/docs/web/search/filtering.mdx b/docs/web/search/filtering.mdx index a3ad6f735..099aea73c 100644 --- a/docs/web/search/filtering.mdx +++ b/docs/web/search/filtering.mdx @@ -4,10 +4,8 @@ sidebarTitle: Filtering description: "Use predicates to select rows and control when filters apply to search." icon: "filter" availability: - oss: available + embedded: available enterprise: available - summary: >- - Metadata filtering is available in LanceDB Embedded and LanceDB Enterprise. --- import { PyFilterSearch, TsFilterSearchBody, TsFilterSearchTail } from '/snippets/search_examples.mdx'; diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 858492576..0f9930dc3 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -4,10 +4,8 @@ sidebarTitle: Full-Text Search (FTS) description: "Find records by words, phrases or partial matches using a full-text index." icon: "book" availability: - oss: available + embedded: available enterprise: available - summary: >- - Full-text search is available in LanceDB Embedded and LanceDB Enterprise. --- import { diff --git a/docs/web/search/hybrid-search.mdx b/docs/web/search/hybrid-search.mdx index 1100c073a..6b769b6a8 100644 --- a/docs/web/search/hybrid-search.mdx +++ b/docs/web/search/hybrid-search.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Hybrid Search" description: "Combine vector similarity and keyword matches in a single ranked result set." icon: "search" availability: - oss: available + embedded: available enterprise: available - summary: >- - Hybrid search is available in LanceDB Embedded and LanceDB Enterprise. --- import { PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; diff --git a/docs/web/search/index.mdx b/docs/web/search/index.mdx index c4bdd5cae..86a0b1b17 100644 --- a/docs/web/search/index.mdx +++ b/docs/web/search/index.mdx @@ -4,10 +4,8 @@ sidebarTitle: Overview description: "Choose vector, full-text or hybrid search and return the records your application needs." icon: "list" availability: - oss: available + embedded: available enterprise: available - summary: >- - Vector, full-text and hybrid search are available in LanceDB Embedded and LanceDB Enterprise. --- import { PyVectorSearch, TsVectorSearchBody, TsVectorSearchTail } from '/snippets/search_examples.mdx'; @@ -68,7 +66,7 @@ and removes it when finished. This query returns the puppy and dog records, ordered by vector distance. It searches the three-row table directly, without an ANN index or an embedding -service. For connection options, see [Connect](/basics/connect). +service. For connection options, see [Connect](/basics/catalog). diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx new file mode 100644 index 000000000..8f51995d3 --- /dev/null +++ b/docs/web/search/realtime-read.mdx @@ -0,0 +1,74 @@ +--- +title: "Real Time reads" +sidebarTitle: "Real Time Read" +description: "Query a table with the real time engine enabled and get writes back within milliseconds of being written, merged transparently with the base table." +icon: "magnifying-glass" +keywords: ["rte", "real time engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] +availability: + embedded: unavailable + enterprise: available +--- + +A table with the [real time engine](/tables/realtime-engine) enabled queries +the same way as any other table — nothing about `search`, filtering, or SQL +changes. This page covers what you get back and how it performs; for enabling +RTE and writing to a table, see [Real Time writes](/ingestion/realtime-write). + +## Query a real time table {#query} + +Every query runs against the base table and the fresh tier (unflushed +memtables and SSTables) in parallel, and the two are merged into one result. +Fresh rows supersede base rows with the same primary key, so a row written a +moment ago is already reflected: + + +```python Python icon="python" +# continuing the `frames` table connected and written to in Real Time writes +import numpy as np + +query_vector = np.random.rand(frames.schema.field("embedding").type.list_size).astype("float32") + +frames.search(query_vector, vector_column_name="embedding").limit(10).to_list() +frames.search("gripper closing on a cup", fts_columns="caption").limit(10).to_list() +``` + + +Vector, full-text, BTree, bitmap, and most other scalar indexes are maintained +on the memtable, so new rows are searchable through the index as soon as +they're written — not just after the next compaction. + +## Read performance {#read-performance} + +Reads on an RTE table stay close to those on a fully compacted table, even +with the fresh tier at its fullest before compaction. + +The table below compares a 5M-row table with a 128-dimension IVF-PQ index plus +BTree and FTS indexes, with and without RTE. The RTE table holds one +unflushed memtable and three SSTables, each from a 100k-row write wave, half of +which are updates to existing rows. Latencies are p50 in milliseconds. + +| Query | Without RTE | With RTE | +| --- | --: | --: | +| Primary-key lookup | 62 | 63 | +| Vector search | 68 | 71 | +| Vector search with prefilter | 90 | 91 | +| Full-text term | 63 | 64 | +| Full-text phrase | 68 | 82 | +| Hybrid search (RRF) | 68 | 83 | +| SQL point lookup | 189 | 187 | + +Most queries are within a few milliseconds of the base table. Hybrid and phrase +queries add roughly 15 ms to merge the two tiers. + + +Support for all table operations on RTE tables is coming soon. Time travel, +branching, `count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet +available. + + +## Next steps {#next-steps} + +- [Real Time writes](/ingestion/realtime-write) — enable RTE and write to a table +- [How the real time engine works](/tables/realtime-engine#how-it-works) +- [Hybrid search](/search/hybrid-search) +- [Vector search](/search/vector-search) diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index 59fbc1cc9..8c43fd0e6 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -4,10 +4,8 @@ sidebarTitle: "Vector Search" description: "Search by vector similarity, choose a distance metric and tune your queries." icon: "arrow-up-right-dots" availability: - oss: available + embedded: available enterprise: available - summary: >- - Vector search is available in LanceDB Embedded and LanceDB Enterprise. --- import { diff --git a/docs/web/snippets/quickstart.mdx b/docs/web/snippets/quickstart.mdx index c7cf98e32..cd8976768 100644 --- a/docs/web/snippets/quickstart.mdx +++ b/docs/web/snippets/quickstart.mdx @@ -1,66 +1,66 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyQuickstartAddData = "table.add(\n [\n {\n \"id\": \"4\",\n \"name\": \"Morgana\",\n \"role\": \"Sorceress\",\n \"description\": \"Powerful sorceress of Avalon.\",\n \"stats\": {\"strength\": 2, \"magic\": 5, \"leadership\": 4, \"wisdom\": 4},\n \"vector\": [0.3, 0.9, 0.6, 0.8],\n }\n ]\n)\n"; +export const PyQuickstartAddData = "table.add(\n [\n {\n \"frame_id\": \"4\",\n \"video_id\": \"clip-2\",\n \"caption\": \"a gripper lowering a cup onto the table\",\n \"stats\": {\"motion\": 5, \"sharpness\": 4, \"exposure\": 4, \"framing\": 2},\n \"embedding\": [0.3, 0.9, 0.6, 0.8],\n }\n ]\n)\n"; -export const PyQuickstartAddFeature = "table.add_columns(\n {\n \"power_score\": \"cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)\"\n }\n)\n"; +export const PyQuickstartAddFeature = "table.add_columns(\n {\n \"quality_score\": \"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)\"\n }\n)\n"; -export const PyQuickstartComputedFeature = "table.add_columns(computed={\"description_length\": \"length(description)\"})\ntable.refresh_column(\"description_length\")\n"; +export const PyQuickstartComputedFeature = "table.add_columns(computed={\"caption_length\": \"length(caption)\"})\ntable.refresh_column(\"caption_length\")\n"; -export const PyQuickstartComputedFeatureEnterprise = "table.add_columns(computed={\"description_length\": \"length(description)\"})\njob = table.refresh_column_async(\"description_length\")\njob.wait()\n"; +export const PyQuickstartComputedFeatureEnterprise = "table.add_columns(computed={\"caption_length\": \"length(caption)\"})\njob = table.refresh_column_async(\"caption_length\")\njob.wait()\n"; -export const PyQuickstartCreateTable = "table = db.create_table(\"characters\", data=data, mode=\"overwrite\")\n"; +export const PyQuickstartCreateTable = "table = db.create_table(\"frames\", data=data, mode=\"overwrite\")\n"; -export const PyQuickstartCreateTableAsync = "async_table = await async_db.create_table(\n \"characters\",\n data=data,\n mode=\"overwrite\",\n)\n"; +export const PyQuickstartCreateTableAsync = "async_table = await async_db.create_table(\n \"frames\",\n data=data,\n mode=\"overwrite\",\n)\n"; -export const PyQuickstartCurateWithMetadata = "curated = (\n table.search(query_vector)\n .where(\"stats.magic >= 4\")\n .select([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(curated)\n"; +export const PyQuickstartCurateWithMetadata = "curated = (\n table.search(query_vector)\n .where(\"stats.motion >= 4\")\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(curated)\n"; -export const PyQuickstartData = "data = [\n {\n \"id\": \"1\",\n \"name\": \"King Arthur\",\n \"role\": \"King\",\n \"description\": \"Leader of Camelot and wielder of Excalibur.\",\n \"stats\": {\"strength\": 4, \"magic\": 1, \"leadership\": 5, \"wisdom\": 4},\n \"vector\": [0.7, 0.1, 0.9, 0.7],\n },\n {\n \"id\": \"2\",\n \"name\": \"Merlin\",\n \"role\": \"Wizard\",\n \"description\": \"Advisor and prophet with deep magical knowledge.\",\n \"stats\": {\"strength\": 2, \"magic\": 5, \"leadership\": 4, \"wisdom\": 5},\n \"vector\": [0.2, 0.9, 0.4, 0.9],\n },\n {\n \"id\": \"3\",\n \"name\": \"Sir Lancelot\",\n \"role\": \"Knight\",\n \"description\": \"Legendary knight known for courage and combat skill.\",\n \"stats\": {\"strength\": 5, \"magic\": 1, \"leadership\": 3, \"wisdom\": 3},\n \"vector\": [0.9, 0.1, 0.5, 0.4],\n },\n]\n"; +export const PyQuickstartData = "data = [\n {\n \"frame_id\": \"1\",\n \"video_id\": \"clip-1\",\n \"caption\": \"a robot arm reaching toward a cup\",\n \"stats\": {\"motion\": 3, \"sharpness\": 4, \"exposure\": 4, \"framing\": 3},\n \"embedding\": [0.7, 0.1, 0.9, 0.7],\n },\n {\n \"frame_id\": \"2\",\n \"video_id\": \"clip-1\",\n \"caption\": \"a two-finger gripper closing on a cup\",\n \"stats\": {\"motion\": 5, \"sharpness\": 4, \"exposure\": 5, \"framing\": 2},\n \"embedding\": [0.2, 0.9, 0.4, 0.9],\n },\n {\n \"frame_id\": \"3\",\n \"video_id\": \"clip-2\",\n \"caption\": \"a robot arm holding a cup steady\",\n \"stats\": {\"motion\": 2, \"sharpness\": 3, \"exposure\": 3, \"framing\": 4},\n \"embedding\": [0.9, 0.1, 0.5, 0.4],\n },\n]\n"; -export const PyQuickstartMultimodalBytes = "from pathlib import Path\n\nimage_bytes = Path(\"data/sir-lancelot.jpg\").read_bytes()\n\nmultimodal_table = db.create_table(\n \"character_images\",\n data=[\n {\n \"id\": \"lancelot\",\n \"description\": \"Portrait of Sir Lancelot\",\n \"image\": image_bytes,\n \"vector\": [0.9, 0.1, 0.5, 0.4],\n }\n ],\n mode=\"overwrite\",\n)\n"; +export const PyQuickstartMultimodalBytes = "from pathlib import Path\n\nimage_bytes = Path(\"data/sample-frame.jpg\").read_bytes()\n\nmultimodal_table = db.create_table(\n \"frame_images\",\n data=[\n {\n \"frame_id\": \"thumb-1\",\n \"caption\": \"Sample frame thumbnail\",\n \"image\": image_bytes,\n \"embedding\": [0.9, 0.1, 0.5, 0.4],\n }\n ],\n mode=\"overwrite\",\n)\n"; export const PyQuickstartOutputPandas = "# Ensure you run `pip install pandas` beforehand\nresult = table.search(query_vector).limit(2).to_pandas()\nprint(result)\n"; -export const PyQuickstartQueryFeature = "features = table.search().select([\"name\", \"role\", \"power_score\"]).to_polars()\nprint(features)\n"; +export const PyQuickstartQueryFeature = "features = table.search().select([\"frame_id\", \"video_id\", \"quality_score\"]).to_polars()\nprint(features)\n"; -export const PyQuickstartTraining = "import torch\nfrom lancedb.permutation import Permutation\n\ntable.add_columns(\n {\n \"magic\": \"cast(stats.magic as float)\",\n \"strength\": \"cast(stats.strength as float)\",\n }\n)\ndataset = Permutation.identity(table).select_columns([\"magic\", \"strength\"])\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True)\n"; +export const PyQuickstartTraining = "import torch\nfrom lancedb.permutation import Permutation\n\ntable.add_columns(\n {\n \"motion\": \"cast(stats.motion as float)\",\n \"sharpness\": \"cast(stats.sharpness as float)\",\n }\n)\ndataset = Permutation.identity(table).select_columns([\"motion\", \"sharpness\"])\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, shuffle=True)\n"; -export const PyQuickstartVectorSearch1 = "# Search for examples similar to a \"wise magical advisor\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install polars` beforehand\nresult = (\n table.search(query_vector)\n .select([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(result)\n"; +export const PyQuickstartVectorSearch1 = "# Search for frames similar to \"a gripper closing on an object\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install polars` beforehand\nresult = (\n table.search(query_vector)\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .to_polars()\n)\nprint(result)\n"; -export const PyQuickstartVectorSearch1Async = "# Search for examples similar to a \"wise magical advisor\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install polars` beforehand\nasync_result = await (\n await async_table.search(query_vector)\n).select([\"name\", \"role\", \"description\", \"_distance\"]).limit(2).to_polars()\nprint(async_result)\n"; +export const PyQuickstartVectorSearch1Async = "# Search for frames similar to \"a gripper closing on an object\"\nquery_vector = [0.2, 0.8, 0.4, 0.9]\n\n# Ensure you run `pip install polars` beforehand\nasync_result = await (\n await async_table.search(query_vector)\n).select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"]).limit(2).to_polars()\nprint(async_result)\n"; -export const TsQuickstartAddData = "await table.add([\n {\n id: \"4\",\n name: \"Morgana\",\n role: \"Sorceress\",\n description: \"Powerful sorceress of Avalon.\",\n stats: { strength: 2, magic: 5, leadership: 4, wisdom: 4 },\n vector: [0.3, 0.9, 0.6, 0.8],\n },\n]);\n"; +export const TsQuickstartAddData = "await table.add([\n {\n frame_id: \"4\",\n video_id: \"clip-2\",\n caption: \"a gripper lowering a cup onto the table\",\n stats: { motion: 5, sharpness: 4, exposure: 4, framing: 2 },\n embedding: [0.3, 0.9, 0.6, 0.8],\n },\n]);\n"; -export const TsQuickstartAddFeature = "await table.addColumns([\n {\n name: \"power_score\",\n valueSql:\n \"cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)\",\n },\n]);\n"; +export const TsQuickstartAddFeature = "await table.addColumns([\n {\n name: \"quality_score\",\n valueSql:\n \"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)\",\n },\n]);\n"; -export const TsQuickstartCreateTable = "const table = await db.createTable(\"characters\", data, { mode: \"overwrite\" });\n"; +export const TsQuickstartCreateTable = "const table = await db.createTable(\"frames\", data, { mode: \"overwrite\" });\n"; -export const TsQuickstartCurateWithMetadata = "const curated = await table\n .search(queryVector)\n .where(\"stats.magic >= 4\")\n .select([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(curated);\n"; +export const TsQuickstartCurateWithMetadata = "const curated = await table\n .search(queryVector)\n .where(\"stats.motion >= 4\")\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(curated);\n"; -export const TsQuickstartData = "const data = [\n {\n id: \"1\",\n name: \"King Arthur\",\n role: \"King\",\n description: \"Leader of Camelot and wielder of Excalibur.\",\n stats: { strength: 4, magic: 1, leadership: 5, wisdom: 4 },\n vector: [0.7, 0.1, 0.9, 0.7],\n },\n {\n id: \"2\",\n name: \"Merlin\",\n role: \"Wizard\",\n description: \"Advisor and prophet with deep magical knowledge.\",\n stats: { strength: 2, magic: 5, leadership: 4, wisdom: 5 },\n vector: [0.2, 0.9, 0.4, 0.9],\n },\n {\n id: \"3\",\n name: \"Sir Lancelot\",\n role: \"Knight\",\n description: \"Legendary knight known for courage and combat skill.\",\n stats: { strength: 5, magic: 1, leadership: 3, wisdom: 3 },\n vector: [0.9, 0.1, 0.5, 0.4],\n },\n];\n"; +export const TsQuickstartData = "const data = [\n {\n frame_id: \"1\",\n video_id: \"clip-1\",\n caption: \"a robot arm reaching toward a cup\",\n stats: { motion: 3, sharpness: 4, exposure: 4, framing: 3 },\n embedding: [0.7, 0.1, 0.9, 0.7],\n },\n {\n frame_id: \"2\",\n video_id: \"clip-1\",\n caption: \"a two-finger gripper closing on a cup\",\n stats: { motion: 5, sharpness: 4, exposure: 5, framing: 2 },\n embedding: [0.2, 0.9, 0.4, 0.9],\n },\n {\n frame_id: \"3\",\n video_id: \"clip-2\",\n caption: \"a robot arm holding a cup steady\",\n stats: { motion: 2, sharpness: 3, exposure: 3, framing: 4 },\n embedding: [0.9, 0.1, 0.5, 0.4],\n },\n];\n"; -export const TsQuickstartMultimodalBytes = "const arrow = await import(\"apache-arrow\");\nconst { readFile } = await import(\"node:fs/promises\");\n\nconst imageBytes = await readFile(\"data/sir-lancelot.jpg\");\nconst imageSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Utf8()),\n new arrow.Field(\"description\", new arrow.Utf8()),\n new arrow.Field(\"image\", new arrow.Binary()),\n new arrow.Field(\n \"vector\",\n new arrow.FixedSizeList(\n 4,\n new arrow.Field(\"item\", new arrow.Float32(), true),\n ),\n ),\n]);\nconst imageData = lancedb.makeArrowTable(\n [\n {\n id: \"lancelot\",\n description: \"Portrait of Sir Lancelot\",\n image: imageBytes,\n vector: [0.9, 0.1, 0.5, 0.4],\n },\n ],\n { schema: imageSchema },\n);\nconst multimodalTable = await db.createTable(\n \"character_images\",\n imageData,\n { mode: \"overwrite\" },\n);\n"; +export const TsQuickstartMultimodalBytes = "const arrow = await import(\"apache-arrow\");\nconst { readFile } = await import(\"node:fs/promises\");\n\nconst imageBytes = await readFile(\"data/sample-frame.jpg\");\nconst imageSchema = new arrow.Schema([\n new arrow.Field(\"frame_id\", new arrow.Utf8()),\n new arrow.Field(\"caption\", new arrow.Utf8()),\n new arrow.Field(\"image\", new arrow.Binary()),\n new arrow.Field(\n \"embedding\",\n new arrow.FixedSizeList(\n 4,\n new arrow.Field(\"item\", new arrow.Float32(), true),\n ),\n ),\n]);\nconst imageData = lancedb.makeArrowTable(\n [\n {\n frame_id: \"thumb-1\",\n caption: \"Sample frame thumbnail\",\n image: imageBytes,\n embedding: [0.9, 0.1, 0.5, 0.4],\n },\n ],\n { schema: imageSchema },\n);\nconst multimodalTable = await db.createTable(\n \"frame_images\",\n imageData,\n { mode: \"overwrite\" },\n);\n"; -export const TsQuickstartQueryFeature = "const features = await table\n .query()\n .select([\"name\", \"role\", \"power_score\"])\n .toArray();\nconsole.table(features);\n"; +export const TsQuickstartQueryFeature = "const features = await table\n .query()\n .select([\"frame_id\", \"video_id\", \"quality_score\"])\n .toArray();\nconsole.table(features);\n"; -export const TsQuickstartVectorSearch1 = "// Search for examples similar to a \"wise magical advisor\"\nconst queryVector = [0.2, 0.8, 0.4, 0.9];\n\nconst result = await table\n .search(queryVector)\n .select([\"name\", \"role\", \"description\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(result);\n"; +export const TsQuickstartVectorSearch1 = "// Search for frames similar to \"a gripper closing on an object\"\nconst queryVector = [0.2, 0.8, 0.4, 0.9];\n\nconst result = await table\n .search(queryVector)\n .select([\"frame_id\", \"video_id\", \"caption\", \"_distance\"])\n .limit(2)\n .toArray();\nconsole.table(result);\n"; -export const RsQuickstartAddData = "let more_data = vec![Character {\n id: \"4\".to_string(),\n name: \"Morgana\".to_string(),\n role: \"Sorceress\".to_string(),\n description: \"Powerful sorceress of Avalon.\".to_string(),\n stats: Stats {\n strength: 2,\n magic: 5,\n leadership: 4,\n wisdom: 4,\n },\n vector: [0.3, 0.9, 0.6, 0.8],\n}];\ntable\n .add(characters_to_reader(schema.clone(), &more_data))\n .execute()\n .await\n .unwrap();\n"; +export const RsQuickstartAddData = "let more_data = vec![Frame {\n frame_id: \"4\".to_string(),\n video_id: \"clip-2\".to_string(),\n caption: \"a gripper lowering a cup onto the table\".to_string(),\n stats: Stats {\n motion: 5,\n sharpness: 4,\n exposure: 4,\n framing: 2,\n },\n embedding: [0.3, 0.9, 0.6, 0.8],\n}];\ntable\n .add(frames_to_reader(schema.clone(), &more_data))\n .execute()\n .await\n .unwrap();\n"; -export const RsQuickstartAddFeature = "table\n .add_columns(\n NewColumnTransform::SqlExpressions(vec![(\n \"power_score\".to_string(),\n \"cast(((stats.strength + stats.magic + stats.leadership + stats.wisdom) / 4.0) as float)\"\n .to_string(),\n )]),\n None,\n )\n .await\n .unwrap();\n"; +export const RsQuickstartAddFeature = "table\n .add_columns(\n NewColumnTransform::SqlExpressions(vec![(\n \"quality_score\".to_string(),\n \"cast(((stats.motion + stats.sharpness + stats.exposure + stats.framing) / 4.0) as float)\"\n .to_string(),\n )]),\n None,\n )\n .await\n .unwrap();\n"; -export const RsQuickstartCreateTable = "use lancedb::database::CreateTableMode;\n\nlet schema = characters_schema();\nlet table = db\n .create_table(\"characters\", characters_to_reader(schema.clone(), &data))\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; +export const RsQuickstartCreateTable = "use lancedb::database::CreateTableMode;\n\nlet schema = frames_schema();\nlet table = db\n .create_table(\"frames\", frames_to_reader(schema.clone(), &data))\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; -export const RsQuickstartCurateWithMetadata = "let curated = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .only_if(\"stats.magic >= 4\")\n .select(Select::Columns(vec![\n \"name\".to_string(),\n \"role\".to_string(),\n \"description\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{curated:?}\");\n"; +export const RsQuickstartCurateWithMetadata = "let curated = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .only_if(\"stats.motion >= 4\")\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"caption\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{curated:?}\");\n"; -export const RsQuickstartData = "let data = vec![\n Character {\n id: \"1\".to_string(),\n name: \"King Arthur\".to_string(),\n role: \"King\".to_string(),\n description: \"Leader of Camelot and wielder of Excalibur.\".to_string(),\n stats: Stats {\n strength: 4,\n magic: 1,\n leadership: 5,\n wisdom: 4,\n },\n vector: [0.7, 0.1, 0.9, 0.7],\n },\n Character {\n id: \"2\".to_string(),\n name: \"Merlin\".to_string(),\n role: \"Wizard\".to_string(),\n description: \"Advisor and prophet with deep magical knowledge.\".to_string(),\n stats: Stats {\n strength: 2,\n magic: 5,\n leadership: 4,\n wisdom: 5,\n },\n vector: [0.2, 0.9, 0.4, 0.9],\n },\n Character {\n id: \"3\".to_string(),\n name: \"Sir Lancelot\".to_string(),\n role: \"Knight\".to_string(),\n description: \"Legendary knight known for courage and combat skill.\".to_string(),\n stats: Stats {\n strength: 5,\n magic: 1,\n leadership: 3,\n wisdom: 3,\n },\n vector: [0.9, 0.1, 0.5, 0.4],\n },\n];\n"; +export const RsQuickstartData = "let data = vec![\n Frame {\n frame_id: \"1\".to_string(),\n video_id: \"clip-1\".to_string(),\n caption: \"a robot arm reaching toward a cup\".to_string(),\n stats: Stats {\n motion: 3,\n sharpness: 4,\n exposure: 4,\n framing: 3,\n },\n embedding: [0.7, 0.1, 0.9, 0.7],\n },\n Frame {\n frame_id: \"2\".to_string(),\n video_id: \"clip-1\".to_string(),\n caption: \"a two-finger gripper closing on a cup\".to_string(),\n stats: Stats {\n motion: 5,\n sharpness: 4,\n exposure: 5,\n framing: 2,\n },\n embedding: [0.2, 0.9, 0.4, 0.9],\n },\n Frame {\n frame_id: \"3\".to_string(),\n video_id: \"clip-2\".to_string(),\n caption: \"a robot arm holding a cup steady\".to_string(),\n stats: Stats {\n motion: 2,\n sharpness: 3,\n exposure: 3,\n framing: 4,\n },\n embedding: [0.9, 0.1, 0.5, 0.4],\n },\n];\n"; -export const RsQuickstartDefineStruct = "use std::sync::Arc;\n\nuse lancedb::arrow::arrow_array::types::Float32Type;\nuse lancedb::arrow::arrow_array::{\n FixedSizeListArray, Int8Array, LargeStringArray, RecordBatch, RecordBatchIterator,\n RecordBatchReader, StructArray,\n};\nuse lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema};\n\n// Define structs representing the data schema\n#[derive(Debug, Clone)]\nstruct Stats {\n strength: i8,\n magic: i8,\n leadership: i8,\n wisdom: i8,\n}\n\n#[derive(Debug, Clone)]\nstruct Character {\n id: String,\n name: String,\n role: String,\n description: String,\n stats: Stats,\n vector: [f32; 4],\n}\n\nfn characters_schema() -> Arc {\n Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::LargeUtf8, false),\n Field::new(\"name\", DataType::LargeUtf8, false),\n Field::new(\"role\", DataType::LargeUtf8, false),\n Field::new(\"description\", DataType::LargeUtf8, false),\n Field::new(\n \"stats\",\n DataType::Struct(Fields::from(vec![\n Arc::new(Field::new(\"strength\", DataType::Int8, false)),\n Arc::new(Field::new(\"magic\", DataType::Int8, false)),\n Arc::new(Field::new(\"leadership\", DataType::Int8, false)),\n Arc::new(Field::new(\"wisdom\", DataType::Int8, false)),\n ])),\n false,\n ),\n Field::new(\n \"vector\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n ]))\n}\n\nfn characters_to_reader(\n schema: Arc,\n rows: &[Character],\n) -> Box {\n let ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.id.as_str()));\n let names = LargeStringArray::from_iter_values(rows.iter().map(|row| row.name.as_str()));\n let roles = LargeStringArray::from_iter_values(rows.iter().map(|row| row.role.as_str()));\n let descriptions =\n LargeStringArray::from_iter_values(rows.iter().map(|row| row.description.as_str()));\n\n let strength = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.strength));\n let magic = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.magic));\n let leadership = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.leadership));\n let wisdom = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.wisdom));\n let stats_fields: Vec = vec![\n Arc::new(Field::new(\"strength\", DataType::Int8, false)),\n Arc::new(Field::new(\"magic\", DataType::Int8, false)),\n Arc::new(Field::new(\"leadership\", DataType::Int8, false)),\n Arc::new(Field::new(\"wisdom\", DataType::Int8, false)),\n ];\n let stats = StructArray::new(\n stats_fields.into(),\n vec![\n Arc::new(strength),\n Arc::new(magic),\n Arc::new(leadership),\n Arc::new(wisdom),\n ],\n None,\n );\n\n let vectors = FixedSizeListArray::from_iter_primitive::(\n rows.iter()\n .map(|row| Some(row.vector.iter().copied().map(Some).collect::>())),\n 4,\n );\n\n let batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(ids),\n Arc::new(names),\n Arc::new(roles),\n Arc::new(descriptions),\n Arc::new(stats),\n Arc::new(vectors),\n ],\n )\n .unwrap();\n\n Box::new(RecordBatchIterator::new(\n vec![Ok(batch)].into_iter(),\n schema,\n ))\n}\n"; +export const RsQuickstartDefineStruct = "use std::sync::Arc;\n\nuse lancedb::arrow::arrow_array::types::Float32Type;\nuse lancedb::arrow::arrow_array::{\n FixedSizeListArray, Int8Array, LargeStringArray, RecordBatch, RecordBatchIterator,\n RecordBatchReader, StructArray,\n};\nuse lancedb::arrow::arrow_schema::{DataType, Field, FieldRef, Fields, Schema};\n\n// Define structs representing the data schema\n#[derive(Debug, Clone)]\nstruct Stats {\n motion: i8,\n sharpness: i8,\n exposure: i8,\n framing: i8,\n}\n\n#[derive(Debug, Clone)]\nstruct Frame {\n frame_id: String,\n video_id: String,\n caption: String,\n stats: Stats,\n embedding: [f32; 4],\n}\n\nfn frames_schema() -> Arc {\n Arc::new(Schema::new(vec![\n Field::new(\"frame_id\", DataType::LargeUtf8, false),\n Field::new(\"video_id\", DataType::LargeUtf8, false),\n Field::new(\"caption\", DataType::LargeUtf8, false),\n Field::new(\n \"stats\",\n DataType::Struct(Fields::from(vec![\n Arc::new(Field::new(\"motion\", DataType::Int8, false)),\n Arc::new(Field::new(\"sharpness\", DataType::Int8, false)),\n Arc::new(Field::new(\"exposure\", DataType::Int8, false)),\n Arc::new(Field::new(\"framing\", DataType::Int8, false)),\n ])),\n false,\n ),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n ]))\n}\n\nfn frames_to_reader(\n schema: Arc,\n rows: &[Frame],\n) -> Box {\n let frame_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.frame_id.as_str()));\n let video_ids = LargeStringArray::from_iter_values(rows.iter().map(|row| row.video_id.as_str()));\n let captions =\n LargeStringArray::from_iter_values(rows.iter().map(|row| row.caption.as_str()));\n\n let motion = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.motion));\n let sharpness = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.sharpness));\n let exposure = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.exposure));\n let framing = Int8Array::from_iter_values(rows.iter().map(|row| row.stats.framing));\n let stats_fields: Vec = vec![\n Arc::new(Field::new(\"motion\", DataType::Int8, false)),\n Arc::new(Field::new(\"sharpness\", DataType::Int8, false)),\n Arc::new(Field::new(\"exposure\", DataType::Int8, false)),\n Arc::new(Field::new(\"framing\", DataType::Int8, false)),\n ];\n let stats = StructArray::new(\n stats_fields.into(),\n vec![\n Arc::new(motion),\n Arc::new(sharpness),\n Arc::new(exposure),\n Arc::new(framing),\n ],\n None,\n );\n\n let embeddings = FixedSizeListArray::from_iter_primitive::(\n rows.iter()\n .map(|row| Some(row.embedding.iter().copied().map(Some).collect::>())),\n 4,\n );\n\n let batch = RecordBatch::try_new(\n schema.clone(),\n vec![\n Arc::new(frame_ids),\n Arc::new(video_ids),\n Arc::new(captions),\n Arc::new(stats),\n Arc::new(embeddings),\n ],\n )\n .unwrap();\n\n Box::new(RecordBatchIterator::new(\n vec![Ok(batch)].into_iter(),\n schema,\n ))\n}\n"; -export const RsQuickstartMultimodalBytes = "use lancedb::arrow::arrow_array::BinaryArray;\n\nlet image_bytes = std::fs::read(\"data/sir-lancelot.jpg\").unwrap();\n\nlet image_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::LargeUtf8, false),\n Field::new(\"description\", DataType::LargeUtf8, false),\n Field::new(\"image\", DataType::Binary, false),\n Field::new(\n \"vector\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n]));\nlet image_vectors = [[0.9_f32, 0.1, 0.5, 0.4]];\nlet image_batch = RecordBatch::try_new(\n image_schema.clone(),\n vec![\n Arc::new(LargeStringArray::from_iter_values([\"lancelot\"])),\n Arc::new(LargeStringArray::from_iter_values([\n \"Portrait of Sir Lancelot\",\n ])),\n Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n image_vectors\n .iter()\n .map(|vector| Some(vector.iter().copied().map(Some).collect::>())),\n 4,\n ),\n ),\n ],\n)\n.unwrap();\nlet image_reader: Box = Box::new(RecordBatchIterator::new(\n vec![Ok(image_batch)].into_iter(),\n image_schema,\n));\nlet multimodal_table = db\n .create_table(\"character_images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; +export const RsQuickstartMultimodalBytes = "use lancedb::arrow::arrow_array::BinaryArray;\n\nlet image_bytes = std::fs::read(\"data/sample-frame.jpg\").unwrap();\n\nlet image_schema = Arc::new(Schema::new(vec![\n Field::new(\"frame_id\", DataType::LargeUtf8, false),\n Field::new(\"caption\", DataType::LargeUtf8, false),\n Field::new(\"image\", DataType::Binary, false),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(Arc::new(Field::new(\"item\", DataType::Float32, true)), 4),\n false,\n ),\n]));\nlet image_embeddings = [[0.9_f32, 0.1, 0.5, 0.4]];\nlet image_batch = RecordBatch::try_new(\n image_schema.clone(),\n vec![\n Arc::new(LargeStringArray::from_iter_values([\"thumb-1\"])),\n Arc::new(LargeStringArray::from_iter_values([\n \"Sample frame thumbnail\",\n ])),\n Arc::new(BinaryArray::from_iter_values([image_bytes.as_slice()])),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n image_embeddings\n .iter()\n .map(|vector| Some(vector.iter().copied().map(Some).collect::>())),\n 4,\n ),\n ),\n ],\n)\n.unwrap();\nlet image_reader: Box = Box::new(RecordBatchIterator::new(\n vec![Ok(image_batch)].into_iter(),\n image_schema,\n));\nlet multimodal_table = db\n .create_table(\"frame_images\", image_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n"; -export const RsQuickstartOutputArray = "let result = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .select(Select::Columns(vec![\n \"name\".to_string(),\n \"role\".to_string(),\n \"description\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{result:?}\");\n"; +export const RsQuickstartOutputArray = "let result = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"caption\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{result:?}\");\n"; -export const RsQuickstartQueryFeature = "let features = table\n .query()\n .select(Select::Columns(vec![\n \"name\".to_string(),\n \"role\".to_string(),\n \"power_score\".to_string(),\n ]))\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{features:?}\");\n"; +export const RsQuickstartQueryFeature = "let features = table\n .query()\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"quality_score\".to_string(),\n ]))\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{features:?}\");\n"; -export const RsQuickstartVectorSearch1 = "use lancedb::arrow::IntoPolars;\nuse lancedb::query::{ExecutableQuery, QueryBase, Select};\n\n// Search for examples similar to a \"wise magical advisor\"\nlet query_vector = [0.2, 0.8, 0.4, 0.9];\n\nlet result = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .select(Select::Columns(vec![\n \"name\".to_string(),\n \"role\".to_string(),\n \"description\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{result:?}\");\n"; +export const RsQuickstartVectorSearch1 = "use lancedb::arrow::IntoPolars;\nuse lancedb::query::{ExecutableQuery, QueryBase, Select};\n\n// Search for frames similar to \"a gripper closing on an object\"\nlet query_vector = [0.2, 0.8, 0.4, 0.9];\n\nlet result = table\n .query()\n .nearest_to(&query_vector)\n .unwrap()\n .select(Select::Columns(vec![\n \"frame_id\".to_string(),\n \"video_id\".to_string(),\n \"caption\".to_string(),\n \"_distance\".to_string(),\n ]))\n .limit(2)\n .execute()\n .await\n .unwrap()\n .into_polars()\n .await\n .unwrap();\nprintln!(\"{result:?}\");\n"; diff --git a/docs/web/sql/data-types.mdx b/docs/web/sql/data-types.mdx index 051368525..c5f362a6b 100644 --- a/docs/web/sql/data-types.mdx +++ b/docs/web/sql/data-types.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Data Types" description: "How Lance columns appear to SQL, including the types SQL has no name for." icon: shapes keywords: ["sql types", "arrow", "cast", "pseudo-columns", "vector", "json"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - There is no SQL type layer over Lance storage. The table provider hands DataFusion the dataset's Arrow schema directly, so a column is the same object to the query engine as it is to the format. diff --git a/docs/web/sql/ddl/database.mdx b/docs/web/sql/ddl/database.mdx new file mode 100644 index 000000000..6f4ab557f --- /dev/null +++ b/docs/web/sql/ddl/database.mdx @@ -0,0 +1,50 @@ +--- +title: "Database" +sidebarTitle: "Database" +description: "ATTACH DATABASE: bind a database to a storage location." +icon: database +keywords: ["attach database", "database", "sql", "ddl"] +availability: + embedded: unavailable + enterprise: available +--- + +A database is the catalog's top-level container: it holds +[namespaces](/sql/ddl/namespace), which hold tables, views and other objects. +`ATTACH DATABASE` binds a name to a storage location so its objects become +reachable. + +## ATTACH DATABASE {#attach} + +```sql +ATTACH DATABASE analytics WITH (location = 'analytics') +ATTACH DATABASE IF NOT EXISTS analytics WITH (location = 'analytics') +``` + +`location` is the only supported option, and the only way to say where a +database lives: a relative subdirectory, never an absolute path or a URI. + + +An absolute path (`/tmp/db`), an `s3://` or `file://` URI, a Windows path +(`C:/db`), a `..` segment, an empty string and a doubled slash (`sub//db`) +are all refused. + + +`IF NOT EXISTS` makes the statement a no-op rather than an error when the +database is already attached. + + +A quoted name reaches characters a bare identifier cannot, such as +`` ATTACH DATABASE "team/search" WITH (location = 'team-search') ``. + + +## What to read next {#next} + + + + CREATE SCHEMA inside an attached database. + + + Creating tables once a database and namespace exist. + + diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index caf4c4cd5..1593c2d7b 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -17,6 +17,15 @@ AS 'def f(x): return x * 2' WITH (pip = 'numpy==1.26.4', python_version = '3.11') ``` +A function takes more than one parameter; each one binds a separate column +or literal where the function is called: + +```sql +CREATE FUNCTION ratio(numerator float64, denominator float64) RETURNS float64 +LANGUAGE python +AS 'def ratio(numerator, denominator): return numerator / denominator' +``` + Parameter and result types are Arrow type names, not SQL ones: `int64`, `float64`, `utf8`, `bool`, `date32`, and lists such as `list` or `fixed_size_list`. `BIGINT` is refused. A parameter accepts nulls @@ -51,6 +60,20 @@ version is unaffected. the function is baked into an image before the version becomes usable. +## Call it {#call} + +Once registered, a function is callable by name in any query, the same as a +built-in scalar function: + +```sql +SELECT id, f(x) AS doubled FROM my_table +``` + +This is also the fastest way to check a new registration before binding it to +a column: call it over a few rows, or over literal arguments, before +committing to [a computed column](/sql/ddl/table#computed-column) that fills +from it. + ## SHOW FUNCTIONS {#show} ```sql diff --git a/docs/web/sql/ddl/grant.mdx b/docs/web/sql/ddl/grant.mdx new file mode 100644 index 000000000..85da7832a --- /dev/null +++ b/docs/web/sql/ddl/grant.mdx @@ -0,0 +1,77 @@ +--- +title: "Grant" +sidebarTitle: "Grant" +description: "GRANT and REVOKE: privileges on Secrets and Functions." +icon: user-lock +keywords: ["grant", "revoke", "privileges", "authorization", "sql", "ownership"] +--- + +Enterprise [SQL runs in LanceDB Enterprise.](/sql) + +```sql +GRANT [, ...] ON { SECRET | FUNCTION } TO [, ...] +GRANT [, ...] ON SCHEMA TO [, ...] +REVOKE [, ...] ON ... FROM [, ...] +``` + +```sql +GRANT USAGE, UPDATE ON SECRET api_key TO ROLE readers, writers +GRANT CREATE FUNCTION ON SCHEMA analytics TO ROLE data_science +REVOKE USAGE ON FUNCTION embed FROM ROLE readers +``` + +## Privileges {#privileges} + +| Privilege | Allows | +| --- | --- | +| `OWNERSHIP` | everything on the object | +| `USAGE` | using it: binding a Secret's value, calling a Function | +| `UPDATE` | changing it | +| `CREATE SECRET` | creating a Secret inside a `SCHEMA` | +| `CREATE FUNCTION` | creating a Function inside a `SCHEMA` | + + +`OWNERSHIP` cannot be revoked, only granted to someone else, which transfers +it: an object always has exactly one owner. `GRANT OWNERSHIP` is refused with +more than one grantee for the same reason. + + +These are a subset of the full privilege model; see +[Authorization](/governance/authorization#privileges) for privileges on +tables, views and namespaces, which this statement does not grant. + +## Grantees {#grantees} + +```sql + ::= [ ROLE ] | [ { USER | GROUP } ] { | ID '' } +``` + +```sql +GRANT USAGE ON SECRET api_key TO ROLE readers, USER alice, GROUP ID 'g1' +``` + +A grantee is a role, or a user or group named by its identity-directory name +or its directory ID. A grantee with no leading `ROLE`/`USER`/`GROUP` keyword +takes the kind of the one before it, so `TO ROLE a, b` names two roles -- +but the first grantee in the list always needs its keyword. An unquoted name +is folded to lowercase before it is looked up; a quoted name is looked up +exactly as written. + +## Naming the target {#targets} + +A `SECRET` or `FUNCTION` target can be qualified with its namespace and +database, the same as anywhere else: `SECRET analytics.api_key`, +`SECRET db1.analytics.api_key`. A `SCHEMA` target is the namespace itself. +There is no `TABLE` target: table privileges are granted through +[Authorization](/governance/authorization), not this statement. + +## What to read next {#next} + + + + The full privilege model, and how creation privileges resolve upward. + + + Creating the schemas these privileges apply to. + + diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index fb84e881c..dd900ee52 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Index" description: "CREATE INDEX and DROP INDEX: one column, with the algorithm chosen by USING." icon: bolt keywords: ["create index", "drop index", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ## CREATE INDEX {#create} ```sql diff --git a/docs/web/sql/ddl/job.mdx b/docs/web/sql/ddl/job.mdx index 323dc1b1e..1b66e1e29 100644 --- a/docs/web/sql/ddl/job.mdx +++ b/docs/web/sql/ddl/job.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Job" description: "SHOW JOBS, SHOW ERRORS, and controlling a running job with PAUSE, RESUME and CANCEL." icon: hourglass-half keywords: ["show jobs", "show errors", "pause job", "resume job", "cancel job", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A [job](/basics/jobs) is not a catalog object (it has no schema and is not namespaced), but it has its own SQL statements, grouped here the same way the catalog objects are. @@ -32,7 +33,7 @@ SHOW ERRORS ON documents SHOW ERRORS ON documents FOR JOB 'job-abc' LIMIT 100 ``` -Why rows failed. Reach for this when a [refresh](/sql/dml/refresh) reports +Why rows failed. Reach for this when a [refresh](/sql/dml/refresh-column) reports fewer filled rows than you expected. **Errors and limits** diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index a8dfb8fbe..25fcab76e 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Materialized View" description: "CREATE MATERIALIZED VIEW and SHOW MATERIALIZED VIEWS; refreshing is a REFRESH statement." icon: table keywords: ["materialized view", "create materialized view", "show materialized views", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A materialized view stores a query's result as rows, kept current by a refresh. It is the counterpart to a [view](/sql/ddl/view), which stores only the query. @@ -28,6 +29,29 @@ Once created, a materialized view can be queried like a table. Use the statements below to list, refresh and drop it. For SDK methods, see [Materialized views](/management/materialized-view#create). +{/* +Draft for automatic materialized-view refresh. Enable this section, and +"ALTER MATERIALIZED VIEW" below, when the server feature is released. + +Set scheduling options at creation, continuing the join and chained +Functions from [Functions](/management/function#chain): + +```sql +CREATE MATERIALIZED VIEW frames_captioned AS +SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg, + caption(extract_frame(v.video, f.ts)) AS caption +FROM videos v JOIN frames f ON v.id = f.video_id +WHERE f.selected = true +WITH (auto_refresh_enabled = false, auto_refresh_interval_seconds = 5) +``` + +`auto_refresh_enabled` and `auto_refresh_interval_seconds` work the same way +here as for a [computed column](/sql/ddl/table#automatic-refresh-options): +the interval is a minimum pacing after the last successful refresh, and +automatic execution needs the same server-side switch enabled. Omitting +`WITH` leaves automatic refresh at the server's default. +*/} + ## SHOW MATERIALIZED VIEWS {#show} ```sql @@ -45,9 +69,37 @@ on a `db://` connection. REFRESH MATERIALIZED VIEW chunks ``` -See [REFRESH](/sql/dml/refresh#refresh-materialized-view) for the full syntax, +See [REFRESH MATERIALIZED VIEW](/sql/dml/refresh-materialized-view) for the full syntax, and compatibility notes for older server versions. +{/* +Draft for automatic materialized-view refresh. Enable this section when the +server feature is released; see the note on "CREATE MATERIALIZED VIEW" above. + +## ALTER MATERIALIZED VIEW {#alter} + +```sql +ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_enabled = true; +ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_interval_seconds = 300; +ALTER MATERIALIZED VIEW frames_captioned SET auto_refresh_enabled = false; +``` + +The whole view toggles together; there is no per-output granularity the way +a multi-output Function column has one setting per output. SET takes effect +immediately and does not itself run a refresh: + +- **Disabling** prevents new automatic refreshes. An inflight one may still + finish, and `REFRESH MATERIALIZED VIEW` keeps working manually. +- **Re-enabling catches up the entire backlog in one pass**, the same as a + computed column's [automatic refresh](/sql/ddl/table#automatic-refresh-options): + the next scheduler tick picks up every source change accumulated since the + view was disabled, immediately, with no further write needed to trigger it. + +A materialized view's *initial* population, at `CREATE` or when the server +runs it, happens regardless of `auto_refresh_enabled`; only refreshes after +that are gated by the setting. +*/} + ## Dropping one {#drop} A materialized view **is** a table, so it is dropped with @@ -55,9 +107,8 @@ A materialized view **is** a table, so it is dropped with stored rows, unlike dropping a [view](/sql/ddl/view#drop). -**Enterprise job type:** `mat_view_refresh` for a refresh, or `sql` on a -deployment that rebuilds views through SQL. Dropping one runs the same job as -dropping any table, `drop_table` or `drop_object`. +**Enterprise job type for a refresh:** `sql`. Dropping, by contrast, runs the +same job as dropping any table, `drop_table` or `drop_object`. ## What to read next {#next} @@ -66,7 +117,7 @@ dropping any table, `drop_table` or `drop_object`. Creating one from the SDK. - - How a refresh works, locally and in LanceDB Enterprise. + + How a refresh works, in LanceDB Enterprise.
diff --git a/docs/web/sql/ddl/namespace.mdx b/docs/web/sql/ddl/namespace.mdx index 472f3c1ad..dd50031ac 100644 --- a/docs/web/sql/ddl/namespace.mdx +++ b/docs/web/sql/ddl/namespace.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Namespace" description: "CREATE SCHEMA and DROP SCHEMA: the SQL spelling of namespace DDL." icon: folder-tree keywords: ["namespace", "schema", "create schema", "drop schema", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A [namespace](/management/namespace) is addressed in SQL as a `SCHEMA`, the standard's name for the same concept. @@ -46,6 +47,9 @@ default) states that requirement rather than changing it. ## What to read next {#next} + + Attaching the database a namespace lives in. + The SDK equivalent, and how a namespace fits the catalog hierarchy. diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 2d1ac6cbc..b1a5e8f1e 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Table" description: "CREATE, DESCRIBE, ALTER, CLONE and DROP TABLE." icon: table keywords: ["create table", "alter table", "drop table", "describe", "clone", "ddl"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ## CREATE TABLE {#create} ```sql @@ -50,7 +51,7 @@ ALTER TABLE t ADD COLUMN doubled AS value * 2 `AS ` declares a [computed column](/feature-engineering/add-computed-column). The column is committed empty and the expression is stored, not evaluated: declaring one on a billion-row table costs what declaring one on an empty table -costs. [`REFRESH COLUMN`](/sql/dml/refresh) fills it. +costs. [`REFRESH COLUMN`](/sql/dml/refresh-column) fills it. {/* Draft for automatic computed-column refresh. Enable this section when the @@ -74,19 +75,35 @@ and is minimum pacing after a successful refresh of that output; unchanged inputs do not force work. A new column is immediately eligible for its first refresh. The server's separate automatic-refresh switch must also be enabled. -These options also work beside a Function binding's `version` and `branch`: +These options also work beside a Function binding's `version` and `branch`, +continuing the [`caption` Function](/management/function#chain) from Functions: ```sql -ALTER TABLE t ADD COLUMN (label, score) AS classify(text) +ALTER TABLE frames ADD COLUMN caption AS caption(extract_frame(video, ts)) WITH (version = 'fv_1', auto_refresh_enabled = true, auto_refresh_interval_seconds = 300); -ALTER TABLE t ALTER COLUMN score SET auto_refresh_enabled = false; +ALTER TABLE frames ALTER COLUMN caption SET auto_refresh_enabled = false; ``` Declaration settings initialize every output in the group; later SET commands -change one output. Disabling automatic refresh prevents new submissions while -allowing inflight jobs to finish and explicit REFRESH COLUMN to run. Column -SUSPEND/RESUME syntax is not supported. +change one output. SET takes effect immediately and does not itself read or +write any row: + +- **Disabling** prevents new automatic submissions. Inflight jobs may still + finish, explicit `REFRESH COLUMN` keeps working, and rows written while + disabled commit with no computed value -- they do not queue anywhere + separate. +- **Re-enabling catches up the entire backlog in one pass.** The next + scheduler tick processes every row left unfilled since the column was + disabled, immediately, with no further write required to trigger it: a + column disabled for an hour and re-enabled fills everything that + accumulated during that hour, not just rows written after the moment it + is re-enabled. + +Column SUSPEND/RESUME syntax is not supported; `SET auto_refresh_enabled` is +the only toggle. The current setting is in the column's own field metadata, +`computed_column.auto_refresh_enabled`, readable from `DESCRIBE` or the +SDK's `table.schema` without submitting a job to ask. */} {/* @@ -148,7 +165,7 @@ ALTER TABLE t SET RTE WITH (maintained_indexes = '') ALTER TABLE t UNSET RTE ``` -The [realtime engine](/tables/realtime-engine) puts a write-ahead log in front +The [real time engine](/tables/realtime-engine) puts a write-ahead log in front of the table, making small frequent writes cheap by batching them out of the commit path. `sharding` and `buckets` spread the log so concurrent writers do not contend on one place; `bucket` sharding names its `column`, which must be diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index ec923063b..c6c1f7ecb 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -4,10 +4,11 @@ sidebarTitle: "View" description: "CREATE VIEW and DROP VIEW: a saved query, evaluated when read." icon: eye keywords: ["create view", "drop view", "sql", "catalog"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A view stores a **query**, not rows. Reading it runs the query against current data, so a view is never stale, and never faster than the query it wraps. It is the counterpart to a [materialized view](/sql/ddl/materialized-view), which diff --git a/docs/web/sql/dml/delete.mdx b/docs/web/sql/dml/delete.mdx index 429271de3..29b8f65d9 100644 --- a/docs/web/sql/dml/delete.mdx +++ b/docs/web/sql/dml/delete.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Delete" description: "DELETE FROM ... WHERE: rows are marked, not erased." icon: trash keywords: ["delete", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql DELETE FROM documents WHERE created_at < TIMESTAMP '2025-01-01 00:00:00' ``` diff --git a/docs/web/sql/dml/insert.mdx b/docs/web/sql/dml/insert.mdx index 44007c6a3..71a7d1182 100644 --- a/docs/web/sql/dml/insert.mdx +++ b/docs/web/sql/dml/insert.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Insert" description: "INSERT INTO, including INSERT ... SELECT to move rows server-side." icon: plus keywords: ["insert", "insert into", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql INSERT INTO documents (id, title) VALUES (1, 'Merlin'), (2, 'Arthur') diff --git a/docs/web/sql/dml/refresh.mdx b/docs/web/sql/dml/refresh-column.mdx similarity index 63% rename from docs/web/sql/dml/refresh.mdx rename to docs/web/sql/dml/refresh-column.mdx index d454069a9..db5d26475 100644 --- a/docs/web/sql/dml/refresh.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -1,19 +1,18 @@ --- -title: "REFRESH" -sidebarTitle: "REFRESH" -description: "Filling computed columns and bringing materialized views up to date." +title: "REFRESH COLUMN" +sidebarTitle: "REFRESH COLUMN" +description: "Filling a computed column: idempotent, scoped, and resumable." icon: arrows-rotate -keywords: ["refresh column", "refresh materialized view", "backfill", "cascade"] +keywords: ["refresh column", "backfill", "computed column"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - -LanceDB extensions with no DataFusion equivalent. They are what makes +A LanceDB extension with no DataFusion equivalent. It is what makes [feature engineering](/feature-engineering) reachable from SQL: a column declared by [DDL](/sql/ddl/table#computed-column) starts empty, and a refresh fills it. -## REFRESH COLUMN {#refresh-column} - ```sql REFRESH COLUMN ON [TABLE] [WHERE ] @@ -33,7 +32,7 @@ can recompute values the failed run had already written. `WHERE` scopes the refresh, which is how you fill a slice and check it before committing to the whole table. -### Options {#refresh-column-options} +## Options {#options} | Option | Meaning | | --- | --- | @@ -62,39 +61,22 @@ memory and GPU options there. */} -## REFRESH MATERIALIZED VIEW {#refresh-materialized-view} - -```sql -REFRESH MATERIALIZED VIEW -``` - -```sql -REFRESH MATERIALIZED VIEW chunks -``` - -A refresh updates the view's stored result. Refresh views in dependency order, -starting with their source views. - - -Some older server versions accepted `WITH (full = true)` and `CASCADE`. -Those options are not accepted by the SQL implementation described here. -Use the basic statement above; do not assume that the options accepted by a -local SDK's `refresh()` method are also SQL options. - - ## Watching a refresh {#watching} -Both statements submit work that outlives the call. Track it with +A refresh submits work that outlives the call. Track it with [`SHOW JOBS`](/sql/ddl/job#show), and diagnose failures with [`SHOW ERRORS`](/sql/ddl/job#errors). ## See also {#see-also} - + The same operation from the SDKs, and what a refresh guarantees. Declaring the columns this fills. + + Bringing a view's stored result up to date, instead of a column. + diff --git a/docs/web/sql/dml/refresh-materialized-view.mdx b/docs/web/sql/dml/refresh-materialized-view.mdx new file mode 100644 index 000000000..8e1886f23 --- /dev/null +++ b/docs/web/sql/dml/refresh-materialized-view.mdx @@ -0,0 +1,50 @@ +--- +title: "REFRESH MATERIALIZED VIEW" +sidebarTitle: "REFRESH MATERIALIZED VIEW" +description: "Bringing a materialized view's stored result up to date." +icon: arrows-rotate +keywords: ["refresh materialized view", "cascade"] +availability: + embedded: unavailable + enterprise: available +--- + +A LanceDB extension with no DataFusion equivalent. + +```sql +REFRESH MATERIALIZED VIEW +``` + +```sql +REFRESH MATERIALIZED VIEW chunks +``` + +A refresh updates the view's stored result. Refresh views in dependency order, +starting with their source views. + + +Some older server versions accepted `WITH (full = true)` and `CASCADE`. +Those options are not accepted by the SQL implementation described here. +Use the basic statement above; do not assume that the options accepted by a +local SDK's `refresh()` method are also SQL options. + + +## Watching a refresh {#watching} + +A refresh submits work that outlives the call. Track it with +[`SHOW JOBS`](/sql/ddl/job#show), and diagnose failures with +[`SHOW ERRORS`](/sql/ddl/job#errors). + +## See also {#see-also} + + + + Creating the view this refreshes. + + + The same operation from the SDKs, and automatic refresh. + + + Filling a computed column, instead of a view. + + diff --git a/docs/web/sql/dml/update.mdx b/docs/web/sql/dml/update.mdx index b527d1ec0..68512e155 100644 --- a/docs/web/sql/dml/update.mdx +++ b/docs/web/sql/dml/update.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Update" description: "UPDATE ... SET ... WHERE, and why it does not recompute derived columns." icon: pen keywords: ["update", "sql"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql UPDATE documents SET title = upper(title) WHERE category = 'film' ``` diff --git a/docs/web/sql/dql/aggregation.mdx b/docs/web/sql/dql/aggregation.mdx index fe02dc17a..cc41397b4 100644 --- a/docs/web/sql/dql/aggregation.mdx +++ b/docs/web/sql/dql/aggregation.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Aggregation" description: "GROUP BY, HAVING, and the aggregate function set." icon: layer-group keywords: ["group by", "having", "count", "sum", "avg", "aggregate", "approximate"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Use SQL aggregates to summarize records, either across a whole table or within groups. Common examples include counts by category, totals and averages. diff --git a/docs/web/sql/dql/changes.mdx b/docs/web/sql/dql/changes.mdx new file mode 100644 index 000000000..012c06ff8 --- /dev/null +++ b/docs/web/sql/dql/changes.mdx @@ -0,0 +1,76 @@ +--- +title: "Changes since a version" +sidebarTitle: "Changes" +description: "CHANGES: read the rows appended to a table since an earlier version." +icon: clock-rotate-left +keywords: ["changes", "append", "incremental", "cdc", "version"] +availability: + embedded: unavailable + enterprise: available +--- + +`CHANGES` reads the rows appended to a table since an earlier +[version](/management/table#versioning), without rescanning rows that were +already there: + +```sql +SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) +``` + +This returns the rows appended after version 42, up to the table's current +version at the time the query runs. + +## Strictly append-only {#strict} + +The clause is named for what it requires, not just what it does: every +change to the table between the starting version and the current one must +be an append. If any of them inserted with changes other than a pure append +-- an update, a delete, a merge -- the query is refused rather than silently +returning an incomplete or wrong result. Re-run it with a later starting +version that is itself after the non-append write, or read the table in full +instead of incrementally. + +`INFORMATION => APPEND_ONLY` is the only supported value: it names what kind +of history the clause is willing to read, not a choice among several. `AT +(VERSION => ...)` takes a positive integer; there is no `AT (TIMESTAMP => +...)` form for this clause, unlike other version qualifiers. + +## Where the clause can go {#placement} + +It attaches to a table in `FROM`, including inside a subquery, a CTE, a join, +a set operation, or `EXPLAIN`: + +```sql +WITH recent AS ( + SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 42) +) +SELECT count(*) FROM recent + +SELECT * FROM events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 10) a +JOIN events CHANGES (INFORMATION => APPEND_ONLY) AT (VERSION => 20) b + ON a.id = b.id +``` + +Each occurrence of a table keeps its own starting version, even when the same +table is referenced more than once in one statement. + +## Unsupported forms {#refused} + +| | | +| --- | --- | +| `CHANGES (INFORMATION => DEFAULT)` | only `APPEND_ONLY` is supported | +| `AT (TIMESTAMP => ...)` | only `AT (VERSION => ...)` is supported | +| `AT (VERSION => 0)` | the starting version must be positive | +| `... END (VERSION => ...)` | not supported; the current version is always the end | +| `CHANGES ... TABLESAMPLE (...)` | cannot be combined on the same table reference | + +## What to read next {#next} + + + + CREATE, ALTER, CLONE and versioning basics. + + + The rest of the query grammar this clause attaches to. + + diff --git a/docs/web/sql/dql/dedupe.mdx b/docs/web/sql/dql/dedupe.mdx new file mode 100644 index 000000000..c82e72c13 --- /dev/null +++ b/docs/web/sql/dql/dedupe.mdx @@ -0,0 +1,99 @@ +--- +title: "DEDUPE" +sidebarTitle: "DEDUPE" +description: "The dedupe() table function: one representative row per near-duplicate group, scanned over the index." +icon: layer-group +keywords: ["dedupe", "vector_dedup", "sql", "deduplication", "near-duplicate", "table function"] +availability: + embedded: unavailable + enterprise: available +--- + +`dedupe` scans a vector column's [index](/indexing/vector-index) partitions +for rows closer than a distance threshold, resolves the overlapping pairs it +finds into duplicate groups, and returns one representative row per group -- +without a full pairwise scan or a shuffle. See +[`duplicate_pairs`](/sql/dql/duplicate-pairs) to inspect the pairs themselves +before committing to this resolution. + +```sql +SELECT * FROM dedupe(
, , + distance_threshold => + [, resolution => 'connected_components' | 'direct_representative'] + [, selection => 'all' | 'first' | 'random', count => , seed => ] +) +``` + +```sql +SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) +``` + + +Earlier releases spelled this `vector_dedup`; that name is rejected on +current deployments. + + +## Input {#input} + +| Argument | Type | Required | Meaning | +| --- | --- | --- | --- | +| table name | string literal | yes | the table to scan | +| vector column | string literal | yes | the indexed vector column to compare | +| `distance_threshold` | float | yes | maximum distance for a pair to count as close | +| `resolution` | `'connected_components'` (default) \| `'direct_representative'` | no | how overlapping pairs group together -- see [Resolution](#resolution) | +| `selection` | `'all'` (default) \| `'first'` \| `'random'` | no | which index partitions to scan | +| `count` | int | no | number of partitions to sample when `selection => 'random'` | +| `seed` | int | no | random seed when `selection => 'random'` | + +`id_column` is refused on `dedupe`: it has no separate pair-identifier output +to project onto, only [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) +accepts it. + +## Output {#output} + +One row per duplicate group, **in the table's own schema** -- every column of +`
`, including a BlobV2 column, comes through unchanged on the +representative row Lance selected for that group. Unlike +[`duplicate_pairs`](/sql/dql/duplicate-pairs#output), there is no fixed +`dedupe`-specific schema to document: the output schema is the source +table's schema. + +Because the result is already shaped like the table, it composes directly +into a new table or a materialized view: + +```sql +CREATE MATERIALIZED VIEW frames_deduped AS +SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) +``` + +## Resolution {#resolution} + +`resolution` chooses how overlapping pairs group together: + +| `resolution` | | +| --- | --- | +| `connected_components` (default) | groups transitively: if a~b and b~c are both close, all three resolve together | +| `direct_representative` | only pairs within the threshold of each other resolve together | + +## Sampling partitions {#sampling} + +`selection` scopes the scan to a sample of partitions instead of all of them, +the same `all` (default) / `first` / `random` choice as +[`ivf_partition`](/sql/scalar-functions#ivf-partition). Use it to estimate a +duplicate rate on a large table before scanning it in full: + +```sql +SELECT * FROM dedupe('frames', 'vec', + distance_threshold => 0.02, selection => 'random', count => 100, seed => 42) +``` + +## What to read next {#next} + + + + Inspect the close pairs themselves instead of the resolved groups. + + + When to reach for this instead of exact-key deduplication. + + diff --git a/docs/web/sql/dql/duplicate-pairs.mdx b/docs/web/sql/dql/duplicate-pairs.mdx new file mode 100644 index 000000000..e8651a28c --- /dev/null +++ b/docs/web/sql/dql/duplicate-pairs.mdx @@ -0,0 +1,97 @@ +--- +title: "DUPLICATE_PAIRS" +sidebarTitle: "DUPLICATE_PAIRS" +description: "The duplicate_pairs() table function: every close pair in a vector column, scanned over the index." +icon: clone +keywords: ["duplicate_pairs", "vector_duplicate_pairs", "sql", "deduplication", "near-duplicate", "table function"] +availability: + embedded: unavailable + enterprise: available +--- + +`duplicate_pairs` scans a vector column's [index](/indexing/vector-index) +partitions for every pair of rows closer than a distance threshold, without a +full pairwise scan or a shuffle. It returns one row per close pair, not one +row per source row -- use it to inspect what would be collapsed before +committing to [`dedupe`](/sql/dql/dedupe), which resolves these same pairs +into groups. + +```sql +SELECT * FROM duplicate_pairs(
, , + distance_threshold => + [, id_column => ] + [, selection => 'all' | 'first' | 'random', count => , seed => ] +) +``` + +```sql +SELECT * FROM duplicate_pairs('frames', 'vec', distance_threshold => 0.02) +``` + + +Earlier releases spelled this `vector_duplicate_pairs`; that name is rejected +on current deployments. + + +## Input {#input} + +| Argument | Type | Required | Meaning | +| --- | --- | --- | --- | +| table name | string literal | yes | the table to scan | +| vector column | string literal | yes | the indexed vector column to compare | +| `distance_threshold` | float | yes | maximum distance for a pair to count as close | +| `id_column` | column name | no | project this column's value instead of the internal row ID -- see [Application-level identifiers](#id-column) | +| `selection` | `'all'` (default) \| `'first'` \| `'random'` | no | which index partitions to scan | +| `count` | int | no | number of partitions to sample when `selection => 'random'` | +| `seed` | int | no | random seed when `selection => 'random'` | + +`resolution` is refused on `duplicate_pairs`: a pair has no notion of a group, +only [`dedupe`](/sql/dql/dedupe#input) accepts it. + +## Output {#output} + +One row per close pair found, in a fixed schema independent of the source +table: + +| Column | Type | Meaning | +| --- | --- | --- | +| `row_id_a` | uint64 | internal row ID of the first row in the pair, the same identifier as the [`_rowid`](/sql/data-types#pseudo-columns) pseudo-column | +| `row_id_b` | uint64 | internal row ID of the second row in the pair | +| `distance` | float32 | distance between the pair's vectors, at or below `distance_threshold` | +| `segment_id` | int64 | which index segment the pair was found in | +| `partition_id` | int64 | which index partition the pair was found in | +| `dataset_version` | int64 | the dataset version the scan ran against | + +### Application-level identifiers {#id-column} + +A row ID is internal and not stable across compaction. Pass `id_column`, a +top-level scalar column such as a primary key, to project its value instead: +`row_id_a`/`row_id_b` are replaced by `id_a`/`id_b`, typed like `id_column`. + +```sql +SELECT * FROM duplicate_pairs('frames', 'vec', distance_threshold => 0.02, id_column => 'frame_id') +``` + +## Sampling partitions {#sampling} + +`selection` scopes the scan to a sample of partitions instead of all of them, +the same `all` (default) / `first` / `random` choice as +[`ivf_partition`](/sql/scalar-functions#ivf-partition). Use it to estimate a +distance threshold or duplicate rate on a large table before scanning it in +full: + +```sql +SELECT * FROM duplicate_pairs('frames', 'vec', + distance_threshold => 0.02, selection => 'random', count => 100, seed => 42) +``` + +## What to read next {#next} + + + + Resolve these same pairs into one representative row per group. + + + When to reach for this instead of exact-key deduplication. + + diff --git a/docs/web/sql/dql/explain.mdx b/docs/web/sql/dql/explain.mdx index 1fc4dc191..151a861bc 100644 --- a/docs/web/sql/dql/explain.mdx +++ b/docs/web/sql/dql/explain.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Explain" description: "EXPLAIN, EXPLAIN ANALYZE and EXPLAIN VERBOSE: reading and measuring a plan from SQL." icon: map keywords: ["explain", "explain analyze", "explain verbose", "query plan"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql EXPLAIN SELECT * FROM documents WHERE identifier < 1000 EXPLAIN ANALYZE SELECT * FROM documents WHERE identifier < 1000 diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index f6d5bc696..3dc6d3a3e 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Full-Text Search" description: "The fts() table function: match, fuzzy, phrase, boolean, boost and multi-match queries from SQL." icon: magnifying-glass keywords: ["fts", "sql", "full text search", "fuzzy", "phrase", "boolean", "boost", "multi-match"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Full-text search is a **table function**, `fts(table, query)`, rather than a predicate: it produces a relevance score alongside the matching rows, and a `WHERE` clause has nowhere to put one. The two string-literal arguments are diff --git a/docs/web/sql/dql/join.mdx b/docs/web/sql/dql/join.mdx index 5ccf49f50..ecc81ec31 100644 --- a/docs/web/sql/dql/join.mdx +++ b/docs/web/sql/dql/join.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Joins" description: "Combining rows from more than one table, including across namespaces." icon: link keywords: ["join", "inner", "left", "outer", "cross", "namespace"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Use SQL joins to combine rows from two or more tables. ## The join types {#types} @@ -70,3 +71,29 @@ Avoid selecting blob or vector columns you do not need on either side of a join. The join multiplies rows before projection is applied in some plans, so a wide column can be materialized many more times than the result has rows. + +## Late materialization for wide columns {#late-materialization} + +The planner can avoid the multiplication above: when a join narrows down to +a key column (such as `_rowid` or another narrow, selective column) before a +wide one is needed, it can defer reading a BlobV2 or vector column until +after the join has already settled which rows survive, instead of reading it +for every candidate row first. In a plan where this applies, the wide column +is read once per surviving row, where the worker runs, and never pulled into +the query node to be joined directly. + +```sql +SELECT d.title, b.caption +FROM documents AS d +JOIN (SELECT _rowid, caption FROM captions WHERE source = 'model-v2') AS b + ON b._rowid = d._rowid +``` + +This is query planning, not a syntax you opt into: a join written this way +is a **candidate** for the planner to defer the wide read, not a guarantee. +Confirm it for a specific query with [`EXPLAIN`](/sql/dql/explain) -- +`RemoteTake` in the plan means the deferral happened; its absence means the +wide column was read eagerly, even if the SQL above matches exactly. Neither +a passing query nor an `EXPLAIN` that omits `RemoteTake` tells you how much +I/O a plan did or did not save -- read the plan's own row and byte counts for +that. diff --git a/docs/web/sql/dql/sampling.mdx b/docs/web/sql/dql/sampling.mdx index 03e518f1b..954247142 100644 --- a/docs/web/sql/dql/sampling.mdx +++ b/docs/web/sql/dql/sampling.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Sampling" description: "TABLESAMPLE: draw a random subset of a table, by rows or by fragments." icon: dice keywords: ["tablesample", "sampling", "bernoulli", "system", "repeatable", "random"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Use `TABLESAMPLE` to explore a subset of a table or estimate aggregate statistics. The sampling method determines how much data is read and whether the table's physical layout influences the sample. diff --git a/docs/web/sql/dql/select.mdx b/docs/web/sql/dql/select.mdx index cfc02c9c4..621061204 100644 --- a/docs/web/sql/dql/select.mdx +++ b/docs/web/sql/dql/select.mdx @@ -4,10 +4,11 @@ sidebarTitle: "SELECT" description: "Projection, filtering, ordering, and composing queries out of other queries." icon: table-columns keywords: ["select", "where", "order by", "limit", "cte", "union", "distinct"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - ```sql [WITH cte AS (...)] SELECT [ALL | DISTINCT] select_expr [, ...] diff --git a/docs/web/sql/dql/subqueries.mdx b/docs/web/sql/dql/subqueries.mdx index 48887da72..3c5b5d11d 100644 --- a/docs/web/sql/dql/subqueries.mdx +++ b/docs/web/sql/dql/subqueries.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Subqueries" description: "Queries inside queries: scalar, IN, EXISTS, correlated, and derived tables." icon: code-branch keywords: ["subquery", "exists", "in", "correlated", "derived table", "lateral"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A subquery is allowed anywhere an expression or a relation is. ## As a relation {#derived} diff --git a/docs/web/sql/dql/window.mdx b/docs/web/sql/dql/window.mdx index 14b052861..e90f601c6 100644 --- a/docs/web/sql/dql/window.mdx +++ b/docs/web/sql/dql/window.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Window Functions" description: "Compute over a set of rows related to the current one, without collapsing them." icon: chart-simple keywords: ["window", "over", "partition by", "row_number", "rank", "lag", "lead"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A window function computes across a set of rows related to the current one and returns a value **per row**. That is the difference from [aggregation](/sql/dql/aggregation), which collapses the rows it covers. diff --git a/docs/web/sql/functions.mdx b/docs/web/sql/functions.mdx index 9f7b8985b..9f6a25229 100644 --- a/docs/web/sql/functions.mdx +++ b/docs/web/sql/functions.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Functions" description: "Where to find each kind of function, and the dialect version they come from." icon: function keywords: ["functions", "datafusion", "scalar", "aggregate", "window", "fts", "table function"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - LanceDB executes SQL with [Apache DataFusion](https://datafusion.apache.org), currently **version 54**. The function set is DataFusion's default registration plus what Lance adds. @@ -77,6 +78,29 @@ like any other column (order by it, filter on it, project it) and exists only in a relation that came from `fts()`. See [Data types](/sql/data-types#pseudo-columns). +### `dedupe` and `duplicate_pairs` {#dedupe} + +Scan a vector column's [index](/indexing/vector-index) partitions for rows +closer than a distance threshold, without a full pairwise scan or a shuffle: + +```sql +SELECT * FROM duplicate_pairs('frames', 'vec', distance_threshold => 0.02) +SELECT * FROM dedupe('frames', 'vec', distance_threshold => 0.02) +``` + + +Earlier releases spelled these `vector_duplicate_pairs` and `vector_dedup`; +those names are rejected on current deployments. + + +`duplicate_pairs` returns every close pair it finds, in a fixed schema. +`dedupe` instead resolves overlapping pairs into duplicate groups and returns +one representative row **in the table's own schema** per group, so its result +composes directly into `CREATE TABLE ... AS` or +`CREATE MATERIALIZED VIEW ... AS`. See [`DEDUPE`](/sql/dql/dedupe) and +[`DUPLICATE_PAIRS`](/sql/dql/duplicate-pairs) for the full input and output +schema, resolution grouping, and partition sampling. + ### `generate_series` {#generate-series} ```sql diff --git a/docs/web/sql/index.mdx b/docs/web/sql/index.mdx index 5793b5235..74561fca3 100644 --- a/docs/web/sql/index.mdx +++ b/docs/web/sql/index.mdx @@ -32,7 +32,7 @@ for batch in reader: SQL results arrive as Arrow record batches. Iterating over the reader avoids collecting the entire result in application memory. See -[Queries](/basics/query) for result handling. +[Read and manage results](/basics/sql#results) for more. ## Usage {#usage} @@ -47,6 +47,7 @@ operations that have no SQL form, such as a merge insert. See | | | | --- | --- | +| [Database](/sql/ddl/database) | `ATTACH DATABASE` | | [Namespace](/sql/ddl/namespace) | `CREATE SCHEMA`, `DROP SCHEMA` | | [Table](/sql/ddl/table) | `CREATE`, `DESCRIBE`, `ALTER`, `CLONE`, `DROP TABLE` | | [View](/sql/ddl/view) | `CREATE VIEW`, `DROP VIEW` | @@ -67,7 +68,8 @@ Draft for the Functions release. Add this row to the table above, after Index: | [Update](/sql/dml/update) | `UPDATE ... SET` | | [Delete](/sql/dml/delete) | `DELETE FROM` | | [Copy](/sql/dml/copy) | `COPY` (refused by recent deployment versions) | -| [Refresh](/sql/dml/refresh) | filling computed columns and materialized views | +| [Refresh column](/sql/dml/refresh-column) | filling a computed column | +| [Refresh materialized view](/sql/dml/refresh-materialized-view) | bringing a view's stored result up to date | ### DQL {#dql} @@ -80,6 +82,7 @@ Draft for the Functions release. Add this row to the table above, after Index: | [Aggregation](/sql/dql/aggregation) | `GROUP BY`, `HAVING`, the aggregate set | | [Window functions](/sql/dql/window) | `OVER`, framing, ranking and offset functions | | [Sampling](/sql/dql/sampling) | `TABLESAMPLE`, by rows or by fragments | +| [Changes](/sql/dql/changes) | `CHANGES`: rows appended since an earlier version | | [Full-Text Search](/sql/dql/fts) | the `fts()` table function, and its query forms | | [Explain](/sql/dql/explain) | `EXPLAIN`, `EXPLAIN ANALYZE`, `EXPLAIN VERBOSE` | diff --git a/docs/web/sql/operators.mdx b/docs/web/sql/operators.mdx index 3e27e6bb2..156fab3b0 100644 --- a/docs/web/sql/operators.mdx +++ b/docs/web/sql/operators.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Operators" description: "Comparison, logical and arithmetic operators, literals, and precedence." icon: plus-minus keywords: ["operators", "literals", "precedence", "null", "cast", "interval"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - LanceDB uses DataFusion's SQL operators. This page describes comparison, logical and arithmetic operators, literal values, type conversions and operator precedence. diff --git a/docs/web/sql/prepared-statements.mdx b/docs/web/sql/prepared-statements.mdx index 2b94b9c9a..cc0b1257e 100644 --- a/docs/web/sql/prepared-statements.mdx +++ b/docs/web/sql/prepared-statements.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Prepared Statements" description: "What a deployment does when a Flight SQL client prepares a statement or binds parameter values." icon: bolt keywords: ["prepared statement", "flight sql", "parameters", "bind"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - A Flight SQL client can prepare a statement before it runs it. A deployment accepts that, but it keeps no plan between runs and does not accept parameter values. @@ -50,6 +51,13 @@ Do not put untrusted input, such as a value from a user or a request, directly into the statement text. Quoting it does not protect the statement the way binding a parameter would. + +This limitation is specific to the Flight SQL protocol's `PREPARE`/bind step. +The Python SDK's `execute_query(sql, parameters=...)` binds parameter values +through a separate, LanceDB-specific mechanism -- see +[Parameters in SQL queries](/basics/sql#parameters). + + ## When to use prepared statements {#when} Prepare a statement when your client requires it, or to get a statement's diff --git a/docs/web/sql/scalar-functions.mdx b/docs/web/sql/scalar-functions.mdx index f44c935c4..1af20bb96 100644 --- a/docs/web/sql/scalar-functions.mdx +++ b/docs/web/sql/scalar-functions.mdx @@ -4,10 +4,11 @@ sidebarTitle: "Scalar Functions" description: "The per-row function set: math, string, regex, date/time, array, struct, and what Lance adds." icon: calculator keywords: ["scalar functions", "string functions", "math functions", "regex", "array functions", "json"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) - Functions that take a value and return a value, one row at a time. The set is based on DataFusion's registration plus Lance and deployment-specific functions. The names below are selected examples, not an exhaustive catalog @@ -98,6 +99,21 @@ functions supported by your deployment and inspect SQL index-backed plan. See [SQL vector search](/basics/sql#no-vector-sql). +A third, optional argument is a comma-separated options string. `metric` +selects `l2` (default, alias `euclidean`), `cosine`, or `dot`; the +index-search rewrite also reads `nprobes` and `use_index`: + +```sql +SELECT id FROM documents +ORDER BY distance(embedding, ARRAY[0.1, 0.2, 0.3], 'metric=cosine,nprobes=20') +LIMIT 10 + +-- Force a flat scan, bypassing the index: +SELECT id FROM documents +ORDER BY exact_distance(embedding, ARRAY[0.1, 0.2, 0.3], 'use_index=false') +LIMIT 10 +``` + ## Structs and fields {#structs} ```text @@ -146,6 +162,44 @@ semantics and the simple tokenizer. query, the planner uses it instead of scanning, which is the reason to prefer it over `LIKE` for keyword tests. +### `ivf_partition(vector, ...)` {#ivf-partition} + +```sql +SELECT ivf_partition(embedding, selection => 'random', count => 100, seed => 42) AS partition, + array_agg(id) AS ids +FROM documents +GROUP BY partition +``` + +Assigns each row to one of `count` IVF-style partitions over `vector`, using +the named arguments `selection` (partition-center strategy; `'random'` is +sampled with `seed`) and `seed`. Grouping by its result buckets rows by +vector proximity without building or querying a vector index — useful for +blocking a large table into comparable chunks, such as before a pairwise +similarity pass. + +### `blob_descriptor(column)` {#blob-descriptor} + +```sql +SELECT id, blob_descriptor(video) AS descriptor FROM videos +``` + +A [BlobV2](/management/table#managed-blobs) column's bytes are not fetched by +a plain `SELECT`: that already returns `large_binary`, the same as any other +binary column. `blob_descriptor` instead returns a small struct describing +where the payload lives, without reading it. Pass one row's descriptor to +the SDK's blob file reader to open that payload directly: + +```python +rows = db.execute_query("SELECT id, blob_descriptor(video) AS descriptor FROM videos").read_all().to_pylist() +with table.open_blob_file(rows[0]["descriptor"]) as reader: + payload = reader.read() +``` + +A descriptor is pinned to the table version it was read at: it keeps +resolving correctly even after the table is appended to and checked out to a +newer version. + ### JSON accessors {#json} | Function | Returns | diff --git a/docs/web/static/assets/images/enterprise/architecture.png b/docs/web/static/assets/images/enterprise/architecture.png deleted file mode 100644 index aa00854da4ffddafd3861f6fcb2866cec653f7f9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 99871 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�LWX%B_Z(57ZL^nLQ= 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%0AWbN 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 diff --git a/docs/web/static/assets/images/overview/lancedb-architecture.svg b/docs/web/static/assets/images/overview/lancedb-architecture.svg deleted file mode 100644 index 585dfe991..000000000 --- a/docs/web/static/assets/images/overview/lancedb-architecture.svg +++ /dev/null @@ -1,60 +0,0 @@ - - LanceDB Embedded and Enterprise architecture - LanceDB Embedded runs the application and embedded library in one process with local disk or object storage. Enterprise separates query serving, read execution and caching, and indexing and background workers. The control plane governs the service. Enterprise persists tables in object storage. Both offerings use the Lance format, without automatically sharing storage. - - - - - - - - LanceDB Embedded - Embedded library - - Application + - LanceDB library - Queries - Indexing - Maintenance - - - Local disk or object storage - - - LanceDB Enterprise - Distributed multimodal - lakehouse - - Applications + - LanceDB SDK - - - Query serving - - - - Read - execution - + caching - - Indexing + - background - work - - - - Durable object storage - - Control plane - Manages the service - - - Shared foundation: Lance format - diff --git a/docs/web/static/assets/images/overview/lancedb-suite.svg b/docs/web/static/assets/images/overview/lancedb-suite.svg deleted file mode 100644 index 2eb7378a2..000000000 --- a/docs/web/static/assets/images/overview/lancedb-suite.svg +++ /dev/null @@ -1,92 +0,0 @@ - - LanceDB suite - LanceDB Embedded supports search. LanceDB Enterprise is a multimodal lakehouse for curation, feature engineering, search and retrieval, and training. Both are built on the Lance open lakehouse format for multimodal AI. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - LanceDB Embedded - Search - - - - - - - - - - - - - - - LanceDB Enterprise - Multimodal Lakehouse - - Curation - Feature - Engineering - Search & - Retrieval - Training - - - - - - - - - - Lance Open Lakehouse Format for Multimodal AI - - diff --git a/docs/web/static/assets/images/overview/training-data-lifecycle.svg b/docs/web/static/assets/images/overview/training-data-lifecycle.svg deleted file mode 100644 index 4998ee2e3..000000000 --- a/docs/web/static/assets/images/overview/training-data-lifecycle.svg +++ /dev/null @@ -1,49 +0,0 @@ - - Training data lifecycle - Four pillars of the LanceDB training data lifecycle: Curation, Feature Engineering, Search and Retrieval, and Training. - - - - - - - - - - - - - - - - - - - - - - - - - Curation - - - - - - Feature - Engineering - - - - - - Search & - Retrieval - - - - - - Training - diff --git a/docs/web/static/assets/logo/lance-logo-gray.png b/docs/web/static/assets/logo/lance-logo-gray.png new file mode 100644 index 0000000000000000000000000000000000000000..79252d4950f8f4528c1a507359b130aa1afc37de GIT binary patch literal 57024 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 Sz0sXKdT(0r)T4f}s{aGkd+>Mw literal 0 HcmV?d00001 diff --git a/docs/web/static/assets/logo/lance-logo-gray.svg b/docs/web/static/assets/logo/lance-logo-gray.svg deleted file mode 100644 index 764b68db7..000000000 --- a/docs/web/static/assets/logo/lance-logo-gray.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/docs/web/static/assets/logo/light-lancedb-logo.svg b/docs/web/static/assets/logo/light-lancedb-logo.svg index b0746745e..99e50467d 100644 --- a/docs/web/static/assets/logo/light-lancedb-logo.svg +++ b/docs/web/static/assets/logo/light-lancedb-logo.svg @@ -1,14 +1,3 @@ - - - - - - - - - - - - - - \ No newline at end of file + + + diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx index af06ec7a9..baf46b265 100644 --- a/docs/web/tables/branching.mdx +++ b/docs/web/tables/branching.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Branch" description: "Fork isolated, writable lines of table history in LanceDB. Run experiments, backfills, and index rebuilds without disturbing production reads on main." icon: "code-branch" availability: - oss: available + embedded: available enterprise: available - summary: >- - Branches work in the embedded library and in LanceDB Enterprise. Comparing a - branch with `main` and promoting its new columns onto `main` is available - only in LanceDB Enterprise. --- import { PyConnect, diff --git a/docs/web/tables/consistency.mdx b/docs/web/tables/consistency.mdx index 87df024ab..78aedb23f 100644 --- a/docs/web/tables/consistency.mdx +++ b/docs/web/tables/consistency.mdx @@ -4,12 +4,8 @@ sidebarTitle: "Consistency" description: "Understand when readers see changes and choose the freshness your application needs." icon: "water" availability: - oss: available + embedded: available enterprise: available - summary: >- - Configure read freshness in LanceDB Embedded and LanceDB Enterprise. Embedded - checks for table updates; Enterprise uses the connection setting to tighten its - configured freshness bound. --- import { PyReadConsistency } from '/snippets/read_consistency.mdx'; @@ -82,7 +78,7 @@ a write completing and a reader seeing it. ## Learn more {#next} -- [Connect](/basics/connect): configure your client. +- [Connect](/basics/catalog): configure your client. - [Table versioning](/management/table#versioning): read and restore retained versions. - [Guarantees](/basics/guarantees): understand commit and failure boundaries. diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index 88738791c..b3ca31346 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -1,229 +1,42 @@ --- -title: "Realtime engine (RTE)" -sidebarTitle: "Realtime Engine" +title: "Real Time engine (RTE)" +sidebarTitle: "Real Time Engine" description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." icon: "bolt" -keywords: ["rte", "realtime engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +keywords: ["rte", "real time engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] +availability: + embedded: unavailable + enterprise: available --- -Enterprise - -## What is the realtime engine? {#what-is-rte} +## What is the real time engine? {#what-is-rte} Every write to a LanceDB table is normally a commit to the underlying Lance dataset. That is ideal for bulk loads, but a stream of small upserts becomes a stream of small commits, and each write is only visible once its commit lands. -The realtime engine (RTE) puts an LSM-style write tier in front of the table. +The real time engine (RTE) puts an LSM-style write tier in front of the table. It turns many small writes into a few large commits, and makes each write **searchable within milliseconds** of being acknowledged. It is enabled per table, and nothing about how you query that table changes. ## How it works {#how-it-works} -- **Writes.** A `merge_insert` or `delete` lands in an in-memory **memtable** - and is acknowledged once it is durable in the write-ahead log on object - storage. +- **[Writes](/ingestion/realtime-write).** A `merge_insert` or `delete` lands in + an in-memory **memtable** and is acknowledged once it is durable in the + write-ahead log on object storage. - **Flush and compaction.** Memtables freeze into **SSTables**, which background jobs compact into the base table, catching its indexes up as they go. See [Background jobs](/maintenance/background-jobs#wal). -- **Reads.** Every query runs against the base table and the fresh tier - (memtables and SSTables) in parallel. Fresh rows supersede base rows with the - same primary key, and the two are merged into one result. +- **[Reads](/search/realtime-read).** Every query runs against the base table + and the fresh tier (memtables and SSTables) in parallel. Fresh rows supersede + base rows with the same primary key, and the two are merged into one result. - **Indexes stay fresh.** Vector, full-text, BTree, bitmap, and most other scalar indexes are maintained on the memtable, so new rows are searchable through the index as soon as they are written. -## Getting started {#getting-started} - -### 1. Create a table with a primary key {#primary-key} - -RTE deduplicates writes by primary key. Create the table with a non-nullable -key column, then declare it with `set_unenforced_primary_key`. The key is a -single `int32`, `int64`, string, or binary column, and cannot be changed once -set. - -```python -from datetime import timedelta - -import lancedb -import numpy as np -import pyarrow as pa -from lancedb import RTEWriteSpec -from lancedb.index import FTS, BTree, IvfPq - -db = lancedb.connect("db://my_db", api_key="...", host_override="https://...") - -n, dim = 1024, 128 -schema = pa.schema([ - pa.field("id", pa.int64(), nullable=False), - pa.field("vector", pa.list_(pa.float32(), dim)), - pa.field("text", pa.utf8()), -]) -initial_data = pa.table({ - "id": pa.array(range(n), pa.int64()), - "vector": pa.FixedSizeListArray.from_arrays( - pa.array(np.random.rand(n * dim).astype("float32")), dim), - "text": pa.array([f"doc {i} alpha bravo" for i in range(n)]), -}, schema=schema) -table = db.create_table("docs", initial_data, schema=schema) -table.set_unenforced_primary_key("id") -``` - -Or in SQL: - -```sql -ALTER TABLE docs SET UNENFORCED PRIMARY KEY (id) -``` - -### 2. Create indexes {#indexes} - -By default, RTE maintains every supported index on the table, including -indexes created after it is enabled. A scalar index on the primary key is -required for partial updates and deletes. - -```python -table.create_index("vector", config=IvfPq()) -table.create_index("text", config=FTS()) -table.create_index("id", config=BTree()) -table.wait_for_index(["vector_idx", "text_idx", "id_idx"], timeout=timedelta(minutes=5)) -``` - -### 3. Enable RTE {#enable} - -```python -table.enable_rte(RTEWriteSpec.unsharded()) -``` - -Or in SQL: - -```sql -ALTER TABLE docs SET RTE -``` - -### 4. Write and query {#write-and-query} - - -On an RTE table, an upsert through `merge_insert` is the only way to write -rows. Use the form below exactly: `when_matched_update_all()` with no filter, -plus `when_not_matched_insert_all()`. Other `merge_insert` forms, such as -conditional updates or deleting rows missing from the source, are rejected. - - -Writes go through `merge_insert` on the primary key, and are visible to queries -immediately: - -```python -new_rows = pa.table({ - "id": pa.array([2000, 2001], pa.int64()), - "vector": pa.FixedSizeListArray.from_arrays( - pa.array(np.random.rand(2 * dim).astype("float32")), dim), - "text": pa.array(["fresh charlie delta", "fresh echo foxtrot"]), -}, schema=schema) -query_vector = np.random.rand(dim).astype("float32") - -table.merge_insert("id") \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute(new_rows) - -table.search(query_vector).limit(10).to_list() -table.search("charlie").limit(10).to_list() -``` - -**Partial updates.** Send the primary key plus only the columns you want to -change; omitted columns keep their current values. This requires a scalar -index on the primary key. - -```python -patch = pa.table( - {"id": [0, 1], "text": ["doc 0 revised", "doc 1 revised"]}, - schema=pa.schema([schema.field("id"), schema.field("text")]), -) -table.merge_insert("id").when_matched_update_all().when_not_matched_insert_all().execute(patch) -``` - -**Deletes.** The predicate must bind the primary key to literal values. Ranges, -`OR`, and filters on other columns are rejected. Deletes require a scalar index -on the primary key. - -```python -table.delete("id IN (2000, 2001)") -``` - -### Disabling RTE {#disable} - -Stop writes and wait for in-flight writes to finish, then flush pending writes -into the base table and disable. `checkpoint_rte()` only drains writes that -existed when it started, so anything written during the checkpoint can be left -behind. `disable_rte()` is rejected while the write-ahead log still holds rows, -so run `checkpoint_rte()` first. - -```python -table.checkpoint_rte() -table.disable_rte() -``` - -## Performance {#performance} - -### Writes {#write-performance} - -RTE acknowledges a write as soon as it is durable in the write-ahead log, so -ingest is no longer limited by how fast the table can commit. - -**Compared with writing directly to the table.** On tables ranging from -hundreds of thousands to tens of millions of rows, RTE delivered 4–12× the -write throughput and 24–52× lower p99 write latency, depending on the mix of -inserts, updates, and deletes. - -**Scaling with shards.** An RTE table can be split into -[shards](/sql/ddl/table#properties) that write independently, and a single -table's ingest grows with its shard count. In our testing on AWS, with every -index on the table (vector, full-text, and BTree) kept current, a single table -reached these peak rates: - -| Shards | Peak ingest | -| --: | --: | -| 1 | 90 MB/s | -| 2 | 170 MB/s | -| 4 | 340 MB/s | -| 8 | 625 MB/s | -| 16 | 690 MB/s | -| 32 | 885 MB/s | - -Adding shards scales a table's ingest nearly linearly. - -### Reads {#read-performance} - -Reads on an RTE table stay close to those on a fully compacted table, even -with the fresh tier at its fullest before compaction. - -The table below compares a 5M-row table with a 128-dimension IVF-PQ index plus -BTree and FTS indexes, with and without RTE. The RTE table holds one -unflushed memtable and three SSTables, each from a 100k-row write wave, half of -which are updates to existing rows. Latencies are p50 in milliseconds. - -| Query | Without RTE | With RTE | -| --- | --: | --: | -| Primary-key lookup | 62 | 63 | -| Vector search | 68 | 71 | -| Vector search with prefilter | 90 | 91 | -| Full-text term | 63 | 64 | -| Full-text phrase | 68 | 82 | -| Hybrid search (RRF) | 68 | 83 | -| SQL point lookup | 189 | 187 | - -Most queries are within a few milliseconds of the base table. Hybrid and phrase -queries add roughly 15 ms to merge the two tiers. - - -Support for all table operations on RTE tables is coming soon. Time travel, -branching, `count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet -available. - - ## Next steps {#next-steps} -- [Merge insert](/ingestion/merge-insert) +- [Real Time writes](/ingestion/realtime-write) — enable RTE and write to a table +- [Real Time reads](/search/realtime-read) — query an RTE table and its performance - [Background jobs](/maintenance/background-jobs#wal) -- [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index a839f5d8c..47a3a6703 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -1,38 +1,13 @@ --- -title: "Loading Data for Model Training" -sidebarTitle: "Data Loading & Shuffles" -description: "Stream, shuffle, transform, and resume model training data with LanceDB." +title: "PyTorch Data Loader" +sidebarTitle: "PyTorch Data Loader" +description: "Stream, shuffle, transform, and resume model training data with StreamingDataset." icon: boxes-stacked availability: - oss: available + embedded: available enterprise: available - summary: >- - Streaming, shuffling and resuming training data work with local, - object-storage and deployment tables in the Python SDK. --- -LanceDB provides an excellent data backend for training machine learning models. For basic use cases, a `Table` can be fed directly into a data loader. For a more complete solution, a `StreamingDataset` adds prefetching, elastic determinism, resumability, multithreaded transformations, and more. - -## Basic Data Loading - -Most model training frameworks feed data into a model by sequencing through successive batches, a process -often referred to as **data loading**. The simplest way to perform data loading is to read a LanceDB table in batches, -in the order its rows are stored, through an identity `Permutation`. A table itself is not iterable. - - -```py Python icon=Python -import lancedb -from lancedb.permutation import Permutation - -db = lancedb.connect("file://some/db/path") -table = db.open_table("some_table") - -for batch in Permutation.identity(table).with_format("arrow").iter(batch_size=1024): - print(batch.to_pydict()) -``` - - -## Advanced Data Loading Advanced data loading scenarios can be handled by the `StreamingDataset`. This object allows you to apply preprocessing before training, pipelined reads, and more. Use this when the training data does not fit in memory, or when you need deterministic global batches across cluster sizes. @@ -56,30 +31,15 @@ for batch in dataloader: ``` -The `StreamingDataset` wraps a LanceDB `Table` and yields plain Python dictionaries by default. Whether iterating directly or through a PyTorch `DataLoader`, only one iterator can be simultaneously active on a `StreamingDataset` instance. +The `StreamingDataset` wraps a LanceDB `Table` and yields plain Python dictionaries by default. Whether iterating directly or through a PyTorch `DataLoader`, only one iterator can be simultaneously active on a `StreamingDataset` instance. -`StreamingDataset` is built on the `permutation` API and works with both LanceDB Embedded and LanceDB Enterprise. The underlying table data can live on local disk or object storage. +`StreamingDataset` is built on the [`Permutation`](/training/permutation) API and works with both LanceDB Embedded and LanceDB Enterprise. The underlying table data can live on local disk or object storage. -To understand the wide range of scenarios handled by `StreamingDataset`, consider a model trained with stochastic gradient descent (SGD) and distributed data parallelism (DDP). In this example, we need to load batches onto multiple GPUs -across multiple servers. After each batch is processed, the GPUs exchange weights and the next batch is loaded. We -fix the following terminology: +## Filtering {#filtering} -- **World size** - The number of GPUs being loaded simultaneously. For example, if we have $2$ servers with $4$ - GPUs each, the world size is $8$. -- **Rank** - The identifier of an individual GPU. It is an integer in the range `[0, world_size)`. - Each rank is allocated a disjoint portion of the source data. -- **Batch size** - The number of rows processed by one GPU in a single training step. For example, $128$. -- **Global batch size** - The total number of rows processed across all GPUs in a training step (sometimes called a "minibatch" in machine learning literature). For - example, if we have $8$ GPUs with batch size $128$, the global batch size is $1024$. - - -Other concepts, such as read batch size and `num_workers`, are introduced in the relevant sections below. - -### Filtering - -The `StreamingDataset` object allows you to train models on only the subset of rows that satisfy a user-defined filter, specified using the `filter` parameter. This can be useful for removing large rows, badly-sourced data, and a wide range of other applications. +The `StreamingDataset` object allows you to train models on only the subset of rows that satisfy a user-defined filter, specified using the `filter` parameter. This can be useful for removing large rows, badly-sourced data, and a wide range of other applications. You can also use the `columns` parameter to load only a subset of columns. @@ -93,7 +53,7 @@ ds = StreamingDataset( ``` -### Shuffling Rows +## Shuffling Rows {#shuffling-rows} In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles at one of two granularities, selected by the `shuffle_clump_size` parameter. @@ -102,21 +62,20 @@ In model training, model quality can be hurt by unintentionally learning pattern with the same inputs remain reproducible. Set `shuffle_seed = None` to generate a random seed upon pipeline initialization. -#### Row-Level Shuffle {#one-phase-shuffle} +### Row-Level Shuffle {#one-phase-shuffle} By default, `shuffle_clump_size` is `None` and rows are shuffled individually: the rows of the source dataset are shuffled according to a pseudorandom permutation, then fed in batches to the accelerator. This gives the best possible randomness, but can exhibit low throughput. - - -```py Python icon=Python + +```py Python icon=Python # 1-phase shuffled read: rows shuffled individually. -for epoch in range(num_epochs): - ds = StreamingDataset( - table, - shuffle_seed=42, - epoch=epoch, # changes the permutation each epoch - ) - for sample in ds: +for epoch in range(num_epochs): + ds = StreamingDataset( + table, + shuffle_seed=42, + epoch=epoch, # changes the permutation each epoch + ) + for sample in ds: train_step(sample) #Evaluation: deterministic sequential order, no shuffle. @@ -124,11 +83,9 @@ eval_ds = StreamingDataset(table, shuffle=False) for sample in eval_ds: eval_step(sample) ``` - - -#### Clumped Shuffle {#two-phase-shuffle} +### Clumped Shuffle {#two-phase-shuffle} Setting `shuffle_clump_size` to an integer shuffles contiguous groups ("clumps") of that many rows instead of single rows. Each clump keeps its rows in storage order and moves as a unit, so storage I/O consists mostly of contiguous reads rather than single-row fetches. Larger clumps improve I/O locality, which matters most on object storage, at the cost of randomness. @@ -153,57 +110,7 @@ for sample in eval_ds: ``` -### Parallelism & Elasticity - -When loading data, `StreamingDataset` partitions the source dataset among disjoint parallel threads called **splits**. Each rank is allocated a contiguous group of splits, and each DataLoader worker associated to a rank gets a contiguous subgroup of its rank's splits. - -If using `shuffle=False`, data is allocated to splits naively in ordered contiguous blocks of equal size. With `shuffle=True` -(the default), the rows of the source dataset are shuffled and distributed among splits such that each split receives the same -number of rows; with `shuffle_clump_size` set, they are shuffled in clumps of that many contiguous rows. - -The number of splits defaults to `world_size` if `num_splits` is omitted during initialization. This is not recommended, as a later run using a different world size will then construct a different layout and structure of global batches. - -To get **elastic determinism**, choose a fixed `num_splits` that is compatible with every topology you plan to use. -For example, a run with `num_splits=8` and $4$ GPUs assigns $2$ splits to each rank. The ranks pull from their splits in -round-robin order, producing the same global batches as a run with $8$ GPUs and the same `num_splits`, `shuffle_seed`, -and `epoch`. - -The following constraints apply: - -- `num_splits` must be divisible by `world_size`. -- With DataLoader worker processes, `num_splits` must be divisible by `world_size * num_workers`. -- For the same samples to form each global training step across topologies, `global_batch_size` must be a multiple of - `num_splits`. -- The filtered row count must be at least `num_splits`. If it is not evenly divisible by `num_splits`, up to - `num_splits - 1` surplus rows are dropped so that every split has the same length. - -For example, to switch between $8$ and $6$ GPUs, use a common multiple such as $24$ for `num_splits`. Highly composite values can support many layouts; for example, `num_splits = 48` is compatible with $10$ distinct possible GPU counts. Remember to include `num_workers` when checking divisibility. - - -```py Python icon=Python -import torch.distributed as dist - -dist.init_process_group("nccl") -rank = dist.get_rank() -world_size = dist.get_world_size() - -# num_splits=48 is divisible by many integers, -# so this dataset works unchanged as you add or remove GPUs. -ds = StreamingDataset( - table, - num_splits=48, - shuffle_seed=42, - epoch=current_epoch, - rank=rank, - world_size=world_size, -) - -for sample in ds: - train_step(sample) -``` - - -### Fetching +## Fetching {#fetching} Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`). @@ -220,13 +127,12 @@ ds = StreamingDataset( ``` -### Transforming +## Transforming {#transforming} -Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter. +Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter. A transformation function must receive a PyArrow `RecordBatch` and return an iterable. For example, the default transform function returns a list of Python dictionaries. Furthermore, the input expected by PyTorch must match the collation function used in the PyTorch data loader. PyTorch's default collation function accepts a Python dictionary and several other types, and is thus compatible with the default `StreamingDataset` transform function. If your custom transform function returns something different (for example, Arrow record batches), you may need to provide a compatible PyTorch collation function. - ```py Python icon=Python import pyarrow as pa @@ -245,9 +151,50 @@ ds = StreamingDataset(table, shuffle_seed=42, transform=normalize) `StreamingDataset` manages expensive transforms through a -`ThreadPoolExecutor` whose worker count equals the number of available CPUs. Furthermore, transformations are applied to batches (instead of individual samples) to amortize per-batch overhead. +`ThreadPoolExecutor` whose worker count equals the number of available CPUs (`transform_parallelism`). Furthermore, transformations are applied to batches (instead of individual samples) to amortize per-batch overhead. -##### DataLoader Workers +Heavier per-sample work belongs in the same function, such as decoding +video. Store each clip in a Blob v2 column (`lancedb.blob("video")`). A scan +returns small descriptors instead of the video bytes, so reading other +columns never pulls video in. `fetch_blob_files` opens the clips for a batch +of rows as file handles, and `torchcodec`'s `VideoDecoder` decodes just the +frames you ask for. `ExtractFrames` samples 8 evenly spaced frames from each +clip: + + +```py Python icon=Python +import functools +from torchcodec.decoders import VideoDecoder + +class ExtractFrames: + def __init__(self, uri: str, name: str, num_frames: int = 8) -> None: + self.uri, self.name, self.num_frames = uri, name, num_frames + + @functools.cached_property + def table(self) -> lancedb.table.Table: + return lancedb.connect(self.uri).open_table(self.name) + + def __call__(self, rb: pa.RecordBatch) -> list[dict[str, torch.Tensor]]: + samples = [] + for blob in self.table.fetch_blob_files("video", rb["_rowid"]): + decoder = VideoDecoder(blob) + idx = torch.linspace(0, len(decoder) - 1, self.num_frames).long() + samples.append({"frames": decoder.get_frames_at(idx.tolist()).data}) + return samples + +# `clips` is the table "clips" in the database at `uri`, with a Blob v2 column "video" +train = StreamingDataset(clips, columns=["_rowid"], transform=ExtractFrames(uri, "clips")) +``` + + +Real data has bad rows, such as a truncated frame. Raise inside the +transform and set `on_transform_error="skip"` (or `"warn"` to log each +failure). `StreamingDataset` re-runs the failing batch one row at a time, +drops only the rows that raise, and counts them in `dataset.rows_skipped`. +When the bad rows match a SQL predicate, prefer `filter=` instead: it runs +before the splits are built, so every split keeps the same length. + +### DataLoader Workers {#dataloader-workers} The thread-based transformation model that `StreamingDataset` uses by default is only effective when the transform function releases the GIL. This is true for many Python scientific libraries, including NumPy, PyArrow, and @@ -259,6 +206,7 @@ loading in the rank's main process, and add workers only after confirming an una workers, `num_splits` must be divisible by `world_size * num_workers`. Use the `forkserver` or `spawn` multiprocessing context because LanceDB uses internal threads. + ```py Python icon=Python dataloader = torch.utils.data.DataLoader( dataset, @@ -268,12 +216,87 @@ dataloader = torch.utils.data.DataLoader( persistent_workers=True, ) ``` + -By default, `StreamingDataset` serializes enough table state to reopen the table in each worker. For custom connection -setup, pass a picklable `connection_factory` callable that accepts a table name and returns an open table. This avoids -serializing connection credentials into worker state. +By default, `StreamingDataset` serializes enough table state to reopen the +table in each worker. Remote LanceDB Enterprise tables (`db://...`) work the +same way: workers reopen the table from the pickled connection state. +Replace the URI, API key, region and endpoint below with your deployment +details. In application code, load credentials from environment variables +or a secrets manager: -### Observability + +```py Python icon=Python +import lancedb +import torch +from lancedb.util import tbl_to_tensor + +db = lancedb.connect( + "db://my-database", + api_key="your-api-key", + region="us-east-1", + host_override="https://your-endpoint", +) +table = db.open_table("my_table") + +dataloader = torch.utils.data.DataLoader( + table, + batch_size=512, + num_workers=4, + multiprocessing_context="forkserver", + collate_fn=tbl_to_tensor, +) +``` + + + +This sends the connection state, including the API key, to each worker. Use a connection factory if credentials should be loaded inside the worker or your `client_config` contains a non-serializable `header_provider`. + + +#### Providing a custom connection factory {#providing-a-custom-connection-factory} + +For custom connection setup, pass a picklable `connection_factory` callable +that accepts a table name and returns an open table. This avoids +serializing connection credentials into worker state: it loads the API key +inside each worker instead. Set it in the shell before starting the Python +program, then replace the database URI, region and endpoint in the factory +with your deployment details: + +```shell +export LANCEDB_API_KEY="your-api-key" +``` + + +```py Python icon=Python +import os +import lancedb +import torch +from lancedb.permutation import Permutation + +def open_table(name: str): + db = lancedb.connect( + "db://my-database", + api_key=os.environ["LANCEDB_API_KEY"], + region="us-east-1", + host_override="https://your-endpoint", + ) + return db.open_table(name) + +table = open_table("my_table") +permutation = ( + Permutation.identity(table) + .with_connection_factory(open_table) +) +dataloader = torch.utils.data.DataLoader( + permutation, + batch_size=512, + num_workers=4, + multiprocessing_context="forkserver", +) +``` + + +## Observability {#observability} Optimizing data loader performance can be tricky, as runtime bottlenecks are often difficult to locate across various stages of the I/O and CPU pipelines. To help distinguish bottlenecks, `StreamingDataset` exposes several pipeline counters: `raw_queue_depth` shows the number of loaded rows waiting to be transformed, and `prefetch_queue_depth` is the number of transformed rows ready to be consumed. `unscanned_rows` and @@ -320,161 +343,13 @@ are cumulative across iterations of the same dataset instance; because work runs can exceed wall-clock time. The queue depths report rows currently waiting in the pipeline, and the progress counters reflect the latest iterator snapshot. -### Checkpointing -`StreamingDataset` provides checkpointing in case your model training fails partway through a run. Use `StreamingDataset.state_dict()` to capture the current number of samples consumed from each split in a Python dictionary, and `load_state_dict()` to restore the last saved position. +## Next steps {#next} -A stored `StreamingDataset` state reflects only round-robin cycles that have been completed across all splits; samples completed partway through a cycle at the time of saving can be replayed. To ensure efficient saving, make sure `global_batch_size` is a multiple of `num_splits`, as in the example below. - - -```py Python icon=Python -import torch - -global_batch_size = 48 # one sample per split in each global step -batch_size = global_batch_size // world_size - -dataset = StreamingDataset( - table, - num_splits=48, - shuffle_seed=42, - epoch=current_epoch, - rank=rank, - world_size=world_size, -) -dataloader = torch.utils.data.DataLoader( - dataset, - batch_size=batch_size, - num_workers=0, -) - -for step, batch in enumerate(dataloader): - train_step(batch) - - if (step + 1) % checkpoint_interval == 0: - torch.save( - {"model": model.state_dict(), "dataset": dataset.state_dict()}, - f"checkpoint_{step + 1}.pt", - ) - -# --- resuming after a crash --- -checkpoint = torch.load("checkpoint_100.pt") -model.load_state_dict(checkpoint["model"]) - -dataset_state = checkpoint["dataset"] -dataset = StreamingDataset( - table, - num_splits=dataset_state["num_splits"], - shuffle_seed=dataset_state["shuffle_seed"], - epoch=dataset_state["epoch"], - rank=rank, - world_size=world_size, # may differ from the run that saved the checkpoint -) -dataset.load_state_dict(dataset_state) -dataloader = torch.utils.data.DataLoader( - dataset, - batch_size=global_batch_size // world_size, - num_workers=0, -) - -for batch in dataloader: - train_step(batch) -``` - - -`load_state_dict()` rejects a checkpoint whose `num_splits` or `shuffle_seed` differs from the new dataset. For an -exact resume, also use the same table snapshot, `epoch`, `shuffle`, `filter`, and other data-selection settings. The -`world_size` and number of DataLoader workers may change as long as the split and batch-size divisibility constraints -still hold. - -##### Checkpointing with Multiple DataLoader Workers - -Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when `num_workers = 0`. With `num_workers > 0`, calling `state_dict()` often raises `RuntimeError`. In this case, use `StreamingDataLoader` for multi-worker prefetch and exact resumability. It carries a state snapshot -alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the -trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. - - -```py Python icon=Python -from lancedb.streaming import StreamingDataset, StreamingDataLoader - -dataset = StreamingDataset( - table, - num_splits=48, - shuffle_seed=42, - epoch=current_epoch, - rank=rank, - world_size=world_size, -) -dataloader = StreamingDataLoader( - dataset, - batch_size=batch_size, - num_workers=4, -) - -for step, batch in enumerate(dataloader): - train_step(batch) - - if (step + 1) % checkpoint_interval == 0: - torch.save( - {"model": model.state_dict(), "dataset": dataset.state_dict()}, - f"checkpoint_{step + 1}.pt", - ) -``` - - -`StreamingDataLoader` accepts the same arguments as `torch.utils.data.DataLoader`, with a few restrictions: - -- `dataset` must be a `StreamingDataset` (subclasses that override `__iter__` are not supported). -- `in_order = True` is required so that consumer-committed checkpoints stay deterministic. -- `persistent_workers = True` is not supported, because prefetched worker copies cannot be restored from parent-committed state. -- `drop_last = True` is not supported, because incomplete tails discarded by worker replicas cannot be checkpointed topology-independently. - -With more than one worker, call `state_dict()` at a complete logical step boundary where every split assigned to the -rank has the same consumed-sample count. Calling it mid-step raises `RuntimeError` asking you to consume more batches -first. - -##### Resuming Across Different Topologies - -When training across ranks, each rank owns its own subset of splits and only its own splits have exact progress. To -resume on a different `world_size`, collect the `state_dict()` from every rank of the previous run and merge them with -`StreamingDataset.merge_state_dicts` before calling `load_state_dict()` on the new run. The merge is topology-agnostic: -pass the full list of per-rank states in, and hand the identical merged dict to every rank of the resumed job, -regardless of whether the topology grew, shrank, or stayed the same. - - -```py Python icon=Python -# On each rank of the previous run: -state = dataset.state_dict() -# ...gather `state` from every rank into a single list `states` (for example -# via torch.distributed all-gather or by saving one file per rank). - -merged = StreamingDataset.merge_state_dicts(states) - -# On each rank of the resumed run (world_size may differ): -dataset = StreamingDataset( - table, - num_splits=merged["num_splits"], - shuffle_seed=merged["shuffle_seed"], - epoch=merged["epoch"], - rank=rank, - world_size=new_world_size, -) -dataset.load_state_dict(merged) -``` - - -## Permutations - -In specific use cases, you may need the flexibility to shuffle, split, and select data without using the full `StreamingDataset` object. In these cases, use `Permutation`, the lower-level functionality on which `StreamingDataset` -is built. A `Permutation` defines a customizable row ordering, and supports map-style access through `__getitem__()` -and batched access through `__getitems__()`. - -##### Version Pinning - -A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads -from a `StreamingDataset` that wraps it, and every DataLoader worker after it starts) resolves against that pinned -version. This makes iteration deterministic across compactions and worker restarts: the permutation only addresses rows -that existed when it was built, and rows appended to the base table afterwards are not visible through the existing -permutation. - -To include newly appended rows, build a new `Permutation` (and any `StreamingDataset` that depends on it) -against the updated table. Permutations written before this behavior shipped continue to -read as they did before. + + + The lower-level row ordering StreamingDataset is built on. + + + Multi-GPU sharding, elastic determinism, and checkpointing. + + diff --git a/docs/web/training/distributed-training.mdx b/docs/web/training/distributed-training.mdx new file mode 100644 index 000000000..549539591 --- /dev/null +++ b/docs/web/training/distributed-training.mdx @@ -0,0 +1,216 @@ +--- +title: "Distributed Training" +sidebarTitle: "Distributed Training" +description: "Shard StreamingDataset across ranks and workers, with elastic determinism and checkpointing." +icon: server +availability: + embedded: available + enterprise: available +--- + +To understand the wide range of scenarios handled by [`StreamingDataset`](/training/data-loading) across a +distributed job, consider a model trained with stochastic gradient descent (SGD) and distributed data parallelism +(DDP). In this example, we need to load batches onto multiple GPUs across multiple servers. After each batch is +processed, the GPUs exchange weights and the next batch is loaded. We fix the following terminology: + +- **World size** - The number of GPUs being loaded simultaneously. For example, if we have $2$ servers with $4$ + GPUs each, the world size is $8$. +- **Rank** - The identifier of an individual GPU. It is an integer in the range `[0, world_size)`. + Each rank is allocated a disjoint portion of the source data. +- **Batch size** - The number of rows processed by one GPU in a single training step. For example, $128$. +- **Global batch size** - The total number of rows processed across all GPUs in a training step (sometimes called a "minibatch" in machine learning literature). For + example, if we have $8$ GPUs with batch size $128$, the global batch size is $1024$. + +Other concepts, such as read batch size and `num_workers`, are introduced in [PyTorch Data Loader](/training/data-loading). + +## Parallelism & Elasticity {#parallelism-&-elasticity} + +When loading data, `StreamingDataset` partitions the source dataset among disjoint parallel threads called **splits**. Each rank is allocated a contiguous group of splits, and each DataLoader worker associated to a rank gets a contiguous subgroup of its rank's splits. + +If using `shuffle=False`, data is allocated to splits naively in ordered contiguous blocks of equal size. With `shuffle=True` +(the default), the rows of the source dataset are shuffled and distributed among splits such that each split receives the same +number of rows; with `shuffle_clump_size` set, they are shuffled in clumps of that many contiguous rows. + +The number of splits defaults to `world_size` if `num_splits` is omitted during initialization. This is not recommended, as a later run using a different world size will then construct a different layout and structure of global batches. + +To get **elastic determinism**, choose a fixed `num_splits` that is compatible with every topology you plan to use. +For example, a run with `num_splits=8` and $4$ GPUs assigns $2$ splits to each rank. The ranks pull from their splits in +round-robin order, producing the same global batches as a run with $8$ GPUs and the same `num_splits`, `shuffle_seed`, +and `epoch`. + +The following constraints apply: + +- `num_splits` must be divisible by `world_size`. +- With DataLoader worker processes, `num_splits` must be divisible by `world_size * num_workers`. +- For the same samples to form each global training step across topologies, `global_batch_size` must be a multiple of + `num_splits`. +- The filtered row count must be at least `num_splits`. If it is not evenly divisible by `num_splits`, up to + `num_splits - 1` surplus rows are dropped so that every split has the same length. + +For example, to switch between $8$ and $6$ GPUs, use a common multiple such as $24$ for `num_splits`. Highly composite values can support many layouts; for example, `num_splits = 48` is compatible with $10$ distinct possible GPU counts. Remember to include `num_workers` when checking divisibility. + + +```py Python icon=Python +import torch.distributed as dist + +dist.init_process_group("nccl") +rank = dist.get_rank() +world_size = dist.get_world_size() + +# num_splits=48 is divisible by many integers, +# so this dataset works unchanged as you add or remove GPUs. +ds = StreamingDataset( + table, + num_splits=48, + shuffle_seed=42, + epoch=current_epoch, + rank=rank, + world_size=world_size, +) + +for sample in ds: + train_step(sample) +``` + + +## Checkpointing {#checkpointing} + +`StreamingDataset` provides checkpointing in case your model training fails partway through a run. Use `StreamingDataset.state_dict()` to capture the current number of samples consumed from each split in a Python dictionary, and `load_state_dict()` to restore the last saved position. + +A stored `StreamingDataset` state reflects only round-robin cycles that have been completed across all splits; samples completed partway through a cycle at the time of saving can be replayed. To ensure efficient saving, make sure `global_batch_size` is a multiple of `num_splits`, as in the example below. + + +```py Python icon=Python +import torch + +global_batch_size = 48 # one sample per split in each global step +batch_size = global_batch_size // world_size + +dataset = StreamingDataset( + table, + num_splits=48, + shuffle_seed=42, + epoch=current_epoch, + rank=rank, + world_size=world_size, +) +dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=batch_size, + num_workers=0, +) + +for step, batch in enumerate(dataloader): + train_step(batch) + + if (step + 1) % checkpoint_interval == 0: + torch.save( + {"model": model.state_dict(), "dataset": dataset.state_dict()}, + f"checkpoint_{step + 1}.pt", + ) + +# --- resuming after a crash --- +checkpoint = torch.load("checkpoint_100.pt") +model.load_state_dict(checkpoint["model"]) + +dataset_state = checkpoint["dataset"] +dataset = StreamingDataset( + table, + num_splits=dataset_state["num_splits"], + shuffle_seed=dataset_state["shuffle_seed"], + epoch=dataset_state["epoch"], + rank=rank, + world_size=world_size, # may differ from the run that saved the checkpoint +) +dataset.load_state_dict(dataset_state) +dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=global_batch_size // world_size, + num_workers=0, +) + +for batch in dataloader: + train_step(batch) +``` + + +`load_state_dict()` rejects a checkpoint whose `num_splits` or `shuffle_seed` differs from the new dataset. For an +exact resume, also use the same table snapshot, `epoch`, `shuffle`, `filter`, and other data-selection settings. The +`world_size` and number of DataLoader workers may change as long as the split and batch-size divisibility constraints +still hold. + +### Checkpointing with Multiple DataLoader Workers {#checkpointing-with-multiple-dataloader-workers} + +Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when `num_workers = 0`. With `num_workers > 0`, calling `state_dict()` often raises `RuntimeError`. In this case, use `StreamingDataLoader` for multi-worker prefetch and exact resumability. It carries a state snapshot +alongside every internal batch and commits it to the parent `StreamingDataset` only when that batch is returned to the +trainer. The trainer receives the same collated batch it would receive from a standard `DataLoader`. + + +```py Python icon=Python +from lancedb.streaming import StreamingDataset, StreamingDataLoader + +dataset = StreamingDataset( + table, + num_splits=48, + shuffle_seed=42, + epoch=current_epoch, + rank=rank, + world_size=world_size, +) +dataloader = StreamingDataLoader( + dataset, + batch_size=batch_size, + num_workers=4, +) + +for step, batch in enumerate(dataloader): + train_step(batch) + + if (step + 1) % checkpoint_interval == 0: + torch.save( + {"model": model.state_dict(), "dataset": dataset.state_dict()}, + f"checkpoint_{step + 1}.pt", + ) +``` + + +`StreamingDataLoader` accepts the same arguments as `torch.utils.data.DataLoader`, with a few restrictions: + +- `dataset` must be a `StreamingDataset` (subclasses that override `__iter__` are not supported). +- `in_order = True` is required so that consumer-committed checkpoints stay deterministic. +- `persistent_workers = True` is not supported, because prefetched worker copies cannot be restored from parent-committed state. +- `drop_last = True` is not supported, because incomplete tails discarded by worker replicas cannot be checkpointed topology-independently. + +With more than one worker, call `state_dict()` at a complete logical step boundary where every split assigned to the +rank has the same consumed-sample count. Calling it mid-step raises `RuntimeError` asking you to consume more batches +first. + +### Resuming Across Different Topologies {#resuming-across-different-topologies} + +When training across ranks, each rank owns its own subset of splits and only its own splits have exact progress. To +resume on a different `world_size`, collect the `state_dict()` from every rank of the previous run and merge them with +`StreamingDataset.merge_state_dicts` before calling `load_state_dict()` on the new run. The merge is topology-agnostic: +pass the full list of per-rank states in, and hand the identical merged dict to every rank of the resumed job, +regardless of whether the topology grew, shrank, or stayed the same. + + +```py Python icon=Python +# On each rank of the previous run: +state = dataset.state_dict() +# ...gather `state` from every rank into a single list `states` (for example +# via torch.distributed all-gather or by saving one file per rank). + +merged = StreamingDataset.merge_state_dicts(states) + +# On each rank of the resumed run (world_size may differ): +dataset = StreamingDataset( + table, + num_splits=merged["num_splits"], + shuffle_seed=merged["shuffle_seed"], + epoch=merged["epoch"], + rank=rank, + world_size=new_world_size, +) +dataset.load_state_dict(merged) +``` + diff --git a/docs/web/training/object-detection.mdx b/docs/web/training/object-detection.mdx index 620409728..6e9213a57 100644 --- a/docs/web/training/object-detection.mdx +++ b/docs/web/training/object-detection.mdx @@ -7,7 +7,7 @@ icon: car This example walks through fine-tuning an autonomous vehicle (AV) perception model on targeted failure-mode slices of [BDD100K](https://www.bdd100k.com/) (riders, nighttime pedestrians, and distant pedestrians) using LanceDB as a single multimodal table from raw JPEG bytes through to the PyTorch training loop. -The full pipeline lives in the [lancedb/training](https://github.com/lancedb/training/tree/main/object-detection) repository. This page focuses on the parts most relevant to training: defining curated splits as materialized views, loading them through the [`Permutation`](/training/data-loading) API, and pinning checkpoints to an exact data version. +The full pipeline lives in the [lancedb/training](https://github.com/lancedb/training/tree/main/object-detection) repository. This page focuses on the parts most relevant to training: defining curated splits as materialized views, loading them through the [`Permutation`](/training/permutation) API, and pinning checkpoints to an exact data version. ## What you get {#what-you-get} @@ -155,7 +155,7 @@ with gconn.local_ray_context(): ## 4\. PyTorch DataLoader via the Permutation API {#4-pytorch-dataloader-via-the-permutation-api} -The training script doesn't know about the filter: it opens a view by name and reads through the [`Permutation`](/training/data-loading) API. Each DataLoader worker reopens its own connection lazily, reads Arrow batches directly from Lance (zero-copy, no intermediate file format), and the collate function decodes the whole batch in one pass. `Permutation` provides random-access indexing over the table, so shuffling is a cheap pointer rewrite rather than a full-dataset shuffle on disk. +The training script doesn't know about the filter: it opens a view by name and reads through the [`Permutation`](/training/permutation) API. Each DataLoader worker reopens its own connection lazily, reads Arrow batches directly from Lance (zero-copy, no intermediate file format), and the collate function decodes the whole batch in one pass. `Permutation` provides random-access indexing over the table, so shuffling is a cheap pointer rewrite rather than a full-dataset shuffle on disk. ```py Python icon=Python import lancedb diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx new file mode 100644 index 000000000..751056541 --- /dev/null +++ b/docs/web/training/permutation.mdx @@ -0,0 +1,123 @@ +--- +title: "Permutation" +sidebarTitle: "Permutation" +description: "The low-level, customizable row ordering that StreamingDataset is built on." +icon: shuffle +availability: + embedded: available + enterprise: available +--- + +Most model training frameworks feed data into a model by sequencing through successive batches, a process +often referred to as **data loading**. The simplest way to perform data loading is to read a LanceDB table in batches, +in the order its rows are stored, through an identity `Permutation`. A table itself is not iterable. + + +```py Python icon=Python +import lancedb +from lancedb.permutation import Permutation + +db = lancedb.connect("file://some/db/path") +table = db.open_table("some_table") + +for batch in Permutation.identity(table).with_format("arrow").iter(batch_size=1024): + print(batch.to_pydict()) +``` + + +In specific use cases, you may need the flexibility to shuffle, split, and select data without using the full +[`StreamingDataset`](/training/data-loading) object. In these cases, use `Permutation`, the lower-level +functionality `StreamingDataset` is built on. A `Permutation` defines a customizable row ordering, and supports +map-style access through `__getitem__()` and batched access through `__getitems__()`. + +## Version Pinning {#version-pinning} + +A `Permutation` is pinned to the version of its base table at the time it was constructed, and every read (including future reads +from a `StreamingDataset` that wraps it, and every DataLoader worker after it starts) resolves against that pinned +version. This makes iteration deterministic across compactions and worker restarts: the permutation only addresses rows +that existed when it was built, and rows appended to the base table afterwards are not visible through the existing +permutation. + +To include newly appended rows, build a new `Permutation` (and any `StreamingDataset` that depends on it) +against the updated table. Permutations written before this behavior shipped continue to +read as they did before. + +## Output formats {#output-formats} + +By default, a `Table` data loader emits Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to +turn the fetched items into one batch. PyTorch's default collate function only knows how to combine tensors, NumPy +arrays, numbers, dicts, and lists, so it does not accept Arrow data directly. When using a `Table` directly, pass +LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it converts numeric Arrow columns into a +column-major `torch.Tensor` with shape `(columns, rows)`. + +`Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function +can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a +significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you +want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor +conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` +with one of the transform formats described below. + +To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map +the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, +`pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and +`torch` formats will all require at least one full copy of the data and are the slowest options. + +### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} + +The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the +entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting +Tensor will have shape `(C, R)`. However, this format generates an error if you are using a +`torch.utils.data.DataLoader` with the default collation function: + +```text +TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor +``` + +This error occurs because the default collation function does not currently expect a single two-dimensional tensor. +It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format +requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function +in addition to specifying the `torch_col` format. + +```py Python icon=Python +from lancedb.permutation import Permutation + +permutation = Permutation.identity(table).with_format("torch_col") +dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) +``` + +This will now output a single two-dimensional tensor for each batch. + +## Selecting columns {#selecting-columns} + +By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need +a subset of columns, you can significantly reduce your I/O requirements by selecting only the columns you need. The +`Permutation` class provides a `select_columns` method that provides this functionality. + +```py Python icon=Python +import lancedb +import pyarrow as pa +import torch +from lancedb.permutation import Permutation + +db = lancedb.connect("memory://") +prompts = db.create_table( + "prompts", + pa.table( + { + "id": range(4), + "prompt": ["north", "south", "east", "west"], + "embedding": [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], + } + ), +) + +permutation = Permutation.identity(prompts).select_columns(["id", "prompt"]) +dataloader = torch.utils.data.DataLoader( + permutation, batch_size=1024, shuffle=True +) + +for batch in dataloader: + print(sorted(batch)) # ['id', 'prompt']: the embedding is never read +``` + +Each batch is a dict of the selected columns, the default `Permutation` format described above. diff --git a/docs/web/training/torch.mdx b/docs/web/training/torch.mdx deleted file mode 100644 index 6a6f0c12f..000000000 --- a/docs/web/training/torch.mdx +++ /dev/null @@ -1,334 +0,0 @@ ---- -title: "PyTorch Integration" -sidebarTitle: "PyTorch" -description: Use a LanceDB table as a PyTorch IterableDataset, mapped onto the `torch.utils.data` concepts you already know. -icon: fire -availability: - oss: available - enterprise: available - summary: >- - The PyTorch integration works with local, object-storage and deployment - tables in the Python SDK. ---- - -`StreamingDataset` is a LanceDB table exposed as a PyTorch -[`IterableDataset`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset), -so it drops into a stock [`DataLoader`](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader). -It handles per-epoch shuffling, sharding across ranks and workers, prefetching, and exact resume, so you -don't write those yourself. The shuffle is fixed when the dataset is constructed, so each epoch needs a new -`StreamingDataset` built with that epoch's number. - -## Quickstart {#quickstart} - -```py Python icon=Python -import lancedb, pyarrow as pa, torch -from torch import nn -from lancedb.streaming import StreamingDataset - -def to_samples(rb: pa.RecordBatch): - f = lambda c: torch.from_dlpack(rb[c].flatten()).view(len(rb), -1) - rows = zip(f("observation_state"), f("action")) - return [{"state": s, "action": a} for s, a in rows] - -uri = "hf://datasets/lance-format/lerobot-xvla-soft-fold/data" -db = lancedb.connect(uri, storage_options={"hf_enable_resolve_cache": "true"}) -table = db.open_table("frames") -train = StreamingDataset( - table, columns=["observation_state", "action"], - transform=to_samples) - -model = nn.Sequential(nn.Linear(96, 256), nn.ReLU(), nn.Linear(256, 14)) -opt = torch.optim.AdamW(model.parameters(), lr=1e-3) -for batch in torch.utils.data.DataLoader(train, batch_size=256): - loss = nn.MSELoss()(model(batch["state"]), batch["action"]) - opt.zero_grad() - loss.backward() - opt.step() -``` - -`StreamingDataset` is a standard PyTorch `IterableDataset`, so it works with everything built for one: a stock -`DataLoader`, its default `collate_fn`, and worker processes. The transform returns plain tensors, so the -model, loss and optimizer are unmodified PyTorch. Here it streams the -[`lerobot-xvla-soft-fold`](https://huggingface.co/datasets/lance-format/lerobot-xvla-soft-fold) dataset -straight from the Hugging Face Hub to train a policy that predicts each `action` from the robot's -`observation_state`. - -## PyTorch concepts in LanceDB {#concept-map} - -| In PyTorch you would write | In LanceDB you use | -| --- | --- | -| An `IterableDataset` that reads files in `__iter__` | `StreamingDataset(table)` | -| `DistributedSampler`, or sharding by `get_worker_info()` in `__iter__` | `rank=` and `world_size=`. Each rank and each DataLoader worker reads its own disjoint splits | -| Decoding in `__getitem__` or `collate_fn` | `transform=`, which receives a whole Arrow `RecordBatch` and runs in a thread pool | -| `random_split`, `Subset`, or reading only the fields a model needs | `filter=""` and `columns=[...]`. Unselected columns are never read from storage | -| `StatefulDataLoader` | `state_dict()` and `load_state_dict()`, plus `StreamingDataLoader` for workers | - -The dataset does not copy your data. At construction it computes a shuffled assignment of row IDs to -`num_splits` fixed splits, then reads rows from the table as it iterates. It reads the table version -that exists at construction, so rows appended later do not appear mid-epoch. - -## Optimizations {#optimizations} - -The quickstart works as written. These sections cover what to tune as training scales up: the transform that -builds each sample, running across many GPUs, and the output format of a `Table` or `Permutation`. - -### Transform {#transform} - -A `transform` turns a batch of Arrow rows into the per-sample items your `DataLoader` collates. It receives a -whole `pyarrow.RecordBatch` (`read_batch_size` rows, 64 by default) rather than one sample at a time, so -vectorized code is cheap, and it must return exactly one item per row. The quickstart's transform is the -whole pattern: columns become tensors and each row becomes a dict, which the default `collate_fn` stacks into -a batch. Without a transform, rows arrive as plain Python dicts. - -Heavier per-sample work belongs in the same function, such as decoding video. Store each clip in a blob v2 -column (`lancedb.blob("video")`). A scan returns small descriptors instead of the video bytes, so reading -other columns never pulls video in. `fetch_blob_files` opens the clips for a batch of rows as file handles, -and torchcodec's `VideoDecoder` decodes just the frames you ask for. `ExtractFrames` samples 8 evenly spaced -frames from each clip: - -```py Python icon=Python -import functools -from torchcodec.decoders import VideoDecoder - -class ExtractFrames: - def __init__(self, uri: str, name: str, num_frames: int = 8) -> None: - self.uri, self.name, self.num_frames = uri, name, num_frames - - @functools.cached_property - def table(self) -> lancedb.table.Table: - return lancedb.connect(self.uri).open_table(self.name) - - def __call__(self, rb: pa.RecordBatch) -> list[dict[str, torch.Tensor]]: - samples = [] - for blob in self.table.fetch_blob_files("video", rb["_rowid"]): - decoder = VideoDecoder(blob) - idx = torch.linspace(0, len(decoder) - 1, self.num_frames).long() - samples.append({"frames": decoder.get_frames_at(idx.tolist()).data}) - return samples - -# `clips` is the table "clips" in the database at `uri`, with a blob v2 column "video" -train = StreamingDataset(clips, columns=["_rowid"], transform=ExtractFrames(uri, "clips")) -``` - -Transforms run in a thread pool, one thread per CPU by default (`transform_parallelism`), overlapping with -storage reads and your training step. NumPy, PyArrow and PyTorch release the GIL, so vectorized -work runs in parallel. A pure-Python loop does not. If a profile shows the transform is the bottleneck, move -it into [DataLoader workers](#using-multiple-dataloader-workers). - -Real data has bad rows, such as a truncated frame. Raise inside the transform and set -`on_transform_error="skip"` (or `"warn"` to log each failure). LanceDB re-runs the failing batch one row at a -time, drops only the rows that raise, and counts them in `dataset.rows_skipped`. When the bad rows match a SQL -predicate, prefer `filter=`: it runs before the splits are built, so every split keeps the same length. - -### Distributed Training {#distributed-training} - -`StreamingDataset` takes the place of `DistributedSampler`. Pass the rank and world size, and each rank reads -its own disjoint part of the table, together covering it once per epoch: - -```py Python icon=Python -import torch.distributed as dist - -dist.init_process_group("nccl") -train = StreamingDataset( - table, columns=["observation_state", "action"], transform=to_samples, - num_splits=48, shuffle_seed=42, epoch=epoch, - rank=dist.get_rank(), world_size=dist.get_world_size()) -``` - -Everything after the dataset is standard distributed PyTorch. Wrap the model in `DistributedDataParallel` -and pass `batch_size` to the `DataLoader` per GPU, so the global batch is `batch_size * world_size`. Nothing -in the data path changes. - -Three arguments matter in distributed runs: - -- **`num_splits`** is how many fixed streams the table is divided into. It must be divisible by `world_size`, - and by `world_size * num_workers` when you use DataLoader workers. Choose a number with many divisors, such - as 48, and runs on 8, 4 or 2 GPUs see the same data at every step, provided the global batch size is a multiple of - `num_splits`. -- **`shuffle_seed` and `epoch`** must be identical on every rank. Pass a fixed `shuffle_seed` and increase - `epoch` each epoch. `shuffle_seed=None` draws a different random seed in each process, so ranks would read - overlapping rows and miss others. -- **`rank` and `world_size`** come from your launcher, for example `torchrun`. - -To resume after a failure, save `train.state_dict()` next to the model. It records progress per split, so the -resumed run continues from the same row even on a different number of GPUs. See -[Parallelism & Elasticity](/training/data-loading#parallelism-&-elasticity) and -[Checkpointing](/training/data-loading#checkpointing) for the batch-size rules and the multi-worker case. - -### Output Formats {#output-formats} - -By default, a `Table` data loader will emit Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to -turn the fetched items into one batch. PyTorch's default collate function only knows how to combine tensors, NumPy -arrays, numbers, dicts, and lists, so it does not accept Arrow data directly. When using a `Table` directly, pass -LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it converts numeric Arrow columns into a -column-major `torch.Tensor` with shape `(columns, rows)`. - -`Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function -can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a -significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you -want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor -conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` -with one of the transform formats described below. - -To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map -the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, -`pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and -`torch` formats will all require at least one full copy of the data and are the slowest options. - -#### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} - -The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the -entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting -Tensor will have shape `(C, R)`. However, this format generates an error if you are using a -`torch.utils.data.DataLoader` with the default collation function: - -```text -TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor -``` - -This error occurs because the default collation function does not currently expect a single two-dimensional tensor. -It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format -requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function -in addition to specifying the `torch_col` format. - -```py Python icon=Python -from lancedb.permutation import Permutation - -permutation = Permutation.identity(table).with_format("torch_col") -dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) -``` - -This will now output a single two-dimensional tensor for each batch. - -## Selecting columns {#selecting-columns} - -By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need -a subset of columns, you can significantly reduce your I/O requirements by selecting only the columns you need. The -`Permutation` class provides a `select_columns` method that provides this functionality. - -```py Python icon=Python -import lancedb -import pyarrow as pa -import torch -from lancedb.permutation import Permutation - -db = lancedb.connect("memory://") -prompts = db.create_table( - "prompts", - pa.table( - { - "id": range(4), - "prompt": ["north", "south", "east", "west"], - "embedding": [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], - } - ), -) - -permutation = Permutation.identity(prompts).select_columns(["id", "prompt"]) -dataloader = torch.utils.data.DataLoader( - permutation, batch_size=1024, shuffle=True -) - -for batch in dataloader: - print(sorted(batch)) # ['id', 'prompt']: the embedding is never read -``` - -Each batch is a dict of the selected columns, the default `Permutation` format -described above. - -## Using multiple DataLoader workers {#using-multiple-dataloader-workers} - -Set `num_workers > 0` to read from LanceDB in multiple PyTorch worker processes. `Permutation` objects and tables in LanceDB Enterprise are picklable, so each worker reopens the table after it starts. A LanceDB Embedded table is not, so wrap it in a `Permutation`, as below, to read it from several workers. - -Prefer the `forkserver` start method when using multiple workers. LanceDB uses internal threads, so the default `fork` method is unsafe; `forkserver` avoids that while being cheaper to start than `spawn`, and became the default on Linux and other supported POSIX platforms in Python -3.14. macOS and Windows default to `spawn`. See -[Python's start-method documentation](https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods). See [the performance guide](/search#performance) for more multiprocessing guidance. - - -`forkserver` is only available on POSIX systems (Linux and macOS). On Windows, use `spawn`, the only available start method. - - -```py Python icon=Python -import torch -from lancedb.permutation import Permutation - -permutation = Permutation.identity(table) -dataloader = torch.utils.data.DataLoader( - permutation, - batch_size=1024, - shuffle=True, - num_workers=4, - multiprocessing_context="forkserver", - persistent_workers=True, -) -``` - -### Enterprise tables in DataLoader workers {#remote-tables-in-dataloader-workers} - -LanceDB Enterprise tables (`db://...`) work the same way: workers reopen the table from the pickled connection state. Replace the URI, API key, region and endpoint below with your deployment details. In application code, load credentials from environment variables or a secrets manager. - -```py Python icon=Python -import lancedb -import torch -from lancedb.util import tbl_to_tensor - -db = lancedb.connect( - "db://my-database", - api_key="your-api-key", - region="us-east-1", - host_override="https://your-endpoint", -) -table = db.open_table("my_table") - -dataloader = torch.utils.data.DataLoader( - table, - batch_size=512, - num_workers=4, - multiprocessing_context="forkserver", - collate_fn=tbl_to_tensor, -) -``` - - -This sends the connection state, including the API key, to each worker. Use a connection factory if credentials should be loaded inside the worker or your `client_config` contains a non-serializable `header_provider`. - - -### Providing a custom connection factory {#providing-a-custom-connection-factory} - -`Permutation.with_connection_factory` lets each worker reopen the base table with custom logic. The factory takes the table name, returns a LanceDB table, and must be picklable. - -This example loads the API key inside each worker. Set it in the shell before -starting the Python program, then replace the database URI, region and endpoint -in the factory with your deployment details: - -```shell -export LANCEDB_API_KEY="your-api-key" -``` - -```py Python icon=Python -import os -import lancedb -import torch -from lancedb.permutation import Permutation - -def open_table(name: str): - db = lancedb.connect( - "db://my-database", - api_key=os.environ["LANCEDB_API_KEY"], - region="us-east-1", - host_override="https://your-endpoint", - ) - return db.open_table(name) - -table = open_table("my_table") -permutation = ( - Permutation.identity(table) - .with_connection_factory(open_table) -) -dataloader = torch.utils.data.DataLoader( - permutation, - batch_size=512, - num_workers=4, - multiprocessing_context="forkserver", -) -``` diff --git a/docs/web/training/why-lancedb.mdx b/docs/web/training/why-lancedb.mdx deleted file mode 100644 index af10d4edc..000000000 --- a/docs/web/training/why-lancedb.mdx +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: "Why LanceDB for Training" -sidebarTitle: "Why LanceDB" -description: "Use LanceDB as the multimodal data layer for model training, fine-tuning, curation, and feature engineering workflows." -icon: fire ---- - -LanceDB is built for AI teams that need a practical data layer between raw multimodal datasets and model training. -Instead of moving data through separate systems for curation, feature engineering, search, manifests, and training, -you can keep the whole workflow attached to one versioned LanceDB table. - -That table can hold images, video, audio, text, annotations, metadata, embeddings, tokenized fields, model outputs, -quality signals, and training-ready tensors. As the dataset evolves, LanceDB lets you add new columns, filter rows, -pin versions, and read batches without rewriting the original data. - -![Training data lifecycle: Curation, Feature Engineering, Search and Retrieval, Training](/static/assets/images/overview/training-data-lifecycle.svg) - -The LanceDB multimodal lakehouse connects curation, feature engineering, retrieval, and training data access -through Lance tables. Data loaders read these tables into training frameworks, which run the model training. - -## A connected data lifecycle {#a-connected-data-lifecycle} - -Training pipelines usually need more than a pile of files. They need curation, derived features, reproducible splits, -fast random access, and a clean path into frameworks such as PyTorch. LanceDB keeps these pieces connected through -the same table model, whether you organize a workflow as one table or several related tables. - - - - Use filters, vector search, full-text search, and retrieval workflows to find the examples that matter: hard negatives, - long-tail failure modes, duplicate clusters, low-quality samples, or targeted fine-tuning slices. - - - Add embeddings, detections, OCR output, labels, token IDs, hidden states, deduplication flags, or quality scores as - new columns. Lance's columnar layout and schema evolution avoid rewriting large raw media columns when you add features. - - - Build filtered splits and materialized views from the table instead of exporting CSV manifests. Data versions and tags - make it possible to tie a checkpoint back to the exact rows and features used for training. - - - Use fast random access and column projection to read only the columns a training step needs. LanceDB tables can be read - from local storage or object storage, and integrate with data loading patterns such as PyTorch datasets. - - - -## Lance as the foundation {#lance-as-the-foundation} - -LanceDB is built on [Lance](https://lance.org/), an open-source lakehouse format designed for multimodal AI data. -The table below highlights the Lance features that enable the multimodal lakehouse on top. - -| Capability | Why it matters for training | -|---|---| -| **Multimodal columns** | Store raw bytes, annotations, metadata, embeddings, and features together. | -| **Fast random access** | Support shuffled and sampled reads without reshuffling the dataset on disk. | -| **Column projection** | Read only images, tokens, labels, embeddings, or hidden states needed by a given run. | -| **Schema evolution** | Add new feature columns without rewriting existing media columns. | -| **Versioning** | Reproduce experiments against the same table snapshot, even as the dataset evolves. | -| **Search and filtering** | Find and materialize useful training slices directly from the table. | - -## Search inside training workflows {#search-inside-training-workflows} - -Search is not limited to QA systems, agents, or production retrieval apps. It is also a practical way to inspect, -curate, and improve training data: - -- Find visually similar examples when debugging model failures. -- Retrieve hard negatives or near-duplicates for contrastive training. -- Combine vector search, full-text search, and metadata filters to build targeted fine-tuning slices. -- Reuse the same table for both offline curation and production retrieval. - -In LanceDB, retrieval and training workflows can operate over the same multimodal tables instead of forcing teams to -manage separate data systems for each stage. - -## Projects using LanceDB for training workflows {#projects-using-lancedb-for-training-workflows} - - - - A platform for reproducible world-model research built on a LanceDB data layer, reporting faster data loading on Push-T workloads. - - - A joint-embedding predictive world model from pixels, trained on the stable-worldmodel platform and its LanceDB data layer. - - - A drop-in LanceDB backend for Hugging Face LeRobot datasets with faster loading across robotics datasets. - - - -In the world-model ecosystem, [stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) reports -3-4x faster data loading on Push-T versus HDF5 / MP4 at a fraction of the disk footprint. Across these projects, -LanceDB and Lance provide the multimodal data layer that keeps raw observations, annotations, features, and training -access patterns in one format instead of scattering them across task-specific stores. - -## Next steps {#next-steps} - - - - Learn how to use LanceDB permutations to select rows, project columns, split datasets, and shuffle training reads. - - - Use LanceDB tables and permutations with `torch.utils.data.DataLoader`. - - - Fine-tune an AV perception model on curated failure-mode slices backed by one LanceDB table. - - - Fine-tune a VLM on TextVQA using LanceDB and Geneva to cache expensive training features. - - diff --git a/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx b/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx index 7f6110162..31f847473 100644 --- a/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx +++ b/docs/web/tutorials/feature-engineering/feature-engineering-101.mdx @@ -5,7 +5,6 @@ description: "Add derived feature columns to an existing table." --- Adds new derived features to a table, the pattern documented under -[data evolution](/feature-engineering/data-evolution) and [computed columns](/feature-engineering/add-computed-column). diff --git a/docs/web/tutorials/feature-engineering/materialized-views.mdx b/docs/web/tutorials/feature-engineering/materialized-views.mdx index 5e1a77bd4..32641a2d1 100644 --- a/docs/web/tutorials/feature-engineering/materialized-views.mdx +++ b/docs/web/tutorials/feature-engineering/materialized-views.mdx @@ -6,7 +6,7 @@ description: "Persist query results as physical tables and keep them current." Creates [materialized views](/management/materialized-view): query results persisted as physical tables, brought up to date by a -[refresh](/feature-engineering/materialized-views). +[refresh](/feature-engineering/refresh-materialized-view). This example is a runnable notebook in the From 8440574f2a5addf4e4c6246741b488ab7429ac08 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Thu, 29 Oct 2026 10:38:11 -0700 Subject: [PATCH 173/180] docs: use the new overview diagrams on the landing page (#4714) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Updates the overview diagrams on the landing page. Rebased onto #4732, which moved the architecture and offerings content into `index.mdx` and drew it as Mermaid diagrams; this PR replaces those with the guide's diagrams. - **Architecture** (`#architecture`): the suite diagram (`lancedb-suite.svg`) replaces the first Mermaid diagram. Its Enterprise boxes read Search, Data exploration & curation, Feature engineering, Training, matching the guide's product hierarchy. - **LanceDB Embedded** (`#1-lancedb-oss`): adds the guide's Embedded diagram. Its storage box reads "Local Disk or Object Storage", since Embedded supports both. - **LanceDB Enterprise** (`#2-lancedb-enterprise`): the guide's Distributed diagram replaces the second Mermaid diagram. This also drops that diagram's "column + MV refresh" label; automatic refresh is still gated. - **Functions** are still unpublished, so the "Functions ·" label is removed from the Distributed diagram's jobs fleet. At release, restore the designer's original image from the Notion guide. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- docs/web/index.mdx | 38 +------- .../images/overview/lancedb-distributed.png | Bin 0 -> 106258 bytes .../images/overview/lancedb-embedded.png | Bin 0 -> 40240 bytes .../assets/images/overview/lancedb-suite.svg | 92 ++++++++++++++++++ 4 files changed, 96 insertions(+), 34 deletions(-) create mode 100644 docs/web/static/assets/images/overview/lancedb-distributed.png create mode 100644 docs/web/static/assets/images/overview/lancedb-embedded.png create mode 100644 docs/web/static/assets/images/overview/lancedb-suite.svg diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 3cd157897..17fc014eb 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -47,22 +47,7 @@ LanceDB Embedded and Enterprise are both built on [Lance](/basics/lance), which indexes in open, columnar files. The format and table model are the same across both offerings -- what changes is how storage and compute are organized around them. -```mermaid -%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 45, "rankSpacing": 55, "padding": 12}}}%% -flowchart TB - subgraph Embedded["LanceDB Embedded"] - EmbApp(["Your application
+ LanceDB SDK"]) - end - - subgraph Enterprise["LanceDB Enterprise"] - EntSdk(["LanceDB SDK"]) --> EntEngine{{"Enterprise Distributed Engine"}} - end - - Lance[("Lance format
table data, versions, indexes")] - - Embedded --> Lance - Enterprise --> Lance -``` +![LanceDB suite: LanceDB Embedded for search, and LanceDB Enterprise for search, data exploration and curation, feature engineering, and training, both on the Lance format](/static/assets/images/overview/lancedb-suite.svg) Embedded reads and writes tables on local disk or in object storage from inside your application process. Enterprise keeps durable table data and index artifacts in object storage, independently of the machines serving @@ -87,6 +72,8 @@ Rust -- the application itself plans queries, builds indexes, and runs backgroun server to deploy. This fits local retrieval applications, notebooks, development, and single-node data pipelines, where your application controls its own compute resources and [table maintenance](/maintenance/compaction). +![LanceDB Embedded: the LanceDB SDK and the Lance format run in your application, reading and writing tables on local disk or in object storage.](/static/assets/images/overview/lancedb-embedded.png) + ### 2\. LanceDB Enterprise {#2-lancedb-enterprise} [LanceDB Enterprise](/enterprise) is a petabyte-scale (and beyond), distributed **multimodal lakehouse** platform @@ -97,24 +84,7 @@ and background work sized and scaled as separate components. A control plane gov and cluster lifecycle, separately from the data-plane components in the diagram below. See [Distributed search](/enterprise/distributed-search) for how query nodes and plan executors divide a request. -```mermaid -%%{init: {"flowchart": {"curve": "basis", "nodeSpacing": 45, "rankSpacing": 55, "padding": 12}}}%% -flowchart TB - Clients(["Clients"]) - QueryFleet{{"Query Fleet
query serving"}} - ExecutorRing{{"Executor Ring
read execution + cache"}} - MonitoringFleet{{"Monitoring Fleet"}} - JobWorkerFleet{{"Job Worker Fleet
indexing, column + MV refresh, compaction"}} - Storage[("Cloud Object Storage")] - - Clients --> QueryFleet - QueryFleet -- reads --> ExecutorRing - QueryFleet -- writes --> Storage - QueryFleet -- notifies --> MonitoringFleet - MonitoringFleet -- creates jobs --> JobWorkerFleet - ExecutorRing -- reads --> Storage - JobWorkerFleet -- writes --> Storage -``` +![LanceDB Distributed: the LanceDB SDK connects to LanceDB Enterprise, where a query fleet, executor and cache fleets, the realtime engine, and a jobs fleet run on top of the Lance format and object storage.](/static/assets/images/overview/lancedb-distributed.png) Teams choose Enterprise to: diff --git a/docs/web/static/assets/images/overview/lancedb-distributed.png b/docs/web/static/assets/images/overview/lancedb-distributed.png new file mode 100644 index 0000000000000000000000000000000000000000..893e884d663ece30eb8257372d3a282d3b15a8bc GIT binary patch literal 106258 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 Kmi}?`@BatntY!)T literal 0 HcmV?d00001 diff --git a/docs/web/static/assets/images/overview/lancedb-embedded.png b/docs/web/static/assets/images/overview/lancedb-embedded.png new file mode 100644 index 0000000000000000000000000000000000000000..5aa36011b4bba66dd3e7575d38f9efcbfa51e81e GIT binary patch literal 40240 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%0A4_*^?(iJ-B2q8(!h~l-aR(zDk@Ji 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 + LanceDB suite + LanceDB Embedded supports search. LanceDB Enterprise is a multimodal lakehouse for search, data exploration and curation, feature engineering, and training. Both are built on the Lance open lakehouse format for multimodal AI. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + LanceDB Embedded + Search + + + + + + + + + + + + + + + LanceDB Enterprise - Multimodal Lakehouse + + Search + Data exploration + & curation + Feature + engineering + Training + + + + + + + + + + Lance Open Lakehouse Format for Multimodal AI + + From 1d15bb3ada827e7460518a724e571b588c4a8cbf Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Thu, 29 Oct 2026 10:38:14 -0700 Subject: [PATCH 174/180] docs: address staging review comments (#4715) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Addresses some comments on the staging branch. Rebased onto #4732, which rebuilt `index.mdx` and the quickstart and reverted the landing copy to the pre-v0.4 headings; the final copy is reapplied here. | Comment | Page | Change | | --- | --- | --- | | Taylor: drop the comma | `index.mdx` | "one, unified platform" → "one unified platform" | | Taylor: "Preparing t…" + "Data doesn't slow down" | `index.mdx` | "Training data and experimentation slow down…" → "Preparing training data and running experiments slow down…" | | Fei: subtitles should align with the new home page | `index.mdx` | Follows the final homepage copy (v0.4): "Train on the right data faster" with the hero subtitle, "Accelerate the data flywheel for model research" with its intro, and the five v0.4 sections as steps, each linking to the page that backs it (search, curation, branches, versions, computed columns and materialized views, `StreamingDataset`). Wording the docs can't back yet is left out: "zero-copy", "lineage", "cached across clouds". Anchors renamed to match; nothing links to the old ones | | Fei: quickstart seems OSS-only | `quickstart.mdx` | Tip at the top: for Enterprise only the connection changes, linking the Enterprise connection in step 2 | Fei's "list all Enterprise features as a catalog" comment is now covered by #4732's feature comparison table (`/#compare`), so the separate table this PR added to `basics/offerings.mdx` was dropped along with that page. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- docs/web/index.mdx | 44 +++++++++++++++++++++++++++++------------ docs/web/quickstart.mdx | 6 ++++++ 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 17fc014eb..d6e12ed3d 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -10,28 +10,46 @@ keywords: ["multimodal lakehouse", "training", "feature engineering", "search", one data layer for curation, feature engineering, search and retrieval, and model training. It is built on top of [Lance](/basics/lance), an open-source lakehouse format designed for multimodal AI data. -Move from data exploration to model training on one, unified platform without needing to manage a +Move from data exploration to model training on one unified platform without needing to manage a fragmented stack of storage, feature, retrieval, and training systems. -## Build better models, faster {#build-better-models-faster} +## Train on the right data faster {#train-on-the-right-data-faster} -Training data and experimentation slow down when raw data, metadata, embeddings, features, and governance +Search, curate, and train at petabyte scale, with all your multimodal data in one table. + +Preparing training data and running experiments slow down when raw data, metadata, embeddings, features, and governance artifacts live in separate systems. LanceDB keeps them together in one versioned multimodal table, so AI teams spend less time stitching infrastructure together and more time improving datasets, testing features, and keeping GPUs fed. +## Accelerate the data flywheel for model research {#accelerate-the-data-flywheel-for-model-research} + +Keep your AI data in one table, and give each agent-driven experiment its own isolated branch. +Find the failure, fix the data, and retrain. + - - Store images, video, audio, text, annotations, embeddings, and model-generated features together in one schema-enforced table. - The same table can support dataset curation, feature backfills, experiment splits, retrieval, and training. + + Start from one failed grasp or evaluation example. [Search](/search/) multimodal data, metadata, and embeddings + together, retrieve similar examples, and [curate](/curation) them into a targeted training subset. - - Training workloads mix fast random access with high-throughput sequential scans. LanceDB is designed for both, so - teams can shuffle data into GPU-ready batches more efficiently, improve input throughput, and iterate on experiments faster. + + Don't let an agent silently corrupt your data and ruin a training run. Give each agent its own + [branch](/tables/branching), a writable fork of the table, to experiment on, and review the changes before + they reach `main`. See [Run experiments on branches](/agent-branch-experiments). - - Whether the end user is a human or an agent, LanceDB powers production retrieval workloads such as semantic search, - hybrid search, RAG, agent memory, and recommendation systems. Retrieval runs against the same LanceDB tables used - for curation, feature engineering, and training workflows. + + Keep episodes, frames, metadata, features, and embeddings together in one schema-enforced table, without + pipelines to keep them in sync. Table [versions](/management/table#versioning) let you trace each training + run back to the exact data it used. + + + Define the [computed columns](/feature-engineering/add-computed-column) and + [materialized views](/feature-engineering/materialized-views) your experiment needs, such as extracted features + or embeddings, and refresh them as your data changes. On LanceDB Enterprise, column refreshes run as background + jobs on the cluster instead of in your code. + + + Keep GPUs fed. [`StreamingDataset`](/training/data-loading) streams multimodal training data into PyTorch with + globally shuffled, deterministic batches, combining fast random access with high-throughput scans. diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index c84ae191a..02ec850bb 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -10,6 +10,12 @@ import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuick This quickstart uses LanceDB Embedded with a local database and works without an account or API key. LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. + +Using LanceDB Enterprise? Only the connection changes. In step 2, use the +[Enterprise](#connect-to-lancedb-enterprise) connection with your deployment's database URI, API key, and endpoint +in place of the local directory. The remaining steps use the same API. + + ## 1\. Install LanceDB {#1-install-lancedb} Choose your language. Python uses Pandas to display the search results. TypeScript needs Node.js 22.18 or later to run the `.mts` example directly. From dcddd541c818a0bfa0b531961997c5928865fed8 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Thu, 29 Oct 2026 10:59:09 -0700 Subject: [PATCH 175/180] docs: link home page sections through /index (#4740) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Changes links to home page sections from `/#` to `/index#`. The docs site's Assemble CI fails `mint broken-links --check-anchors` on every `/#architecture` link since #4732 moved the Architecture page onto the home page. The anchor exists; Mint 4.2.888's checker can't resolve any anchor on the root page `/`, but resolves `/index#…`. `docs.lancedb.com/index` serves the home page, so readers land in the same place. Verified by assembling the site with this change and the matching Enterprise docs change: `mint validate` passes and `mint broken-links --check-anchors --check-redirects` finds no broken links. The `docs.json` redirects keep `/#architecture`, which the checker accepts. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- docs/web/basics/guarantees.mdx | 2 +- docs/web/basics/lance.mdx | 2 +- docs/web/enterprise/benchmarks.mdx | 2 +- docs/web/enterprise/deployment/kubernetes.mdx | 2 +- docs/web/enterprise/distributed-search.mdx | 2 +- docs/web/enterprise/index.mdx | 6 +++--- docs/web/enterprise/security.mdx | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/web/basics/guarantees.mdx b/docs/web/basics/guarantees.mdx index 42392c5ba..bdfe86286 100644 --- a/docs/web/basics/guarantees.mdx +++ b/docs/web/basics/guarantees.mdx @@ -88,4 +88,4 @@ cannot undo `drop_table`. - [Cleanup](/maintenance/cleanup): configure retention and understand protected versions. - [Jobs](/basics/jobs): distinguish submission, completion and cancellation. - [Refresh a computed column](/feature-engineering/refresh-column): understand partial progress. -- [Architecture](/#architecture): understand storage and background maintenance. +- [Architecture](/index#architecture): understand storage and background maintenance. diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 883992afd..42d474de9 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -42,4 +42,4 @@ those fields together. - [Lance format specification](https://lance.org/format): how the format works. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. -- [Architecture](/#architecture): how LanceDB Embedded and Enterprise build on Lance. +- [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance. diff --git a/docs/web/enterprise/benchmarks.mdx b/docs/web/enterprise/benchmarks.mdx index b733aef78..402dfd56a 100644 --- a/docs/web/enterprise/benchmarks.mdx +++ b/docs/web/enterprise/benchmarks.mdx @@ -10,7 +10,7 @@ keywords: ["benchmarks", "performance", "throughput", "latency"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/#architecture) for what differs between the two. +[Architecture](/index#architecture) for what differs between the two. Benchmark results are specific to a deployment's shape (cluster size, storage class, dataset), so they are published with LanceDB Enterprise. diff --git a/docs/web/enterprise/deployment/kubernetes.mdx b/docs/web/enterprise/deployment/kubernetes.mdx index 3b1f4dea9..0133cf065 100644 --- a/docs/web/enterprise/deployment/kubernetes.mdx +++ b/docs/web/enterprise/deployment/kubernetes.mdx @@ -10,7 +10,7 @@ keywords: ["kubernetes", "k8s", "aks", "deployment", "helm"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/#architecture) for what differs between the two. +[Architecture](/index#architecture) for what differs between the two. The Kubernetes deployment procedure is published with LanceDB Enterprise. See [LanceDB Enterprise](/enterprise#deployment) for the general shape, and diff --git a/docs/web/enterprise/distributed-search.mdx b/docs/web/enterprise/distributed-search.mdx index f7c6001a5..8b4e9b233 100644 --- a/docs/web/enterprise/distributed-search.mdx +++ b/docs/web/enterprise/distributed-search.mdx @@ -11,7 +11,7 @@ availability: Distributed search spreads index execution, table-data reads, and caching across multiple serving machines in LanceDB Enterprise. Query nodes plan queries and combine results. Plan executors cache index structures and table data and execute -the remote work. See [Architecture](/#architecture). +the remote work. See [Architecture](/index#architecture). ## Embedded search {#embedded-search} diff --git a/docs/web/enterprise/index.mdx b/docs/web/enterprise/index.mdx index 59ab7e3a0..1c3a893a2 100644 --- a/docs/web/enterprise/index.mdx +++ b/docs/web/enterprise/index.mdx @@ -10,7 +10,7 @@ keywords: ["enterprise", "deployment", "cluster"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/#architecture) for what differs between the two. +[Architecture](/index#architecture) for what differs between the two. LanceDB Enterprise runs the lakehouse as a service: a control plane for configuration, identity and policy; a data plane serving reads and writes; and @@ -30,7 +30,7 @@ Draft for the Functions release. Add this row to the table above, after SQL: | [Functions](/management/function) | Python running on workers | */} -See [Architecture](/#architecture) for the two shapes side by side. +See [Architecture](/index#architecture) for the two shapes side by side. ## Getting a deployment {#deployment} @@ -39,4 +39,4 @@ published with LanceDB Enterprise rather than here. [Contact us](https://www.lancedb.com/contact) to get started; see the [Kubernetes deployment guide](/enterprise/deployment/kubernetes) for a worked example. Embedded LanceDB has nothing to deploy: it is a library your process links -against -- see [LanceDB Embedded](/#1-lancedb-oss). +against. See [LanceDB Embedded](/index#1-lancedb-oss). diff --git a/docs/web/enterprise/security.mdx b/docs/web/enterprise/security.mdx index b8d9d72c5..96846daa0 100644 --- a/docs/web/enterprise/security.mdx +++ b/docs/web/enterprise/security.mdx @@ -10,7 +10,7 @@ keywords: ["compliance", "security", "soc2", "encryption", "audit"] This page describes a LanceDB Enterprise capability. The embedded form of LanceDB has no server to provide it. See -[Architecture](/#architecture) for what differs between the two. +[Architecture](/index#architecture) for what differs between the two. Compliance posture (certifications, data residency, encryption at rest and in transit, audit logging) is a property of a deployment, so it is documented From a4f52cd205098064b1513d9586a011589cfc8e0e Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:28:54 -0700 Subject: [PATCH 176/180] fix(python): add a Blob V2 array construction helper (#4734) Fixes #4733 PyArrow expects Blob V2 storage structs when constructing a record batch and cannot infer the extension array from raw bytes. LanceDB already converts binary values during ingestion, but batch writers had no supported array constructor. Add `lancedb.schema.blob_array(payloads)` for iterables of inline bytes and nulls, using the same extension type resolver as `blob()`. The helper preserves empty blobs and null blobs and works with both pylance's type and LanceDB's fallback. Document the descriptor fields, exclusive inline/external representations, batch construction, and existing binary conversion in synchronous and asynchronous `create_table` / `add` APIs. Validation: - Reproduced the reported `ArrowTypeError` on the original code; both new regression cases fail against the original schema module. - 256 focused blob tests and schema doctests passed; one optional PyAV test skipped. - Both new regression cases also passed with PyArrow 25, with and without pylance imports. - Python package Ruff checks and formatting passed. - MkDocs build passed, with an existing unrelated `SecretReference` cross-reference warning. Repository-wide Ruff reports 48 existing errors in `docs/web-tests`. Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- docs/src/python/python.md | 30 +++++++++ python/python/lancedb/db.py | 8 +++ python/python/lancedb/schema.py | 68 ++++++++++++++++++++- python/python/lancedb/table.py | 8 +++ python/python/tests/test_blob_array.py | 85 ++++++++++++++++++++++++++ 5 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 python/python/tests/test_blob_array.py diff --git a/docs/src/python/python.md b/docs/src/python/python.md index af3f9d598..b3c0c4672 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -589,6 +589,34 @@ with `search().with_row_id(True).to_arrow()` and pass the result to the fetch AP One missing or deleted row ID rejects the entire blob-read batch; the APIs do not return partial results. +To construct inline Blob V2 arrays for ingestion in record batches, use +[blob_array][lancedb.schema.blob_array]. It accepts bytes and `None`, preserving +the distinction between an empty blob (`b""`) and a null blob: + +```python +import pyarrow as pa +from lancedb.schema import blob, blob_array + +schema = pa.schema([pa.field("video_id", pa.string()), blob("video")]) +batch = pa.RecordBatch.from_arrays( + [pa.array(["a", "b", "c"]), blob_array([b"abc", None, b""])], + schema=schema, +) +table = db.create_table("videos", data=iter([batch]), schema=schema) +table.add(iter([batch])) +``` + +`create_table(..., schema=...)` also casts plain binary values into blob columns +declared in the schema. `table.add(...)` casts them using the table's schema. +These conversions apply to Python rows and plain binary Arrow columns. +PyArrow's `RecordBatch.from_pylist(..., schema=...)` cannot convert raw bytes +into the blob extension type; use `blob_array` and `RecordBatch.from_arrays` +when constructing batches explicitly. + +For external blob references, construct the descriptor struct described by +[blob][lancedb.schema.blob], then wrap it with `pa.ExtensionArray.from_storage`. +Inline `data` and external `uri` representations are mutually exclusive. + LanceDB Distributed SQL returns blob bytes by default. Select `blob_descriptor(video)` to return an openable reference instead, then use [`open_blob_file`][lancedb.table.Table.open_blob_file] or the lazy iterable @@ -647,6 +675,8 @@ so the fetch APIs cannot read their bytes yet. ::: lancedb.blob +::: lancedb.schema.blob_array + ::: lancedb._blob.BlobFile options: show_root_full_path: false diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 32f7dc43c..e13e3dc9c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -416,6 +416,10 @@ class DBConnection(EnforceOverrides): - pyarrow.Schema - [LanceModel][lancedb.pydantic.LanceModel] + + Plain binary values are cast into blob columns declared with + [blob][lancedb.schema.blob]. To construct Arrow record batches + explicitly, use [blob_array][lancedb.schema.blob_array]. mode: str; default "create" The mode to use when creating the table. Can be "create", "overwrite", or "exist_ok". @@ -2598,6 +2602,10 @@ class AsyncConnection(object): - pyarrow.Schema - [LanceModel][lancedb.pydantic.LanceModel] + + Plain binary values are cast into blob columns declared with + [blob][lancedb.schema.blob]. To construct Arrow record batches + explicitly, use [blob_array][lancedb.schema.blob_array]. mode: Literal["create", "overwrite", "exist_ok"]; default "create" The mode to use when creating the table. Can be "create", "overwrite", or "exist_ok". diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py index 342053d6a..d92f7f692 100644 --- a/python/python/lancedb/schema.py +++ b/python/python/lancedb/schema.py @@ -6,7 +6,7 @@ import ctypes import importlib -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Iterable, Optional import pyarrow as pa import pyarrow.ipc @@ -229,8 +229,30 @@ def blob( Maximum size in bytes of a single packed blob sidecar file before a new one is started. Must be positive. + Notes + ----- Thresholds are validated and stored as Arrow field metadata, with the same format as ``lance.blob_field``. They do not require pylance. + + The extension's storage is a struct with nullable fields ``data`` + (large_binary), ``uri`` (string), ``position`` (uint64), and ``size`` + (uint64). Each non-null blob must set exactly one of ``data`` and ``uri``: + + - Inline bytes use ``data``, leaving all other fields null. ``b""`` is a + valid empty blob; use a null struct for a null blob. + - External blobs use ``uri``, leaving ``data`` null. Set both ``position`` + and ``size`` to select a byte range, or leave both null for the whole + object. A range's ``size`` must be greater than zero. + + Use [blob_array][lancedb.schema.blob_array] to build inline blob arrays + for Arrow record batches. For external descriptors, build the struct + array with ``field.type.storage_type`` and wrap it with + ``pa.ExtensionArray.from_storage(field.type, storage)``. + + ``create_table(..., schema=...)`` casts plain binary values into blob + columns declared by this field, and ``table.add(...)`` does the same + using the table's schema. PyArrow's ``RecordBatch.from_pylist`` does not + perform this conversion; construct blob arrays explicitly instead. """ metadata = {} for threshold, value, allow_zero, key in ( @@ -269,6 +291,50 @@ def blob( return field.with_metadata(metadata) if metadata else field +def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray: + """Build a Lance blob v2 extension array from inline bytes. + + Uses the same extension type as [blob][lancedb.schema.blob], with or + without pylance installed. + + Parameters + ---------- + payloads: + An iterable of ``bytes`` or ``None``. ``None`` creates a null blob; + ``b""`` creates a valid empty blob. + + Returns + ------- + pa.ExtensionArray + Inline blob values ready to use in Arrow tables or record batches. + + Raises + ------ + TypeError + If a payload is neither ``bytes`` nor ``None``. + + Examples + -------- + >>> import pyarrow as pa + >>> from lancedb.schema import blob, blob_array + >>> schema = pa.schema([blob("video")]) + >>> videos = blob_array([b"abc", None, b""]) + >>> batch = pa.RecordBatch.from_arrays([videos], schema=schema) + >>> batch.num_rows + 3 + """ + blob_type = _resolve_blob_type()() + descriptors = [] + for payload in payloads: + if payload is not None and not isinstance(payload, bytes): + raise TypeError( + f"payloads must contain bytes or None, got {type(payload).__name__}" + ) + descriptors.append(None if payload is None else {"data": payload}) + storage = pa.array(descriptors, type=blob_type.storage_type) + return pa.ExtensionArray.from_storage(blob_type, storage) + + def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType: """A help function to create a vector type. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 98a841bd0..be42dc802 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2183,6 +2183,10 @@ class Table(ABC): ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. + Plain binary values are cast into blob columns using the table's schema. + To construct Arrow record batches explicitly, use + [blob_array][lancedb.schema.blob_array]. + Parameters ---------- data: DATA @@ -6475,6 +6479,10 @@ class AsyncTable: ) -> AddResult: """Add more data to the [AsyncTable][lancedb.table.AsyncTable]. + Plain binary values are cast into blob columns using the table's schema. + To construct Arrow record batches explicitly, use + [blob_array][lancedb.schema.blob_array]. + Parameters ---------- data: DATA diff --git a/python/python/tests/test_blob_array.py b/python/python/tests/test_blob_array.py new file mode 100644 index 000000000..9eb8221f0 --- /dev/null +++ b/python/python/tests/test_blob_array.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import subprocess +import sys +import textwrap + +import pytest + + +@pytest.mark.parametrize("with_pylance", [False, True]) +def test_blob_array(with_pylance): + # Use fresh processes so each extension class can own Arrow's registry. + script = textwrap.dedent( + """\ + import importlib.abc + import sys + + if sys.argv[1] == "False": + class MissingLance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance" or fullname.startswith("lance."): + raise ModuleNotFoundError(fullname, name="lance") + sys.meta_path.insert(0, MissingLance()) + + import lancedb + import pyarrow as pa + from lancedb.schema import blob, blob_array + + if sys.argv[1] == "True": + from lance.blob import BlobType + else: + from lancedb.schema import _FallbackBlobType as BlobType + + schema = pa.schema([blob("video")]) + payloads = [b"abc", None, b"", b"\\x00\\xff"] + for values in ([], [None, None], payloads): + for source in (values, iter(values)): + array = blob_array(source) + assert isinstance(array, pa.ExtensionArray) + assert type(array.type) is BlobType + assert array.type == schema.field("video").type + assert array.null_count == values.count(None) + assert array.storage.to_pylist() == [ + None if value is None else { + "data": value, "uri": None, "position": None, "size": None + } + for value in values + ] + batch = pa.RecordBatch.from_arrays([array], schema=schema) + with pa.BufferOutputStream() as sink: + with pa.ipc.new_stream(sink, schema) as writer: + writer.write_batch(batch) + restored = pa.ipc.open_stream(sink.getvalue()).read_next_batch() + assert restored.equals(batch) + + for invalid in ("file:///video", {"data": b"abc"}, 123): + try: + blob_array([invalid]) + except TypeError as error: + assert "bytes or None" in str(error) + else: + raise AssertionError(f"accepted unsupported payload: {invalid!r}") + + # Batch iterators are the ingestion path that needs explicit arrays. + batches = [ + pa.RecordBatch.from_arrays([blob_array([value])], schema=schema) + for value in payloads + ] + table = lancedb.connect("memory:///").create_table( + "videos", data=iter(batches[:2]), schema=schema + ) + table.add(iter(batches[2:])) + row_ids = table.search().with_row_id(True).to_arrow()["_rowid"] + assert table.fetch_blobs("video", row_ids).to_pylist() == payloads + if sys.argv[1] == "False": + assert "lance" not in sys.modules + """ + ) + result = subprocess.run( + [sys.executable, "-c", script, str(with_pylance)], + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr From 2347e97e56031f8dc3c7aa0cf764bc8f5ad6048d Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Thu, 29 Oct 2026 11:55:30 -0700 Subject: [PATCH 177/180] docs: list features in the landing page comparison table (#4743) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Replaces the generated availability table under **Compare features** on the landing page with a hand-written list of features, grouped by area, with separate Embedded and Enterprise columns. The generated table listed every page that declares `availability`, including overview and basic CRUD pages. Rows such as "Overview" appeared three times without context, and pages like Insert, Update, Database and the integrations showed up as if they were features. | Area | Features | | --- | --- | | Search | Vector, full-text and hybrid search, filtering, reranking, query plans, distributed search | | Indexing | Vector, full-text and scalar indexes | | SQL and curation | SQL, aggregation, sampling, joins, ranking and deduplication, near-duplicate detection, chunking, changes since a version, views | | Feature engineering | Computed columns, materialized views, embedding registry | | Training | PyTorch data loader, permutations, distributed training | | Data management | Branches, compaction and cleanup, background jobs, Real Time engine | | Security | Authentication, authorization | Each ✅/❌ matches the linked page's `availability` on `main`; SQL, which declares none, is Enterprise-only. Functions are left out until it's settled whether they are published. The same list, limited to 1.10 features, is in the Enterprise 1.10 editions in lancedb/docs#398. Checked by assembling the docs site with this change: `mint validate` passes and `mint broken-links --check-anchors --check-redirects` finds no broken links. Vale reports no new warnings. After this merges, the committed `lancedb` skill in lancedb/docs needs a rebuild (`make assemble && make skill`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- docs/web/index.mdx | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/web/index.mdx b/docs/web/index.mdx index d6e12ed3d..21c9134af 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -119,7 +119,39 @@ To set up LanceDB Enterprise in your organization, [reach out to us](https://www ### Compare features {#compare} -{/* availability-comparison */} +| Area | Feature | Embedded | Enterprise | +| --- | --- | :-: | :-: | +| **Search** | [Vector search](/search/vector-search) | ✅ | ✅ | +| | [Full-text search](/search/full-text-search) | ✅ | ✅ | +| | [Hybrid search](/search/hybrid-search) | ✅ | ✅ | +| | [Filtering](/search/filtering) | ✅ | ✅ | +| | [Reranking](/reranking) | ✅ | ✅ | +| | [Query plans](/search/explain) | ✅ | ✅ | +| | [Distributed search](/enterprise/distributed-search) | ❌ | ✅ | +| **Indexing** | [Vector indexes](/indexing/vector-index) | ✅ | ✅ | +| | [Full-text indexes](/indexing/fts-index) | ✅ | ✅ | +| | [Scalar indexes](/indexing/scalar-index) | ✅ | ✅ | +| **SQL and curation** | [SQL (Arrow Flight SQL)](/basics/sql) | ❌ | ✅ | +| | [Aggregation and profiling](/curation/aggregate) | ❌ | ✅ | +| | [Sampling](/curation/sampling) | ❌ | ✅ | +| | [Joins](/curation/join) | ❌ | ✅ | +| | [Ranking and deduplication](/curation/windowing) | ❌ | ✅ | +| | [Near-duplicate detection](/curation/dedupe) | ❌ | ✅ | +| | [Chunking](/curation/chunking) | ❌ | ✅ | +| | [Changes since a version](/curation/changes) | ❌ | ✅ | +| | [Views](/management/view) | ❌ | ✅ | +| **Feature engineering** | [Computed columns, with refresh](/feature-engineering/add-computed-column) | ✅ | ✅ | +| | [Materialized views](/management/materialized-view) | ❌ | ✅ | +| | [Embedding registry](/embedding) | ✅ | ✅ | +| **Training** | [PyTorch data loader](/training/data-loading) | ✅ | ✅ | +| | [Permutations](/training/permutation) | ✅ | ✅ | +| | [Distributed training](/training/distributed-training) | ✅ | ✅ | +| **Data management** | [Branches](/tables/branching) | ✅ | ✅ | +| | [Compaction and cleanup](/maintenance/compaction) | ✅ | ✅ | +| | [Background jobs (managed indexing and maintenance)](/maintenance/background-jobs) | ❌ | ✅ | +| | [Real Time engine (streaming writes and reads)](/tables/realtime-engine) | ❌ | ✅ | +| **Security** | [Authentication](/enterprise/authentication) | ❌ | ✅ | +| | [Authorization](/governance/authorization) | ❌ | ✅ | ## Projects using LanceDB {#projects-using-lancedb} From 301ccad3aaa3c3a307c79899a8ae1cb26335d500 Mon Sep 17 00:00:00 2001 From: Colin Patrick McCabe Date: Thu, 29 Oct 2026 12:39:46 -0700 Subject: [PATCH 178/180] feat: add a LanceDB command line (#4600) Add a LanceDB command line with the following functionality: - `lancedb auth`: log in with OAuth, check cached OAuth session status, or log out. - `lancedb profile`: Create, edit, list, show, select, and delete connection profiles. - When no subcommand is given, we will attempt to create a SQL shell. Update ci/check_cargo_lock.py and its regression tests to allow pruning dependency edges while their target packages remain in Cargo.lock. Removing the CLI from the Python source distribution can disable optional features such as Axum tracing, even though other SDK dependencies still require the tracing package. --- .github/workflows/cli.yml | 45 + .github/workflows/pypi-publish.yml | 8 +- .github/workflows/rust.yml | 16 +- Cargo.lock | 2673 ++++++++++++--------- Cargo.toml | 8 + ci/check_cargo_lock.py | 7 +- ci/tests/test_check_cargo_lock.py | 34 +- docs/web/basics/sql.mdx | 3 + docs/web/docs.json | 6 + docs/web/tools/cli.mdx | 217 ++ rust/lancedb/Cargo.toml | 15 +- rust/lancedb/cli/Cargo.toml | 52 + rust/lancedb/cli/src/auth.rs | 419 ++++ rust/lancedb/cli/src/auth/tests.rs | 417 ++++ rust/lancedb/cli/src/cli.rs | 166 ++ rust/lancedb/cli/src/client.rs | 2110 ++++++++++++++++ rust/lancedb/cli/src/dml_result.rs | 137 ++ rust/lancedb/cli/src/formatter.rs | 2516 +++++++++++++++++++ rust/lancedb/cli/src/lib.rs | 55 + rust/lancedb/cli/src/main.rs | 10 + rust/lancedb/cli/src/mocks.rs | 119 + rust/lancedb/cli/src/profile.rs | 494 ++++ rust/lancedb/cli/src/server_config.rs | 1310 ++++++++++ rust/lancedb/cli/src/sql_executor.rs | 140 ++ rust/lancedb/cli/src/table_writer.rs | 380 +++ rust/lancedb/cli/tests/command_surface.rs | 339 +++ rust/lancedb/cli/tests/flight_sql_tls.rs | 643 +++++ rust/lancedb/src/connection.rs | 6 + rust/lancedb/src/database.rs | 6 + rust/lancedb/src/job.rs | 2 + rust/lancedb/src/remote/db.rs | 10 + rust/lancedb/src/remote/sql.rs | 20 +- 32 files changed, 11206 insertions(+), 1177 deletions(-) create mode 100644 .github/workflows/cli.yml create mode 100644 docs/web/tools/cli.mdx create mode 100644 rust/lancedb/cli/Cargo.toml create mode 100644 rust/lancedb/cli/src/auth.rs create mode 100644 rust/lancedb/cli/src/auth/tests.rs create mode 100644 rust/lancedb/cli/src/cli.rs create mode 100644 rust/lancedb/cli/src/client.rs create mode 100644 rust/lancedb/cli/src/dml_result.rs create mode 100644 rust/lancedb/cli/src/formatter.rs create mode 100644 rust/lancedb/cli/src/lib.rs create mode 100644 rust/lancedb/cli/src/main.rs create mode 100644 rust/lancedb/cli/src/mocks.rs create mode 100644 rust/lancedb/cli/src/profile.rs create mode 100644 rust/lancedb/cli/src/server_config.rs create mode 100644 rust/lancedb/cli/src/sql_executor.rs create mode 100644 rust/lancedb/cli/src/table_writer.rs create mode 100644 rust/lancedb/cli/tests/command_surface.rs create mode 100644 rust/lancedb/cli/tests/flight_sql_tls.rs diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml new file mode 100644 index 000000000..eb57a3804 --- /dev/null +++ b/.github/workflows/cli.yml @@ -0,0 +1,45 @@ +name: CLI +on: + push: + branches: [main] + pull_request: + paths: + - 'rust/lancedb/**' + - 'Cargo.toml' + - 'Cargo.lock' + - '.github/workflows/cli.yml' +permissions: + contents: read +jobs: + test: + strategy: + matrix: + os: [ubuntu-24.04, macos-14] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1 + with: + components: clippy + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + - name: Install Linux prerequisites + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y protobuf-compiler libssl-dev clang + - name: Install macOS prerequisites + if: runner.os == 'macOS' + run: brew install protobuf + - name: Build standalone CLI binary + run: cargo build --locked --profile ci -p lancedb-cli --bin lancedb + - name: Test standalone CLI + run: cargo test --locked --profile ci -p lancedb-cli + - name: Test SDK SQL + run: cargo test --locked --profile ci -p lancedb --features remote --lib remote::sql + - name: Lint CLI + run: cargo clippy --locked --profile ci -p lancedb-cli --all-targets --all-features -- -D warnings + - name: Check SDK without remote support + # Feature-disabled SDK code has existing unused-code warnings; this is a compile check. + env: + RUSTFLAGS: "" + run: cargo check --locked --profile ci -p lancedb --no-default-features --tests diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 1784c4c8a..d45833def 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -187,12 +187,14 @@ jobs: command: sdist working-directory: python args: --out dist - # maturin ships the nodejs-only pins in Cargo.lock. Remove this step when - # the pinned maturin fixes https://github.com/PyO3/maturin/issues/2609. + # maturin ships pins used only by other workspace members in Cargo.lock. + # Remove this step when the pinned maturin fixes + # https://github.com/PyO3/maturin/issues/2609. - name: Sync Cargo.lock to the packaged workspace shell: bash run: | - # A repo lock in sync with every manifest means the prune only drops pins. + # A synced repo lock lets the prune drop packages and optional edges + # without changing the remaining pins or adding dependency edges. cargo metadata --locked --format-version 1 > /dev/null mkdir "$RUNNER_TEMP/sdist-src" tar -xzf python/dist/lancedb-*.tar.gz -C "$RUNNER_TEMP/sdist-src" diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 96b0f2bfb..9b24a1f77 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -404,10 +404,18 @@ jobs: # unreadable outside their own branch anyway, since GitHub scopes # caches to the creating ref. save-if: ${{ github.ref == 'refs/heads/main' }} - - name: Downgrade dependencies - # aws-smithy-types 1.6.1+ requires rustc 1.94.1 - run: cargo update -p aws-smithy-types --precise 1.5.0 + - name: Resolve MSRV-compatible dependencies + # Resolve the AWS SDK and Smithy crates together: newer SDK releases + # require newer Smithy versions, so downgrading only Smithy can fail. + run: cargo +${{ matrix.msrv }} update --config 'resolver.incompatible-rust-versions="fallback"' + - name: Keep Xet dependencies compatible with the MSRV + # Xet 1.7 does not declare its MSRV, but requires sysinfo 0.39 (Rust 1.95). + # Downgrade parents before their dependencies to satisfy their constraints. + run: | + for crate in hf-xet xet-data xet-client xet-core-structures xet-runtime; do + cargo +${{ matrix.msrv }} update -p "$crate" --precise 1.6.0 + done - name: cargo +${{ matrix.msrv }} check env: RUSTUP_TOOLCHAIN: ${{ matrix.msrv }} - run: cargo check --profile ci --workspace --tests --benches --all-features + run: cargo check --locked --profile ci --workspace --tests --benches --all-features diff --git a/Cargo.lock b/Cargo.lock index 40811ab1d..a58fa195a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,7 +23,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "cipher", "cpufeatures 0.2.17", ] @@ -34,7 +34,7 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "const-random", "getrandom 0.3.4", "once_cell", @@ -44,9 +44,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -68,9 +68,9 @@ checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" [[package]] name = "alloc-stdlib" -version = "0.2.2" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" dependencies = [ "alloc-no-stdlib", ] @@ -92,9 +92,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "android_system_properties" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" dependencies = [ "libc", ] @@ -141,7 +141,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -152,7 +152,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -172,11 +172,11 @@ dependencies = [ [[package]] name = "ar_archive_writer" -version = "0.5.1" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb93bbb63b9c227414f6eb3a0adfddca591a8ce1e9b60661bb08969b87e340b" +checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" dependencies = [ - "object", + "object 0.39.1", ] [[package]] @@ -211,9 +211,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arrow" @@ -390,7 +390,7 @@ dependencies = [ "arrow-select", "chrono", "half", - "indexmap 2.14.0", + "indexmap 2.14.2", "itoa", "lexical-core", "memchr", @@ -445,7 +445,7 @@ version = "58.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21ca356ad6425cecb6eb7b28e4f659f1ee7880fbb1a16127de7dd62901efee9e" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "serde_core", "serde_json", ] @@ -495,9 +495,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.42" +version = "0.4.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79b3f8a79cccc2898f31920fc69f304859b3bd567490f75ebf51ae1c792a9ac" +checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970" dependencies = [ "compression-codecs", "compression-core", @@ -537,7 +537,7 @@ dependencies = [ "bytes", "derive_builder", "futures", - "rand 0.8.6", + "rand 0.8.8", "reqwest 0.12.28", "reqwest-eventsource", "secrecy", @@ -552,13 +552,13 @@ dependencies = [ [[package]] name = "async-recursion" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -569,7 +569,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -583,9 +583,12 @@ dependencies = [ [[package]] name = "asyncband" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2d85fd3d291fabcc40c7232c92c280ec1754fd7b5d7ea769f143222143e179a" +checksum = "5d2050892d4691cf110586070786712b504985a4d37ed64a9cd8a402718e1706" +dependencies = [ + "hashbrown 0.17.1", +] [[package]] name = "atoi" @@ -610,15 +613,15 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-config" -version = "1.8.16" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f156acdd2cf55f5aa53ee416c4ac851cf1222694506c0b1f78c85695e9ca9d" +checksum = "b8d7b388a9fc3a6db15a5ec778c38b354eff1364882c94d08e0252f7a47dcaa4" dependencies = [ "aws-credential-types", "aws-runtime", @@ -630,13 +633,14 @@ dependencies = [ "aws-smithy-json", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", "hex", "http 1.5.0", - "sha1 0.10.6", + "sha1 0.10.7", "time", "tokio", "tracing", @@ -646,9 +650,9 @@ dependencies = [ [[package]] name = "aws-credential-types" -version = "1.2.14" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f20799b373a1be121fe3005fba0c2090af9411573878f224df44b42727fcaf7" +checksum = "e93964ffdaf57857f544be3666a5f57570bb699e934700f11b49708f61bb556e" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", @@ -682,9 +686,9 @@ dependencies = [ [[package]] name = "aws-runtime" -version = "1.7.3" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dcd93c82209ac7413532388067dce79be5a8780c1786e5fae3df22e4dee2864" +checksum = "25b43ad47adc2517efe3d706559d94b97e50e80e0321b3cadbc9f77cee88adcd" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -710,10 +714,11 @@ dependencies = [ [[package]] name = "aws-sdk-bedrockruntime" -version = "1.130.0" +version = "1.145.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2f7bca252e3c5c8f0ed12c5501bf8b0fbadb937cd9fdd71a0ebd9d7526540f" +checksum = "aed4de4a98241f9dd95ddad4223755b7afc3327d0a148a2a29286c95ef64db5e" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -724,6 +729,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -737,10 +743,11 @@ dependencies = [ [[package]] name = "aws-sdk-dynamodb" -version = "1.111.0" +version = "1.126.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc418346e3cb248c7d59e642acbcb06488b7c7cd2ba6ebc79e8003f618c60099" +checksum = "84916ddc26951545be16e11fe45277e2d2561b9d0f2d0538274fb750c09b3eae" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -749,6 +756,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -757,14 +765,16 @@ dependencies = [ "http 1.5.0", "regex-lite", "tracing", + "url", ] [[package]] name = "aws-sdk-kms" -version = "1.106.0" +version = "1.120.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2336350f96efcf9c2552b7fdb4dd07a0c1fef11f22b28fb020a9e33e7925cf9d" +checksum = "d6b0fe38fee2ba5b6cd24d32d08365b314ae1adea123649e061a7eb6300b6f5b" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -773,6 +783,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -785,10 +796,11 @@ dependencies = [ [[package]] name = "aws-sdk-s3" -version = "1.132.0" +version = "1.148.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5575840a3a6b11f6011463ebe359320dfe5b67babb5e9b06fed6ddf809a9ab40" +checksum = "8a61c1db3987ab6c8740fb87f248864687d50549401115244a84f02c3047b2d5" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -800,6 +812,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", @@ -810,20 +823,21 @@ dependencies = [ "http 0.2.12", "http 1.5.0", "http-body 1.1.0", - "lru", + "lru 0.18.5", "percent-encoding", "regex-lite", - "sha2 0.11.0", + "sha2 0.11.1", "tracing", "url", ] [[package]] name = "aws-sdk-sso" -version = "1.98.0" +version = "1.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69c77aafa20460c68b6b3213c84f6423b6e76dbf89accd3e1789a686ffd9489" +checksum = "65700d75f6da78c89a61a49f1539979400a4609d3329376b1dc2133d7a1b2b90" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -832,6 +846,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -844,10 +859,11 @@ dependencies = [ [[package]] name = "aws-sdk-ssooidc" -version = "1.100.0" +version = "1.113.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c7e7b09346d5ca22a2a08267555843a6a0127fb20d8964cb6ecfb8fdb190225" +checksum = "eb1147c254af7b6cee3ace90ae7da6f21366ce9a9b899035fa8a0fdf586eb75a" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -856,6 +872,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -868,10 +885,11 @@ dependencies = [ [[package]] name = "aws-sdk-sts" -version = "1.103.0" +version = "1.116.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2249b81a2e73a8027c41c378463a81ec39b8510f184f2caab87de912af0f49b" +checksum = "035c7392e751d20bf1060d625d023587eb14099646110a9cff7c697bfe4b253a" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -881,6 +899,7 @@ dependencies = [ "aws-smithy-query", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", @@ -893,9 +912,9 @@ dependencies = [ [[package]] name = "aws-sigv4" -version = "1.4.3" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68dc0b907359b120170613b5c09ccc61304eac3998ff6274b97d93ee6490115a" +checksum = "31d955e76ff96acd555bf06fa0fa6d5bf9335fa84ae7c64481b20ae61d231f70" dependencies = [ "aws-credential-types", "aws-smithy-eventstream", @@ -903,7 +922,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "bytes", - "crypto-bigint 0.5.5", + "crypto-bigint", "form_urlencoded", "hex", "hmac 0.13.0", @@ -911,8 +930,7 @@ dependencies = [ "http 1.5.0", "p256", "percent-encoding", - "ring", - "sha2 0.11.0", + "sha2 0.11.1", "subtle", "time", "tracing", @@ -921,9 +939,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "1.2.14" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffcaf626bdda484571968400c326a244598634dc75fd451325a54ad1a59acfc" +checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" dependencies = [ "futures-util", "pin-project-lite", @@ -932,9 +950,9 @@ dependencies = [ [[package]] name = "aws-smithy-checksums" -version = "0.64.7" +version = "0.65.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10efbbcec1e044b81600e2fc562a391951d291152d95b482d5b7e7132299d762" +checksum = "b67ecd999972b58e67cab052f5129906c08c25883bd0788ceefc55ef97d61307" dependencies = [ "aws-smithy-http", "aws-smithy-types", @@ -947,15 +965,15 @@ dependencies = [ "md-5", "pin-project-lite", "sha1 0.11.0", - "sha2 0.11.0", + "sha2 0.11.1", "tracing", ] [[package]] name = "aws-smithy-eventstream" -version = "0.60.20" +version = "0.61.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf09d74e5e32f76b8762da505a3cd59303e367a664ca67295387baa8c1d7548" +checksum = "80c2051c2f1016fb8e6548dd07b8bc2ac9c3fe583721444b92f515e856d31609" dependencies = [ "aws-smithy-types", "bytes", @@ -964,9 +982,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.63.6" +version = "0.64.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231" +checksum = "37843d9add67c3aff5856f409c6dc315d3cdff60f9c0cb5b670dab1e9920306d" dependencies = [ "aws-smithy-eventstream", "aws-smithy-runtime-api", @@ -986,9 +1004,9 @@ dependencies = [ [[package]] name = "aws-smithy-http-client" -version = "1.1.13" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3ef8931ad1c98aa6a55b4256f847f3116090819844e0dd41ea682cac5dd2d3" +checksum = "7bd25384a4e437aa8d8f339afad4b69e786b936a7cb10db668a7aaf66717b1a8" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", @@ -1010,9 +1028,9 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.62.7" +version = "0.63.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "701a947f4797e52a911e114a898667c746c39feea467bbd1abd7b3721f702ffa" +checksum = "3385d469edbe8b60cc72002784652b5efca39178192aa9cc4b44c9875c6bdc18" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-schema", @@ -1021,28 +1039,31 @@ dependencies = [ [[package]] name = "aws-smithy-observability" -version = "0.2.6" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06c2315d173edbf1920da8ba3a7189695827002e4c0fc961973ab1c54abca9c" +checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c" dependencies = [ "aws-smithy-runtime-api", ] [[package]] name = "aws-smithy-query" -version = "0.60.15" +version = "0.62.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd" +checksum = "f1d1d71f6562be974caa85442ecd90194c40fdb5df045f182a6c2e872ce95056" dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", + "aws-smithy-xml", "urlencoding", ] [[package]] name = "aws-smithy-runtime" -version = "1.11.3" +version = "1.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182" +checksum = "3296253d3a91b3f938a3f2bcce4daebadcb4aa4228153fcec90f9d23532b4484" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -1066,9 +1087,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api" -version = "1.12.3" +version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9db177daa6ba8afb9ee1aefcf548c907abcf52065e394ee11a92780057fe0e8c" +checksum = "6d881a7b7ad179fd6611680c9de89f716fb00ab40299a9a7b8c6913e8f7511a8" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", @@ -1084,20 +1105,20 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api-macros" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d7396fd9500589e62e460e987ecb671bad374934e55ec3b5f498cc7a8a8a7b7" +checksum = "221eaa237ddf1ca79b60d1372aad77e47f9c0ea5b3ce5099da8c61d027dc77b3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "aws-smithy-schema" -version = "0.1.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5" +checksum = "e8f395d93304280b64b7632fea798d177e74897fe7f063416ce627cd6fa24829" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", @@ -1132,22 +1153,26 @@ dependencies = [ [[package]] name = "aws-smithy-xml" -version = "0.60.15" +version = "0.62.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3" +checksum = "0b932c8d6dc127fc980eecd78f8694ae9b9551b69a93a7def2a199c1c0033daf" dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", "xmlparser", ] [[package]] name = "aws-types" -version = "1.3.15" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4bbcaa9304ea40902d3d5f42a0428d1bd895a2b0f6999436fb279ffddc58ac" +checksum = "209f3a6d82a6e9e5f94abbed94c7a26e1c052341002bf57a5fb5481f625896fc" dependencies = [ "aws-credential-types", "aws-smithy-async", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "rustc_version", "tracing", @@ -1195,10 +1220,13 @@ checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core 0.5.6", "bytes", + "form_urlencoded", "futures-util", "http 1.5.0", "http-body 1.1.0", "http-body-util", + "hyper", + "hyper-util", "itoa", "matchit 0.8.4", "memchr", @@ -1206,10 +1234,15 @@ dependencies = [ "percent-encoding", "pin-project-lite", "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", "sync_wrapper", + "tokio", "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -1249,6 +1282,7 @@ dependencies = [ "sync_wrapper", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -1261,7 +1295,7 @@ dependencies = [ "getrandom 0.2.17", "instant", "pin-project-lite", - "rand 0.8.6", + "rand 0.8.8", "tokio", ] @@ -1283,19 +1317,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" dependencies = [ "addr2line", - "cfg-if 1.0.4", + "cfg-if", "libc", - "miniz_oxide", - "object", + "miniz_oxide 0.8.9", + "object 0.37.3", "rustc-demangle", "windows-link", ] [[package]] name = "base16ct" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" [[package]] name = "base64" @@ -1339,9 +1373,9 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bigdecimal" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695" +checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653" dependencies = [ "autocfg", "libm", @@ -1373,15 +1407,15 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.11.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "bitvec" -version = "1.0.1" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" dependencies = [ "funty", "radium", @@ -1400,16 +1434,15 @@ dependencies = [ [[package]] name = "blake3" -version = "1.8.5" +version = "1.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" dependencies = [ - "arrayref", "arrayvec", "cc", - "cfg-if 1.0.4", + "cfg-if", "constant_time_eq", - "cpufeatures 0.3.0", + "cpufeatures 0.3.1", ] [[package]] @@ -1423,9 +1456,9 @@ dependencies = [ [[package]] name = "block-buffer" -version = "0.12.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ "hybrid-array", ] @@ -1471,26 +1504,26 @@ dependencies = [ [[package]] name = "bstr" -version = "1.12.1" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" dependencies = [ "memchr", "regex-automata", - "serde", + "serde_core", ] [[package]] name = "bumpalo" -version = "3.20.2" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] name = "bytecheck" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0caa33a2c0edca0419d15ac723dff03f1956f7978329b1e3b5fdaaaed9d3ca8b" +checksum = "26333eeac754f0ad8a6bcd0eb0ac012156302e4e16b852b72ee399aea4f12c29" dependencies = [ "bytecheck_derive", "ptr_meta", @@ -1500,13 +1533,13 @@ dependencies = [ [[package]] name = "bytecheck_derive" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89385e82b5d1821d2219e0b095efa2cc1f246cbf99080f3be46a1a85c0d392d9" +checksum = "46d07918caa9eeaaf06b7873925c53a61daac173539b4f7715090745e44e4e69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -1526,13 +1559,13 @@ dependencies = [ [[package]] name = "bytemuck_derive" -version = "1.10.2" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -1568,14 +1601,14 @@ dependencies = [ "gemm", "half", "libm", - "memmap2 0.9.10", + "memmap2 0.9.12", "num-traits", "num_cpus", "rand 0.9.5", "rand_distr 0.5.1", "rayon", "safetensors", - "thiserror 2.0.18", + "thiserror 2.0.21", "yoke", "zip", ] @@ -1593,7 +1626,7 @@ dependencies = [ "rayon", "safetensors", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -1632,9 +1665,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.62" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" dependencies = [ "find-msvc-tools", "jobserver", @@ -1653,21 +1686,21 @@ dependencies = [ [[package]] name = "cfg-if" -version = "0.1.10" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" @@ -1675,8 +1708,8 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ - "cfg-if 1.0.4", - "cpufeatures 0.3.0", + "cfg-if", + "cpufeatures 0.3.1", "rand_core 0.10.1", ] @@ -1765,28 +1798,52 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.1" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] name = "clap_builder" -version = "4.6.0" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ + "anstream", "anstyle", "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", ] [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] [[package]] name = "cmake" @@ -1815,14 +1872,14 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] name = "combine" -version = "4.6.7" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -1836,14 +1893,14 @@ checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47" dependencies = [ "crossterm", "unicode-segmentation", - "unicode-width", + "unicode-width 0.2.2", ] [[package]] name = "compression-codecs" -version = "0.4.38" +version = "0.4.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf" +checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe" dependencies = [ "compression-core", "flate2", @@ -1852,9 +1909,9 @@ dependencies = [ [[package]] name = "compression-core" -version = "0.4.32" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" [[package]] name = "concurrent-queue" @@ -1874,7 +1931,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "unicode-width", + "unicode-width 0.2.2", "windows-sys 0.59.0", ] @@ -1918,9 +1975,9 @@ checksum = "18f12cc9948ed9604230cdddc7c86e270f9401ccbe3c2e98a4378c5e7632212f" [[package]] name = "const_panic" -version = "0.2.15" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e262cdaac42494e3ae34c43969f9cdeb7da178bdb4b66fa6a1ea2edb4c8ae652" +checksum = "9603f79528ece8163c496f8932121cb36cfe46259e9c907bb3d8205139d7caa3" dependencies = [ "typewit", ] @@ -1966,6 +2023,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "countio" version = "0.3.0" @@ -1981,7 +2044,7 @@ version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", ] [[package]] @@ -1995,47 +2058,30 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] -[[package]] -name = "crc" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9710d3b3739c2e349eb44fe848ad0b7c8cb1e42bd87ee49371df2f7acaf3e675" -dependencies = [ - "crc-catalog", -] - -[[package]] -name = "crc-catalog" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" - [[package]] name = "crc-fast" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fd92aca2c6001b1bf5ba0ff84ee74ec8501b52bbef0cac80bf25a6c1d87a83d" +checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5" dependencies = [ - "crc", "digest 0.10.7", - "rustversion", "spin 0.10.1", ] [[package]] name = "crc32fast" -version = "1.5.0" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", ] [[package]] @@ -2076,18 +2122,18 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.15" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -2095,18 +2141,18 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.20" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-queue" -version = "0.3.12" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" dependencies = [ "crossbeam-utils", ] @@ -2123,9 +2169,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crossterm" @@ -2133,11 +2179,11 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "crossterm_winapi", "document-features", "parking_lot", - "rustix", + "rustix 1.1.5", "winapi", ] @@ -2158,9 +2204,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-bigint" -version = "0.4.9" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", "rand_core 0.6.4", @@ -2168,16 +2214,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "crypto-bigint" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - [[package]] name = "crypto-common" version = "0.1.7" @@ -2190,9 +2226,9 @@ dependencies = [ [[package]] name = "crypto-common" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ "hybrid-array", ] @@ -2220,9 +2256,9 @@ dependencies = [ [[package]] name = "ctor" -version = "1.0.12" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d83cb7e7a873830708d6b02a78cd36a592c6fa14bf267b68725103b85c0d77f" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" dependencies = [ "link-section", "linktime-proc-macro", @@ -2230,9 +2266,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" dependencies = [ "cmov", ] @@ -2274,7 +2310,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -2287,7 +2323,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2298,7 +2334,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core 0.20.11", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -2309,16 +2345,16 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core 0.24.1", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] name = "dashmap" -version = "6.1.0" +version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "crossbeam-utils", "hashbrown 0.14.5", "lock_api", @@ -2361,7 +2397,7 @@ dependencies = [ "datafusion-session", "datafusion-sql", "futures", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "log", "object_store 0.13.2", @@ -2434,7 +2470,7 @@ dependencies = [ "foldhash 0.2.0", "half", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "libc", "log", @@ -2600,7 +2636,7 @@ dependencies = [ "datafusion-functions-aggregate-common", "datafusion-functions-window-common", "datafusion-physical-expr-common", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "serde_json", "sqlparser 0.62.0", @@ -2614,7 +2650,7 @@ checksum = "b7b19a8c95522bee8cbb313d74263b85e355d2b52f42e67ef5694bf5de9e9356" dependencies = [ "arrow", "datafusion-common", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", ] @@ -2646,7 +2682,7 @@ dependencies = [ "num-traits", "rand 0.9.5", "regex", - "sha2 0.11.0", + "sha2 0.11.1", "uuid", ] @@ -2759,7 +2795,7 @@ checksum = "1a3614234dd93578c92428cb4f408e020874f0d2b7e6c90c928d9d28b5df2ceb" dependencies = [ "datafusion-doc", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -2774,7 +2810,7 @@ dependencies = [ "datafusion-expr", "datafusion-expr-common", "datafusion-physical-expr", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "log", "regex", @@ -2795,7 +2831,7 @@ dependencies = [ "datafusion-physical-expr-common", "half", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "parking_lot", "petgraph", @@ -2828,7 +2864,7 @@ dependencies = [ "datafusion-common", "datafusion-expr-common", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "parking_lot", "pin-project", @@ -2876,7 +2912,7 @@ dependencies = [ "futures", "half", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "log", "num-traits", @@ -2927,7 +2963,7 @@ dependencies = [ "datafusion-common", "datafusion-expr", "datafusion-functions-nested", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "regex", "sqlparser 0.62.0", @@ -2950,9 +2986,9 @@ dependencies = [ [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -2960,33 +2996,23 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ - "thiserror 2.0.18", -] - -[[package]] -name = "der" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" -dependencies = [ - "const-oid 0.9.6", - "zeroize", + "thiserror 2.0.21", ] [[package]] @@ -3002,11 +3028,10 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" dependencies = [ - "powerfmt", "serde_core", ] @@ -3028,7 +3053,7 @@ dependencies = [ "darling 0.20.11", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -3038,7 +3063,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -3059,19 +3084,40 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer 0.12.0", + "block-buffer 0.12.1", "const-oid 0.10.2", - "crypto-common 0.2.1", + "crypto-common 0.2.2", "ctutils", ] +[[package]] +name = "directories" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a49173b84e034382284f27f1af4dcbbd231ffa358c0fe316541a7337f376a35" +dependencies = [ + "dirs-sys 0.4.1", +] + [[package]] name = "dirs" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ - "dirs-sys", + "dirs-sys 0.5.0", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.4.6", + "windows-sys 0.48.0", ] [[package]] @@ -3082,8 +3128,8 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users", - "windows-sys 0.59.0", + "redox_users 0.5.3", + "windows-sys 0.61.2", ] [[package]] @@ -3092,19 +3138,19 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "objc2", ] [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -3165,36 +3211,38 @@ dependencies = [ [[package]] name = "ecdsa" -version = "0.14.8" +version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der 0.6.1", + "der", + "digest 0.10.7", "elliptic-curve", "rfc6979", - "signature 1.6.4", + "signature", + "spki", ] [[package]] name = "either" -version = "1.15.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "elliptic-curve" -version = "0.12.3" +version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ "base16ct", - "crypto-bigint 0.4.9", - "der 0.6.1", + "crypto-bigint", "digest 0.10.7", "ff", "generic-array", "group", - "pkcs8 0.9.0", + "pem-rfc7468", + "pkcs8", "rand_core 0.6.4", "sec1", "subtle", @@ -3209,18 +3257,23 @@ checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" [[package]] name = "encoding_rs" -version = "0.8.35" +version = "0.8.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", ] [[package]] name = "encoding_rs_io" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cc3c5651fb62ab8aa3103998dade57efdd028544bd300516baa31840c252a83" +checksum = "fba3fe847045ecff794b9c138293a80db914678c453ad63fbf0c6a9eb6e00b22" dependencies = [ "encoding_rs", ] @@ -3240,7 +3293,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -3252,7 +3305,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -3295,14 +3348,14 @@ checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -3311,9 +3364,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "esaxx-rs" version = "0.1.10" @@ -3331,11 +3390,10 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -3386,21 +3444,32 @@ checksum = "95765f67b4b18863968b4a1bd5bb576f732b29a4a28c7cd84c09fa3e2875f33c" [[package]] name = "fast-float2" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8eb564c5c7423d25c886fb561d1e4ee69f72354d16918afa32c08811f6b6a55" +checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" [[package]] name = "fastrand" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fd-lock" +version = "4.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" +dependencies = [ + "cfg-if", + "rustix 1.1.5", + "windows-sys 0.59.0", +] [[package]] name = "ff" -version = "0.12.1" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ "rand_core 0.6.4", "subtle", @@ -3408,9 +3477,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.9" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "findshlibs" @@ -3436,18 +3505,19 @@ version = "25.12.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "rustc_version", ] [[package]] name = "flate2" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.9.1", + "zlib-rs", ] [[package]] @@ -3486,6 +3556,21 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "foreign_vec" version = "0.1.0" @@ -3509,7 +3594,7 @@ checksum = "643b47d510032a01e5af70dca288b0c5ec531646c1a8392e793fb5b0c13bef30" dependencies = [ "anyhow", "bytes", - "cfg-if 1.0.4", + "cfg-if", "foyer-tokio", "mixtrics", "parking_lot", @@ -3534,7 +3619,7 @@ checksum = "ae51f5089f3d9025ae77f17ea66d2489ac0f82fbb1d91462807bea174d486d82" dependencies = [ "anyhow", "asyncband", - "bitflags 2.11.1", + "bitflags 2.13.2", "datasketches", "equivalent", "foyer-common", @@ -3562,9 +3647,9 @@ dependencies = [ [[package]] name = "frostem" -version = "1.20260804.1" +version = "1.20260821.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" +checksum = "9e2488a10218a17366ce6bd38b6d081b4387a9548d350029db9feddc9bb44d6d" [[package]] name = "fs4" @@ -3572,7 +3657,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" dependencies = [ - "rustix", + "rustix 1.1.5", "windows-sys 0.59.0", ] @@ -3608,9 +3693,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" dependencies = [ "futures-channel", "futures-core", @@ -3623,9 +3708,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", "futures-sink", @@ -3633,15 +3718,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-executor" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" dependencies = [ "futures-core", "futures-task", @@ -3650,44 +3735,44 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-macro" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] name = "futures-sink" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-timer" -version = "3.0.3" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-channel", "futures-core", @@ -3702,12 +3787,9 @@ dependencies = [ [[package]] name = "gearhash" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8cf82cf76cd16485e56295a1377c775ce708c9f1a0be6b029076d60a245d213" -dependencies = [ - "cfg-if 0.1.10", -] +checksum = "616e8f476a586f1b078d9eece21f7a071f27997e709e2b471f5697deea53bda9" [[package]] name = "gemm" @@ -3830,12 +3912,12 @@ dependencies = [ [[package]] name = "generator" -version = "0.8.8" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9" +checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37" dependencies = [ "cc", - "cfg-if 1.0.4", + "cfg-if", "libc", "log", "rustversion", @@ -3851,6 +3933,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -3882,15 +3965,16 @@ dependencies = [ [[package]] name = "geo-types" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94776032c45f950d30a13af6113c2ad5625316c9abfbccee4dd5a6695f8fe0f5" +checksum = "777d18aa0f12f8b285331cd867133ee14422b3f023f6d388034c47d43e28786a" dependencies = [ "approx", "num-traits", "rayon", "rstar", "serde", + "thiserror 2.0.21", ] [[package]] @@ -3982,7 +4066,7 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "js-sys", "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -3995,7 +4079,7 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "libc", "r-efi 5.3.0", "wasip2", @@ -4003,17 +4087,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -4040,14 +4122,14 @@ checksum = "53010ccb100b96a67bc32c0175f0ed1426b31b655d562898e57325f81c023ac0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "glob" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "gloo-timers" @@ -4079,11 +4161,11 @@ dependencies = [ "io-uring", "itoa", "libc", - "lru", + "lru 0.16.4", "prost", "rand 0.9.5", "serde", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-stream", "tonic", @@ -4095,9 +4177,9 @@ dependencies = [ [[package]] name = "group" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", "rand_core 0.6.4", @@ -4106,9 +4188,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.16" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -4116,7 +4198,7 @@ dependencies = [ "futures-core", "futures-sink", "http 1.5.0", - "indexmap 2.14.0", + "indexmap 2.14.2", "slab", "tokio", "tokio-util", @@ -4130,7 +4212,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "bytemuck", - "cfg-if 1.0.4", + "cfg-if", "crunchy", "num-traits", "rand 0.9.5", @@ -4227,9 +4309,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" [[package]] name = "hex" @@ -4254,7 +4336,7 @@ dependencies = [ "reqwest 0.12.28", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "ureq", "windows-sys 0.60.2", @@ -4262,9 +4344,9 @@ dependencies = [ [[package]] name = "hf-xet" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c237ef4fb0ce1962a5117f8bd8c74454b41629826a9df17d14a1840ca18f0754" +checksum = "f24754aef4f6c3d57bc4a0dc2648ca74487050eda01c361b3eefa11feeafd662" dependencies = [ "anyhow", "async-trait", @@ -4273,7 +4355,7 @@ dependencies = [ "more-asserts", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-util", "tokio_with_wasm", @@ -4318,7 +4400,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "libc", "windows-link", ] @@ -4367,9 +4449,9 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", @@ -4392,24 +4474,24 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "humantime" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" [[package]] name = "hybrid-array" -version = "0.4.12" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ "typenum", ] [[package]] name = "hyper" -version = "1.9.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -4429,9 +4511,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.9" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http 1.5.0", "hyper", @@ -4441,7 +4523,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.10", + "webpki-roots 1.0.11", ] [[package]] @@ -4458,17 +4540,34 @@ dependencies = [ ] [[package]] -name = "hyper-util" -version = "0.1.20" +name = "hyper-tls" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ - "base64 0.22.1", + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", "bytes", "futures-channel", "futures-util", "http 1.5.0", "http-body 1.1.0", + "httparse", "hyper", "ipnet", "libc", @@ -4560,9 +4659,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -4572,26 +4671,11 @@ dependencies = [ "zerovec", ] -[[package]] -name = "icu_locale" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5a396343c7208121dc86e35623d3dfe19814a7613cfd14964994cdc9c9a2e26" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_locale_data", - "icu_provider", - "potential_utf", - "tinystr", - "zerovec", -] - [[package]] name = "icu_locale_core" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -4602,16 +4686,30 @@ dependencies = [ ] [[package]] -name = "icu_locale_data" -version = "2.2.0" +name = "icu_locale_fallback" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5fdcc9ac77c6d74ff5cf6e65ef3181d6af32003b16fce3a77fb451d2f695993" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" [[package]] name = "icu_normalizer" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -4623,16 +4721,17 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ + "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -4643,15 +4742,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -4666,30 +4765,26 @@ dependencies = [ [[package]] name = "icu_segmenter" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c0794db0b1a86193ac9c48768d0e6c52c54448e0870ad87907d456ee0dac964" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" dependencies = [ "icu_collections", - "icu_locale", + "icu_locale_fallback", "icu_provider", "icu_segmenter_data", "potential_utf", + "smallvec", "utf8_iter", + "zerotrie", "zerovec", ] [[package]] name = "icu_segmenter_data" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" - -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" [[package]] name = "ident_case" @@ -4731,9 +4826,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", @@ -4750,7 +4845,7 @@ dependencies = [ "console", "number_prefix", "portable-atomic", - "unicode-width", + "unicode-width 0.2.2", "web-time", ] @@ -4761,7 +4856,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "232929e1d75fe899576a3d5c7416ad0d88dbfbb3c3d6aa00873a7408a50ddb88" dependencies = [ "ahash", - "indexmap 2.14.0", + "indexmap 2.14.2", "is-terminal", "itoa", "log", @@ -4788,25 +4883,25 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", ] [[package]] name = "io-uring" -version = "0.7.12" +version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d09b98f7eace8982db770e4408e7470b028ce513ac28fecdc6bf4c30fe92b62" +checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" dependencies = [ - "bitflags 2.11.1", - "cfg-if 1.0.4", + "bitflags 2.13.2", + "cfg-if", "libc", ] [[package]] name = "ipnet" -version = "2.12.0" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "is-terminal" @@ -4816,7 +4911,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4884,32 +4979,31 @@ checksum = "9028f49264629065d057f340a86acb84867925865f73bbf8d47b4d149a7e88b8" [[package]] name = "jieba-macros" -version = "0.10.1" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46adade69b634535a8f495cf87710ed893cff53e1dbc9dd750c2ab81c5defb82" +checksum = "455f837e9d0255b68a712200db247c68fdad4941b72471b76bfa61c3b0c1f79f" dependencies = [ "phf_codegen 0.13.1", ] [[package]] name = "jieba-rs" -version = "0.10.1" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11b53580aaa8ec8b713da271da434f8947409242c537a9ab3f7b76bdbb19e8a9" +checksum = "b6a8bbb0f77ee810f0689a30b7cec56b875751ef4ec2e74fd995613dc52b3ae1" dependencies = [ "bytecount", "cedarwood", "jieba-macros", "phf 0.13.1", - "regex", "rustc-hash", ] [[package]] name = "jiff" -version = "0.2.35" +version = "0.2.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" dependencies = [ "defmt", "jiff-core", @@ -4926,30 +5020,31 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" dependencies = [ "defmt", + "log", ] [[package]] name = "jiff-static" -version = "0.2.35" +version = "0.2.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" dependencies = [ "jiff-core", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "jiff-tzdb" -version = "0.1.6" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c900ef84826f1338a557697dc8fc601df9ca9af4ac137c7fb61d4c6f2dfd3076" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" [[package]] name = "jiff-tzdb-platform" @@ -4966,13 +5061,13 @@ version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "combine", "jni-macros", "jni-sys", "log", "simd_cesu8", - "thiserror 2.0.18", + "thiserror 2.0.21", "walkdir", "windows-link", ] @@ -4987,7 +5082,7 @@ dependencies = [ "quote", "rustc_version", "simd_cesu8", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -5006,28 +5101,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" dependencies = [ "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "jobserver" -version = "0.1.34" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" dependencies = [ - "getrandom 0.3.4", + "getrandom 0.4.3", "libc", ] [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -5124,7 +5218,7 @@ dependencies = [ "semver", "serde", "serde_json", - "snafu 0.9.0", + "snafu 0.9.2", "tokio", "tokio-stream", "tokio-util", @@ -5218,7 +5312,7 @@ dependencies = [ "rand 0.9.5", "roaring", "serde_json", - "snafu 0.9.0", + "snafu 0.9.2", "tempfile", "tokio", "tokio-util", @@ -5311,7 +5405,7 @@ source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22b dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -5552,7 +5646,7 @@ dependencies = [ "jiff", "nom 8.0.0", "num-traits", - "ordered-float 5.3.0", + "ordered-float 5.5.1", "serde", "serde_json", "zmij", @@ -5585,7 +5679,7 @@ dependencies = [ "lance-namespace-reqwest-client", "serde", "serde_json", - "snafu 0.9.0", + "snafu 0.9.2", ] [[package]] @@ -5692,7 +5786,7 @@ dependencies = [ "semver", "serde", "serde_json", - "snafu 0.9.0", + "snafu 0.9.2", "tokio", "tracing", "url", @@ -5838,6 +5932,49 @@ dependencies = [ "tokio", ] +[[package]] +name = "lancedb-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "arrow-array", + "arrow-buffer", + "arrow-cast", + "arrow-flight", + "arrow-json", + "arrow-schema", + "async-trait", + "axum 0.8.9", + "base64 0.22.1", + "clap", + "csv", + "directories", + "futures", + "half", + "http 1.5.0", + "lancedb", + "prost", + "rcgen", + "reqwest 0.12.28", + "rustls", + "rustyline", + "serde", + "serde_ignored", + "serde_json", + "sha2 0.10.9", + "sqlparser 0.62.0", + "tempfile", + "termsize", + "tokio", + "tokio-stream", + "toml", + "tonic", + "tracing", + "unicode-width 0.2.2", + "url", + "which", +] + [[package]] name = "lancedb-nodejs" version = "0.41.0-beta.17" @@ -5896,19 +6033,13 @@ dependencies = [ [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" dependencies = [ "spin 0.9.9", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "lexical-core" version = "1.0.6" @@ -5978,7 +6109,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "windows-link", ] @@ -5990,18 +6121,18 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.16" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] [[package]] name = "libsais-rs" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40fe164dbd47ea0c20e78a121c980ef673326905f1d4fba55e3645a20ef6717f" +checksum = "00777f770949ecbe5524eb6630699a501c9c27e4d18493705a7dad49c9bdfbd1" dependencies = [ "rayon", ] @@ -6048,7 +6179,7 @@ dependencies = [ "encoding_rs_io", "glob", "log", - "memmap2 0.9.10", + "memmap2 0.9.12", "num_cpus", "once_cell", "regex", @@ -6057,20 +6188,26 @@ dependencies = [ "serde_json", "strum", "strum_macros 0.28.0", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] name = "link-section" -version = "0.19.2" +version = "0.19.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee1a0d6e252afe82e7bc2db42fba60e02ddf3b1accaf8cb21d96e34ba61f3d4" +checksum = "39c29a617ce3df32c08497bdc1ab6e2376e0b17948ac166a2fbe5977c5954cd9" [[package]] name = "linktime-proc-macro" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "348d0075b1fc163b26d72a7f75fc5141daf2fd1bdf128d873cbaf6785d495bdf" +checksum = "7e57c38c1e860fd37c604281cdfb1dd2216977fd76a50f85ba2f388ef3219616" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "linux-raw-sys" @@ -6080,15 +6217,15 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "litrs" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -6111,7 +6248,7 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "generator", "scoped-tls", "tracing", @@ -6128,10 +6265,19 @@ dependencies = [ ] [[package]] -name = "lru-slab" -version = "0.1.2" +name = "lru" +version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "lz4" @@ -6174,19 +6320,19 @@ dependencies = [ [[package]] name = "macro_rules_attribute" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520" +checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" dependencies = [ "macro_rules_attribute-proc_macro", - "paste", + "pastey", ] [[package]] name = "macro_rules_attribute-proc_macro" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30" +checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" [[package]] name = "matchers" @@ -6211,9 +6357,9 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" [[package]] name = "matrixmultiply" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" dependencies = [ "autocfg", "num_cpus", @@ -6228,25 +6374,15 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "digest 0.11.3", ] -[[package]] -name = "mea" -version = "0.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c709842c4ce65cb91e2666ad5319dfc1efc3af0d34f02075eddca9000d9f8afb" -dependencies = [ - "hashbrown 0.17.1", - "slab", -] - [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" @@ -6259,9 +6395,9 @@ dependencies = [ [[package]] name = "memmap2" -version = "0.9.10" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", "stable_deref_trait", @@ -6296,7 +6432,7 @@ dependencies = [ "crossbeam-epoch", "crossbeam-utils", "hashbrown 0.15.5", - "indexmap 2.14.0", + "indexmap 2.14.2", "metrics", "ordered-float 4.6.0", "quanta", @@ -6333,6 +6469,15 @@ name = "miniz_oxide" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" dependencies = [ "adler2", "simd-adler32", @@ -6340,9 +6485,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.0" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -6351,9 +6496,9 @@ dependencies = [ [[package]] name = "mixtrics" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c46b5adfb7a3ae4996d327a5bdc90e78fec025806dd312bdbe6f07a755e0ec9" +checksum = "1dd94ebec15e61a36cd63b1e8816c83434e42926962cd21ee6e4db898d4d4f05" dependencies = [ "itertools 0.15.0", "parking_lot", @@ -6398,7 +6543,7 @@ checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -6435,6 +6580,12 @@ dependencies = [ "target-features", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "munge" version = "0.4.7" @@ -6452,7 +6603,7 @@ checksum = "4568f25ccbd45ab5d5603dc34318c1ec56b117531781260002151b8530a9f931" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -6476,7 +6627,7 @@ version = "3.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a746ad50efbfb632ade1de4025519a477decbbd798cea1a6ac41d7c44f80083" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "chrono", "ctor", "futures", @@ -6507,7 +6658,7 @@ dependencies = [ "napi-derive-backend", "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -6520,7 +6671,7 @@ dependencies = [ "proc-macro2", "quote", "semver", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -6532,6 +6683,23 @@ dependencies = [ "libloading", ] +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "ndarray" version = "0.16.1" @@ -6569,7 +6737,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" dependencies = [ "bitflags 1.3.2", - "cfg-if 1.0.4", + "cfg-if", + "libc", +] + +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases 0.1.1", "libc", ] @@ -6579,9 +6759,9 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags 2.11.1", - "cfg-if 1.0.4", - "cfg_aliases", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases 0.2.2", "libc", ] @@ -6634,14 +6814,14 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "num-bigint" -version = "0.4.6" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" dependencies = [ "num-integer", "num-traits", @@ -6658,7 +6838,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand 0.8.6", + "rand 0.8.8", "smallvec", "zeroize", ] @@ -6675,9 +6855,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "num-format" @@ -6691,20 +6871,19 @@ dependencies = [ [[package]] name = "num-integer" -version = "0.1.46" +version = "0.1.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" dependencies = [ "num-traits", ] [[package]] name = "num-iter" -version = "0.1.45" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" dependencies = [ - "autocfg", "num-integer", "num-traits", ] @@ -6759,7 +6938,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -6778,7 +6957,7 @@ dependencies = [ "chrono", "getrandom 0.2.17", "http 1.5.0", - "rand 0.8.6", + "rand 0.8.8", "serde", "serde_json", "serde_path_to_error", @@ -6789,9 +6968,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ "objc2-encode", ] @@ -6802,7 +6981,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "objc2", "objc2-foundation", ] @@ -6813,7 +6992,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "dispatch2", "objc2", ] @@ -6830,7 +7009,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "objc2", "objc2-core-foundation", ] @@ -6845,6 +7024,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-open-directory" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb82bed227edf5201dfedf072bba4015a33d3d4a98519837295a90f0a23f676d" +dependencies = [ + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + [[package]] name = "objc2-system-configuration" version = "0.3.2" @@ -6863,6 +7053,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "object_store" version = "0.13.2" @@ -6880,7 +7079,7 @@ dependencies = [ "itertools 0.14.0", "parking_lot", "percent-encoding", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "url", @@ -6915,13 +7114,13 @@ dependencies = [ "parking_lot", "percent-encoding", "quick-xml 0.41.0", - "rand 0.10.1", + "rand 0.10.3", "reqwest 0.13.5", "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "url", @@ -6933,9 +7132,9 @@ dependencies = [ [[package]] name = "object_store_opendal" -version = "0.60.2" +version = "0.60.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c479bcc317f0ed98972b7184e0f9cc1bea83a07f60cdade96d7207a48ebfb779" +checksum = "0bd9da6291f93eb19b7987dac17617de0131760a6ba97a4cd8d6b1a07fa89783" dependencies = [ "async-trait", "asyncband", @@ -6972,7 +7171,7 @@ version = "6.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "libc", "once_cell", "onig_sys", @@ -6996,9 +7195,9 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "opendal" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fe43e16d96bed57937eb7c4a28559bf4c5fc4a3951656505d1fdd4f856349b4" +checksum = "46081824c74bac9f68f0bc4408077f77b0e315c006514719c97af1c2227ac2d2" dependencies = [ "ctor", "opendal-core", @@ -7019,9 +7218,9 @@ dependencies = [ [[package]] name = "opendal-core" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de4566a412776e3f65d53dd9fceced5b432a0a9c9a1e8d50ccf58823795e5c5b" +checksum = "33d5a635dfea36a7a0c3bbb2ca34c97af17f98dd69b0cdf31a1d436a346e0a12" dependencies = [ "anyhow", "asyncband", @@ -7033,7 +7232,7 @@ dependencies = [ "log", "md-5", "percent-encoding", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-core", "serde", "serde_json", @@ -7045,9 +7244,9 @@ dependencies = [ [[package]] name = "opendal-http-transport-reqwest" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f772ce6c137ab43647726116d505a649a88d41928fcd813438eb30b02312bcbb" +checksum = "fc025e163c43993e30cf1829a30b791934e5b0f7cd4d7e03acc902a9efb7e8f5" dependencies = [ "bytes", "futures", @@ -7059,9 +7258,9 @@ dependencies = [ [[package]] name = "opendal-layer-concurrent-limit" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3734c648617e5ad724d49175dde8323550624f9614f50e9e81b7aafae30b1734" +checksum = "06b44bdf694cccb7d90515b3eac6623975a2813abf4f5c438b4949a329d6a45b" dependencies = [ "asyncband", "futures", @@ -7071,9 +7270,9 @@ dependencies = [ [[package]] name = "opendal-layer-logging" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a8daab5a91eac76f94516e7c71e677195c9221840ce8f5e71815e3fc8207742" +checksum = "520d3de5d246c82a246c431ef0f52b8d2f091c7c49a3fd7a6f0ff519b1e7725f" dependencies = [ "log", "opendal-core", @@ -7081,9 +7280,9 @@ dependencies = [ [[package]] name = "opendal-layer-retry" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb8e22cb1f86ef9af771a8947d3ccf380c8f5b76236f628314dd41c9ba73331a" +checksum = "2a02c59479b047878f4a0f269f23c847f24d67d1ff19f2b20fdd5a3bceefd451" dependencies = [ "backon", "log", @@ -7092,9 +7291,9 @@ dependencies = [ [[package]] name = "opendal-layer-timeout" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08ac6c77fe0d1b18e0064a02c19b98dbebcab78bf5e7753ad1f3abbc18850ff4" +checksum = "afffa0cf8a6690b3b44cc510816ba675638eb236699a7d449e44ac3344bafd36" dependencies = [ "opendal-core", "tokio", @@ -7102,9 +7301,9 @@ dependencies = [ [[package]] name = "opendal-service-azblob" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6cf31b02e7b44191d97c07254eea109b5da9c17210a29e478c8d0dc26dffb1f" +checksum = "b674507cd2f764f6b40d5f88d284bb293c519d76e8aa0103987f970da412eeac" dependencies = [ "base64 0.23.1", "bytes", @@ -7112,20 +7311,20 @@ dependencies = [ "log", "opendal-core", "opendal-service-azure-common", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-azure-storage", "reqsign-core", "reqsign-file-read-tokio", "serde", - "sha2 0.11.0", + "sha2 0.11.1", "uuid", ] [[package]] name = "opendal-service-azdls" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "354f4a8d26f0fb7639f5c4ad3a924d7c75625830f69550b8c807c080ea0df8bc" +checksum = "afeb287cf2b03ab8d99d77a8e9687e908eb7898e2da1af6ccd00590c7095cae6" dependencies = [ "asyncband", "base64 0.23.1", @@ -7134,7 +7333,7 @@ dependencies = [ "log", "opendal-core", "opendal-service-azure-common", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-azure-storage", "reqsign-core", "reqsign-file-read-tokio", @@ -7144,9 +7343,9 @@ dependencies = [ [[package]] name = "opendal-service-azure-common" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8107324c3f3cb9970fe20526c2c341b7c5769acbd4699bab73bd525f5fd63d62" +checksum = "bdf9c9d0bfd1fa3638eec485c7f3448252cbb5a81774a2aa7abadc3e4f1ea43e" dependencies = [ "http 1.5.0", "opendal-core", @@ -7154,15 +7353,15 @@ dependencies = [ [[package]] name = "opendal-service-cos" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "feb737e6609b4fd42e4773b7b2d8d05031b63cd0df46c7ba68ddd64bae1dd3f3" +checksum = "423127c9e81b1ef4253883743ea6696c06dfad0fa6dcb1247887039919e53772" dependencies = [ "bytes", "http 1.5.0", "log", "opendal-core", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-core", "reqsign-file-read-tokio", "reqsign-tencent-cos", @@ -7171,9 +7370,9 @@ dependencies = [ [[package]] name = "opendal-service-gcs" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d80eca6f9227bdf65d43e5b8d5fe75dca8cfab1da07571442a0420400847bea" +checksum = "f9e5197fce0cd5929db9129a7e71e503841aa20bea4f1dcc54ab097a5f3652e9" dependencies = [ "async-trait", "bytes", @@ -7181,7 +7380,7 @@ dependencies = [ "log", "opendal-core", "percent-encoding", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-core", "reqsign-file-read-tokio", "reqsign-google", @@ -7193,9 +7392,9 @@ dependencies = [ [[package]] name = "opendal-service-goosefs" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2134aca0ef64dbff844cb1e608d28833f2a1b34b884e7d6b307416e966694e9f" +checksum = "6ca356f23424fa0129367c3eca426eb3ec0c3cfaf628bb2972fa597f8bd10805" dependencies = [ "asyncband", "bytes", @@ -7207,9 +7406,9 @@ dependencies = [ [[package]] name = "opendal-service-hf" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a0cba627efaee637746804b74bc2c2b2b207fe214307e1e2ba31b49aad708a3" +checksum = "32c1a4076d933180b66b57a0f305e48f2de1a72b50648114cb9943a8bc9e28b8" dependencies = [ "asyncband", "bytes", @@ -7224,15 +7423,15 @@ dependencies = [ [[package]] name = "opendal-service-oss" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0ebfa355b1d4edb0e5b2a5b86d8de9f811fae1d7baca6d65246b230b2afc0bd" +checksum = "30e973fcebfa413432c024c41d65fad8034b22c065250c587e0c3a70f1a27eb6" dependencies = [ "bytes", "http 1.5.0", "log", "opendal-core", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-aliyun-oss", "reqsign-core", "reqsign-file-read-tokio", @@ -7241,9 +7440,9 @@ dependencies = [ [[package]] name = "opendal-service-s3" -version = "0.59.2" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2942f2d8d3d4953c0e8d07cd1244879628d084948e48ce6b6d808c5938f7858d" +checksum = "0932321e27c712a30ef72db56b12f31e41e9f0d2d3841d63a91bc8075cd8f0ef" dependencies = [ "base64 0.23.1", "bytes", @@ -7252,7 +7451,7 @@ dependencies = [ "log", "md-5", "opendal-core", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-aws-v4", "reqsign-core", "reqsign-file-read-tokio", @@ -7261,10 +7460,47 @@ dependencies = [ ] [[package]] -name = "openssl-probe" -version = "0.2.1" +name = "openssl" +version = "0.10.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] [[package]] name = "option-ext" @@ -7283,9 +7519,9 @@ dependencies = [ [[package]] name = "ordered-float" -version = "5.3.0" +version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7d950ca161dc355eaf28f82b11345ed76c6e1f6eb1f4f4479e0323b9e2fbd0e" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" dependencies = [ "num-traits", ] @@ -7317,12 +7553,13 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" [[package]] name = "p256" -version = "0.11.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ "ecdsa", "elliptic-curve", + "primeorder", "sha2 0.10.9", ] @@ -7358,7 +7595,7 @@ version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "libc", "redox_syscall", "smallvec", @@ -7386,6 +7623,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "path_abs" version = "0.5.1" @@ -7418,6 +7661,16 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -7447,7 +7700,7 @@ checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset", "hashbrown 0.15.5", - "indexmap 2.14.0", + "indexmap 2.14.2", "serde", ] @@ -7506,7 +7759,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ "phf_shared 0.11.3", - "rand 0.8.6", + "rand 0.8.8", ] [[package]] @@ -7563,7 +7816,7 @@ checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -7574,9 +7827,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pin-utils" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" [[package]] name = "pkcs1" @@ -7584,9 +7837,9 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" dependencies = [ - "der 0.7.10", - "pkcs8 0.10.2", - "spki 0.7.3", + "der", + "pkcs8", + "spki", ] [[package]] @@ -7597,21 +7850,11 @@ checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" dependencies = [ "aes", "cbc", - "der 0.7.10", + "der", "pbkdf2", "scrypt", "sha2 0.10.9", - "spki 0.7.3", -] - -[[package]] -name = "pkcs8" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" -dependencies = [ - "der 0.6.1", - "spki 0.6.0", + "spki", ] [[package]] @@ -7620,17 +7863,17 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der 0.7.10", + "der", "pkcs5", "rand_core 0.6.4", - "spki 0.7.3", + "spki", ] [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "planus" @@ -7757,14 +8000,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "465f70d3e96b6d0b1a43c358ba451286b8c8bd56696feff020d65702aa33e35c" dependencies = [ "ahash", - "bitflags 2.11.1", + "bitflags 2.13.2", "bytemuck", "chrono", "chrono-tz 0.8.6", "comfy-table", "either", "hashbrown 0.14.5", - "indexmap 2.14.0", + "indexmap 2.14.2", "num-traits", "once_cell", "polars-arrow", @@ -7772,7 +8015,7 @@ dependencies = [ "polars-error", "polars-row", "polars-utils", - "rand 0.8.6", + "rand 0.8.8", "rand_distr 0.4.3", "rayon", "regex", @@ -7831,7 +8074,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89b2632b1af668e2058d5f8f916d8fbde3cac63d03ae29a705f598e41dcfeb7f" dependencies = [ "ahash", - "bitflags 2.11.1", + "bitflags 2.13.2", "glob", "once_cell", "polars-arrow", @@ -7862,7 +8105,7 @@ dependencies = [ "either", "hashbrown 0.14.5", "hex", - "indexmap 2.14.0", + "indexmap 2.14.2", "memchr", "num-traits", "polars-arrow", @@ -7971,7 +8214,7 @@ dependencies = [ "polars-error", "polars-lazy", "polars-plan", - "rand 0.8.6", + "rand 0.8.8", "serde", "serde_json", "sqlparser 0.39.0", @@ -8006,7 +8249,7 @@ dependencies = [ "ahash", "bytemuck", "hashbrown 0.14.5", - "indexmap 2.14.0", + "indexmap 2.14.2", "num-traits", "once_cell", "polars-error", @@ -8020,24 +8263,24 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.13.1" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "portable-atomic-util" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ "portable-atomic", ] [[package]] name = "potential_utf" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ "serde_core", "writeable", @@ -8046,9 +8289,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "pprof" @@ -8058,7 +8301,7 @@ checksum = "afad4d4df7b31280028245f152d5a575083e2abb822d05736f5e47653e77689f" dependencies = [ "aligned-vec", "backtrace", - "cfg-if 1.0.4", + "cfg-if", "findshlibs", "inferno", "libc", @@ -8080,7 +8323,7 @@ checksum = "38a01da47675efa7673b032bf8efd8214f1917d89685e07e395ab125ea42b187" dependencies = [ "aligned-vec", "backtrace", - "cfg-if 1.0.4", + "cfg-if", "findshlibs", "inferno", "libc", @@ -8091,7 +8334,7 @@ dependencies = [ "spin 0.10.1", "symbolic-demangle", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -8110,7 +8353,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ "proc-macro2", - "syn 2.0.117", + "syn 2.0.119", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", ] [[package]] @@ -8119,14 +8371,14 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit", + "toml_edit 0.25.17+spec-1.1.0", ] [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] @@ -8143,9 +8395,9 @@ dependencies = [ [[package]] name = "prost-build" -version = "0.14.3" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" +checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" dependencies = [ "heck 0.5.0", "itertools 0.14.0", @@ -8156,7 +8408,7 @@ dependencies = [ "prost", "prost-types", "regex", - "syn 2.0.117", + "syn 2.0.119", "tempfile", ] @@ -8170,23 +8422,23 @@ dependencies = [ "itertools 0.14.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "prost-types" -version = "0.14.3" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" +checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" dependencies = [ "prost", ] [[package]] name = "psm" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645dbe486e346d9b5de3ef16ede18c26e6c70ad97418f4874b8b1889d6e761ea" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" dependencies = [ "ar_archive_writer", "cc", @@ -8194,32 +8446,32 @@ dependencies = [ [[package]] name = "ptr_meta" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b9a0cf95a1196af61d4f1cbdab967179516d9a4a4312af1f31948f8f6224a79" +checksum = "743da816b98c921cdbe8628ef7381b76f25ecf4da599fc80aca90eae7ef70cc0" dependencies = [ "ptr_meta_derive", ] [[package]] name = "ptr_meta_derive" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7347867d0a7e1208d93b46767be83e2b8f978c3dad35f775ac8d8847551d6fe1" +checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] name = "pulp" -version = "0.22.2" +version = "0.22.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e205bb30d5b916c55e584c22201771bcf2bad9aabd5d4127f38387140c38632" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" dependencies = [ "bytemuck", - "cfg-if 1.0.4", + "cfg-if", "libm", "num-complex", "paste", @@ -8231,9 +8483,9 @@ dependencies = [ [[package]] name = "pulp-wasm-simd-flag" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" [[package]] name = "pyo3" @@ -8274,7 +8526,7 @@ checksum = "c23399970eea9c31d0ac84cee4a9d8dd05f89b1da2f4dd5bb44b32a3f66db4f8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -8305,7 +8557,7 @@ dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -8318,7 +8570,7 @@ dependencies = [ "proc-macro2", "pyo3-build-config", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -8364,6 +8616,16 @@ dependencies = [ "serde", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quick_cache" version = "0.6.24" @@ -8378,19 +8640,19 @@ dependencies = [ [[package]] name = "quinn" -version = "0.11.9" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", - "cfg_aliases", + "cfg_aliases 0.2.2", "pin-project-lite", "quinn-proto", "quinn-udp", "rustc-hash", "rustls", "socket2", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -8404,16 +8666,16 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", - "rand 0.10.1", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash", "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.18", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -8421,23 +8683,23 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.14" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ - "cfg_aliases", + "cfg_aliases 0.2.2", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "quote" -version = "1.0.45" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -8472,18 +8734,18 @@ dependencies = [ [[package]] name = "rancor" -version = "0.1.1" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a063ea72381527c2a0561da9c80000ef822bdd7c3241b1cc1b12100e3df081ee" +checksum = "9b534442d0fcdb55d66f373d9cac6d33b6293a2335bc2136dbd06ce0e87d2572" dependencies = [ "ptr_meta", ] [[package]] name = "rand" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha 0.3.1", @@ -8502,12 +8764,12 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.1" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -8562,7 +8824,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ "num-traits", - "rand 0.8.6", + "rand 0.8.8", ] [[package]] @@ -8603,15 +8865,15 @@ dependencies = [ "brotli", "once_cell", "paste", - "rand 0.8.6", + "rand 0.8.8", "unicase", ] [[package]] name = "rangemap" -version = "1.7.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" [[package]] name = "rapidhash" @@ -8628,7 +8890,7 @@ version = "11.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] @@ -8668,6 +8930,18 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48406db8ac1f3cbc7dcdb56ec355343817958a356ff430259bb07baf7607e1e1" +dependencies = [ + "pem 3.0.6", + "ring", + "time", + "yasna", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -8691,7 +8965,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" dependencies = [ "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -8709,38 +8983,48 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", ] [[package]] name = "redox_users" -version = "0.5.2" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" dependencies = [ "getrandom 0.2.17", "libredox", - "thiserror 2.0.18", + "thiserror 1.0.69", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", ] [[package]] name = "ref-cast" -version = "1.0.25" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.25" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -8757,9 +9041,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.16" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", @@ -8786,18 +9070,18 @@ checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" [[package]] name = "rend" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cadadef317c2f20755a64d7fdc48f9e7178ee6b0e1f7fce33fa60f1d68a276e6" +checksum = "663ba70707f96e871406fe10d68128412e619b06d1d47cb91c3a4c6501176240" dependencies = [ "bytecheck", ] [[package]] name = "reqsign-aliyun-oss" -version = "3.1.3" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e6d659fcdbca6fe2d7ef109c2e28499b7be80501f1bb86c10caf5ec8ac1219" +checksum = "28cf3d65d37ac910073d921c1cc58c3e4e6c963795c6062eee196e6d19054dde" dependencies = [ "anyhow", "form_urlencoded", @@ -8812,9 +9096,9 @@ dependencies = [ [[package]] name = "reqsign-aws-core" -version = "3.1.1" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bac4749b7dfa7bfaccd01eb03e9dc795ed37e3f20d6f0f38e2c67ee85ad6bc86" +checksum = "d38c902d8ec745bd9eadd1abbcbe227f4c1fc2926b2ec8929f89234af3114500" dependencies = [ "bytes", "form_urlencoded", @@ -8822,7 +9106,7 @@ dependencies = [ "http 1.5.0", "log", "percent-encoding", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-core", "rust-ini", "serde", @@ -8833,14 +9117,14 @@ dependencies = [ [[package]] name = "reqsign-aws-v4" -version = "3.3.0" +version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff250f0fd0b913fbd565e405acc553da0f13bde30bfb5403178c9d0313cdc15f" +checksum = "906bfd028f96bfe73fdb892ce26f3b3f99b4f30feb9bd024be58bd6657f68b2b" dependencies = [ "bytes", "http 1.5.0", "log", - "quick-xml 0.41.0", + "quick-xml 0.42.0", "reqsign-aws-core", "reqsign-core", "serde", @@ -8848,17 +9132,18 @@ dependencies = [ [[package]] name = "reqsign-azure-storage" -version = "3.1.2" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2824e7da3c2cc42ac3406c674eb57c89127fdcd97f3a73c608cfc680505ea134" +checksum = "7260e6c1d89422ba62d624a32c491b561386fb364ac4bf0959c740e34b251a2e" dependencies = [ "anyhow", + "asyncband", "base64 0.23.1", "bytes", "form_urlencoded", "http 1.5.0", "log", - "pem", + "pem 4.0.0", "percent-encoding", "reqsign-core", "rsa", @@ -8869,34 +9154,33 @@ dependencies = [ [[package]] name = "reqsign-core" -version = "3.3.1" +version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff052daffb0599681c50f85c59e7236438976efe991ab864edd9f3b235501a0f" +checksum = "85fed85c436b6b920e4b36310f699a77771a91e38ae483df48447bd7d162671c" dependencies = [ "anyhow", + "asyncband", "base64 0.23.1", "bytes", - "futures", "hex", "hmac 0.13.0", "http 1.5.0", "jiff", "log", - "mea", "percent-encoding", "rsa", "serde", "serde_json", "sha1 0.11.0", - "sha2 0.11.0", + "sha2 0.11.1", "windows-sys 0.61.2", ] [[package]] name = "reqsign-file-read-tokio" -version = "3.0.6" +version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3235df90a6bca681aa47dd86f2393d122a6d77042aa8a7c81e218cd45c5bfc0" +checksum = "586a8e198057773f9616901fd723a4bc186812b9765bc0f20368661d6169d906" dependencies = [ "anyhow", "reqsign-core", @@ -8905,9 +9189,9 @@ dependencies = [ [[package]] name = "reqsign-google" -version = "3.1.1" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "272a5813571885c1455ffe106f0c768577e6ce69313446d4476e8d41dcf6ac5a" +checksum = "719e55931cc81b8dcd69f95f0a2def55617cb76cb3aa2f8c439e10682e46fa10" dependencies = [ "bytes", "form_urlencoded", @@ -8924,9 +9208,9 @@ dependencies = [ [[package]] name = "reqsign-tencent-cos" -version = "3.0.4" +version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "764629c90f7c3566a6d4e4641ebab9acd604ce02e16eda4d37c7d7e79e16ed90" +checksum = "9a98625e0f3eab846348b7524f1f5b5c97ffc348002845463520be371b7ab7cd" dependencies = [ "anyhow", "http 1.5.0", @@ -8954,11 +9238,13 @@ dependencies = [ "http-body-util", "hyper", "hyper-rustls", + "hyper-tls", "hyper-util", "js-sys", "log", "mime", "mime_guess", + "native-tls", "percent-encoding", "pin-project-lite", "quinn", @@ -8970,17 +9256,18 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", + "tokio-native-tls", "tokio-rustls", "tokio-util", "tower", - "tower-http 0.6.10", + "tower-http 0.6.11", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.10", + "webpki-roots 1.0.11", ] [[package]] @@ -9018,7 +9305,7 @@ dependencies = [ "tokio-rustls", "tokio-util", "tower", - "tower-http 0.6.10", + "tower-http 0.6.11", "tower-service", "url", "wasm-bindgen", @@ -9045,27 +9332,26 @@ dependencies = [ [[package]] name = "reqwest-middleware" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "199dda04a536b532d0cc04d7979e39b1c763ea749bf91507017069c00b96056f" +checksum = "07bc3f1384cffa4f274dad2d4ddd73aed32fed8f786d96c6be8aa4e5fd3c3b58" dependencies = [ "anyhow", "async-trait", "http 1.5.0", "reqwest 0.13.5", - "thiserror 2.0.18", + "thiserror 2.0.21", "tower-service", ] [[package]] name = "rfc6979" -version = "0.3.1" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ - "crypto-bigint 0.4.9", "hmac 0.12.1", - "zeroize", + "subtle", ] [[package]] @@ -9084,7 +9370,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", - "cfg-if 1.0.4", + "cfg-if", "getrandom 0.2.17", "libc", "untrusted 0.9.0", @@ -9093,14 +9379,14 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.8.17" +version = "0.8.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "815cc8a37159a463064825246cadb07961e25cd9885908606f6d08a98d8f8874" +checksum = "d9776093b7ca170454ab1406954f7b7d97a57c51dc6c0642957fb2ef25c2d399" dependencies = [ "bytecheck", "bytes", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "munge", "ptr_meta", "rancor", @@ -9112,13 +9398,13 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.8.17" +version = "0.8.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ed1a78a1b19d184b0daa629dd9a024573173ec7d485b287cb369fb3607cc1c" +checksum = "1c25ef604ac7dd839d44d64648952ea23c97866f124ff671b0ed2cf3ad9bb06e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -9149,11 +9435,11 @@ dependencies = [ "num-integer", "num-traits", "pkcs1", - "pkcs8 0.10.2", + "pkcs8", "rand_core 0.6.4", "sha2 0.10.9", - "signature 2.2.0", - "spki 0.7.3", + "signature", + "spki", "subtle", "zeroize", ] @@ -9187,7 +9473,7 @@ version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "glob", "proc-macro-crate", "proc-macro2", @@ -9195,7 +9481,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.117", + "syn 2.0.119", "unicode-ident", ] @@ -9205,21 +9491,21 @@ version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "ordered-multimap", ] [[package]] name = "rustc-demangle" -version = "0.1.27" +version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" [[package]] name = "rustc-hash" -version = "2.1.2" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustc_version" @@ -9232,15 +9518,28 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "errno", "libc", - "linux-raw-sys", - "windows-sys 0.52.0", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", ] [[package]] @@ -9261,9 +9560,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.3" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -9273,9 +9572,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.14.1" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" dependencies = [ "web-time", "zeroize", @@ -9283,9 +9582,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", @@ -9299,14 +9598,14 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] name = "rustls-platform-verifier-android" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" @@ -9322,9 +9621,31 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rustyline" +version = "14.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7803e8936da37efd9b6d4478277f4b2b9bb5cdb37a113e8d63222e58da647e63" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "clipboard-win", + "fd-lock", + "home", + "libc", + "log", + "memchr", + "nix 0.28.0", + "radix_trie", + "unicode-segmentation", + "unicode-width 0.1.14", + "utf8parse", + "windows-sys 0.52.0", +] [[package]] name = "ryu" @@ -9378,9 +9699,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -9399,9 +9720,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.1" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", @@ -9434,14 +9755,14 @@ dependencies = [ [[package]] name = "sec1" -version = "0.3.0" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ "base16ct", - "der 0.6.1", + "der", "generic-array", - "pkcs8 0.9.0", + "pkcs8", "subtle", "zeroize", ] @@ -9462,7 +9783,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -9518,7 +9839,17 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", +] + +[[package]] +name = "serde_ignored" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798" +dependencies = [ + "serde", + "serde_core", ] [[package]] @@ -9528,7 +9859,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "foldhash 0.2.0", - "indexmap 2.14.0", + "indexmap 2.14.2", "itoa", "memchr", "serde", @@ -9558,13 +9889,22 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", ] [[package]] @@ -9590,10 +9930,10 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.14.0", + "indexmap 2.14.2", "jiff", "schemars 0.9.0", - "schemars 1.2.1", + "schemars 1.2.3", "serde_core", "serde_json", "serde_with_macros", @@ -9609,7 +9949,7 @@ dependencies = [ "darling 0.24.1", "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -9618,7 +9958,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "itoa", "ryu", "serde", @@ -9647,16 +9987,16 @@ checksum = "94e153fc76e1c6a068703d6d29c508a0b15c061c4b7e43da59cc097bc342673c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "sha1" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "cpufeatures 0.2.17", "digest 0.10.7", ] @@ -9667,8 +10007,8 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ - "cfg-if 1.0.4", - "cpufeatures 0.3.0", + "cfg-if", + "cpufeatures 0.3.1", "digest 0.11.3", ] @@ -9684,19 +10024,19 @@ version = "0.10.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "cpufeatures 0.2.17", "digest 0.10.7", ] [[package]] name = "sha2" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ - "cfg-if 1.0.4", - "cpufeatures 0.3.0", + "cfg-if", + "cpufeatures 0.3.1", "digest 0.11.3", ] @@ -9722,9 +10062,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.3.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook-registry" @@ -9736,16 +10076,6 @@ dependencies = [ "libc", ] -[[package]] -name = "signature" -version = "1.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" -dependencies = [ - "digest 0.10.7", - "rand_core 0.6.4", -] - [[package]] name = "signature" version = "2.2.0" @@ -9771,15 +10101,15 @@ dependencies = [ [[package]] name = "simd-adler32" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" [[package]] name = "simd_cesu8" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" dependencies = [ "rustc_version", "simdutf8", @@ -9793,15 +10123,15 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "sketches-ddsketch" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c6f73aeb92d671e0cc4dca167e59b2deb6387c375391bc99ee743f326994a2b" +checksum = "45f82fa313d625dd72aaa65ec0c9f8c95407add0510c1bef3c18ea7257ec34ce" [[package]] name = "slab" @@ -9811,9 +10141,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" [[package]] name = "smartstring" @@ -9837,11 +10167,11 @@ dependencies = [ [[package]] name = "snafu" -version = "0.9.0" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d4bced6a69f90b2056c03dcff2c4737f98d6fb9e0853493996e1d253ca29c6" +checksum = "e45cb604038abb7b926b679887b3226d8d0f23874b66623625a0454be425a4b7" dependencies = [ - "snafu-derive 0.9.0", + "snafu-derive 0.9.2", ] [[package]] @@ -9853,29 +10183,29 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "snafu-derive" -version = "0.9.0" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54254b8531cafa275c5e096f62d48c81435d1015405a91198ddb11e967301d40" +checksum = "287f59010008f0d7cf5e3b03196d666c1acc46c8d3e9cf34c28a1a7157601e72" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "socket2" -version = "0.6.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -9916,16 +10246,6 @@ dependencies = [ "lock_api", ] -[[package]] -name = "spki" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" -dependencies = [ - "base64ct", - "der 0.6.1", -] - [[package]] name = "spki" version = "0.7.3" @@ -9933,7 +10253,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", - "der 0.7.10", + "der", ] [[package]] @@ -9975,7 +10295,7 @@ checksum = "a6dd45d8fc1c79299bfbb7190e42ccbbdf6a5f52e4a6ad98d92357ea965bd289" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -9986,15 +10306,15 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stacker" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "640c8cdd92b6b12f5bcb1803ca3bbf5ab96e5e6b6b96b9ab77dabe9e880b3190" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" dependencies = [ "cc", - "cfg-if 1.0.4", + "cfg-if", "libc", "psm", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -10027,9 +10347,9 @@ checksum = "e51f1e89f093f99e7432c491c382b88a6860a5adbe6bf02574bf0a08efff1978" [[package]] name = "stop-words" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d68df56303396bcfb639455b3c166804aeb7994005010aab5e9e8a1277b8871d" +checksum = "c1ed527ae13a020ac2404e32746ecee62d632aafe64f8e0df2bb3545ae96f6d1" dependencies = [ "serde_json", ] @@ -10086,7 +10406,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -10098,7 +10418,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -10114,7 +10434,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "332615d90111d8eeaf86a84dc9bbe9f65d0d8c5cf11b4caccedc37754eb0dcfd" dependencies = [ "debugid", - "memmap2 0.9.10", + "memmap2 0.9.12", "stable_deref_trait", "uuid", ] @@ -10149,9 +10469,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.117" +version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" dependencies = [ "proc-macro2", "quote", @@ -10160,9 +10480,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.3" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -10180,13 +10500,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -10195,7 +10515,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "byteorder", "enum-as-inner", "libc", @@ -10209,7 +10529,7 @@ version = "0.30.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "core-foundation-sys", "libc", "ntapi", @@ -10219,15 +10539,16 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.38.4" +version = "0.39.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" +checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" dependencies = [ "libc", "memchr", "ntapi", "objc2-core-foundation", "objc2-io-kit", + "objc2-open-directory", "windows 0.62.2", ] @@ -10237,7 +10558,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -10283,10 +10604,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.2", + "getrandom 0.4.3", "once_cell", - "rustix", - "windows-sys 0.52.0", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "termsize" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f11ff5c25c172608d5b85e2fb43ee9a6d683a7f4ab7f96ae07b3d8b590368fd" +dependencies = [ + "libc", + "winapi", ] [[package]] @@ -10308,7 +10639,7 @@ checksum = "c26ef8b00e4d382e59f6a8ddb3cd790b3a5bb29f21a358a9a69ea2f29f13f27b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -10317,7 +10648,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "944ad38adcbb71eaa682c56bceeb079e4ca82b4b3edc2a0fde5cb297b77dac8d" dependencies = [ - "syn 2.0.117", + "syn 2.0.119", "test-log-core", ] @@ -10332,11 +10663,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -10347,18 +10678,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -10372,21 +10703,20 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", ] [[package]] name = "time" -version = "0.3.47" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "itoa", "num-conv", "powerfmt", "serde_core", @@ -10396,15 +10726,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] name = "time-macros" -version = "0.2.27" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" dependencies = [ "num-conv", "time-core", @@ -10421,9 +10751,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.3" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "serde_core", @@ -10442,18 +10772,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.11.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokenizers" @@ -10473,7 +10794,7 @@ dependencies = [ "monostate", "onig", "paste", - "rand 0.8.6", + "rand 0.8.8", "rayon", "rayon-cond", "regex", @@ -10506,31 +10827,41 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", ] [[package]] name = "tokio-retry" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40f644c762e9d396831ae2f8935c954b0d758c4532e924bead0f666d0c1c8640" +checksum = "4a129d95275ebf4c493ec53bf0f8cd95f5ac161bc4f381700809a54f595d4470" dependencies = [ "pin-project-lite", - "rand 0.10.1", + "rand 0.10.3", "tokio", ] [[package]] name = "tokio-rustls" -version = "0.26.4" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -10538,9 +10869,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.18" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" dependencies = [ "futures-core", "pin-project-lite", @@ -10550,13 +10881,14 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.18" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -10582,39 +10914,80 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d01145a2c788d6aae4cd653afec1e8332534d7d783d01897cefcafe4428de992" dependencies = [ "quote", - "syn 2.0.117", + "syn 2.0.119", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", ] [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" dependencies = [ "serde_core", ] [[package]] name = "toml_edit" -version = "0.25.11+spec-1.1.0" +version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap 2.14.0", - "toml_datetime", + "indexmap 2.14.2", + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_write", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", - "winnow", + "winnow 1.0.4", ] [[package]] name = "toml_parser" -version = "1.1.2+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ - "winnow", + "winnow 1.0.4", ] +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tonic" version = "0.14.6" @@ -10665,7 +11038,7 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap 2.14.0", + "indexmap 2.14.2", "pin-project-lite", "slab", "sync_wrapper", @@ -10682,7 +11055,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ - "bitflags 2.11.1", + "bitflags 2.13.2", "bytes", "http 1.5.0", "http-body 1.1.0", @@ -10695,12 +11068,12 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.10" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68d6fdd9f81c2819c9a8b0e0cd91660e7746a8e6ea2ba7c6b2b057985f6bcb51" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "async-compression", - "bitflags 2.11.1", + "bitflags 2.13.2", "bytes", "futures-core", "futures-util", @@ -10748,7 +11121,7 @@ checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" dependencies = [ "crossbeam-channel", "symlink", - "thiserror 2.0.18", + "thiserror 2.0.21", "time", "tracing-subscriber", ] @@ -10761,7 +11134,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -10824,24 +11197,24 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "twox-hash" -version = "2.1.2" +version = "2.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" dependencies = [ - "rand 0.9.5", + "rand 0.10.3", ] [[package]] name = "typed-path" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" [[package]] name = "typenum" -version = "1.20.0" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "typewit" @@ -10851,27 +11224,27 @@ checksum = "214ca0b2191785cbc06209b9ca1861e048e39b5ba33574b3cedd58363d5bb5f6" [[package]] name = "unicase" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" [[package]] name = "unicode-blocks" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b12e05d9e06373163a9bb6bb8c263c261b396643a99445fe6b9811fd376581b" +checksum = "328edfd6d0bb91a22e592bed3a3b54c7b1f5c92a517f5a7aca24a2caef10c363" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] @@ -10896,9 +11269,15 @@ dependencies = [ [[package]] name = "unicode-segmentation" -version = "1.13.2" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" @@ -10906,12 +11285,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "unicode_categories" version = "0.1.1" @@ -10998,7 +11371,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -11011,6 +11384,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -11035,9 +11414,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -11059,20 +11438,11 @@ dependencies = [ [[package]] name = "wasip2" -version = "1.0.3+wasi-0.2.9" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] @@ -11086,11 +11456,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" dependencies = [ - "cfg-if 1.0.4", + "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", @@ -11099,19 +11469,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11119,48 +11490,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap 2.14.0", - "wasm-encoder", - "wasmparser", -] - [[package]] name = "wasm-streams" version = "0.4.2" @@ -11187,23 +11536,11 @@ dependencies = [ "web-sys", ] -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.11.1", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.98" +version = "0.3.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" dependencies = [ "js-sys", "wasm-bindgen", @@ -11237,9 +11574,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" dependencies = [ "rustls-pki-types", ] @@ -11250,23 +11587,35 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.10", + "webpki-roots 1.0.11", ] [[package]] name = "webpki-roots" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" dependencies = [ "rustls-pki-types", ] [[package]] -name = "whoami" -version = "2.1.2" +name = "which" +version = "6.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "998767ef88740d1f5b0682a9c53c24431453923962269c2db68ee43788c5a40d" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" +dependencies = [ + "either", + "home", + "rustix 0.38.44", + "winsafe", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" dependencies = [ "libc", "libredox", @@ -11307,7 +11656,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -11388,7 +11737,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -11399,7 +11748,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -11447,6 +11796,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -11483,6 +11841,21 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -11525,6 +11898,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -11537,6 +11916,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -11549,6 +11934,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -11573,6 +11964,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -11585,6 +11982,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -11597,6 +12000,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -11609,6 +12018,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -11623,112 +12038,39 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winnow" -version = "1.0.3" +version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" dependencies = [ "memchr", ] [[package]] -name = "wit-bindgen" -version = "0.51.0" +name = "winnow" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" dependencies = [ - "wit-bindgen-rust-macro", + "memchr", ] +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck 0.5.0", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck 0.5.0", - "indexmap 2.14.0", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.11.1", - "indexmap 2.14.0", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap 2.14.0", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "wkb" -version = "0.9.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a120b336c7ad17749026d50427c23d838ecb50cd64aaea6254b5030152f890a9" +checksum = "04ab2f2845abe967a213998446345a1a6fc9a8f318cd88f668a8e507861d13bc" dependencies = [ "byteorder", "geo-traits", @@ -11751,9 +12093,9 @@ dependencies = [ [[package]] name = "writeable" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "wyz" @@ -11766,20 +12108,21 @@ dependencies = [ [[package]] name = "xet-client" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3b8da8cc70aa2e3c500c0400e012df82c656ab9fca47f9f939fffc5afd89aca" +checksum = "15500e5fc9e17be15224f9e34cb07d41fb2805d9dbbf7bd3507c982fd1eb3efd" dependencies = [ "anyhow", "async-trait", "base64 0.22.1", "bytes", + "chrono", "crc32fast", "futures", "http 1.5.0", "hyper", "more-asserts", - "rand 0.10.1", + "rand 0.10.3", "redb", "reqwest 0.13.5", "reqwest-middleware", @@ -11788,13 +12131,14 @@ dependencies = [ "serde_repr", "statrs", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-retry", "tokio_with_wasm", "tracing", "url", "urlencoding", + "uuid", "web-time", "xet-core-structures", "xet-runtime", @@ -11802,9 +12146,9 @@ dependencies = [ [[package]] name = "xet-core-structures" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73503c223783dccc864abde22115e09d12f190448a0baf58ab2c54bc709e2f99" +checksum = "5080d5803c8bf15fa56ef934050a46b225801bad3ea4cb8bb3c46c5c37976516" dependencies = [ "async-trait", "base64 0.22.1", @@ -11814,17 +12158,17 @@ dependencies = [ "countio", "futures", "futures-util", - "getrandom 0.4.2", + "getrandom 0.4.3", "heapify", "itertools 0.14.0", "lz4_flex", "more-asserts", - "rand 0.10.1", + "rand 0.10.3", "regex", "safe-transmute", "serde", "static_assertions", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-util", "tracing", @@ -11835,9 +12179,9 @@ dependencies = [ [[package]] name = "xet-data" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89052ec5dec2187cad30b86af92cc24fd61c4a57a795f1ff7ff5f38d49184eb" +checksum = "1287a1657fb67de846030f6605a9960dcdad401c467b490657e6e909d2e0d1c0" dependencies = [ "anyhow", "async-trait", @@ -11847,12 +12191,12 @@ dependencies = [ "http 1.5.0", "itertools 0.14.0", "more-asserts", - "rand 0.10.1", + "rand 0.10.3", "serde", "serde_json", - "sha2 0.11.0", + "sha2 0.11.1", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-util", "tokio_with_wasm", @@ -11867,9 +12211,9 @@ dependencies = [ [[package]] name = "xet-runtime" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af5c60d5eed38ab4c576f4421bae835e7bd07631fb381705605529d2015c106b" +checksum = "921953c885ce83e02b21e8d26444b75c78c9e83076699ced08d5c6fc1cdb48ac" dependencies = [ "anyhow", "async-trait", @@ -11887,13 +12231,13 @@ dependencies = [ "more-asserts", "oneshot", "pin-project", - "rand 0.10.1", + "rand 0.10.3", "reqwest 0.13.5", "serde", "serde_json", "shellexpand", - "sysinfo 0.38.4", - "thiserror 2.0.18", + "sysinfo 0.39.6", + "thiserror 2.0.21", "tokio", "tokio-util", "tokio_with_wasm", @@ -11918,10 +12262,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" [[package]] -name = "yoke" -version = "0.8.2" +name = "yasna" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -11930,34 +12283,34 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.48" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 2.0.119", ] [[package]] @@ -11971,27 +12324,27 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", "synstructure", ] [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zerotrie" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", "yoke", @@ -12001,9 +12354,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.6" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "serde", "yoke", @@ -12013,13 +12366,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.3" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.9", ] [[package]] @@ -12029,16 +12382,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" dependencies = [ "crc32fast", - "indexmap 2.14.0", + "indexmap 2.14.2", "memchr", "typed-path", ] [[package]] -name = "zmij" -version = "1.0.21" +name = "zlib-rs" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zstd" @@ -12046,7 +12405,7 @@ version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" dependencies = [ - "zstd-safe 7.2.4", + "zstd-safe 7.3.0", ] [[package]] @@ -12060,9 +12419,9 @@ dependencies = [ [[package]] name = "zstd-safe" -version = "7.2.4" +version = "7.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" dependencies = [ "zstd-sys", ] diff --git a/Cargo.toml b/Cargo.toml index 546613ce2..343813b65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,6 @@ [workspace] members = [ + "rust/lancedb/cli", "rust/lancedb", "nodejs", "python", @@ -35,6 +36,7 @@ lance-encoding = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" lance-arrow = { version = "=15.0.0-beta.3", path = "python/vendor/lance-arrow" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" +anyhow = "1" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } arrow-array = "58.0.0" @@ -49,6 +51,7 @@ arrow-flight = { version = "58.0.0", features = ["flight-sql-experimental"] } async-trait = "0" # Smithy JSON 0.63 requires the pre-1.7 Document representation; allow the MSRV pin. aws-smithy-types = ">=1.3.6, <1.7" +base64 = "0.22" bytes = "1" datafusion = { version = "54.0.0", default-features = false } datafusion-catalog = "54.0.0" @@ -64,12 +67,15 @@ half = { "version" = "2.7.1", default-features = false, features = [ "num-traits", ] } futures = "0.3" +hf-hub = { version = "0.4.1", default-features = false } +http = "1" log = "0.4" metrics = "0.24" metrics-util = "0.19" moka = { version = "0.12", features = ["future"] } object_store = "0.14.1" pin-project = "1.0.7" +prost = "0.14" rand = "0.9" snafu = "0.8" url = "2" @@ -79,6 +85,8 @@ regex = "1.10" semver = "1.0.25" serde = "1" serde_json = { version = "1", features = ["preserve_order"] } +serial_test = "3" +sha2 = "0.10" tempfile = "3.5.0" tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } tonic = { version = "0.14", features = ["tls-native-roots", "tls-aws-lc"] } diff --git a/ci/check_cargo_lock.py b/ci/check_cargo_lock.py index 551b76794..94cb10aec 100644 --- a/ci/check_cargo_lock.py +++ b/ci/check_cargo_lock.py @@ -1,4 +1,7 @@ -"""Fail if pruning Cargo.lock did more than remove packages and the edges to them. +"""Fail if pruning Cargo.lock changes pins or adds dependency edges. + +Removing workspace members can disable optional dependency edges even when +their target packages remain in use elsewhere in the packaged workspace. Usage: python ci/check_cargo_lock.py """ @@ -45,7 +48,7 @@ def main() -> None: for package, deps in edges_after.items(): if package not in edges_before: errors.append(f"added or changed {package}") - elif deps != edges_before[package] - removed: + elif not deps <= edges_before[package]: errors.append(f"dependencies of {package[:2]} changed") if errors: sys.exit("error: the prune changed Cargo.lock:\n" + "\n".join(errors)) diff --git a/ci/tests/test_check_cargo_lock.py b/ci/tests/test_check_cargo_lock.py index 82570d087..8ffcebd87 100644 --- a/ci/tests/test_check_cargo_lock.py +++ b/ci/tests/test_check_cargo_lock.py @@ -37,14 +37,15 @@ APP = package("app", "1.0.0", ["libc", "untrusted"], source=None) class CheckCargoLockTest(unittest.TestCase): - def run_check(self, after, header="version = 4\n\n"): + def run_check(self, after, header="version = 4\n\n", before=BEFORE): with tempfile.TemporaryDirectory() as tmp: before_path = Path(tmp, "before.lock") after_path = Path(tmp, "after.lock") - before_path.write_text(BEFORE) + before_path.write_text(before) after_path.write_text(header + after) return subprocess.run( [sys.executable, SCRIPT, before_path, after_path], + check=False, capture_output=True, text=True, ) @@ -81,9 +82,36 @@ class CheckCargoLockTest(unittest.TestCase): self.assertNotEqual(result.returncode, 0) self.assertIn("dependencies of ('libc'", result.stderr) - def test_removed_dependency_fails(self): + def test_removed_dependency_passes(self): app = package("app", "1.0.0", ["untrusted"], source=None) result = self.run_check(app + LIBC + UNTRUSTED) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_disabled_optional_dependency_still_used_elsewhere_passes(self): + # Removing the CLI disables axum's tracing feature, but other SDK + # dependencies still need tracing. Its package therefore stays pinned. + app = package("app", "1.0.0", ["axum", "tracing"], source=None) + tracing = package("tracing", "0.1.44") + before = ( + "version = 4\n\n" + app + package("axum", "0.8.9", ["tracing"]) + tracing + ) + after = app + package("axum", "0.8.9") + tracing + result = self.run_check(after, before=before) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_dependency_redirected_to_an_existing_version_fails(self): + before = ( + "version = 4\n\n" + + package("app", "1.0.0", ["untrusted 0.7.1"], source=None) + + package("untrusted", "0.7.1") + + UNTRUSTED + ) + after = ( + package("app", "1.0.0", ["untrusted 0.9.0"], source=None) + + package("untrusted", "0.7.1") + + UNTRUSTED + ) + result = self.run_check(after, before=before) self.assertNotEqual(result.returncode, 0) self.assertIn("dependencies of ('app'", result.stderr) diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 590e3989e..bb4f2cd4a 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -28,6 +28,9 @@ endpoint, returning results as Arrow record batches: any tool with its own Flight SQL integration. A LanceDB-specific SDK is not required to submit SQL. +From the command line, use `lancedb` to open the [SQL shell](/tools/cli) +or execute a statement or file. + The [SQL reference](/sql#connecting) shows a query from Python. See [SDKs](/basics/sdk) for the LanceDB language clients. diff --git a/docs/web/docs.json b/docs/web/docs.json index 5729dd8eb..871e375f8 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -288,6 +288,12 @@ "deployment/support" ] }, + { + "group": "Tools", + "pages": [ + "tools/cli" + ] + }, { "group": "Concepts", "pages": [ diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx new file mode 100644 index 000000000..97b058bd9 --- /dev/null +++ b/docs/web/tools/cli.mdx @@ -0,0 +1,217 @@ +--- +title: "LanceDB CLI" +sidebarTitle: "Command line" +description: "Connect to LanceDB, run SQL, and manage connection profiles with the lancedb command-line client." +icon: terminal +keywords: ["cli", "command line", "sql", "profiles", "authentication"] +--- + +Use the `lancedb` command-line client to open an interactive SQL shell, run a +statement, or execute a SQL file. SQL requires a running deployment with an +[Arrow Flight SQL endpoint](/basics/sql#sql-is-remote). + +## Install + +With Rust and Git installed, build the CLI from the LanceDB repository: + +```sh +git clone https://github.com/lancedb/lancedb.git +cd lancedb +cargo install --locked --path rust/lancedb/cli +``` + +Check the available options: + +```sh +lancedb --help +``` + +## Connect to a deployment + +Get the Flight SQL endpoint, HTTP API endpoint, database name, and credentials +from your deployment administrator. Create a named profile to save the +connection settings: + +```sh +lancedb profile create production \ + --sql-server-url grpcs://sql.example.com:10025 \ + --http-server-url https://query.example.com \ + --database analytics +``` + +The SQL endpoint executes statements. The HTTP endpoint supports shell commands +that inspect table and index metadata. Replace both example URLs with the +endpoints for your deployment; they may use different hosts or ports. + +For API-key authentication, set the credential in your environment: + +```sh +export LANCEDB_API_KEY="YOUR_API_KEY" +lancedb --profile production +``` + +Use `grpcs://` or `https://` for a TLS-protected SQL connection. A bare +`host:port` or a `grpc://` address selects a plaintext connection. + +### Set the default profile + +```sh +lancedb profile set production +lancedb +``` + + +Running `lancedb` opens the SQL shell when the default profile has a Flight SQL +endpoint. If no endpoint is configured, it prints usage and connection setup +guidance. Command and file execution also require a configured endpoint. + + +To connect to an existing server on localhost, explicitly select the built-in +local profile: + +```sh +lancedb --profile local +``` + +This profile uses Flight SQL on port `10025` and HTTP on port `10024`. + +## Run SQL + +Execute a statement and exit: + +```sh +lancedb --profile production --command 'SELECT 1' --format json +``` + +To execute a file, separate its statements with semicolons. For example, save +the following as `queries.sql`: + +```sql +SELECT COUNT(*) FROM documents; +SELECT id, text FROM documents LIMIT 10; +``` + +Run the file with: + +```sh +lancedb --profile production --file queries.sql +``` + +Quoted strings and comments in SQL files are preserved when statements are +split. `--command` and `--file` are mutually exclusive. + +### Choose an output format + +For query results, `--format` accepts the following values: + +| Format | Output | +| --- | --- | +| `table` | A display table, the default | +| `csv` | Comma-separated values with column headers | +| `json` | A JSON array of rows | +| `ndjson` | One JSON row per line | + +```sh +lancedb --profile production --command 'SELECT id FROM documents' --format csv +``` + +## Use the SQL shell + +End SQL statements with a semicolon. Enter `\?` to see the shell's commands. + +| Command | Purpose | +| --- | --- | +| `\dt` | List tables | +| `\d documents` | Show a table's columns and indexes | +| `\di` | List indexes | +| `\dj` | List jobs | +| `\c analytics` | Connect to another database | +| `\e` | Edit the query buffer in an external editor | +| `\watch 2` | Repeat the last query or listing every two seconds | +| `\q` | Exit the shell | + +Add `+` to `\dt`, `\d`, or `\di` for more detail. Use Ctrl+C to cancel the +current input or stop watching a query, and Ctrl+D to exit. + +Large interactive results use a pager. Set `NO_PAGER=1` to disable paging. + +### Inspect jobs with SQL + +```sh +lancedb --profile production --command 'SHOW JOBS' +lancedb --profile production --command "SHOW ERRORS ON documents FOR JOB 'JOB_ID'" +lancedb --profile production --command "CANCEL JOB 'JOB_ID'" +``` + +See the [job SQL reference](/sql/ddl/job) for syntax and deployment requirements, +and the [SQL reference](/sql) for other supported statements. + +## Manage profiles + +Profiles are stored in `~/.lancedb/config.toml`. The CLI reuses existing +Enterprise profiles and cached OAuth sessions. + +```sh +lancedb profile list +lancedb profile show production +lancedb profile edit production --database staging +lancedb profile delete production +``` + +Use `lancedb profile create NAME` without connection flags for interactive +setup. For a single SQL invocation, flags such as `--database` and +`--sql-server-url` override the selected profile. + +Put each command's flags after that command. For example, use +`lancedb auth login --profile production` or `lancedb profile edit production +--database staging`. + +## Authenticate with OAuth + +To use OAuth, configure an `oidc` table in the selected profile with your +identity provider's settings. For example, add the following to +`~/.lancedb/config.toml` for a device-code login: + +```toml +[profiles.production.oidc] +flow = "device_code" +issuer_url = "https://identity.example.com" +client_id = "YOUR_CLIENT_ID" +scopes = ["openid", "offline_access"] +``` + +Choose one authentication method per profile. An OAuth profile cannot also +contain `api_key` or `oidc_access_token_file`. Environment credentials override +the profile, so clear API-key overrides before connecting with OAuth: + +```sh +unset LANCEDB_API_KEY +lancedb auth login --profile production +lancedb auth status --profile production +lancedb --profile production +``` + +`auth login` follows the profile's OAuth flow. Browser and device-code sessions +cache refresh tokens for later commands. Use `lancedb auth logout --profile +production` to clear the profile's cached session. + +See [authentication](/enterprise/authentication) for identity provider setup and +available authentication methods. + +## Configure TLS + +To trust a private certificate authority, pass its PEM certificate: + +```sh +lancedb --profile production --ca-cert /path/to/ca.pem +``` + +If the server requires mutual TLS, supply both a client certificate and its +PKCS#8 private key. Save these settings in the profile with: + +```sh +lancedb profile edit production \ + --ca-cert /path/to/ca.pem \ + --client-cert /path/to/client.pem \ + --client-key /path/to/client-key.pem +``` diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 9655b1160..264c0be4d 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -8,6 +8,7 @@ repository.workspace = true keywords.workspace = true categories.workspace = true rust-version.workspace = true +exclude = ["cli/**"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] @@ -22,7 +23,7 @@ arrow-ord = { workspace = true } arrow-cast = { workspace = true } arrow-ipc.workspace = true arrow-flight = { workspace = true, optional = true } -prost = { version = "0.14", optional = true } +prost = { workspace = true, optional = true } chrono = { workspace = true } datafusion-catalog.workspace = true datafusion-common.workspace = true @@ -86,16 +87,16 @@ reqwest = { version = "0.13.0", default-features = false, features = [ "system-proxy", ], optional = true } tonic = { workspace = true, optional = true } -http = { version = "1", optional = true } # Matching what is in reqwest +http = { workspace = true, optional = true } # Matching what is in reqwest oauth2 = { workspace = true, optional = true } urlencoding = { version = "2", optional = true } -base64 = { version = "0.22", optional = true } +base64 = { workspace = true, optional = true } fs4 = { version = "0.13", optional = true } webbrowser = { version = "1", optional = true } uuid = { workspace = true, features = ["v5"] } polars-arrow = { version = ">=0.37,<0.40.0", optional = true } polars = { version = ">=0.37,<0.40.0", optional = true } -hf-hub = { version = "0.4.1", optional = true, default-features = false, features = [ +hf-hub = { workspace = true, optional = true, features = [ "rustls-tls", "tokio", "ureq", @@ -106,10 +107,10 @@ candle-nn = { version = "0.9.1", optional = true } tokenizers = { version = "0.19.1", optional = true } semver = { workspace = true } roaring = "0.11.4" -sha2 = "0.10" +sha2.workspace = true [dev-dependencies] -anyhow = "1" +anyhow.workspace = true lance-testing = { workspace = true } # RestAdapter is only used by cfg(test) code. Keep rest-adapter off the # production remote feature so Python wheels do not resolve its Axum 0.7 stack. @@ -130,7 +131,7 @@ datafusion.workspace = true http-body = "1" # Matching reqwest rstest = "0.23.0" test-log = "0.2" -serial_test = "3" +serial_test.workspace = true [target.'cfg(unix)'.dev-dependencies] pprof = { version = "0.14", features = ["flamegraph"] } diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml new file mode 100644 index 000000000..426df0a1f --- /dev/null +++ b/rust/lancedb/cli/Cargo.toml @@ -0,0 +1,52 @@ +[package] +name = "lancedb-cli" +version = "0.1.0" +edition = "2021" +license.workspace = true +repository.workspace = true +publish = false + +[[bin]] +name = "lancedb" +path = "src/main.rs" + +[dependencies] +tempfile.workspace = true +which = "6" +anyhow.workspace = true +arrow-array.workspace = true +arrow-buffer.workspace = true +arrow-cast.workspace = true +arrow-json = "58.0.0" +arrow-schema.workspace = true +async-trait.workspace = true +clap = { version = "4.5.13", features = ["derive", "env"] } +directories = "5" +futures.workspace = true +http.workspace = true +lancedb = { workspace = true, features = ["remote"] } +rustyline = "14" +rustls = { version = "0.23", features = ["ring"] } +serde = { workspace = true, features = ["derive"] } +serde_ignored = "0.1.14" +serde_json.workspace = true +sha2.workspace = true +sqlparser = { version = "0.62", default-features = false, features = ["std"] } +termsize = "0.1" +tokio = { workspace = true, features = ["full"] } +toml = "0.8" +tracing.workspace = true +unicode-width = "0.2" + +[dev-dependencies] +arrow-flight.workspace = true +prost.workspace = true +rcgen = "0.12" +tokio-stream = { version = "0.1", features = ["net"] } +half.workspace = true +axum = "0.8" +base64.workspace = true +csv = "1" +reqwest = { version = "0.12", features = ["json"] } +tonic.workspace = true +url.workspace = true diff --git a/rust/lancedb/cli/src/auth.rs b/rust/lancedb/cli/src/auth.rs new file mode 100644 index 000000000..090bfd1d8 --- /dev/null +++ b/rust/lancedb/cli/src/auth.rs @@ -0,0 +1,419 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! CLI configuration and transport adapters for LanceDB's OAuth implementation. + +use std::collections::HashMap; +use std::path::PathBuf; + +use anyhow::{anyhow, ensure, Context, Result}; +use clap::{Args, Subcommand}; +use lancedb::remote::{ + AuthorizationCodeOptions, ClientAuthMethod, HeaderProvider, OAuthConfig, OAuthFlow, + OAuthHeaderProvider, OAuthSession, TokenCacheOptions, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tokio::sync::OnceCell; + +use crate::server_config::{Authentication, Config, DEFAULT_PROFILE}; + +const CLIENT_SECRET_ENV: &str = "LANCEDB_OIDC_CLIENT_SECRET"; +pub const OIDC_CREDENTIAL_HEADER: &str = "x-lancedb-credential-type"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OidcFlow { + ClientCredentials, + AuthorizationCode, + DeviceCode, +} + +impl std::fmt::Display for OidcFlow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::ClientCredentials => "client_credentials", + Self::AuthorizationCode => "authorization_code", + Self::DeviceCode => "device_code", + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OidcClientAuthMethod { + None, + ClientSecretBasic, + ClientSecretPost, +} + +impl From for ClientAuthMethod { + fn from(method: OidcClientAuthMethod) -> Self { + match method { + OidcClientAuthMethod::None => Self::None, + OidcClientAuthMethod::ClientSecretBasic => Self::ClientSecretBasic, + OidcClientAuthMethod::ClientSecretPost => Self::ClientSecretPost, + } + } +} + +/// Nonsecret configuration stored inside a connection profile. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OidcConfig { + pub flow: OidcFlow, + pub issuer_url: String, + pub client_id: String, + pub scopes: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_secret_file: Option, + /// When omitted, the SDK selects authentication based on the client secret. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_auth_method: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resource: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub audience: Option, + /// Registered loopback callback URI for authorization-code login. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub redirect_uri: Option, + /// Defaults to the SDK's callback port (8400). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub callback_port: Option, + /// Defaults to the SDK's refresh buffer (300 seconds). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_buffer_secs: Option, +} + +/// One SDK provider is shared by all transports using the resolved profile. +#[derive(Debug)] +pub struct ManagedOidc { + config: OidcConfig, + cache_dir: PathBuf, + provider: OnceCell, +} + +impl PartialEq for ManagedOidc { + fn eq(&self, other: &Self) -> bool { + // Acquired tokens do not change which authentication configuration was selected. + self.config == other.config && self.cache_dir == other.cache_dir + } +} +impl Eq for ManagedOidc {} + +/// A resolved credential, with no provider state attached. +pub enum Credential { + ApiKey(String), + OidcAccessToken(String), +} + +impl std::fmt::Debug for Credential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::ApiKey(_) => "ApiKey()", + Self::OidcAccessToken(_) => "OidcAccessToken()", + }) + } +} + +impl Credential { + pub fn headers(&self) -> Result { + let mut headers = http::HeaderMap::new(); + let (name, value) = match self { + Self::ApiKey(key) => ("x-api-key", key.clone()), + Self::OidcAccessToken(token) => { + headers.insert( + OIDC_CREDENTIAL_HEADER, + http::HeaderValue::from_static("oidc"), + ); + ("authorization", format!("Bearer {token}")) + } + }; + let mut value = http::HeaderValue::from_str(&value) + .map_err(|_| anyhow!("Invalid authentication credential: not a valid HTTP header"))?; + value + .to_str() + .map_err(|_| anyhow!("Invalid authentication credential: expected an ASCII header"))?; + value.set_sensitive(true); + headers.insert(name, value); + Ok(headers) + } +} + +impl Authentication { + pub async fn headers(&self) -> Result { + match self { + Self::ApiKey(key) => Credential::ApiKey(key.clone()).headers(), + Self::OidcAccessToken(token) => Credential::OidcAccessToken(token.clone()).headers(), + Self::OidcAccessTokenFile(path) => { + let token = tokio::fs::read_to_string(path).await.with_context(|| { + format!("Failed to read OIDC access token file {}", path.display()) + })?; + let token = token.trim(); + ensure!(!token.is_empty(), "OIDC access token file is empty"); + Credential::OidcAccessToken(token.to_owned()).headers() + } + Self::ManagedOidc(session) => session.headers().await, + } + } +} + +#[async_trait::async_trait] +impl HeaderProvider for Authentication { + async fn get_headers(&self) -> lancedb::Result> { + let headers = self + .headers() + .await + .map_err(|error| lancedb::Error::Runtime { + message: format!("Authentication failed: {error:#}"), + })?; + Ok(headers + .iter() + .map(|(key, value)| { + ( + key.as_str().to_owned(), + value + .to_str() + .expect("validated credential header") + .to_owned(), + ) + }) + .collect()) + } +} + +impl ManagedOidc { + pub fn for_profile(profile: &str, config: OidcConfig) -> Result { + let root = Config::default_config_path()?; + // Profile names are arbitrary strings; hashing prevents paths from escaping the cache. + let profile_key = format!("{:x}", Sha256::digest(profile.as_bytes())); + Self::new( + config, + root.parent().unwrap().join("auth").join(profile_key), + ) + } + + fn new(config: OidcConfig, cache_dir: PathBuf) -> Result { + ensure!( + !config.client_id.trim().is_empty(), + "OIDC client_id cannot be empty" + ); + ensure!( + !config.scopes.is_empty(), + "OIDC scopes must contain at least one scope" + ); + ensure!( + config.flow == OidcFlow::AuthorizationCode + || (config.redirect_uri.is_none() && config.callback_port.is_none()), + "redirect_uri and callback_port require flow = authorization_code" + ); + Ok(Self { + config, + cache_dir, + provider: OnceCell::new(), + }) + } + + pub fn flow(&self) -> &OidcFlow { + &self.config.flow + } + + async fn sdk_config(&self) -> Result { + let flow = match self.config.flow { + OidcFlow::ClientCredentials => OAuthFlow::ClientCredentials, + OidcFlow::DeviceCode => OAuthFlow::DeviceCode, + OidcFlow::AuthorizationCode => { + let mut options = AuthorizationCodeOptions::new(); + if let Some(uri) = &self.config.redirect_uri { + options = options.redirect_uri(uri); + } + if let Some(port) = self.config.callback_port { + options = options.callback_port(port); + } + OAuthFlow::AuthorizationCode(options) + } + }; + Ok(OAuthConfig { + issuer_url: self.config.issuer_url.clone(), + client_id: self.config.client_id.clone(), + client_secret: self.client_secret().await?, + scopes: self.config.scopes.clone(), + resource: self.config.resource.clone(), + audience: self.config.audience.clone(), + flow, + client_auth_method: self.config.client_auth_method.map(Into::into), + refresh_buffer_secs: self.config.refresh_buffer_secs, + token_cache: (self.config.flow != OidcFlow::ClientCredentials) + .then(|| TokenCacheOptions::new().cache_dir(&self.cache_dir)), + }) + } + + async fn provider(&self) -> Result<&OAuthHeaderProvider> { + self.provider + .get_or_try_init(|| async { + OAuthHeaderProvider::new(self.sdk_config().await?).map_err(sdk_error) + }) + .await + } + + async fn session(&self) -> Result { + OAuthSession::new(self.sdk_config().await?).map_err(sdk_error) + } + + async fn headers(&self) -> Result { + let values = self + .provider() + .await? + .get_headers() + .await + .map_err(sdk_error)?; + let mut headers = http::HeaderMap::new(); + for (name, value) in values { + let name = http::HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| anyhow!("Invalid authentication header name"))?; + let mut value = http::HeaderValue::from_str(&value).map_err(|_| { + anyhow!("Invalid authentication credential: not a valid HTTP header") + })?; + value.to_str().map_err(|_| { + anyhow!("Invalid authentication credential: expected an ASCII header") + })?; + if name == http::header::AUTHORIZATION || name == "x-api-key" { + value.set_sensitive(true); + } + headers.insert(name, value); + } + Ok(headers) + } + + async fn client_secret(&self) -> Result> { + if let Some(secret) = std::env::var_os(CLIENT_SECRET_ENV) { + let secret = secret + .into_string() + .map_err(|_| anyhow!("{CLIENT_SECRET_ENV} must be UTF-8"))?; + ensure!(!secret.is_empty(), "{CLIENT_SECRET_ENV} cannot be empty"); + return Ok(Some(secret)); + } + let Some(path) = self.config.client_secret_file.as_ref() else { + ensure!( + self.config.flow != OidcFlow::ClientCredentials, + "Client credentials require LANCEDB_OIDC_CLIENT_SECRET or oidc.client_secret_file" + ); + return Ok(None); + }; + let secret = tokio::fs::read_to_string(path) + .await + .context("Failed to read OIDC client secret file")?; + let secret = secret.trim(); + ensure!(!secret.is_empty(), "OIDC client secret file is empty"); + Ok(Some(secret.to_owned())) + } +} + +fn sdk_error(error: lancedb::Error) -> anyhow::Error { + // SDK runtime errors can contain provider response bodies and credentials. + // Configuration errors are local; never attach the original runtime error as a cause. + match error { + lancedb::Error::InvalidInput { message } => anyhow!("Invalid OIDC configuration: {message}"), + _ => anyhow!("OIDC authentication failed; check the issuer, client credentials, scopes, and provider availability. For a cached interactive session, try lancedb auth logout followed by lancedb auth login."), + } +} + +#[derive(Args, Debug)] +pub struct AuthArgs { + #[command(subcommand)] + pub command: AuthCommand, +} + +#[derive(Subcommand, Debug)] +pub enum AuthCommand { + /// Log in using the profile's OAuth flow; browser/device sessions cache refresh tokens. + Login(ProfileArgs), + /// Report whether an interactive session is cached, without contacting the provider. + Status(ProfileArgs), + /// Clear the profile's local interactive session; does not revoke provider credentials. + Logout(ProfileArgs), +} + +#[derive(Args, Debug)] +pub struct ProfileArgs { + #[arg(short = 'p', long, value_name = "PROFILE")] + pub profile: Option, +} + +pub async fn run(args: AuthArgs, parent_profile: Option) -> Result<()> { + let profile_args = match &args.command { + AuthCommand::Login(args) | AuthCommand::Status(args) | AuthCommand::Logout(args) => args, + }; + let config = Config::load_default()?; + let profile_name = profile_args + .profile + .clone() + .or(parent_profile) + .or(config.default_profile.clone()) + .unwrap_or_else(|| DEFAULT_PROFILE.to_owned()); + let profile = config + .profiles + .get(&profile_name) + .context("Profile does not exist")?; + profile.validate_authentication()?; + let oidc = profile + .oidc + .clone() + .context("Profile has no managed OIDC configuration")?; + let managed = ManagedOidc::for_profile(&profile_name, oidc)?; + match args.command { + AuthCommand::Login(_) => { + if managed.config.flow == OidcFlow::ClientCredentials { + managed.headers().await?; + println!("Authenticated service account for profile '{profile_name}'. Access tokens are cached only within each process."); + } else { + let status = managed.session().await?.login().await.map_err(sdk_error)?; + println!( + "Authenticated profile '{profile_name}' using {}", + managed.flow() + ); + if !status.refreshable { + eprintln!("The provider returned no refresh token; later commands will need another login. Check the provider's offline-access scope and consent settings."); + } + } + if [ + "LANCEDB_API_KEY", + "LANCEDB_OIDC_ACCESS_TOKEN", + "LANCEDB_OIDC_ACCESS_TOKEN_FILE", + ] + .iter() + .any(|key| std::env::var_os(key).is_some()) + { + eprintln!("Authentication environment overrides are set; ordinary commands will use those credentials instead of this session."); + } + } + AuthCommand::Status(_) => { + if managed.config.flow == OidcFlow::ClientCredentials { + println!("Profile '{profile_name}' uses client credentials; no persistent session is stored."); + } else { + let status = managed.session().await?.status().await.map_err(sdk_error)?; + println!( + "Profile '{profile_name}' uses {}; cached refresh token: {}", + managed.flow(), + if status.refreshable { + "present" + } else { + "not present" + } + ); + } + } + AuthCommand::Logout(_) => { + if managed.config.flow == OidcFlow::ClientCredentials { + println!("Profile '{profile_name}' uses client credentials; no persistent session to clear. Configured credentials remain usable."); + } else { + managed.session().await?.logout().await.map_err(sdk_error)?; + println!("Cleared the local session for profile '{profile_name}'. Provider credentials remain valid."); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/rust/lancedb/cli/src/auth/tests.rs b/rust/lancedb/cli/src/auth/tests.rs new file mode 100644 index 000000000..5d626f5e6 --- /dev/null +++ b/rust/lancedb/cli/src/auth/tests.rs @@ -0,0 +1,417 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use super::*; +use axum::{ + extract::{Form, Query}, + http::{HeaderMap, StatusCode}, + response::Redirect, + routing::{get, post}, + Json, Router, +}; +use base64::Engine; +use std::fs; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tempfile::TempDir; + +struct Provider { + config: OidcConfig, + requests: Arc>>>, + server: tokio::task::JoinHandle<()>, + dir: TempDir, +} + +impl Drop for Provider { + fn drop(&mut self) { + self.server.abort(); + } +} + +impl Provider { + async fn start(flow: OidcFlow, lifetime: u64) -> Self { + let dir = tempfile::tempdir().unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let issuer = format!("http://{}", listener.local_addr().unwrap()); + let secret_file = dir.path().join("secret"); + fs::write(&secret_file, "test-secret\n").unwrap(); + let config = OidcConfig { + client_auth_method: None, + client_secret_file: (flow == OidcFlow::ClientCredentials).then_some(secret_file), + flow, + issuer_url: issuer.clone(), + client_id: "cli-client".into(), + scopes: vec!["openid".into(), "offline_access".into()], + resource: Some("https://api.example.com/a?x=1&y=two".into()), + audience: Some("lancedb + audience".into()), + redirect_uri: None, + callback_port: None, + refresh_buffer_secs: Some(0), + }; + let metadata = serde_json::json!({ + "issuer": issuer, + "token_endpoint": format!("{issuer}/token"), + "authorization_endpoint": format!("{issuer}/authorize"), + "device_authorization_endpoint": format!("{issuer}/device"), + }); + let device = serde_json::json!({ + "device_code": "device-code", "user_code": "CLI-CODE", + "verification_uri": format!("{issuer}/verify"), "expires_in": 60, "interval": 1, + }); + let requests = Arc::new(Mutex::new(Vec::new())); + let device_requests = requests.clone(); + let auth_requests = requests.clone(); + let token_requests = requests.clone(); + let app = Router::new() + .route("/.well-known/openid-configuration", get(move || { + let metadata = metadata.clone(); + async move { Json(metadata) } + })) + .route("/verify", get(|| async { "verified" })) + .route("/device", post(move |Form(form): Form>| { + let device = device.clone(); + device_requests.lock().unwrap().push(form); + async move { Json(device) } + })) + .route("/authorize", get(move |Query(form): Query>| { + assert_eq!(form["code_challenge_method"], "S256"); + let mut redirect = url::Url::parse(&form["redirect_uri"]).unwrap(); + redirect.query_pairs_mut().append_pair("code", "auth-code").append_pair("state", &form["state"]); + auth_requests.lock().unwrap().push(form); + async move { Redirect::to(redirect.as_str()) } + })) + .route("/token", post(move |headers: HeaderMap, Form(form): Form>| { + let mut requests = token_requests.lock().unwrap(); + requests.push(form.clone()); + let number = requests.iter().filter(|request| request.contains_key("grant_type")).count(); + async move { + if form.get("grant_type").is_some_and(|grant| grant == "client_credentials") + && headers.get("authorization").and_then(|value| value.to_str().ok()) + != Some(format!("Basic {}", base64::engine::general_purpose::STANDARD.encode("cli-client:test-secret")).as_str()) { + return (StatusCode::UNAUTHORIZED, Json(serde_json::json!({ + "error": "invalid_client", "error_description": "private-token test-secret invalid-secret" + }))); + } + (StatusCode::OK, Json(serde_json::json!({ + "access_token": format!("token-{number}"), "token_type": "Bearer", "expires_in": lifetime, + "refresh_token": "private-refresh-token", + }))) + } + })); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + Self { + config, + requests, + server, + dir, + } + } + + fn managed(&self) -> ManagedOidc { + ManagedOidc::new(self.config.clone(), self.dir.path().join("cache")).unwrap() + } + + fn assert_targets(&self) { + for request in self.requests.lock().unwrap().iter() { + assert_eq!(request.get("resource"), self.config.resource.as_ref()); + assert_eq!(request.get("audience"), self.config.audience.as_ref()); + } + } + + async fn child(&self, action: &str) -> std::process::Output { + let executable = std::env::current_exe().unwrap(); + let mut command = tokio::process::Command::new(&executable); + command + .args([ + "--exact", + "auth::tests::session_process_helper", + "--nocapture", + ]) + .env("LANCEDB_TEST_AUTH_ACTION", action) + .env( + "LANCEDB_TEST_AUTH_CONFIG", + serde_json::to_string(&self.config).unwrap(), + ) + .env("LANCEDB_TEST_AUTH_CACHE", self.dir.path().join("cache")) + .env_remove(CLIENT_SECRET_ENV); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let browser = self.dir.path().join("browser"); + fs::write(&browser, "#!/bin/sh\nLANCEDB_TEST_BROWSER_URL=\"$1\" exec \"$LANCEDB_TEST_AUTH_EXE\" --exact auth::tests::browser_process_helper --nocapture\n").unwrap(); + fs::set_permissions(&browser, fs::Permissions::from_mode(0o700)).unwrap(); + command + .env("LANCEDB_OAUTH_BROWSER", browser) + .env("LANCEDB_TEST_AUTH_EXE", executable); + } + let output = command.output().await.unwrap(); + assert!( + output.status.success(), + "stdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let output_text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(!output_text.contains("private-refresh-token")); + output + } +} + +#[tokio::test] +async fn sdk_provider_is_shared_and_renews_service_tokens_in_memory() { + let fixture = Provider::start(OidcFlow::ClientCredentials, 1).await; + let authentication = Authentication::ManagedOidc(Arc::new(fixture.managed())); + let cloned = authentication.clone(); + let (first, second) = tokio::join!(authentication.headers(), cloned.headers()); + assert_eq!(first.unwrap()["authorization"], "Bearer token-1"); + assert_eq!(second.unwrap()["authorization"], "Bearer token-1"); + assert_eq!(fixture.requests.lock().unwrap().len(), 1); + tokio::time::sleep(Duration::from_millis(1100)).await; + let headers = authentication.headers().await.unwrap(); + assert_eq!(headers["authorization"], "Bearer token-2"); + assert_eq!(headers[OIDC_CREDENTIAL_HEADER], "oidc"); + assert!(headers["authorization"].is_sensitive()); + assert!(!format!("{headers:?}").contains("token-2")); + assert!(!fixture.dir.path().join("cache").exists()); + fixture.assert_targets(); +} + +#[tokio::test] +async fn sdk_provider_errors_do_not_expose_response_bodies() { + let fixture = Provider::start(OidcFlow::ClientCredentials, 3600).await; + fs::write( + fixture.config.client_secret_file.as_ref().unwrap(), + "invalid-secret", + ) + .unwrap(); + let error = fixture.managed().headers().await.unwrap_err(); + let rendered = format!("{error:#} {error:?}"); + assert!(rendered.contains("OIDC authentication failed")); + for secret in ["private-token", "test-secret", "invalid-secret"] { + assert!(!rendered.contains(secret)); + } +} + +#[tokio::test] +async fn missing_secret_does_not_fall_back() { + let fixture = Provider::start(OidcFlow::ClientCredentials, 3600).await; + fs::remove_file(fixture.config.client_secret_file.as_ref().unwrap()).unwrap(); + assert!(fixture.managed().headers().await.is_err()); + assert!(fixture.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn sdk_provider_reads_updated_external_token_files() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("token"); + fs::write(&path, "first-token\n").unwrap(); + let provider = Authentication::OidcAccessTokenFile(path.clone()); + assert_eq!( + provider.get_headers().await.unwrap()["authorization"], + "Bearer first-token" + ); + fs::write(&path, "second-token\n").unwrap(); + assert_eq!( + provider.get_headers().await.unwrap()["authorization"], + "Bearer second-token" + ); + fs::write(&path, " \n").unwrap(); + assert!(provider.get_headers().await.is_err()); + fs::write(&path, "token\r\ninjected: header").unwrap(); + assert!(provider.get_headers().await.is_err()); +} + +#[tokio::test] +async fn profile_client_auth_method_round_trips_and_reaches_sdk() { + let profile = r#" +flow = "authorization_code" +issuer_url = "http://localhost:18888/realms/lancedb" +client_id = "cli-client" +scopes = ["openid"] +"#; + for (value, expected) in [ + (None, None), + (Some("none"), Some(ClientAuthMethod::None)), + ( + Some("client_secret_basic"), + Some(ClientAuthMethod::ClientSecretBasic), + ), + ( + Some("client_secret_post"), + Some(ClientAuthMethod::ClientSecretPost), + ), + ] { + let text = match value { + Some(value) => format!("{profile}\nclient_auth_method = {value:?}\n"), + None => profile.to_owned(), + }; + let config: OidcConfig = toml::from_str(&text).unwrap(); + let serialized = toml::to_string(&config).unwrap(); + assert_eq!(serialized.contains("client_auth_method"), value.is_some()); + assert_eq!(toml::from_str::(&serialized).unwrap(), config); + let dir = tempfile::tempdir().unwrap(); + let managed = ManagedOidc::new(config, dir.path().join("cache")).unwrap(); + assert_eq!( + managed.sdk_config().await.unwrap().client_auth_method, + expected + ); + } + assert!(toml::from_str::(&format!( + "{profile}\nclient_auth_method = \"unsupported\"\n" + )) + .is_err()); +} + +#[tokio::test] +async fn sdk_rejects_public_client_auth_with_a_secret_before_requesting_tokens() { + let mut fixture = Provider::start(OidcFlow::ClientCredentials, 3600).await; + fixture.config.client_auth_method = Some(OidcClientAuthMethod::None); + assert!(fixture.managed().provider().await.is_err()); + assert!(fixture.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn sdk_config_preserves_profile_options() { + let mut fixture = Provider::start(OidcFlow::AuthorizationCode, 3600).await; + fixture.config.callback_port = Some(9123); + fixture.config.redirect_uri = Some("http://127.0.0.1:9123/cli".into()); + let config = fixture.managed().sdk_config().await.unwrap(); + assert_eq!(config.resource, fixture.config.resource); + assert_eq!(config.audience, fixture.config.audience); + assert_eq!(config.scopes, fixture.config.scopes); + assert_eq!(config.refresh_buffer_secs, Some(0)); + assert_eq!( + config.token_cache.unwrap().cache_dir, + Some(fixture.dir.path().join("cache")) + ); + let OAuthFlow::AuthorizationCode(options) = config.flow else { + panic!("expected browser flow") + }; + assert!(options.use_pkce); + assert_eq!(options.callback_port, Some(9123)); + assert_eq!(options.redirect_uri, fixture.config.redirect_uri); + fixture.config.flow = OidcFlow::DeviceCode; + assert!(ManagedOidc::new(fixture.config.clone(), fixture.dir.path().join("cache")).is_err()); +} + +#[tokio::test] +async fn profile_caches_are_isolated_without_creating_directories() { + let fixture = Provider::start(OidcFlow::DeviceCode, 3600).await; + let first = ManagedOidc::for_profile("a/../b", fixture.config.clone()).unwrap(); + let second = ManagedOidc::for_profile("b", fixture.config.clone()).unwrap(); + assert_ne!(first.cache_dir, second.cache_dir); + assert_eq!(first.cache_dir.parent(), second.cache_dir.parent()); + assert_eq!(first.cache_dir.file_name().unwrap().len(), 64); +} + +#[cfg(unix)] +#[tokio::test] +async fn sdk_interactive_sessions_survive_processes_and_logout() { + for flow in [OidcFlow::AuthorizationCode, OidcFlow::DeviceCode] { + let mut fixture = Provider::start(flow, 3600).await; + if fixture.config.flow == OidcFlow::AuthorizationCode { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + fixture.config.callback_port = Some(listener.local_addr().unwrap().port()); + } + // Ordinary requests trigger acquisition, without an explicit login first. + fixture.child("fetch").await; + let original_requests = fixture.requests.lock().unwrap().len(); + fixture.child("fetch").await; + { + let requests = fixture.requests.lock().unwrap(); + assert_eq!(requests.len(), original_requests + 1); + assert_eq!(requests.last().unwrap()["grant_type"], "refresh_token"); + } + fixture.child("status").await; + fixture.child("logout").await; + assert!( + !fixture + .managed() + .session() + .await + .unwrap() + .status() + .await + .unwrap() + .refreshable + ); + fixture.child("login").await; + fixture.child("status").await; + fixture.assert_targets(); + } +} + +#[tokio::test] +async fn session_process_helper() { + let Ok(action) = std::env::var("LANCEDB_TEST_AUTH_ACTION") else { + return; + }; + let config = serde_json::from_str(&std::env::var("LANCEDB_TEST_AUTH_CONFIG").unwrap()).unwrap(); + let managed = ManagedOidc::new( + config, + std::env::var_os("LANCEDB_TEST_AUTH_CACHE").unwrap().into(), + ) + .unwrap(); + match action.as_str() { + "fetch" => { + managed.headers().await.unwrap(); + } + "login" => { + assert!( + managed + .session() + .await + .unwrap() + .login() + .await + .unwrap() + .refreshable + ); + } + "status" => { + assert!( + managed + .session() + .await + .unwrap() + .status() + .await + .unwrap() + .refreshable + ); + } + "logout" => { + assert!( + managed + .session() + .await + .unwrap() + .logout() + .await + .unwrap() + .removed + ); + } + _ => panic!("unknown action"), + } +} + +#[tokio::test] +async fn browser_process_helper() { + let Ok(url) = std::env::var("LANCEDB_TEST_BROWSER_URL") else { + return; + }; + reqwest::Client::new() + .get(url) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); +} diff --git a/rust/lancedb/cli/src/cli.rs b/rust/lancedb/cli/src/cli.rs new file mode 100644 index 000000000..aa2b4c5d4 --- /dev/null +++ b/rust/lancedb/cli/src/cli.rs @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::server_config::{ConnectionArgs, ResolvedConnection}; +use anyhow::{bail, Context, Result}; +use clap::{CommandFactory, Parser, Subcommand}; + +/// Public client commands. Runtime and administrative commands live in Enterprise. +#[derive(Parser, Debug)] +#[command( + name = "lancedb", + version, + about = "LanceDB command-line client", + args_conflicts_with_subcommands = true +)] +pub struct Args { + #[command(subcommand)] + pub command: Option, + /// SQL options used when no subcommand is given. These are local to the + /// default SQL invocation, so other subcommands use their own options. + #[command(flatten)] + pub sql: SqlArgs, +} + +#[derive(Subcommand, Debug)] +pub enum Commands { + /// Manage OAuth login and cached interactive sessions + Auth(crate::auth::AuthArgs), + /// Manage connection profiles + Profile(crate::profile::ProfileArgs), + /// Run SQL or open an interactive shell against a remote server + Sql(SqlArgs), +} + +#[derive(clap::Args, Debug)] +pub struct SqlArgs { + #[command(flatten)] + pub connection: ConnectionArgs, + /// Execute SQL and exit + #[arg(short = 'c', long = "command", conflicts_with = "file")] + pub command_string: Option, + /// Execute SQL commands from a file and exit + #[arg(short = 'f', long)] + pub file: Option, + /// Output format: table, csv, json, ndjson + #[arg(long, default_value = "table")] + pub format: String, +} + +const SQL_ENDPOINT_HELP: &str = "No Flight SQL endpoint is configured. Use --sql-server-url, \ + select a profile with sql_server_url, or use --profile local for localhost."; + +pub async fn run_sql(args: SqlArgs) -> Result<()> { + let connection = args.connection.resolve_sql()?.context(SQL_ENDPOINT_HELP)?; + run_sql_with_connection(args, connection).await +} + +async fn run_sql_with_connection(args: SqlArgs, connection: ResolvedConnection) -> Result<()> { + if let Some(file) = args.file { + crate::client::run_client_script_with_writer( + &connection, + std::fs::read_to_string(file)?, + args.format, + None, + ) + .await + } else if let Some(sql) = args.command_string { + crate::client::run_client_command_with_writer(&connection, sql, args.format, None).await + } else { + crate::client::run_client_with_writer(&connection, None).await + } +} + +pub async fn run(args: Args) -> Result<()> { + match args.command { + None => match args.sql.connection.resolve_sql()? { + Some(connection) => run_sql_with_connection(args.sql, connection).await, + None if args.sql.command_string.is_none() + && args.sql.file.is_none() + && args.sql.connection.profile.is_none() => + { + println!("{SQL_ENDPOINT_HELP}\n"); + Args::command().print_help()?; + println!(); + Ok(()) + } + None => bail!(SQL_ENDPOINT_HELP), + }, + Some(Commands::Auth(args)) => crate::auth::run(args, None).await, + Some(Commands::Profile(args)) => crate::profile::run_profile_command(args).await, + Some(Commands::Sql(args)) => run_sql(args).await, + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn sql_is_the_default_command() { + let args = Args::try_parse_from(["lancedb"]).unwrap(); + assert!(args.command.is_none()); + assert_eq!(args.sql.format, "table"); + assert!(args.sql.command_string.is_none()); + assert!(args.sql.file.is_none()); + assert!(matches!( + Args::try_parse_from(["lancedb", "sql"]).unwrap().command, + Some(Commands::Sql(_)) + )); + let args = Args::try_parse_from([ + "lancedb", + "--profile", + "production", + "--command", + "SELECT 1", + "--format", + "json", + ]) + .unwrap(); + assert!(args.command.is_none()); + assert_eq!(args.sql.connection.profile.as_deref(), Some("production")); + assert_eq!(args.sql.command_string.as_deref(), Some("SELECT 1")); + assert_eq!(args.sql.format, "json"); + let args = Args::try_parse_from(["lancedb", "--file", "queries.sql"]).unwrap(); + assert_eq!(args.sql.file.as_deref(), Some("queries.sql")); + } + + #[test] + fn default_sql_options_do_not_apply_to_subcommands() { + for args in [ + vec!["lancedb", "--format", "json", "profile", "list"], + vec!["lancedb", "--profile", "production", "profile", "list"], + vec!["lancedb", "--command", "SELECT 1", "profile", "list"], + vec!["lancedb", "profile", "list", "--command", "SELECT 1"], + vec!["lancedb", "profile", "list", "--file", "queries.sql"], + vec!["lancedb", "-c", "SELECT 1", "-f", "query.sql"], + vec!["lancedb", "sql", "-c", "SELECT 1", "-f", "query.sql"], + ] { + assert!(Args::try_parse_from(&args).is_err(), "{args:?}"); + } + assert!(Args::try_parse_from(["lancedb", "profile", "list"]).is_ok()); + } + + #[test] + fn excluded_commands_are_rejected() { + for command in [ + "server", + "admin", + "bench", + "service", + "pe", + "agent", + "management", + "preflight", + "run", + "function-worker", + "job", + "acl", + "load", + ] { + assert!( + Args::try_parse_from(["lancedb", command]).is_err(), + "{command}" + ); + } + } +} diff --git a/rust/lancedb/cli/src/client.rs b/rust/lancedb/cli/src/client.rs new file mode 100644 index 000000000..34035f3c1 --- /dev/null +++ b/rust/lancedb/cli/src/client.rs @@ -0,0 +1,2110 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::formatter::{OutputFormat, QueryResult, ResultFormatter}; +use crate::server_config::{ + parse_endpoint, parse_grpc_endpoint, Authentication, ResolvedConnection, DEFAULT_HTTP_PORT, + DEFAULT_SQL_PORT, +}; +use crate::sql_executor::SdkSqlExecutor; +use crate::sql_executor::{SqlQueryExecutor, SqlResult}; +use anyhow::{anyhow, Context, Result}; +use arrow_schema::Schema; +use directories::ProjectDirs; +use futures::TryStreamExt; +use lancedb::listing::ListingOptions; +use rustyline::completion::{Completer, Pair}; +use rustyline::error::ReadlineError; +use rustyline::highlight::Highlighter; +use rustyline::hint::Hinter; +use rustyline::validate::Validator; +use rustyline::{Editor, Helper}; +use sqlparser::dialect::{Dialect, GenericDialect}; +use sqlparser::tokenizer::{Location, Token, Tokenizer}; +use std::io::{self, Write}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tempfile::NamedTempFile; +use tokio::signal; + +const LANCEDB_ASCII_ART: &str = r#" _ ____ ____ +| | __ _ _ __ ___ ___| _ \| __ ) +| | / _` | '_ \ / __/ _ \ | | | _ \ +| |__| (_| | | | | (_| __/ |_| | |_) | +|_____\__,_|_| |_|\___\___|____/|____/ + "#; + +/// Information about a database table +#[derive(Debug, Clone)] +pub struct TableInfo { + pub name: String, + pub schema: Arc, + pub row_count: Option, + pub size_bytes: Option, + pub num_indices: Option, + pub num_fragments: Option, +} + +/// Information about an index +#[derive(Debug, Clone, serde::Serialize)] +pub struct IndexInfo { + pub name: String, + pub table_name: String, + pub index_type: String, + pub columns: Vec, +} + +/// Statistics about an index +#[derive(Debug, Clone)] +pub struct IndexStats { + pub num_indexed_rows: u64, + pub num_unindexed_rows: u64, + pub distance_type: Option, +} + +/// Result of executing a metacommand +enum MetaCommandResult { + /// Command was handled normally, continue REPL loop + Handled, + /// Replace the current input line with new content (for \e) + ReplaceInput(String), +} + +/// The main client structure using the new architecture +pub struct LanceDBClient { + editor: Editor, + history_path: PathBuf, + sql_executor: S, + sql_connected: bool, + connection: Option>, + formatter: ResultFormatter, + current_database: Option, + connection_info: Option, + interactive_mode: bool, + authentication: Authentication, + last_query: Option, + /// The last re-runnable command (a SQL query or a `\d*` listing + /// metacommand), used by `\watch`. Excludes `\watch` itself so it can't + /// recurse, and one-shot commands like `\c`/`\e`/`\q`. + last_command: Option, + profile_name: String, +} + +#[derive(Clone)] +struct LanceDBCompleter { + table_names: Arc>>, + index_names: Arc>>, + qualified_index_names: Arc>>, +} + +impl LanceDBCompleter { + fn new() -> Self { + Self { + table_names: Arc::new(std::sync::Mutex::new(Vec::new())), + index_names: Arc::new(std::sync::Mutex::new(Vec::new())), + qualified_index_names: Arc::new(std::sync::Mutex::new(Vec::new())), + } + } + + fn update_table_names(&mut self, tables: Vec) { + if let Ok(mut names) = self.table_names.lock() { + *names = tables; + } + } + + fn update_index_names(&mut self, indices: Vec, qualified: Vec) { + if let Ok(mut names) = self.index_names.lock() { + *names = indices; + } + if let Ok(mut names) = self.qualified_index_names.lock() { + *names = qualified; + } + } +} + +impl Completer for LanceDBCompleter { + type Candidate = Pair; + + fn complete( + &self, + line: &str, + pos: usize, + _ctx: &rustyline::Context<'_>, + ) -> rustyline::Result<(usize, Vec)> { + let mut candidates = Vec::new(); + let trimmed = line[..pos].trim_start(); + + // For \di commands, only complete index names (including qualified table.index) + if trimmed.starts_with("\\di+ ") || trimmed.starts_with("\\di ") { + let word_start = line[..pos] + .rfind(|c: char| c.is_whitespace()) + .map(|i| i + 1) + .unwrap_or(0); + let partial = &line[word_start..pos]; + let partial_lower = partial.to_lowercase(); + + // Offer both unqualified and qualified index names + if let Ok(indices) = self.index_names.lock() { + for index in indices.iter() { + if index.to_lowercase().starts_with(&partial_lower) { + candidates.push(Pair { + display: index.clone(), + replacement: index.clone(), + }); + } + } + } + if let Ok(qualified) = self.qualified_index_names.lock() { + for name in qualified.iter() { + if name.to_lowercase().starts_with(&partial_lower) { + candidates.push(Pair { + display: name.clone(), + replacement: name.clone(), + }); + } + } + } + return Ok((word_start, candidates)); + } + + // SQL keywords + let keywords = vec![ + "SELECT", "FROM", "WHERE", "INSERT", "INTO", "VALUES", "UPDATE", "DELETE", "CREATE", + "TABLE", "DROP", "ALTER", "INDEX", "ON", "SHOW", "TABLES", "DESCRIBE", "DESC", "LIMIT", + "ORDER", "BY", "GROUP", "HAVING", "AS", "JOIN", "INNER", "LEFT", "RIGHT", "OUTER", + "AND", "OR", "NOT", "IN", "LIKE", "BETWEEN", "EXISTS", "CASE", "WHEN", "THEN", "ELSE", + "END", + ]; + + // Find the word being completed + let word_start = line[..pos] + .rfind(|c: char| c.is_whitespace() || "(),;".contains(c)) + .map(|i| i + 1) + .unwrap_or(0); + + let partial = &line[word_start..pos]; + let partial_upper = partial.to_uppercase(); + + // Add SQL keywords + for keyword in keywords { + if keyword.starts_with(&partial_upper) { + candidates.push(Pair { + display: keyword.to_string(), + replacement: keyword.to_string(), + }); + } + } + + // Add table names + if let Ok(tables) = self.table_names.lock() { + for table in tables.iter() { + if table.to_lowercase().starts_with(&partial.to_lowercase()) { + candidates.push(Pair { + display: table.clone(), + replacement: table.clone(), + }); + } + } + } + + // Add index names + if let Ok(indices) = self.index_names.lock() { + for index in indices.iter() { + if index.to_lowercase().starts_with(&partial.to_lowercase()) { + candidates.push(Pair { + display: index.clone(), + replacement: index.clone(), + }); + } + } + } + + Ok((word_start, candidates)) + } +} + +impl Hinter for LanceDBCompleter { + type Hint = String; + + fn hint(&self, _line: &str, _pos: usize, _ctx: &rustyline::Context<'_>) -> Option { + None + } +} + +impl Highlighter for LanceDBCompleter {} +impl Validator for LanceDBCompleter {} +impl Helper for LanceDBCompleter {} + +/// Unwrap one of a listing's per-table requests, reporting failure instead of +/// degrading silently. +/// +/// The `\d`-family listings issue several requests per table and render a blank +/// cell for each one that fails, which reads as "this table has no stats" +/// rather than "this request failed". The error carries the request ID the +/// query node logged, so this warning is what makes such a failure traceable. +fn or_warn(result: std::result::Result, subject: &str) -> Option { + match result { + Ok(value) => Some(value), + Err(e) => { + eprintln!("warning: {subject} failed: {e}"); + None + } + } +} + +/// Point `executor` at the Flight SQL address `sql_addr`, preserving its +/// scheme so an `https://`/`grpcs://` address dials TLS. Returns the URL that +/// was dialed along with any connection error, so the caller can report both +/// endpoint failures together. +/// +/// Split out of `connect_internal` so the address-to-transport handoff is +/// reachable without a live REST endpoint. +async fn connect_sql_endpoint( + executor: &mut S, + sql_addr: &str, + database: &str, +) -> Result<(String, Option)> { + let url = parse_grpc_endpoint(sql_addr, DEFAULT_SQL_PORT)?.url(); + executor.set_database(database.to_string()); + let err = executor.connect(&url).await.err(); + Ok((url, err)) +} + +fn connection_failure_message(endpoint: &str, protocol: &str, error: &anyhow::Error) -> String { + // Include the source chain: transport errors often hide the useful cause + // (connection refused, DNS, TLS, etc.) behind a generic outer message. + format!("lancedb: connection failed: {endpoint} ({protocol}): {error:#}") +} + +/// HTTP failures are fatal; SQL-only failures allow metadata commands. +fn report_connection_failures( + sql: Option<(&str, &anyhow::Error)>, + http: Option<(&str, &anyhow::Error)>, +) { + for (protocol, failure) in [("sql", sql), ("http", http)] { + if let Some((endpoint, error)) = failure { + eprintln!("{}", connection_failure_message(endpoint, protocol, error)); + } + } + + if sql.is_none() && http.is_none() { + return; + } + + if http.is_some() { + std::process::exit(1); + } + + eprintln!("lancedb: SQL queries will not work, but metadata commands are available"); +} + +// Helper function to run async operations with Ctrl+C cancellation +async fn run_with_cancellation(operation: F) -> Result> +where + F: std::future::Future>, +{ + tokio::select! { + result = operation => { + match result { + Ok(value) => Ok(Some(value)), + Err(e) => Err(e), + } + } + _ = signal::ctrl_c() => { + println!("\n^C"); + Ok(None) + } + } +} + +/// Default interval for `\watch` when none is given (matches psql). +const DEFAULT_WATCH_INTERVAL_SECS: f64 = 2.0; + +/// Smallest accepted `\watch` interval. A positive-but-tiny value (e.g. +/// `1e-20`, or `1e-6` which converts to a nonzero 1us) passes a bare `> 0.0` +/// check yet leaves effectively no delay between runs, spinning the loop and +/// hammering the server; anything below this floor is rejected. +const MIN_WATCH_INTERVAL_SECS: f64 = 0.1; + +/// Whether a metacommand is something `\watch` should repeat. The `\d*` +/// listing/describe family (`\d`, `\di`, `\dt`, ...) qualifies; `\watch` +/// itself and one-shot commands (`\c`, `\e`, `\q`, `\?`) do not. +fn is_watchable_metacommand(cmd: &str) -> bool { + // Exact-match the recognized `\d`-family verbs, not just a `\d` prefix: + // an unrecognized `\d`-prefixed typo (`\dfoo`) is rejected by + // `handle_metacommand` yet would otherwise clobber `last_command`. + // Only the first token matters, so `\d TABLE` / `\di INDEX` still match. + matches!( + cmd.split_whitespace().next(), + Some("\\d" | "\\d+" | "\\dt" | "\\dt+" | "\\di" | "\\di+" | "\\dj" | "\\dj+") + ) +} + +/// The `SHOW JOBS` statement behind `\dj [TABLE]`. The argument is a literal +/// table name, so it is quoted: a name need not be a bare SQL identifier. +fn show_jobs_statement(table: Option<&str>) -> String { + match table { + Some(table) => format!("SHOW JOBS FOR \"{}\"", table.replace('"', "\"\"")), + None => "SHOW JOBS".to_string(), + } +} + +/// Validate a `\watch` interval in seconds to a `Duration`, or `None` if it is +/// unusable. `try_from_secs_f64` rejects negative, NaN, non-finite ("inf"), and +/// `Duration`-overflowing ("1e300") inputs (so the sleep can't panic); the floor +/// then rejects zero and positive-but-tiny values that would leave no real delay +/// between runs. See [`MIN_WATCH_INTERVAL_SECS`]. +fn watch_interval(secs: f64) -> Option { + let min = Duration::from_secs_f64(MIN_WATCH_INTERVAL_SECS); + Duration::try_from_secs_f64(secs).ok().filter(|d| *d >= min) +} + +/// Parsed `\watch` arguments: how often to repeat, and what to repeat. +struct WatchArgs { + interval: Duration, + /// Inline statement/listing to watch, or `None` to re-run the last command. + target: Option, +} + +/// Parse the argument string after `\watch` into an interval and an optional +/// inline target. A first token that parses as a number is always treated as +/// the interval (real SQL never starts with a bare number), so it is validated +/// as one; anything else means the whole string is the inline target. Thus +/// `\watch` / `\watch 5` re-run the last command, while `\watch SELECT ...` and +/// `\watch 5 SELECT ...` watch that statement (at the default / given interval). +fn parse_watch_args(args: &str) -> Result { + let args = args.trim(); + let default = Duration::from_secs_f64(DEFAULT_WATCH_INTERVAL_SECS); + if args.is_empty() { + return Ok(WatchArgs { + interval: default, + target: None, + }); + } + + let mut it = args.splitn(2, char::is_whitespace); + let first = it.next().unwrap_or(""); + let rest = it.next().unwrap_or("").trim(); + + if let Ok(secs) = first.parse::() { + let interval = watch_interval(secs).ok_or_else(|| { + format!( + "Invalid interval '{first}' (must be a number >= {MIN_WATCH_INTERVAL_SECS}s). \ + Usage: \\watch [seconds] [statement]" + ) + })?; + return Ok(WatchArgs { + interval, + target: (!rest.is_empty()).then(|| rest.to_string()), + }); + } + + Ok(WatchArgs { + interval: default, + target: Some(args.to_string()), + }) +} + +/// Sets `NO_PAGER` for as long as it is alive, restoring the prior value on +/// drop. `should_use_pager` already honours `NO_PAGER`, so this disables +/// paging during a `\watch` loop. Restored even when the loop's future is +/// dropped by Ctrl-C, because the guard is a live local at the await point. +struct NoPagerGuard { + prev: Option, +} + +impl NoPagerGuard { + fn new() -> Self { + let prev = std::env::var("NO_PAGER").ok(); + std::env::set_var("NO_PAGER", "1"); + Self { prev } + } +} + +impl Drop for NoPagerGuard { + fn drop(&mut self) { + match &self.prev { + Some(v) => std::env::set_var("NO_PAGER", v), + None => std::env::remove_var("NO_PAGER"), + } + } +} + +/// Check if output should use a pager +fn should_use_pager(output: &str) -> bool { + if std::env::var("NO_PAGER").is_ok() { + return false; + } + + let term_height = termsize::get().map(|size| size.rows as usize).unwrap_or(24); + let line_count = output.lines().count(); + + line_count > (term_height * 80 / 100) +} + +/// Find an appropriate pager +fn find_pager() -> Option { + if let Ok(pager) = std::env::var("PAGER") { + if !pager.is_empty() { + return Some(pager); + } + } + + let pagers = ["less", "more", "bat"]; + for pager in &pagers { + if which::which(pager).is_ok() { + return Some(pager.to_string()); + } + } + + None +} + +/// Leading whitespace and comments, which the server's tokenizer discards +/// before matching a statement's keywords. +fn strip_leading_trivia(query: &str) -> &str { + let mut rest = query.trim_start(); + loop { + let remainder = if let Some(after) = rest.strip_prefix("--") { + after.find('\n').map_or("", |end| &after[end + 1..]) + } else if let Some(after) = rest.strip_prefix("/*") { + after.find("*/").map_or("", |end| &after[end + 2..]) + } else { + return rest; + }; + rest = remainder.trim_start(); + } +} + +/// Rows of a `SHOW JOBS` listing the interactive shell will print. The registry +/// can hold far more jobs than anyone reads at a terminal, and the server +/// returns the listing in one shot with no cursor to resume from, so the table +/// rendering cuts the display and points at ways to narrow the listing or +/// export every row. +const MAX_DISPLAYED_JOB_ROWS: usize = 1000; + +/// Ready a `SHOW JOBS` listing for display, returning it with any notice to +/// print after the formatted output. +/// +/// The `job_id` marking applies everywhere: it is the input to `CANCEL JOB`, +/// so it has to be copyable rather than readable. The row cut applies only to +/// the interactive table rendering -- CSV/JSON/NDJSON and one-shot invocations +/// are read by programs, which need every row and nothing but the payload. +fn prepare_show_jobs_result( + result: SqlResult, + interactive_table: bool, +) -> (SqlResult, Option) { + let total = crate::formatter::row_count(&result); + let cut = interactive_table && total > MAX_DISPLAYED_JOB_ROWS; + + let notice = cut.then(|| { + format!( + "\nShowing the first {MAX_DISPLAYED_JOB_ROWS} of {total} jobs. Narrow the \ + listing with SHOW JOBS FOR

, or use lancedb sql --command 'SHOW JOBS' \ + --format json to retrieve all rows.\n" + ) + }); + let result = if cut { + crate::formatter::take_rows(result, MAX_DISPLAYED_JOB_ROWS) + } else { + result + }; + ( + crate::formatter::mark_no_truncate(result, &["job_id"]), + notice, + ) +} + +/// The first two keywords of `query`, matched on leading keywords rather than +/// a raw prefix so that `SHOW JOBS` and a comment-prefixed query both match +/// while `SHOW JOBSX` does not. +fn leading_keywords(query: &str) -> Option<(String, String)> { + let mut words = strip_leading_trivia(query) + .trim_end_matches(|c: char| c.is_whitespace() || c == ';') + .split_whitespace(); + let first = words.next()?.to_ascii_uppercase(); + let second = words.next()?.to_ascii_uppercase(); + Some((first, second)) +} + +/// Whether `query` is a `SHOW JOBS` statement. +fn is_show_jobs(query: &str) -> bool { + leading_keywords(query).is_some_and(|(first, second)| first == "SHOW" && second == "JOBS") +} + +/// Columns of a statement's result that a reader copies rather than reads +/// (identifiers), which the table view must not abbreviate. +fn copyable_columns(query: &str) -> &'static [&'static str] { + match leading_keywords(query) { + Some((first, second)) if first == "CANCEL" && second == "JOB" => &["job_id"], + // A Function version is the argument of the next statement a reader + // writes, so it has to survive display in full. + Some((first, second)) if first == "SHOW" && second == "FUNCTIONS" => &["version"], + Some((first, second)) if first == "SHOW" && second == "ERRORS" => { + &["job_id", "function_version"] + } + Some((first, second)) + if first == "REFRESH" && (second == "COLUMN" || second == "MATERIALIZED") => + { + &["job_id"] + } + _ => &[], + } +} + +/// Display output with pager if needed +fn display_with_pager(output: &str, interactive_mode: bool) -> Result<()> { + if !interactive_mode || !should_use_pager(output) { + // Just print directly + print!("{}", output); + io::stdout().flush()?; + return Ok(()); + } + + // Find pager + let Some(pager_cmd) = find_pager() else { + // No pager available, just print + print!("{}", output); + io::stdout().flush()?; + return Ok(()); + }; + + // Set up pager process + let mut cmd = Command::new(&pager_cmd); + + // If using less, add -FRX flags: + // -F: quit if one screen + // -R: raw control chars (for colors) + // -X: no init (don't clear screen) + if pager_cmd.contains("less") { + cmd.arg("-FRX"); + } + + cmd.stdin(Stdio::piped()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()); + + // Spawn pager + let mut child = cmd.spawn()?; + + // Write output to pager + if let Some(mut stdin) = child.stdin.take() { + // Ignore SIGPIPE errors when pager exits early (e.g., user presses 'q') + let _ = stdin.write_all(output.as_bytes()); + let _ = stdin.flush(); + } + + // Wait for pager to finish + let _ = child.wait(); + + Ok(()) +} + +impl LanceDBClient +where + S: SqlQueryExecutor, +{ + fn prompt(&self) -> String { + match &self.current_database { + Some(db) => format!("[{}]:{}=# ", self.profile_name, db), + None => format!("[{}]:lancedb=# ", self.profile_name), + } + } + + fn continuation_prompt(&self) -> &'static str { + " # " + } + + fn open_editor_for_last_query(&self) -> Result> { + // Use last executed query if available, otherwise empty string + let initial_query = self.last_query.as_deref().unwrap_or(""); + self.open_editor_for_query(initial_query) + } + + fn display_query_lines(&self, query: &str) { + // Display each line of the query as if the user had typed it + for (i, line) in query.lines().enumerate() { + if i == 0 { + println!("{}{}", self.prompt(), line); + } else { + println!("{}{}", self.continuation_prompt(), line); + } + } + } + + fn open_editor_for_query(&self, initial_query: &str) -> Result> { + // Determine which editor to use + let editor = std::env::var("EDITOR") + .or_else(|_| std::env::var("VISUAL")) + .unwrap_or_else(|_| { + for editor in &["vim", "vi", "emacs", "nano", "code"] { + if which::which(editor).is_ok() { + return editor.to_string(); + } + } + "vi".to_string() + }); + + // Create a temporary file with .sql extension + let mut temp_file = NamedTempFile::with_suffix(".sql") + .map_err(|e| anyhow!("Failed to create temporary file: {}", e))?; + + // Write initial query to the file + temp_file + .write_all(initial_query.as_bytes()) + .map_err(|e| anyhow!("Failed to write to temporary file: {}", e))?; + temp_file + .flush() + .map_err(|e| anyhow!("Failed to flush temporary file: {}", e))?; + + // Get the path before we move ownership + let temp_path = temp_file.path().to_path_buf(); + + // Launch the editor + let status = Command::new(&editor) + .arg(&temp_path) + .stdin(Stdio::inherit()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .status() + .map_err(|e| anyhow!("Failed to launch editor '{}': {}", editor, e))?; + + if !status.success() { + // Editor exited with error, but we'll still try to read the file + eprintln!("Editor exited with non-zero status"); + } + + // Read the edited content + let edited_content = std::fs::read_to_string(&temp_path) + .map_err(|e| anyhow!("Failed to read edited file: {}", e))?; + + // Check if the content is empty or unchanged + let trimmed = edited_content.trim(); + if trimmed.is_empty() { + return Ok(None); + } + + Ok(Some(edited_content)) + } + + pub async fn new( + database_override: Option, + interactive_mode: bool, + output_format: OutputFormat, + authentication: Authentication, + profile_name: String, + sql_executor: S, + ) -> Result { + // Set up history file + let history_path = if let Some(proj_dirs) = ProjectDirs::from("com", "lancedb", "client") { + let data_dir = proj_dirs.data_dir(); + std::fs::create_dir_all(data_dir)?; + data_dir.join("history.txt") + } else { + PathBuf::from("/tmp/lancedb-history.txt") + }; + + // Create completer + let completer = LanceDBCompleter::new(); + + // Create editor with completer + let mut editor = Editor::with_config( + rustyline::config::Config::builder() + .completion_type(rustyline::config::CompletionType::List) + .build(), + ) + .map_err(|e| anyhow!("Failed to create editor: {}", e))?; + editor.set_helper(Some(completer)); + let _ = editor.load_history(&history_path); + + // Use database override, or system username as default database + let default_database = database_override.unwrap_or_else(|| { + std::env::var("USER") + .or_else(|_| std::env::var("USERNAME")) + .unwrap_or_else(|_| "test".to_string()) + }); + + let formatter = ResultFormatter::new(output_format); + + Ok(Self { + editor, + history_path, + sql_executor, + sql_connected: false, + connection: None, + formatter, + current_database: Some(default_database), + connection_info: None, + interactive_mode, + authentication, + last_query: None, + last_command: None, + profile_name, + }) + } + + pub async fn connect(&mut self, conn: &ResolvedConnection) -> Result<()> { + self.connect_internal(conn, true).await + } + + async fn connect_internal( + &mut self, + conn: &ResolvedConnection, + show_message: bool, + ) -> Result<()> { + let sql_addr = &conn.sql_server_url; + let http_addr = &conn.http_server_url; + + // The REST address keeps whichever scheme the user configured, so an + // https:// address stays on TLS all the way to the transport. + let lancedb_uri = parse_endpoint(http_addr, DEFAULT_HTTP_PORT)?.url(); + + // Build the database URI + let db_name = self.current_database.as_deref().unwrap_or("test"); + + // Try both connections and report failures together + let (flight_server, sql_err) = + connect_sql_endpoint(&mut self.sql_executor, sql_addr, db_name).await?; + + let db_uri = format!("db://{}", db_name); + + // lancedb::connect() is lazy, so we create the connection then probe it + // with a table_names call to verify the HTTP endpoint is reachable. + let mut builder = lancedb::connect(&db_uri) + .region("self-hosted") + .host_override(&lancedb_uri); + if let Authentication::ApiKey(api_key) = &self.authentication { + builder = builder.api_key(api_key); + } else { + // The SDK requires an explicit API key even with a header provider. + // An empty key omits x-api-key; client_config supplies the OIDC headers. + builder = builder.api_key(""); + } + if let Some(client_config) = crate::lancedb_client_config(&conn.tls, &self.authentication) { + builder = builder.client_config(client_config); + } + let connection = builder + .execute() + .await + .map_err(|e| anyhow!("Failed to connect to LanceDB: {}", e))?; + + let http_err = connection + .list_tables(&[], ListingOptions::default().page_limit(1)) + .next_page() + .await + .err() + .map(anyhow::Error::from); + + report_connection_failures( + sql_err.as_ref().map(|err| (flight_server.as_str(), err)), + http_err.as_ref().map(|err| (lancedb_uri.as_str(), err)), + ); + + self.connection = Some(Arc::new(connection)); + self.sql_connected = sql_err.is_none(); + self.connection_info = Some(conn.clone()); + + // Only print connection message in interactive mode and when requested + if self.interactive_mode && show_message { + println!("Connected to SQL: {}, HTTP: {}", sql_addr, http_addr); + } + + // Update table name completions + self.update_completions().await; + + Ok(()) + } + + /// Fetch all table names with pagination + async fn table_names(connection: &lancedb::Connection) -> Result> { + let mut all_tables: Vec = connection + .list_tables(&[], ListingOptions::default().page_limit(100)) + .try_collect() + .await + .map_err(|e| anyhow!("Failed to list tables: {}", e))?; + + // The listing resumes from the store's own cursor, so its pages arrive in key order + // rather than name order. Callers here -- `\d`, `\dt`, and completion -- present the + // whole list to a person, and this walk already holds it in memory, so sort it once. + all_tables.sort(); + + Ok(all_tables) + } + + async fn update_completions(&mut self) { + if let Some(connection) = &self.connection { + if let Ok(table_names) = Self::table_names(connection).await { + if let Some(helper) = self.editor.helper_mut() { + helper.update_table_names(table_names.clone()); + + // Also gather all index names (unqualified and qualified) + let mut all_index_names = Vec::new(); + let mut qualified_index_names = Vec::new(); + for table_name in &table_names { + if let Ok(table) = connection.open_table(table_name).execute().await { + if let Ok(indices) = table.list_indices().await { + for index in indices { + qualified_index_names + .push(format!("{}.{}", table_name, index.name)); + all_index_names.push(index.name); + } + } + } + } + helper.update_index_names(all_index_names, qualified_index_names); + } + } + } + } + + pub async fn run_repl(&mut self) -> Result<()> { + println!("{}", LANCEDB_ASCII_ART); + println!("LanceDB CLI v{}", crate::build_version()); + println!("Type \\? for help or \\q to quit\n"); + + let mut multiline_query = String::new(); + let mut in_multiline = false; + + loop { + let prompt_string; + let prompt = if in_multiline { + self.continuation_prompt() + } else { + prompt_string = self.prompt(); + &prompt_string + }; + + match self.editor.readline(prompt) { + Ok(mut line) => { + let trimmed = line.trim(); + + // Skip empty lines + if trimmed.is_empty() { + continue; + } + + // Handle metacommands + if !in_multiline && trimmed.starts_with('\\') { + match run_with_cancellation(self.handle_metacommand(trimmed)).await { + Err(e) => { + eprintln!("ERROR: {}", e); + continue; + } + Ok(None) => { + // Cancelled + continue; + } + Ok(Some(result)) => { + match result { + MetaCommandResult::Handled => { + // Successful metacommand + self.editor.add_history_entry(&line)?; + // Remember listing metacommands so + // \watch can repeat them. + if is_watchable_metacommand(trimmed) { + self.last_command = Some(trimmed.to_string()); + } + continue; + } + MetaCommandResult::ReplaceInput(new_input) => { + line = new_input; + self.display_query_lines(&line); + // Fall through to process the new input + } + } + } + } + } + + // Now process line normally (either from readline or editor) + let trimmed = line.trim(); + + // Skip empty lines (in case editor returned empty) + if trimmed.is_empty() { + continue; + } + + // Add to history + self.editor.add_history_entry(&line)?; + + // Normal query accumulation + if in_multiline { + multiline_query.push('\n'); + } + multiline_query.push_str(&line); + + // Check if query is complete (ends with semicolon) + if multiline_query.trim().ends_with(';') { + // Store the complete query with semicolon before removing it + self.last_query = Some(multiline_query.clone()); + + // Remove the semicolon + multiline_query.pop(); + // Remember the query so \watch can repeat it. + self.last_command = Some(multiline_query.clone()); + + // Execute the query + match run_with_cancellation(self.execute_query(&multiline_query)).await { + Ok(Some(())) => {} + Ok(None) => {} + Err(e) => { + eprintln!("ERROR: {}", e); + } + } + + // Reset for next query + multiline_query.clear(); + in_multiline = false; + } else { + in_multiline = true; + } + } + Err(ReadlineError::Interrupted) => { + println!("^C"); + multiline_query.clear(); + in_multiline = false; + } + Err(ReadlineError::Eof) => { + println!("\\q"); + break; + } + Err(err) => { + eprintln!("Error: {:?}", err); + break; + } + } + } + + // Save history + self.editor.save_history(&self.history_path)?; + Ok(()) + } + + async fn execute_query(&mut self, query: &str) -> Result<()> { + let start_time = Instant::now(); + + // Check if this is a DDL statement and get the command type + let ddl_command = { + let trimmed = query.trim().to_uppercase(); + if trimmed.starts_with("CREATE TABLE") { + Some("CREATE TABLE") + } else if trimmed.starts_with("CREATE INDEX") { + Some("CREATE INDEX") + } else if trimmed.starts_with("CREATE VIEW") { + Some("CREATE VIEW") + } else if trimmed.starts_with("CREATE") { + Some("CREATE") + } else if trimmed.starts_with("ALTER TABLE") { + Some("ALTER TABLE") + } else if trimmed.starts_with("ALTER INDEX") { + Some("ALTER INDEX") + } else if trimmed.starts_with("ALTER VIEW") { + Some("ALTER VIEW") + } else if trimmed.starts_with("ALTER") { + Some("ALTER") + } else if trimmed.starts_with("DROP TABLE") { + Some("DROP TABLE") + } else if trimmed.starts_with("DROP INDEX") { + Some("DROP INDEX") + } else if trimmed.starts_with("DROP VIEW") { + Some("DROP VIEW") + } else if trimmed.starts_with("DROP") { + Some("DROP") + } else { + None + } + }; + + if !self.sql_connected { + return Err(anyhow!("SQL endpoint is not connected")); + } + + // Execute the query + let result = self.sql_executor.execute_query(query).await?; + + // Display output based on whether it's DDL or not + if let Some(command) = ddl_command { + // For DDL, just echo the command type + println!("{}", command); + } else { + // For non-DDL, format and display the result. + let (result, notice) = if is_show_jobs(query) { + let interactive_table = self.interactive_mode + && matches!(self.formatter.output_format(), OutputFormat::Table); + prepare_show_jobs_result(result, interactive_table) + } else { + ( + crate::formatter::mark_no_truncate(result, copyable_columns(query)), + None, + ) + }; + let query_result = QueryResult::SqlResult(result); + let mut output = self.formatter.format(&query_result)?; + // Appended rather than printed ahead of the payload, so the notice + // travels through the pager with the table it describes. + if let Some(notice) = notice { + output.push_str(¬ice); + } + display_with_pager(&output, self.interactive_mode)?; + } + + let elapsed = start_time.elapsed(); + if self.interactive_mode { + println!("Time: {:.3} ms", elapsed.as_secs_f64() * 1000.0); + } + + Ok(()) + } + + async fn handle_metacommand(&mut self, command: &str) -> Result { + let parts: Vec<&str> = command.split_whitespace().collect(); + if parts.is_empty() { + return Ok(MetaCommandResult::Handled); + } + + let cmd = parts[0]; + match cmd { + "\\?" | "\\h" | "\\help" | "help" => { + self.print_help(); + } + "\\d" | "\\d+" => { + let detailed = cmd.ends_with('+'); + if parts.len() < 2 { + // \d without argument lists tables + self.list_tables(detailed).await?; + } else { + // \d
describes the table + self.describe_table(parts[1]).await?; + } + } + "\\di" | "\\di+" => { + let detailed = cmd.ends_with('+'); + if parts.len() < 2 { + // \di without argument lists all indexes + self.list_all_indexes(detailed).await?; + } else { + // \di describes the specific index + self.describe_index(parts[1], detailed).await?; + } + } + "\\dt" | "\\dt+" => { + let detailed = cmd.ends_with('+'); + self.list_tables(detailed).await?; + } + // `\dj+` is a synonym for now. + "\\dj" | "\\dj+" => { + let statement = show_jobs_statement(parts.get(1).copied()); + self.execute_query(&statement).await?; + } + "\\watch" => { + let args = command.strip_prefix("\\watch").unwrap_or(""); + let spec = match parse_watch_args(args) { + Ok(spec) => spec, + Err(msg) => { + eprintln!("{msg}"); + return Ok(MetaCommandResult::Handled); + } + }; + + // Resolve what to repeat: an inline statement/listing if given, + // otherwise the last command. An inline `\`-target must be a + // repeatable `\d`-family listing -- this also rejects `\watch + // \watch ...`, which would otherwise recurse. + let target = match spec.target { + Some(t) if t.starts_with('\\') => { + if !is_watchable_metacommand(&t) { + eprintln!( + "\\watch: cannot watch '{t}'. Watch a SQL query or a \\d-family listing." + ); + return Ok(MetaCommandResult::Handled); + } + t + } + // Drop a trailing ';' so inline SQL matches the re-run form. + Some(t) => t.trim_end_matches(';').trim_end().to_string(), + None => { + let Some(last) = self.last_command.clone() else { + eprintln!("\\watch: no previous query or listing to watch."); + return Ok(MetaCommandResult::Handled); + }; + last + } + }; + self.watch_loop(target, spec.interval).await?; + } + "\\c" => { + if parts.len() < 2 { + match &self.current_database { + Some(db) => println!("You are now connected to database \"{}\".", db), + None => println!("You are not connected to a database."), + } + } else { + let new_db = parts[1].to_string(); + + // Check if we're already connected to this database + if let Some(current_db) = &self.current_database { + if current_db == &new_db { + println!("You are now connected to database \"{}\".", new_db); + return Ok(MetaCommandResult::Handled); + } + } + + let old_db = self.current_database.clone(); + self.current_database = Some(new_db.clone()); + + // If we're connected, reconnect with the new database + if let Some(conn) = &self.connection_info.clone() { + match self.connect_internal(conn, false).await { + Ok(_) => { + println!("You are now connected to database \"{}\".", new_db); + } + Err(e) => { + eprintln!("connection to database \"{}\" failed: {}", new_db, e); + // Restore the previous database on failure + self.current_database = old_db; + } + } + } else { + println!("You are now connected to database \"{}\".", new_db); + } + } + } + "\\e" => { + // Open editor and return the edited query + match self.open_editor_for_last_query() { + Ok(Some(edited)) => { + return Ok(MetaCommandResult::ReplaceInput(edited.trim().to_string())); + } + Ok(None) => { + // User cancelled or cleared editor + return Ok(MetaCommandResult::Handled); + } + Err(e) => { + return Err(e); + } + } + } + "\\q" | "\\quit" => { + println!("Use Ctrl+D to exit"); + } + _ => { + eprintln!("Invalid command \\{}. Try \\? for help.", &cmd[1..]); + } + } + Ok(MetaCommandResult::Handled) + } + + /// Re-run `command` (a SQL query or a `\d*` listing) every `interval` + /// seconds, clearing the screen between runs, until interrupted with + /// Ctrl-C. The REPL wraps this in `run_with_cancellation`, so Ctrl-C + /// drops this future and returns to the prompt; `NoPagerGuard` restores + /// the pager setting on that drop. Paging is suppressed for the duration + /// so a long listing doesn't block the loop waiting on the pager. + async fn watch_loop(&mut self, command: String, interval: Duration) -> Result<()> { + let _no_pager = NoPagerGuard::new(); + loop { + // Clear screen, cursor home, then a header line. + print!("\x1b[2J\x1b[H"); + println!( + "Watch every {:.1}s -- {} (Ctrl-C to stop)\n", + interval.as_secs_f64(), + command + ); + let _ = io::stdout().flush(); + + let result = if command.starts_with('\\') { + // Recursion (handle_metacommand -> watch_loop -> + // handle_metacommand) needs boxing to keep the future sized. + Box::pin(self.handle_metacommand(&command)) + .await + .map(|_| ()) + } else { + Box::pin(self.execute_query(&command)).await + }; + if let Err(e) = result { + eprintln!("ERROR: {}", e); + } + let _ = io::stdout().flush(); + + tokio::time::sleep(interval).await; + } + } + + fn print_help(&self) { + println!("\nGeneral"); + println!(" \\h, \\?, help show this help"); + println!(" \\q quit lancedb (or use Ctrl+D)"); + println!("\nEditing"); + println!(" \\e edit query buffer in external editor"); + println!("\nInformational"); + println!(" \\d list tables (simple)"); + println!(" \\d+ list tables with stats (detailed)"); + println!(" \\d TABLE describe table (show columns and indexes)"); + println!(" \\di list all indexes (simple)"); + println!(" \\di+ list all indexes with stats (detailed)"); + println!(" \\di [TABLE.]INDEX describe index"); + println!(" \\dt list tables (simple)"); + println!(" \\dt+ list tables with stats (detailed)"); + println!(" \\dj [TABLE] list jobs, optionally only those for TABLE"); + println!(" \\dj+ [TABLE] same as \\dj"); + println!("\nRepeat"); + println!(" \\watch [SEC] re-run the last query or listing every SEC seconds"); + println!( + " \\watch [SEC] STMT watch STMT (a SQL query or \\d-family listing) instead" + ); + println!(" (default 2s; Ctrl-C to stop)"); + println!("\nConnection"); + println!(" \\c [DBNAME] connect to database"); + println!("\nSQL"); + println!(" SQL queries end with semicolon (;)"); + println!(" Use Ctrl+C to cancel current input"); + println!(" Use Ctrl+D to exit"); + println!("\nOutput"); + println!(" Large results are automatically displayed in pager"); + println!(" Set NO_PAGER=1 to disable pager"); + println!(); + } + + async fn list_tables(&mut self, detailed: bool) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + let tables = Self::table_names(connection).await?; + + if tables.is_empty() { + println!("Did not find any relations."); + return Ok(()); + } + + if detailed { + // For \d+ and \dt+, we need to show detailed table information with stats + // Fetch table info for each table + let mut table_infos = Vec::new(); + for table_name in &tables { + let Some(table) = or_warn( + connection.open_table(table_name).execute().await, + &format!("opening table '{table_name}'"), + ) else { + table_infos.push(TableInfo { + name: table_name.clone(), + schema: Arc::new(Schema::empty()), + row_count: None, + size_bytes: None, + num_indices: None, + num_fragments: None, + }); + continue; + }; + + let schema = or_warn( + table.schema().await, + &format!("reading schema for table '{table_name}'"), + ) + .unwrap_or_else(|| Arc::new(Schema::empty())); + let stats = or_warn( + table.stats().await, + &format!("reading stats for table '{table_name}'"), + ); + let row_count = match stats.as_ref() { + Some(s) => Some(s.num_rows as u64), + None => or_warn( + table.count_rows(None).await, + &format!("counting rows for table '{table_name}'"), + ) + .map(|n| n as u64), + }; + + table_infos.push(TableInfo { + name: table_name.clone(), + schema, + row_count, + size_bytes: stats.as_ref().map(|s| s.total_bytes as u64), + num_indices: stats.as_ref().map(|s| s.num_indices as u64), + num_fragments: stats + .as_ref() + .map(|s| s.fragment_stats.num_fragments as u64), + }); + } + + // Use the formatter to display the results + let result = QueryResult::TableListDetailed(table_infos); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } else { + // Simple list without stats + let result = QueryResult::TableList(tables); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } + Ok(()) + } + + async fn describe_table(&mut self, table_name: &str) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + let table = connection + .open_table(table_name) + .execute() + .await + .map_err(|e| anyhow!("Failed to open table '{}': {}", table_name, e))?; + + let schema = table + .schema() + .await + .map_err(|e| anyhow!("Failed to get schema: {}", e))?; + + let stats = table.stats().await.ok(); + let row_count = if let Some(s) = stats.as_ref() { + Some(s.num_rows as u64) + } else { + table.count_rows(None).await.ok().map(|n| n as u64) + }; + + // Get index information + let indices = table.list_indices().await.ok(); + let mut index_info = Vec::new(); + if let Some(indices) = indices { + for index in indices { + let mut info = IndexInfo { + name: index.name.clone(), + table_name: table_name.to_string(), + index_type: index.index_type.to_string(), + columns: index.columns.clone(), + }; + + // Try to get distance type for vector indices + if let Ok(Some(stats)) = table.index_stats(&index.name).await { + if let Some(distance_type) = stats.distance_type { + info.index_type = + format!("{} distance={}", index.index_type, distance_type); + } + } + + index_info.push(info); + } + } + + let table_info = TableInfo { + name: table_name.to_string(), + schema, + row_count, + size_bytes: stats.as_ref().map(|s| s.total_bytes as u64), + num_indices: stats.as_ref().map(|s| s.num_indices as u64), + num_fragments: stats + .as_ref() + .map(|s| s.fragment_stats.num_fragments as u64), + }; + + let result = QueryResult::TableInfoWithIndices(table_info, index_info); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + Ok(()) + } + + async fn list_all_indexes(&mut self, detailed: bool) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + let tables = Self::table_names(connection).await?; + + // Each opened table is kept alongside its indexes because the `\di+` + // pass below needs the same handle: reopening per index would issue one + // request per index where one per table suffices. + let mut per_table = Vec::new(); + for table_name in tables { + // A failure here drops the table from the listing entirely, so it + // has to be reported: an incomplete index list is indistinguishable + // from a table that genuinely has no indexes. + let Some(table) = or_warn( + connection.open_table(&table_name).execute().await, + &format!("opening table '{table_name}'"), + ) else { + continue; + }; + let Some(indices) = or_warn( + table.list_indices().await, + &format!("listing indexes for table '{table_name}'"), + ) else { + continue; + }; + let infos: Vec = indices + .into_iter() + .map(|index| IndexInfo { + name: index.name, + table_name: table_name.clone(), + index_type: index.index_type.to_string(), + columns: index.columns, + }) + .collect(); + per_table.push((table_name, table, infos)); + } + + if detailed { + // Fetch stats for each index + let mut indices_with_stats = Vec::new(); + for (table_name, table, infos) in per_table { + for index in infos { + // `Ok(None)` is an index that legitimately has no stats; + // only `Err` is a failed request. Collapsing the two is what + // makes a failure read as an index without statistics. + let stats = or_warn( + table.index_stats(&index.name).await, + &format!( + "reading stats for index '{}' on table '{}'", + index.name, table_name + ), + ) + .flatten() + .map(|s| IndexStats { + num_indexed_rows: s.num_indexed_rows as u64, + num_unindexed_rows: s.num_unindexed_rows as u64, + distance_type: s.distance_type.map(|dt| dt.to_string()), + }); + indices_with_stats.push((index, stats)); + } + } + let result = QueryResult::IndexListDetailed(indices_with_stats); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } else { + let all_indices: Vec = per_table + .into_iter() + .flat_map(|(_, _, infos)| infos) + .collect(); + let result = QueryResult::IndexList(all_indices); + let output = self.formatter.format(&result)?; + display_with_pager(&output, self.interactive_mode)?; + } + Ok(()) + } + + async fn describe_index(&mut self, index_name: &str, detailed: bool) -> Result<()> { + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow!("Not connected to LanceDB"))?; + + // Support qualified table.index_name syntax + if let Some((table_name, idx_name)) = index_name.split_once('.') { + let table = connection + .open_table(table_name) + .execute() + .await + .map_err(|_| anyhow!("Table \"{}\" not found.", table_name))?; + let indices = table.list_indices().await?; + for index in indices { + if index.name == idx_name { + Self::print_index_details(&index, table_name, detailed, &table).await; + return Ok(()); + } + } + eprintln!( + "Did not find index \"{}\" on table \"{}\".", + idx_name, table_name + ); + return Ok(()); + } + + // Unqualified: search all tables + let tables = Self::table_names(connection).await?; + let mut found_count = 0u32; + + for table_name in &tables { + if let Ok(table) = connection.open_table(table_name).execute().await { + if let Ok(indices) = table.list_indices().await { + for index in &indices { + if index.name == index_name { + if found_count == 0 { + Self::print_index_details(index, table_name, detailed, &table) + .await; + } + found_count += 1; + } + } + } + } + } + + if found_count == 0 { + eprintln!("Did not find any index named \"{}\".", index_name); + } else if found_count > 1 { + eprintln!( + "\nNote: {} indexes named \"{}\" exist across different tables. \ + Use \\di TABLE.INDEX to specify.", + found_count, index_name + ); + } + Ok(()) + } + + async fn print_index_details( + index: &lancedb::index::IndexConfig, + table_name: &str, + detailed: bool, + table: &lancedb::Table, + ) { + println!("Index \"{}\"", index.name); + println!(" Table: {}", table_name); + println!(" Type: {}", index.index_type); + println!(" Columns: {}", index.columns.join(", ")); + + if detailed { + if let Ok(Some(stats)) = table.index_stats(&index.name).await { + println!("\nStatistics:"); + println!(" Indexed rows: {}", stats.num_indexed_rows); + println!(" Unindexed rows: {}", stats.num_unindexed_rows); + if let Some(dist) = stats.distance_type { + println!(" Distance type: {}", dist); + } + } + } + } +} + +// Compatibility functions for tests that use writer +pub async fn run_client_with_writer( + conn: &ResolvedConnection, + writer: Option>, +) -> anyhow::Result<()> { + // If writer is provided, we need different behavior for tests + // For now, just ignore the writer and use the new implementation + let _ = writer; + + // Create concrete implementations + let sql_executor = + SdkSqlExecutor::new_with_authentication(String::new(), conn.authentication.clone()) + .with_tls(conn.tls.clone()); + + let mut client = LanceDBClient::new( + Some(conn.database.clone()), + true, + OutputFormat::Table, + conn.authentication.clone(), + conn.profile_name.clone(), + sql_executor, + ) + .await?; + + if !conn.sql_server_url.is_empty() { + client.connect(conn).await?; + } + + client.run_repl().await +} + +pub async fn run_client_command_with_writer( + conn: &ResolvedConnection, + command: String, + format: String, + writer: Option>, +) -> anyhow::Result<()> { + // If writer is provided, we need to capture output + let _ = writer; + + let output_format = format.parse::()?; + + // Create concrete implementations + let sql_executor = + SdkSqlExecutor::new_with_authentication(String::new(), conn.authentication.clone()) + .with_tls(conn.tls.clone()); + let mut client = LanceDBClient::new( + Some(conn.database.clone()), + false, + output_format, + conn.authentication.clone(), + conn.profile_name.clone(), + sql_executor, + ) + .await?; + + if !conn.sql_server_url.is_empty() { + client.connect(conn).await?; + } + + let trimmed = command.trim(); + if trimmed.starts_with('\\') { + client.handle_metacommand(trimmed).await?; + } else { + client.execute_query(&command).await?; + } + + Ok(()) +} + +/// SQL lexical rules for scripts. Comments, including MySQL-style hints, must +/// remain comments when deciding which statements to submit independently. +#[derive(Debug, Default)] +struct ScriptDialect(GenericDialect); + +impl Dialect for ScriptDialect { + fn dialect(&self) -> std::any::TypeId { + self.0.dialect() + } + + fn is_identifier_start(&self, ch: char) -> bool { + self.0.is_identifier_start(ch) + } + + fn is_identifier_part(&self, ch: char) -> bool { + self.0.is_identifier_part(ch) + } + + fn is_delimited_identifier_start(&self, ch: char) -> bool { + self.0.is_delimited_identifier_start(ch) + } + + fn supports_nested_comments(&self) -> bool { + true + } + + fn supports_multiline_comment_hints(&self) -> bool { + false + } + + fn supports_string_escape_constant(&self) -> bool { + true + } + + fn supports_unicode_string_literal(&self) -> bool { + true + } +} + +/// Split only on SQL delimiter tokens, retaining the original spelling of each +/// statement. Tokenize the whole script before executing any of its statements. +fn split_sql_script(script: &str) -> Result> { + let tokens = Tokenizer::new(&ScriptDialect::default(), script) + .tokenize_with_location() + .context("Failed to tokenize SQL script")?; + // Token locations count characters rather than bytes. Walk the source once + // to translate delimiter locations without changing Unicode or line endings. + let mut offsets = script + .char_indices() + .scan(Location::new(1, 1), |location, (offset, ch)| { + let start = *location; + if ch == '\n' { + location.line += 1; + location.column = 1; + } else { + location.column += 1; + } + Some((start, offset)) + }); + let mut commands = Vec::new(); + let mut start = 0; + let mut has_statement = false; + for token in tokens { + match token.token { + Token::SemiColon => { + let (_, end) = offsets + .find(|(location, _)| *location == token.span.start) + .context("SQL delimiter location is outside the script")?; + if has_statement { + commands.push(script[start..end].trim()); + } + start = end + 1; + has_statement = false; + } + Token::Whitespace(_) => {} + _ => has_statement = true, + } + } + if has_statement { + commands.push(script[start..].trim()); + } + Ok(commands) +} + +pub async fn run_client_script_with_writer( + conn: &ResolvedConnection, + script: String, + format: String, + writer: Option>, +) -> anyhow::Result<()> { + let _ = writer; + let commands = split_sql_script(&script)?; + + let output_format = format.parse::()?; + + // Create concrete implementations + let sql_executor = + SdkSqlExecutor::new_with_authentication(String::new(), conn.authentication.clone()) + .with_tls(conn.tls.clone()); + let mut client = LanceDBClient::new( + Some(conn.database.clone()), + false, + output_format, + conn.authentication.clone(), + conn.profile_name.clone(), + sql_executor, + ) + .await?; + + if !conn.sql_server_url.is_empty() { + client.connect(conn).await?; + } + + for command in commands { + if command.starts_with('\\') { + client.handle_metacommand(command).await?; + } else { + client.execute_query(command).await?; + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{ + connect_sql_endpoint, copyable_columns, is_show_jobs, prepare_show_jobs_result, + MAX_DISPLAYED_JOB_ROWS, + }; + use crate::formatter::{row_count, OutputFormat, QueryResult, ResultFormatter}; + use crate::mocks::test_mocks::MockSqlExecutor; + use crate::sql_executor::SqlResult; + + #[tokio::test] + async fn table_names_follows_short_and_empty_pages_and_sorts() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let app = axum::Router::new().fallback( + |axum::extract::Query(query): axum::extract::Query< + std::collections::HashMap, + >| async move { + assert_eq!(query.get("limit").map(String::as_str), Some("100")); + let page = match query.get("page_token").map(String::as_str) { + None => serde_json::json!({"tables": ["zebra"], "page_token": "empty"}), + Some("empty") => serde_json::json!({"tables": [], "page_token": "last"}), + Some("last") => serde_json::json!({"tables": ["apple"], "page_token": ""}), + token => panic!("unexpected page token: {token:?}"), + }; + axum::Json(page) + }, + ); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let connection = lancedb::connect("db://test") + .api_key("test") + .region("self-hosted") + .host_override(&endpoint) + .execute() + .await + .unwrap(); + + let tables = super::LanceDBClient::::table_names(&connection).await; + server.abort(); + assert_eq!(tables.unwrap(), ["apple", "zebra"]); + } + + #[tokio::test] + async fn http_connection_failure_preserves_status() { + for status in [ + axum::http::StatusCode::UNAUTHORIZED, + axum::http::StatusCode::FORBIDDEN, + ] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let app = axum::Router::new().fallback(move || async move { status }); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let connection = lancedb::connect("db://test") + .api_key("test") + .region("self-hosted") + .host_override(&endpoint) + .execute() + .await + .unwrap(); + let error = connection + .list_tables( + &[], + lancedb::listing::ListingOptions::default().page_limit(1), + ) + .next_page() + .await + .unwrap_err(); + server.abort(); + let message = super::connection_failure_message(&endpoint, "http", &error.into()); + assert!(message.contains(status.as_str()), "{message}"); + assert!(message.contains(&format!("{endpoint} (http)")), "{message}"); + assert!(!message.contains("connection refused"), "{message}"); + } + } + + #[tokio::test] + async fn sql_connection_failure_preserves_transport_cause() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let mut executor = super::SdkSqlExecutor::new_with_api_key(String::new(), String::new()); + let (_, error) = connect_sql_endpoint(&mut executor, &endpoint, "test") + .await + .unwrap(); + let message = super::connection_failure_message(&endpoint, "sql", &error.unwrap()); + assert!( + message.to_lowercase().contains("connection refused"), + "{message}" + ); + assert!(message.contains(&format!("{endpoint} (sql)")), "{message}"); + } + + /// The scheme a user configures must survive all the way to the transport; + /// the CLI used to rebuild every address as plaintext http. + #[tokio::test] + async fn sql_endpoint_preserves_the_configured_scheme() { + for (configured, dialed) in [ + ("localhost:10025", "http://localhost:10025"), + ("localhost", "http://localhost:10025"), + ("http://sql.example.com", "http://sql.example.com:80"), + ("https://sql.example.com", "https://sql.example.com:443"), + ( + "https://sql.example.com:10025", + "https://sql.example.com:10025", + ), + ( + "grpc://sql.example.com:10025", + "http://sql.example.com:10025", + ), + ( + "grpcs://sql.example.com:10025", + "https://sql.example.com:10025", + ), + ("grpcs://[fd00::1]:10025", "https://[fd00::1]:10025"), + ] { + let mut executor = MockSqlExecutor::new(); + let (url, err) = connect_sql_endpoint(&mut executor, configured, "analytics") + .await + .unwrap(); + + assert!(err.is_none()); + assert_eq!(url, dialed, "returned url for {configured}"); + assert_eq!( + executor.get_connected_urls(), + vec![dialed.to_string()], + "url handed to the executor for {configured}" + ); + } + } + + #[tokio::test] + async fn sql_endpoint_rejects_an_unusable_address() { + let mut executor = MockSqlExecutor::new(); + assert!( + connect_sql_endpoint(&mut executor, "ftp://sql.example.com", "analytics") + .await + .is_err() + ); + // A rejected address must not reach the transport at all. + assert!(executor.get_connected_urls().is_empty()); + } + + fn jobs(rows: usize) -> SqlResult { + let ids: Vec = (0..rows as i32).collect(); + SqlResult::Query(vec![ + arrow_array::record_batch!(("job_id", Int32, ids)).unwrap() + ]) + } + + #[test] + fn interactive_table_output_is_cut_and_annotated() { + let over = MAX_DISPLAYED_JOB_ROWS + 1; + let (result, notice) = prepare_show_jobs_result(jobs(over), true); + assert_eq!(row_count(&result), MAX_DISPLAYED_JOB_ROWS); + let notice = notice.unwrap(); + assert!(notice.contains(&format!("first {MAX_DISPLAYED_JOB_ROWS} of {over} jobs"))); + assert!(notice.contains("SHOW JOBS FOR
")); + assert!(notice.contains("lancedb sql --command 'SHOW JOBS' --format json")); + + // At or under the cap the listing is whole and says nothing. + let (result, notice) = prepare_show_jobs_result(jobs(MAX_DISPLAYED_JOB_ROWS), true); + assert_eq!(row_count(&result), MAX_DISPLAYED_JOB_ROWS); + assert!(notice.is_none()); + } + + /// A script reading `--format json` needs every row and a payload its + /// parser accepts, so neither the cut nor the notice may reach it. + #[test] + fn programmatic_output_keeps_every_row_and_stays_parsable() { + let over = MAX_DISPLAYED_JOB_ROWS + 1; + let (result, notice) = prepare_show_jobs_result(jobs(over), false); + assert_eq!(row_count(&result), over); + assert!(notice.is_none()); + + for format in [OutputFormat::Json, OutputFormat::Ndjson, OutputFormat::Csv] { + let output = ResultFormatter::new(format) + .format(&QueryResult::SqlResult(jobs(over))) + .unwrap(); + assert!( + !output.contains("Showing the first"), + "{format:?} output must carry no prose" + ); + } + } + + #[test] + fn show_jobs_is_recognized_through_leading_trivia() { + assert!(is_show_jobs("SHOW JOBS")); + assert!(is_show_jobs(" show jobs ;")); + assert!(is_show_jobs("-- list jobs\nSHOW JOBS;")); + assert!(is_show_jobs("/* list jobs */ SHOW JOBS")); + assert!(is_show_jobs("SHOW JOBS FOR t")); + + assert!(!is_show_jobs("SHOW JOBSX")); + assert!(!is_show_jobs("SELECT job_id FROM t")); + // A query that is only a comment names no statement at all. + assert!(!is_show_jobs("-- SHOW JOBS")); + } + + #[test] + fn copyable_columns_follow_the_statement() { + assert_eq!(copyable_columns("SELECT 1"), &[] as &[&str]); + assert_eq!(copyable_columns("cancel job 'x'"), &["job_id"]); + assert_eq!(copyable_columns("/* run */ Cancel Job 'x';"), &["job_id"]); + assert_eq!(copyable_columns("SHOW FUNCTIONS"), &["version"]); + assert_eq!( + copyable_columns("show errors on t"), + &["job_id", "function_version"] + ); + assert_eq!(copyable_columns("REFRESH COLUMN c ON t"), &["job_id"]); + assert_eq!(copyable_columns("REFRESH MATERIALIZED VIEW v"), &["job_id"]); + assert!(!is_show_jobs("/* SHOW JOBS")); + } +} + +#[cfg(test)] +mod watch_tests { + use super::*; + + #[test] + fn d_family_is_watchable() { + for cmd in [ + "\\d", + "\\d+", + "\\dt", + "\\dt+", + "\\di", + "\\di+", + "\\dj", + "\\dj+", + "\\d mytable", + "\\dj mytable", + ] { + assert!(is_watchable_metacommand(cmd), "{cmd} should be watchable"); + } + } + + #[test] + fn dj_maps_to_show_jobs() { + assert_eq!(show_jobs_statement(None), "SHOW JOBS"); + assert_eq!(show_jobs_statement(Some("t")), r#"SHOW JOBS FOR "t""#); + // Names that do not tokenize as a bare identifier; the parser-side + // round trip is pinned by `parses_show_jobs_for_quoted_table`. + assert_eq!( + show_jobs_statement(Some("my-table")), + r#"SHOW JOBS FOR "my-table""# + ); + assert_eq!(show_jobs_statement(Some("a.b")), r#"SHOW JOBS FOR "a.b""#); + assert_eq!( + show_jobs_statement(Some(r#"a"b"#)), + r#"SHOW JOBS FOR "a""b""# + ); + } + + #[test] + fn one_shot_and_watch_are_not_watchable() { + for cmd in [ + "\\watch", + "\\watch 5", + "\\c", + "\\e", + "\\q", + "\\?", + "\\h", + "", + ] { + assert!( + !is_watchable_metacommand(cmd), + "{cmd} should not be watchable" + ); + } + } + + #[test] + fn unrecognized_d_prefixed_commands_are_not_watchable() { + // A `\d`-prefixed typo/unsupported verb is rejected by + // `handle_metacommand`; it must not be treated as watchable, else it + // would clobber `last_command` and make `\watch` loop an error. + for cmd in ["\\dfoo", "\\ds", "\\dn", "\\dd", "\\d++"] { + assert!( + !is_watchable_metacommand(cmd), + "{cmd} should not be watchable" + ); + } + } + + #[test] + fn watch_interval_accepts_only_sane_positive_seconds() { + // Accept normal intervals, including exactly the floor. + assert!(watch_interval(2.0).is_some()); + assert!(watch_interval(0.5).is_some()); + assert!(watch_interval(MIN_WATCH_INTERVAL_SECS).is_some()); + // Reject non-positive, non-finite, and overflowing values (which would + // panic the sleep), plus positive-but-tiny values below the floor that + // would spin the loop with no real delay (e.g. 1e-20 rounds to a + // zero-length sleep; 1e-6 to a nonzero-but-negligible 1us). + for bad in [f64::INFINITY, 1e300, 0.0, -1.0, f64::NAN, 1e-20, 1e-6, 0.05] { + assert!(watch_interval(bad).is_none(), "{bad} should be rejected"); + } + } + + #[test] + fn parse_watch_args_reads_interval_and_optional_statement() { + // (input after `\watch`, expected secs, expected target) + let cases: &[(&str, f64, Option<&str>)] = &[ + ("", 2.0, None), + (" ", 2.0, None), + ("5", 5.0, None), + ("0.5", 0.5, None), + ("SELECT 1", 2.0, Some("SELECT 1")), + ("5 SELECT * FROM t", 5.0, Some("SELECT * FROM t")), + ("2.5 SELECT 1", 2.5, Some("SELECT 1")), + ("\\di+", 2.0, Some("\\di+")), + ("3 \\dt+", 3.0, Some("\\dt+")), + ]; + for (input, secs, target) in cases { + let got = parse_watch_args(input).unwrap_or_else(|e| panic!("{input:?}: {e}")); + assert_eq!( + got.interval, + Duration::from_secs_f64(*secs), + "interval for {input:?}" + ); + assert_eq!(got.target.as_deref(), *target, "target for {input:?}"); + } + } + + #[test] + fn parse_watch_args_rejects_numeric_but_invalid_intervals() { + // A numeric first token is always an interval attempt (never SQL), so + // an unusable one is an error rather than being treated as a statement. + for bad in [ + "0", + "-1", + "inf", + "1e300", + "1e-20", + "0 SELECT 1", + "-2 SELECT 1", + "1e-20 SELECT 1", + ] { + assert!(parse_watch_args(bad).is_err(), "{bad:?} should be rejected"); + } + } +} diff --git a/rust/lancedb/cli/src/dml_result.rs b/rust/lancedb/cli/src/dml_result.rs new file mode 100644 index 000000000..5955ce458 --- /dev/null +++ b/rust/lancedb/cli/src/dml_result.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Typed DML result serializable to/from RecordBatch for Arrow Flight transport. + +use arrow_array::{Int64Array, RecordBatch, StringArray}; +use arrow_schema::{DataType, Field, Schema}; +use std::fmt; +use std::sync::Arc; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum DmlOperation { + Insert, + Update, + Delete, +} + +impl DmlOperation { + pub fn as_str(self) -> &'static str { + match self { + Self::Insert => "INSERT", + Self::Update => "UPDATE", + Self::Delete => "DELETE", + } + } + + fn parse(s: &str) -> Option { + match s { + "INSERT" => Some(Self::Insert), + "UPDATE" => Some(Self::Update), + "DELETE" => Some(Self::Delete), + _ => None, + } + } +} + +impl fmt::Display for DmlOperation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DmlResult { + pub table: String, + pub operation: DmlOperation, + pub rows_affected: i64, + pub version: i64, +} + +fn schema() -> Schema { + Schema::new(vec![ + Field::new("table", DataType::Utf8, false), + Field::new("operation", DataType::Utf8, false), + Field::new("rows_affected", DataType::Int64, false), + Field::new("version", DataType::Int64, false), + ]) +} + +impl DmlResult { + pub fn new( + table: impl Into, + operation: DmlOperation, + rows_affected: i64, + version: i64, + ) -> Self { + Self { + table: table.into(), + operation, + rows_affected, + version, + } + } + + pub fn to_record_batch(&self) -> RecordBatch { + RecordBatch::try_new( + Arc::new(schema()), + vec![ + Arc::new(StringArray::from(vec![self.table.as_str()])), + Arc::new(StringArray::from(vec![self.operation.as_str()])), + Arc::new(Int64Array::from(vec![self.rows_affected])), + Arc::new(Int64Array::from(vec![self.version])), + ], + ) + .expect("static schema") + } + + pub fn try_from_batch(batch: &RecordBatch) -> Option { + if *batch.schema().as_ref() != schema() || batch.num_rows() != 1 { + return None; + } + Some(Self { + table: batch + .column(0) + .as_any() + .downcast_ref::()? + .value(0) + .to_string(), + operation: DmlOperation::parse( + batch + .column(1) + .as_any() + .downcast_ref::()? + .value(0), + )?, + rows_affected: batch + .column(2) + .as_any() + .downcast_ref::()? + .value(0), + version: batch + .column(3) + .as_any() + .downcast_ref::()? + .value(0), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip() { + let original = DmlResult::new("foo", DmlOperation::Insert, 1, 3); + let batch = original.to_record_batch(); + assert_eq!(DmlResult::try_from_batch(&batch), Some(original)); + } + + #[test] + fn non_dml_returns_none() { + let s = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = RecordBatch::try_new(s, vec![Arc::new(Int64Array::from(vec![1]))]).unwrap(); + assert_eq!(DmlResult::try_from_batch(&batch), None); + } +} diff --git a/rust/lancedb/cli/src/formatter.rs b/rust/lancedb/cli/src/formatter.rs new file mode 100644 index 000000000..05e6deb4d --- /dev/null +++ b/rust/lancedb/cli/src/formatter.rs @@ -0,0 +1,2516 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::client::{IndexInfo, IndexStats, TableInfo}; +use crate::sql_executor::SqlResult; +use crate::table_writer::TableWriter; +use anyhow::Result; +use arrow_array::types::ArrowDictionaryKeyType; +use arrow_array::{ + downcast_dictionary_array, Array, BinaryArray, BooleanArray, DictionaryArray, + FixedSizeListArray, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, + LargeBinaryArray, ListArray, RecordBatch, StringArray, UInt16Array, UInt32Array, UInt64Array, + UInt8Array, +}; +use arrow_buffer::ArrowNativeType; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_json::writer::{make_encoder, Encoder, EncoderFactory, EncoderOptions, NullableEncoder}; +use arrow_schema::{DataType, Field, Schema}; +use std::io::Write; +use std::str::FromStr; +use std::sync::Arc; +use tracing::warn; + +/// Result of a query engine command +#[derive(Debug)] +pub enum QueryResult { + /// SQL query result + SqlResult(SqlResult), + /// List of table names + TableList(Vec), + /// List of tables with detailed stats + TableListDetailed(Vec), + /// Table information + TableInfo(TableInfo), + /// Table information with indices + TableInfoWithIndices(TableInfo, Vec), + /// Index information + IndexList(Vec), + /// List of indices with detailed stats + IndexListDetailed(Vec<(IndexInfo, Option)>), +} + +/// Output format options +#[derive(Debug, Clone, Copy)] +pub enum OutputFormat { + Table, + Csv, + Json, + Ndjson, +} + +impl FromStr for OutputFormat { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "table" => Ok(Self::Table), + "csv" => Ok(Self::Csv), + "json" => Ok(Self::Json), + "ndjson" => Ok(Self::Ndjson), + _ => Err(anyhow::anyhow!( + "Invalid output format: {}. Must be one of: table, csv, json, ndjson", + s + )), + } + } +} + +/// Formats query results for display +pub struct ResultFormatter { + output_format: OutputFormat, + /// Optional override for the terminal width used to choose between table + /// and expanded rendering. `None` auto-detects from the terminal; + /// tests pin it so output is independent of the ambient terminal size. + terminal_width: Option, +} + +impl ResultFormatter { + /// Create a new ResultFormatter + pub fn new(output_format: OutputFormat) -> Self { + Self { + output_format, + terminal_width: None, + } + } + + pub fn with_terminal_width(mut self, width: usize) -> Self { + self.terminal_width = Some(width); + self + } + + pub fn output_format(&self) -> OutputFormat { + self.output_format + } + + /// Format a QueryResult to string + pub fn format(&self, result: &QueryResult) -> Result { + let mut output = Vec::new(); + self.format_to_writer(result, &mut output)?; + Ok(String::from_utf8(output)?) + } + + /// Format a QueryResult to a writer + pub fn format_to_writer(&self, result: &QueryResult, writer: &mut W) -> Result<()> { + match result { + QueryResult::SqlResult(sql_result) => self.format_sql_result(sql_result, writer), + QueryResult::TableList(tables) => self.format_table_list(tables, writer), + QueryResult::TableListDetailed(tables) => { + self.format_table_list_detailed(tables, writer) + } + QueryResult::TableInfo(info) => self.format_table_info(info, writer), + QueryResult::TableInfoWithIndices(info, indices) => { + self.format_table_info_with_indices(info, indices, writer) + } + QueryResult::IndexList(indices) => self.format_index_list(indices, writer), + QueryResult::IndexListDetailed(indices) => { + self.format_index_list_detailed(indices, writer) + } + } + } + + /// Format SQL result + fn format_sql_result(&self, result: &SqlResult, writer: &mut W) -> Result<()> { + match result { + SqlResult::Query(batches) => self.format_record_batches(batches, writer), + SqlResult::Dml(dml) => { + writeln!( + writer, + "{} {} row(s), version {}", + dml.operation, dml.rows_affected, dml.version + )?; + Ok(()) + } + SqlResult::Success => { + writeln!(writer, "Success")?; + Ok(()) + } + } + } + + /// Format record batches + pub fn format_record_batches( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + if batches.is_empty() { + return Ok(()); + } + + match self.output_format { + OutputFormat::Table => self.format_batches_as_table(batches, writer), + OutputFormat::Csv => self.format_batches_as_csv(batches, writer), + OutputFormat::Json => self.format_batches_as_json(batches, writer), + OutputFormat::Ndjson => self.format_batches_as_ndjson(batches, writer), + } + } + + /// Format batches as table + fn format_batches_as_table( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + let schema = batches[0].schema(); + let column_names: Vec = schema.fields().iter().map(|f| f.name().clone()).collect(); + + // Check if this is an EXPLAIN query (has plan_type and plan columns) + let is_explain = + column_names.len() == 2 && column_names[0] == "plan_type" && column_names[1] == "plan"; + + if is_explain { + return self.format_explain_results(batches, writer); + } + + let mut rows = Vec::new(); + let mut total_rows = 0; + + for batch in batches { + total_rows += batch.num_rows(); + for row_idx in 0..batch.num_rows() { + let mut row = Vec::new(); + for col_idx in 0..batch.num_columns() { + let column = batch.column(col_idx); + let field = schema.field(col_idx); + let value = format_arrow_value(column, row_idx, field); + row.push(value); + } + rows.push(row); + } + } + + TableWriter::print_table(writer, &column_names, &rows, self.terminal_width)?; + writeln!( + writer, + "({} row{})", + total_rows, + if total_rows == 1 { "" } else { "s" } + )?; + Ok(()) + } + + /// Format EXPLAIN query results + fn format_explain_results( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + writeln!( + writer, + " QUERY PLAN" + )?; + writeln!(writer, "---------------------------------------------------------------------------------------------------")?; + + let mut logical_plan = String::new(); + let mut physical_plan = String::new(); + let mut plan_with_metrics = String::new(); + + // Extract the plans from the batches + for batch in batches { + for row_idx in 0..batch.num_rows() { + if batch.num_columns() >= 2 { + let plan_type_col = batch.column(0); + let plan_col = batch.column(1); + + let plan_type = plan_type_col + .as_any() + .downcast_ref::() + .map(|arr| arr.value(row_idx)) + .unwrap_or(""); + + let plan = plan_col + .as_any() + .downcast_ref::() + .map(|arr| arr.value(row_idx)) + .unwrap_or(""); + + match plan_type { + "logical_plan" => logical_plan = plan.to_string(), + "physical_plan" => physical_plan = plan.to_string(), + "Plan with Metrics" => plan_with_metrics = plan.to_string(), + _ => {} + } + } + } + } + + // Display logical plan + if !logical_plan.is_empty() { + writeln!(writer, "Logical Plan:")?; + for line in logical_plan.lines() { + writeln!(writer, " {}", line)?; + } + } + + // Display physical plan + if !physical_plan.is_empty() { + if !logical_plan.is_empty() { + writeln!(writer)?; + } + writeln!(writer, "Physical Plan:")?; + for line in physical_plan.lines() { + writeln!(writer, " {}", line)?; + } + } + + // Display plan with metrics (EXPLAIN ANALYZE) + if !plan_with_metrics.is_empty() { + if !logical_plan.is_empty() || !physical_plan.is_empty() { + writeln!(writer)?; + } + for line in plan_with_metrics.lines() { + writeln!(writer, "{}", line)?; + } + } + + writeln!( + writer, + "({} row{})", + batches.iter().map(|b| b.num_rows()).sum::(), + if batches.iter().map(|b| b.num_rows()).sum::() == 1 { + "" + } else { + "s" + } + )?; + Ok(()) + } + + /// Format batches as CSV + fn format_batches_as_csv( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + let schema = batches[0].schema(); + + for (index, field) in schema.fields().iter().enumerate() { + if index > 0 { + write!(writer, ",")?; + } + write_csv_value(writer, field.name())?; + } + writeln!(writer)?; + + let scalar_options = FormatOptions::default(); + let json_options = EncoderOptions::default() + .with_explicit_nulls(true) + .with_encoder_factory(Arc::new(CsvJsonEncoderFactory)); + let mut json_value = Vec::new(); + + for batch in batches { + if batch.num_rows() == 0 { + continue; + } + let schema = batch.schema(); + let mut formatters = schema + .fields() + .iter() + .zip(batch.columns()) + .map(|(field, column)| { + if csv_uses_json(column.data_type()) { + Ok(CsvValueFormatter::Json(make_encoder( + field, + column.as_ref(), + &json_options, + )?)) + } else { + Ok(CsvValueFormatter::Scalar(ArrayFormatter::try_new( + column.as_ref(), + &scalar_options, + )?)) + } + }) + .collect::>>()?; + let nulls: Vec<_> = batch + .columns() + .iter() + .map(|column| column.logical_nulls()) + .collect(); + + for row_idx in 0..batch.num_rows() { + for (col_idx, formatter) in formatters.iter_mut().enumerate() { + if col_idx > 0 { + write!(writer, ",")?; + } + // Logical nulls include null dictionary values and Null arrays. + if nulls[col_idx] + .as_ref() + .is_some_and(|nulls| nulls.is_null(row_idx)) + { + write!(writer, "{CSV_NULL_VALUE}")?; + continue; + } + match formatter { + CsvValueFormatter::Scalar(formatter) => { + write_csv_cell(writer, &formatter.value(row_idx).try_to_string()?)?; + } + CsvValueFormatter::Json(encoder) => { + json_value.clear(); + encoder.encode(row_idx, &mut json_value); + write_csv_cell(writer, std::str::from_utf8(&json_value)?)?; + } + } + } + writeln!(writer)?; + } + } + Ok(()) + } + + /// Format batches as JSON + fn format_batches_as_json( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + if batches.is_empty() { + writeln!(writer, "[]")?; + return Ok(()); + } + // Arrow's bytes go out as written. Re-reading them through + // `serde_json::Value` to pretty-print would round every decimal the + // writer emitted exactly. + let mut json = Vec::new(); + let mut json_writer = arrow_json::writer::WriterBuilder::new() + .with_explicit_nulls(true) + .build::<_, arrow_json::writer::JsonArray>(&mut json); + for batch in batches { + json_writer.write(batch)?; + } + json_writer.finish()?; + writer.write_all(&json)?; + writeln!(writer)?; + Ok(()) + } + + /// Format batches as NDJSON + fn format_batches_as_ndjson( + &self, + batches: &[RecordBatch], + writer: &mut W, + ) -> Result<()> { + if batches.is_empty() { + return Ok(()); + } + let mut json = Vec::new(); + let mut json_writer = arrow_json::writer::WriterBuilder::new() + .with_explicit_nulls(true) + .build::<_, arrow_json::writer::LineDelimited>(&mut json); + for batch in batches { + json_writer.write(batch)?; + } + json_writer.finish()?; + writer.write_all(&json)?; + Ok(()) + } + + /// Format table list + fn format_table_list(&self, tables: &[String], writer: &mut W) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::to_string_pretty(&tables)?; + writeln!(writer, "{}", json)?; + } + _ => { + if tables.is_empty() { + writeln!(writer, "Did not find any relations.")?; + } else { + let headers = vec!["Tables".to_string()]; + let data: Vec> = tables.iter().map(|t| vec![t.clone()]).collect(); + TableWriter::print_table_with_title( + writer, + "List of relations", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + tables.len(), + if tables.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } + + /// Format detailed table list with stats + fn format_table_list_detailed( + &self, + tables: &[TableInfo], + writer: &mut W, + ) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::json!(tables + .iter() + .map(|t| { + serde_json::json!({ + "name": t.name, + "type": "table", + "rows": t.row_count, + "size_bytes": t.size_bytes, + "indices": t.num_indices, + "fragments": t.num_fragments, + }) + }) + .collect::>()); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + _ => { + if tables.is_empty() { + writeln!(writer, "Did not find any relations.")?; + } else { + let headers = vec![ + "Name".to_string(), + "Type".to_string(), + "Rows".to_string(), + "Size".to_string(), + "Indices".to_string(), + "Fragments".to_string(), + ]; + + let data: Vec> = tables + .iter() + .map(|t| { + vec![ + t.name.clone(), + "table".to_string(), + t.row_count.map_or("".to_string(), |r| r.to_string()), + t.size_bytes.map_or("".to_string(), format_bytes), + t.num_indices + .filter(|&n| n > 0) + .map_or("".to_string(), |n| n.to_string()), + t.num_fragments + .filter(|&n| n > 0) + .map_or("".to_string(), |n| n.to_string()), + ] + }) + .collect(); + + TableWriter::print_table_with_title( + writer, + "List of relations", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + tables.len(), + if tables.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } + + /// Format table info + fn format_table_info(&self, info: &TableInfo, writer: &mut W) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::json!({ + "name": info.name, + "schema": schema_to_json(&info.schema), + "row_count": info.row_count, + "size_bytes": info.size_bytes, + "num_indices": info.num_indices, + "num_fragments": info.num_fragments, + }); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + _ => { + // Format as table + writeln!(writer, " Table \"{}\"", info.name)?; + + let headers = vec![ + "Column".to_string(), + "Type".to_string(), + "Nullable".to_string(), + ]; + let mut data = Vec::new(); + + for field in info.schema.fields() { + let data_type = format_data_type(field.data_type()); + let nullable = if field.is_nullable() { "YES" } else { "" }; + data.push(vec![field.name().clone(), data_type, nullable.to_string()]); + } + + TableWriter::print_table(writer, &headers, &data, self.terminal_width)?; + + // Add stats if available + if let Some(row_count) = info.row_count { + writeln!(writer, "\nRows: {}", row_count)?; + } + if let Some(size) = info.size_bytes { + writeln!(writer, "Size: {}", format_bytes(size))?; + } + } + } + Ok(()) + } + + /// Format table info with indices (similar to psql \d
) + fn format_table_info_with_indices( + &self, + info: &TableInfo, + indices: &[IndexInfo], + writer: &mut W, + ) -> Result<()> { + match self.output_format { + OutputFormat::Table => { + // Format as table (psql style) + writeln!(writer, " Table \"{}\"", info.name)?; + + let headers = vec![ + "Column".to_string(), + "Type".to_string(), + "Nullable".to_string(), + ]; + let mut data = Vec::new(); + for field in info.schema.fields() { + let data_type = format_data_type(field.data_type()); + let nullable = if field.is_nullable() { "YES" } else { "" }; + data.push(vec![field.name().clone(), data_type, nullable.to_string()]); + } + TableWriter::print_table(writer, &headers, &data, self.terminal_width)?; + + // List indexes if any + if !indices.is_empty() { + writeln!(writer, "Indexes:")?; + for index in indices { + let columns = index.columns.join(", "); + writeln!( + writer, + " \"{}\" {} ({})", + index.name, index.index_type, columns + )?; + } + } + + // Add stats if available + if let Some(row_count) = info.row_count { + writeln!(writer, "\nRows: {}", row_count)?; + } + if let Some(size) = info.size_bytes { + writeln!(writer, "Size: {}", format_bytes(size))?; + } + } + OutputFormat::Csv => { + // CSV format: output schema info and indices as separate sections + writeln!(writer, "# Table: {}", info.name)?; + writeln!(writer, "# Schema")?; + writeln!(writer, "Column,Type,Nullable")?; + for field in info.schema.fields() { + let data_type = format_data_type(field.data_type()); + let nullable = if field.is_nullable() { "YES" } else { "NO" }; + writeln!(writer, "{},{},{}", field.name(), data_type, nullable)?; + } + + if !indices.is_empty() { + writeln!(writer, "\n# Indices")?; + writeln!(writer, "Index Name,Index Type,Columns")?; + for index in indices { + let columns = index.columns.join(";"); + writeln!(writer, "{},{},{}", index.name, index.index_type, columns)?; + } + } + + if let Some(row_count) = info.row_count { + writeln!(writer, "\n# Row Count: {}", row_count)?; + } + if let Some(size) = info.size_bytes { + writeln!(writer, "# Size: {}", format_bytes(size))?; + } + } + OutputFormat::Json => { + let json = serde_json::json!({ + "name": info.name, + "schema": schema_to_json(&info.schema), + "row_count": info.row_count, + "size_bytes": info.size_bytes, + "num_indices": info.num_indices, + "num_fragments": info.num_fragments, + "indices": indices, + }); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + OutputFormat::Ndjson => { + // NDJSON: one line for table info, one line per index + let table_json = serde_json::json!({ + "type": "table_info", + "name": info.name, + "schema": schema_to_json(&info.schema), + "row_count": info.row_count, + "size_bytes": info.size_bytes, + "num_indices": info.num_indices, + "num_fragments": info.num_fragments, + }); + writeln!(writer, "{}", serde_json::to_string(&table_json)?)?; + + for index in indices { + let index_json = serde_json::json!({ + "type": "index_info", + "table": info.name, + "name": index.name, + "index_type": index.index_type, + "columns": index.columns, + }); + writeln!(writer, "{}", serde_json::to_string(&index_json)?)?; + } + } + } + Ok(()) + } + + /// Format index list + fn format_index_list(&self, indices: &[IndexInfo], writer: &mut W) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::to_string_pretty(&indices)?; + writeln!(writer, "{}", json)?; + } + _ => { + if indices.is_empty() { + writeln!(writer, "Did not find any indexes.")?; + } else { + let headers = vec!["Name".to_string(), "Type".to_string(), "Table".to_string()]; + let data: Vec> = indices + .iter() + .map(|idx| { + vec![ + idx.name.clone(), + idx.index_type.clone(), + idx.table_name.clone(), + ] + }) + .collect(); + + TableWriter::print_table_with_title( + writer, + "List of indices", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + indices.len(), + if indices.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } + + /// Format detailed index list with stats + fn format_index_list_detailed( + &self, + indices: &[(IndexInfo, Option)], + writer: &mut W, + ) -> Result<()> { + match self.output_format { + OutputFormat::Json => { + let json = serde_json::json!(indices + .iter() + .map(|(info, stats)| { + let mut obj = serde_json::json!({ + "name": info.name, + "type": info.index_type, + "table": info.table_name, + "columns": info.columns, + }); + if let Some(stats) = stats { + obj["distance_type"] = serde_json::json!(stats.distance_type); + obj["indexed_rows"] = serde_json::json!(stats.num_indexed_rows); + obj["unindexed_rows"] = serde_json::json!(stats.num_unindexed_rows); + } + obj + }) + .collect::>()); + let json_string = serde_json::to_string_pretty(&json)?; + writeln!(writer, "{}", json_string)?; + } + _ => { + if indices.is_empty() { + writeln!(writer, "Did not find any indexes.")?; + } else { + let headers = vec![ + "Name".to_string(), + "Type".to_string(), + "Distance".to_string(), + "Indexed Rows".to_string(), + "Unindexed Rows".to_string(), + "Table".to_string(), + ]; + + let data: Vec> = indices + .iter() + .map(|(info, stats)| { + let (distance, indexed, unindexed) = if let Some(s) = stats { + ( + s.distance_type.as_deref().unwrap_or(""), + s.num_indexed_rows.to_string(), + s.num_unindexed_rows.to_string(), + ) + } else { + ("", "".to_string(), "".to_string()) + }; + + vec![ + info.name.clone(), + info.index_type.clone(), + distance.to_string(), + indexed, + unindexed, + info.table_name.clone(), + ] + }) + .collect(); + + TableWriter::print_table_with_title( + writer, + "List of relations", + &headers, + &data, + self.terminal_width, + )?; + writeln!( + writer, + "({} row{})", + indices.len(), + if indices.len() == 1 { "" } else { "s" } + )?; + } + } + } + Ok(()) + } +} + +// Helper functions + +enum CsvValueFormatter<'a> { + Scalar(ArrayFormatter<'a>), + Json(NullableEncoder<'a>), +} + +fn csv_uses_json(data_type: &DataType) -> bool { + match data_type { + DataType::Dictionary(_, value) => csv_uses_json(value), + DataType::RunEndEncoded(_, value) => csv_uses_json(value.data_type()), + _ => data_type.is_nested(), + } +} + +const CSV_NULL_VALUE: &str = r"\N"; + +fn write_csv_cell(writer: &mut W, value: &str) -> Result<()> { + // Escape leading backslashes so the null marker cannot collide with data. + if value.starts_with('\\') { + write_csv_value(writer, &format!("\\{value}")) + } else { + write_csv_value(writer, value) + } +} + +fn write_csv_value(writer: &mut W, value: &str) -> Result<()> { + // An empty single-column record must not become a blank line. + if value.is_empty() || value.contains([',', '"', '\n', '\r']) { + write!(writer, "\"{}\"", value.replace('"', "\"\""))?; + } else { + write!(writer, "{value}")?; + } + Ok(()) +} + +#[derive(Debug)] +struct CsvJsonEncoderFactory; + +impl EncoderFactory for CsvJsonEncoderFactory { + fn make_default_encoder<'a>( + &self, + field: &'a arrow_schema::FieldRef, + array: &'a dyn arrow_array::Array, + options: &'a EncoderOptions, + ) -> std::result::Result>, arrow_schema::ArrowError> { + downcast_dictionary_array! { + array => { + let values = make_encoder(field, array.values().as_ref(), options)?; + // Parent encoders must see keys pointing to null values as nulls. + return Ok(Some(NullableEncoder::new( + Box::new(CsvJsonDictionaryEncoder { dictionary: array, values }), + array.logical_nulls(), + ))); + } + _ => {} + } + if !matches!( + array.data_type(), + DataType::Float16 | DataType::Float32 | DataType::Float64 + ) { + return Ok(None); + } + let formatter = ArrayFormatter::try_new(array, &FormatOptions::default())?; + Ok(Some(NullableEncoder::new( + Box::new(CsvJsonFloatEncoder(formatter)), + array.nulls().cloned(), + ))) + } +} + +struct CsvJsonDictionaryEncoder<'a, K: ArrowDictionaryKeyType> { + dictionary: &'a DictionaryArray, + values: NullableEncoder<'a>, +} + +impl Encoder for CsvJsonDictionaryEncoder<'_, K> { + fn encode(&mut self, idx: usize, out: &mut Vec) { + self.values + .encode(self.dictionary.keys().value(idx).as_usize(), out); + } +} + +struct CsvJsonFloatEncoder<'a>(ArrayFormatter<'a>); + +impl Encoder for CsvJsonFloatEncoder<'_> { + fn encode(&mut self, idx: usize, out: &mut Vec) { + let value = self.0.value(idx).to_string(); + // JSON has no non-finite numbers; keep their names instead of turning + // them into nulls, as Arrow's default JSON float encoder does. + if matches!(value.as_str(), "NaN" | "inf" | "-inf") { + out.push(b'"'); + out.extend_from_slice(value.as_bytes()); + out.push(b'"'); + } else { + out.extend_from_slice(value.as_bytes()); + } + } +} + +/// Longest string rendered in full when a column has not opted out of +/// truncation. +const MAX_UNTRUNCATED_STRING_LEN: usize = 50; + +/// Arrow field metadata key marking a column that must be rendered in full. +const NO_TRUNCATE_METADATA_KEY: &str = "lancedb.display.no_truncate"; + +/// Whether this field is marked to render in full. +fn field_opts_out_of_truncation(field: &Field) -> bool { + field + .metadata() + .get(NO_TRUNCATE_METADATA_KEY) + .is_some_and(|value| value == "true") +} + +/// Rows a query returned, across batches. Zero for non-query results. +pub fn row_count(result: &SqlResult) -> usize { + match result { + SqlResult::Query(batches) => batches.iter().map(RecordBatch::num_rows).sum(), + _ => 0, + } +} + +/// Keep the first `limit` rows, for a listing whose reader is a human at a +/// terminal rather than a program. Slices are zero-copy, so the dropped rows +/// cost nothing beyond the memory they already occupy. Non-query results pass +/// through. +pub fn take_rows(result: SqlResult, limit: usize) -> SqlResult { + let SqlResult::Query(batches) = result else { + return result; + }; + + let mut remaining = limit; + let mut kept = Vec::with_capacity(batches.len()); + for batch in batches { + if remaining == 0 { + break; + } + let take = remaining.min(batch.num_rows()); + remaining -= take; + kept.push(batch.slice(0, take)); + } + SqlResult::Query(kept) +} + +/// Mark `columns` so rendering keeps their values whole, for results whose +/// consumer needs to copy a value verbatim rather than read it. +pub fn mark_no_truncate(result: SqlResult, columns: &[&str]) -> SqlResult { + match result { + SqlResult::Query(batches) => SqlResult::Query( + batches + .into_iter() + .map(|batch| mark_batch_columns(batch, columns)) + .collect(), + ), + other => other, + } +} + +/// Rebuild `batch` with the named fields marked, leaving its data untouched. +fn mark_batch_columns(batch: RecordBatch, columns: &[&str]) -> RecordBatch { + let schema = batch.schema(); + let fields: Vec = schema + .fields() + .iter() + .map(|field| { + if !columns.contains(&field.name().as_str()) { + return field.as_ref().clone(); + } + let mut metadata = field.metadata().clone(); + metadata.insert(NO_TRUNCATE_METADATA_KEY.to_string(), "true".to_string()); + field.as_ref().clone().with_metadata(metadata) + }) + .collect(); + + let marked = Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone())); + match RecordBatch::try_new(marked, batch.columns().to_vec()) { + Ok(batch) => batch, + // Only the metadata changed, so this should not fail. Render the + // original rather than the error, at the cost of abbreviating them. + Err(err) => { + warn!("could not mark columns to render in full, values may be abbreviated: {err}"); + batch + } + } +} + +/// Render a string cell, abbreviating it unless the field opts out. +fn format_string_value(value: &str, field: &Field) -> String { + if value.len() <= MAX_UNTRUNCATED_STRING_LEN || field_opts_out_of_truncation(field) { + return value.to_string(); + } + let end = value.floor_char_boundary(MAX_UNTRUNCATED_STRING_LEN); + format!("{}...({} chars)", &value[..end], value.chars().count()) +} + +/// Format arrow value as string +fn format_arrow_value(column: &dyn arrow_array::Array, row_idx: usize, field: &Field) -> String { + if column.is_null(row_idx) { + return "NULL".to_string(); + } + + match field.data_type() { + DataType::Utf8 => { + let array = column.as_any().downcast_ref::().unwrap(); + format_string_value(array.value(row_idx), field) + } + DataType::LargeUtf8 => { + let array = column + .as_any() + .downcast_ref::() + .unwrap(); + format_string_value(array.value(row_idx), field) + } + DataType::Utf8View => { + let array = column + .as_any() + .downcast_ref::() + .unwrap(); + format_string_value(array.value(row_idx), field) + } + DataType::Int8 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Int16 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Int32 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Int64 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt8 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt16 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt32 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::UInt64 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Float32 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Float64 => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::Boolean => { + let array = column.as_any().downcast_ref::().unwrap(); + array.value(row_idx).to_string() + } + DataType::FixedSizeList(inner_field, size) => { + // Handle fixed size vectors (e.g., embeddings) + let list_array = column + .as_any() + .downcast_ref::() + .unwrap(); + let values = list_array.value(row_idx); + + // Format as [value1, value2, ...] for short vectors, with size info for long ones + match inner_field.data_type() { + DataType::Float32 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Float64 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + _ => { + format!("[{} items]", *size) + } + } + } + DataType::List(inner_field) => { + // Handle variable size lists + let list_array = column.as_any().downcast_ref::().unwrap(); + let values = list_array.value(row_idx); + let size = values.len(); + + // Format as [value1, value2, ...] for short vectors, truncated for long ones + match inner_field.data_type() { + DataType::Float32 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Float64 => { + let float_array = values.as_any().downcast_ref::().unwrap(); + if float_array.len() > 10 { + let first = float_array.value(0); + let second = float_array.value(1); + format!("[{}, {}, ...{} more]", first, second, float_array.len() - 2) + } else { + // Show all values if 10 or fewer + let values: Vec = (0..float_array.len()) + .map(|i| float_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Int32 => { + let int_array = values.as_any().downcast_ref::().unwrap(); + if int_array.len() > 10 { + let first = int_array.value(0); + let second = int_array.value(1); + format!("[{}, {}, ...{} more]", first, second, int_array.len() - 2) + } else { + let values: Vec = (0..int_array.len()) + .map(|i| int_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Int64 => { + let int_array = values.as_any().downcast_ref::().unwrap(); + if int_array.len() > 10 { + let first = int_array.value(0); + let second = int_array.value(1); + format!("[{}, {}, ...{} more]", first, second, int_array.len() - 2) + } else { + let values: Vec = (0..int_array.len()) + .map(|i| int_array.value(i).to_string()) + .collect(); + format!("[{}]", values.join(", ")) + } + } + _ => { + format!("[{} items]", size) + } + } + } + DataType::Binary => { + let array = column.as_any().downcast_ref::().unwrap(); + let bytes = array.value(row_idx); + if bytes.len() > 32 { + // Show first few bytes with ellipsis for large binary data + let preview: Vec = bytes[..8].iter().map(|b| format!("{}", b)).collect(); + format!( + "[{}, ...{} more bytes]", + preview.join(", "), + bytes.len() - 8 + ) + } else { + // Show all bytes if small + let values: Vec = bytes.iter().map(|b| format!("{}", b)).collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::LargeBinary => { + let array = column.as_any().downcast_ref::().unwrap(); + let bytes = array.value(row_idx); + if bytes.len() > 32 { + // Show first few bytes with ellipsis for large binary data + let preview: Vec = bytes[..8].iter().map(|b| format!("{}", b)).collect(); + format!( + "[{}, ...{} more bytes]", + preview.join(", "), + bytes.len() - 8 + ) + } else { + // Show all bytes if small + let values: Vec = bytes.iter().map(|b| format!("{}", b)).collect(); + format!("[{}]", values.join(", ")) + } + } + DataType::Struct(fields) => { + let struct_array = column + .as_any() + .downcast_ref::() + .unwrap(); + let mut field_strs = Vec::new(); + + for (i, field) in fields.iter().enumerate() { + let field_column = struct_array.column(i); + let field_value = format_arrow_value(field_column, row_idx, field); + field_strs.push(format!("{}: {}", field.name(), field_value)); + } + + format!("{{{}}}", field_strs.join(", ")) + } + _ => arrow_cast::display::array_value_to_string(column, row_idx) + .unwrap_or_else(|_| format!("{:?}", column.slice(row_idx, 1))), + } +} + +/// Format arrow value as JSON +/// Convert batches to JSON +/// Format data type for display +fn format_data_type(data_type: &arrow_schema::DataType) -> String { + use arrow_schema::DataType; + + match data_type { + DataType::Boolean => "BOOLEAN".to_string(), + DataType::Int8 => "TINYINT".to_string(), + DataType::Int16 => "SMALLINT".to_string(), + DataType::Int32 => "INT".to_string(), + DataType::Int64 => "BIGINT".to_string(), + DataType::UInt8 => "TINYINT UNSIGNED".to_string(), + DataType::UInt16 => "SMALLINT UNSIGNED".to_string(), + DataType::UInt32 => "INT UNSIGNED".to_string(), + DataType::UInt64 => "BIGINT UNSIGNED".to_string(), + DataType::Float32 => "FLOAT".to_string(), + DataType::Float64 => "DOUBLE".to_string(), + DataType::Utf8 => "TEXT".to_string(), + DataType::LargeUtf8 => "TEXT".to_string(), + DataType::Binary => "BLOB".to_string(), + DataType::LargeBinary => "BLOB".to_string(), + DataType::Date32 => "DATE".to_string(), + DataType::Date64 => "DATE".to_string(), + DataType::Timestamp(_unit, tz) => { + let tz_str = tz.as_ref().map(|s| format!(" ({})", s)).unwrap_or_default(); + format!("TIMESTAMP{}", tz_str) + } + DataType::Time32(_) => "TIME".to_string(), + DataType::Time64(_) => "TIME".to_string(), + DataType::Decimal128(precision, scale) => format!("DECIMAL({}, {})", precision, scale), + DataType::Decimal256(precision, scale) => format!("DECIMAL({}, {})", precision, scale), + DataType::List(field) => format!("LIST<{}>", format_data_type(field.data_type())), + DataType::FixedSizeList(field, size) => { + format!("{}[{}]", format_data_type(field.data_type()), size) + } + DataType::Struct(fields) => { + let field_types: Vec = fields + .iter() + .map(|f| format!("{}: {}", f.name(), format_data_type(f.data_type()))) + .collect(); + format!("STRUCT<{}>", field_types.join(", ")) + } + _ => format!("{:?}", data_type), + } +} + +/// Format bytes to human readable +fn format_bytes(bytes: u64) -> String { + const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB", "PB"]; + if bytes == 0 { + return "0 B".to_string(); + } + + let mut size = bytes as f64; + let mut unit_index = 0; + + while size >= 1024.0 && unit_index < UNITS.len() - 1 { + size /= 1024.0; + unit_index += 1; + } + + if unit_index == 0 { + format!("{} {}", bytes, UNITS[unit_index]) + } else { + format!("{:.1} {}", size, UNITS[unit_index]) + } +} + +/// Convert schema to JSON +fn schema_to_json(schema: &Schema) -> serde_json::Value { + use serde_json::json; + + let fields: Vec = schema + .fields() + .iter() + .map(|field| { + json!({ + "name": field.name(), + "type": format_data_type(field.data_type()), + "nullable": field.is_nullable(), + }) + }) + .collect(); + + json!(fields) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::IndexStats; + use crate::dml_result::{DmlOperation, DmlResult}; + use arrow_array::{ + ArrayRef, BooleanArray, FixedSizeListArray, Float32Array, Int32Array, StringArray, + }; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + fn create_test_batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("name", DataType::Utf8, false), + Field::new("score", DataType::Float32, true), + Field::new("active", DataType::Boolean, false), + ])); + + let id_array = Int32Array::from(vec![1, 2, 3]); + let name_array = StringArray::from(vec!["Alice", "Bob", "Charlie"]); + let score_array = Float32Array::from(vec![Some(95.5), None, Some(87.3)]); + let active_array = BooleanArray::from(vec![true, false, true]); + + RecordBatch::try_new( + schema, + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(name_array) as ArrayRef, + Arc::new(score_array) as ArrayRef, + Arc::new(active_array) as ArrayRef, + ], + ) + .unwrap() + } + + fn create_vector_batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "embedding", + DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, true)), + 1024, + ), + false, + ), + ])); + + let id_array = Int32Array::from(vec![1, 2]); + + // Create vectors for 2 rows, each with 1024 elements + let mut vector_data = vec![]; + for row in 0..2 { + for i in 0..1024 { + vector_data.push((row * 1024 + i) as f32 * 0.001); + } + } + let values = Float32Array::from(vector_data); + let list_array = FixedSizeListArray::new( + Arc::new(Field::new("item", DataType::Float32, true)), + 1024, + Arc::new(values), + None, + ); + + RecordBatch::try_new( + schema, + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(list_array) as ArrayRef, + ], + ) + .unwrap() + } + + #[test] + fn test_table_format() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + let expected = concat!( + " id | name | score | active\n", + "----+---------+-------+--------\n", + " 1 | Alice | 95.5 | true \n", + " 2 | Bob | NULL | false \n", + " 3 | Charlie | 87.3 | true \n", + "(3 rows)\n", + ); + + assert_eq!(output, expected); + } + + #[test] + fn test_csv_format() { + let formatter = ResultFormatter::new(OutputFormat::Csv); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + // Check CSV header + assert!(output.starts_with("id,name,score,active\n")); + + // Check data rows + assert!(output.contains("1,Alice,95.5,true")); + assert!(output.contains("2,Bob,\\N,false")); + assert!(output.contains("3,Charlie,87.3,true")); + } + + #[test] + fn test_json_format() { + let formatter = ResultFormatter::new(OutputFormat::Json); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + let json: serde_json::Value = serde_json::from_str(&output).unwrap(); + + assert!(json.is_array()); + let array = json.as_array().unwrap(); + assert_eq!(array.len(), 3); + + // Check first row + assert_eq!(array[0]["id"], 1); + assert_eq!(array[0]["name"], "Alice"); + assert_eq!(array[0]["score"], 95.5); + assert_eq!(array[0]["active"], true); + + // Check NULL handling + assert_eq!(array[1]["score"], serde_json::Value::Null); + } + + /// A timestamp renders as its value, not the `Debug` dump of a one-row array. + #[test] + fn test_table_renders_timestamp_value() { + let ts = arrow_array::TimestampMillisecondArray::from(vec![1_758_217_603_403]) + .with_timezone("UTC"); + let batch = + RecordBatch::try_from_iter(vec![("last_refresh", Arc::new(ts) as ArrayRef)]).unwrap(); + + let output = ResultFormatter::new(OutputFormat::Table) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + + assert_eq!( + output, + " last_refresh \n--------------------------\n 2025-09-18T17:46:43.403Z\n(1 row)\n" + ); + } + + /// Arrow writes the exact decimal token; re-reading it through a + /// `serde_json::Value` would round it to the nearest double. + #[test] + fn test_json_preserves_exact_decimal_tokens() { + let amounts = + arrow_array::Decimal128Array::from(vec![123_456_789_012_345_678_901_234_567_890_i128]) + .with_precision_and_scale(30, 10) + .unwrap(); + let batch = RecordBatch::try_from_iter(vec![( + "amount", + Arc::new(amounts) as arrow_array::ArrayRef, + )]) + .unwrap(); + + let output = ResultFormatter::new(OutputFormat::Json) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + + assert!( + output.contains("12345678901234567890.1234567890"), + "decimal token was rewritten: {output}" + ); + } + + /// The display path elides a long value and previews a list; a machine + /// format has to carry both whole. + #[test] + fn test_json_is_lossless_for_long_and_nested_values() { + let long = "x".repeat(80); + let listed = + arrow_array::ListArray::from_iter_primitive::([ + Some(vec![Some(1), Some(2), Some(3)]), + ]); + let batch = RecordBatch::try_from_iter(vec![ + ( + "note", + Arc::new(arrow_array::LargeStringArray::from(vec![long.as_str()])) + as arrow_array::ArrayRef, + ), + ("scores", Arc::new(listed) as arrow_array::ArrayRef), + ]) + .unwrap(); + + let output = ResultFormatter::new(OutputFormat::Json) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + let json: serde_json::Value = serde_json::from_str(&output).unwrap(); + + assert_eq!(json[0]["note"], long); + assert_eq!(json[0]["scores"], serde_json::json!([1, 2, 3])); + } + + /// A narrow integer used to fall through to a debug dump of the sliced + /// array; `SHOW ERRORS` returns `row_offset` as one. + #[test] + fn test_json_renders_narrow_integers_as_numbers() { + let batch = arrow_array::record_batch!( + ("row_offset", UInt32, [1_u32, 2]), + ("attempt", UInt8, [3_u8, 4]) + ) + .unwrap(); + let output = ResultFormatter::new(OutputFormat::Json) + .format(&QueryResult::SqlResult(SqlResult::Query(vec![batch]))) + .unwrap(); + let json: serde_json::Value = serde_json::from_str(&output).unwrap(); + + assert_eq!(json[0]["row_offset"], 1); + assert_eq!(json[0]["attempt"], 3); + assert_eq!(json[1]["row_offset"], 2); + } + + #[test] + fn test_ndjson_format() { + let formatter = ResultFormatter::new(OutputFormat::Ndjson); + let batch = create_test_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + let lines: Vec<&str> = output.trim().split('\n').collect(); + + assert_eq!(lines.len(), 3); + + // Parse each line as JSON + for line in lines.iter() { + let json: serde_json::Value = serde_json::from_str(line).unwrap(); + assert!(json.is_object()); + assert!(json["id"].is_number()); + assert!(json["name"].is_string()); + } + } + + #[test] + fn test_vector_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let batch = create_vector_batch(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + // Check that vectors are abbreviated + assert!(output.contains("[0, 0.001, ...1022 more]")); + assert!(!output.contains("0.999")); // Should not show all values + } + + #[test] + fn test_empty_result() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = RecordBatch::new_empty(schema); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + + let output = formatter.format(&result).unwrap(); + + assert!(output.contains("(0 rows)")); + } + + #[test] + fn test_table_list_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let tables = vec![ + "users".to_string(), + "products".to_string(), + "orders".to_string(), + ]; + let result = QueryResult::TableList(tables); + + let output = formatter.format(&result).unwrap(); + + let expected = "List of relations + Tables +---------- + users + products + orders +(3 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_table_list_detailed_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(200); + let tables = vec![ + TableInfo { + name: "users".to_string(), + schema: Arc::new(Schema::empty()), + row_count: Some(1000), + size_bytes: Some(1024 * 1024), // 1 MB + num_indices: Some(2), + num_fragments: Some(1), + }, + TableInfo { + name: "products".to_string(), + schema: Arc::new(Schema::empty()), + row_count: Some(500), + size_bytes: Some(512 * 1024), // 512 KB + num_indices: None, + num_fragments: None, + }, + ]; + let result = QueryResult::TableListDetailed(tables); + + let output = formatter.format(&result).unwrap(); + + let expected = " List of relations + Name | Type | Rows | Size | Indices | Fragments +----------+-------+------+----------+---------+----------- + users | table | 1000 | 1.0 MB | 2 | 1 + products | table | 500 | 512.0 KB | | +(2 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_index_list_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let indices = vec![ + IndexInfo { + name: "idx_users_email".to_string(), + table_name: "users".to_string(), + index_type: "IVF_PQ".to_string(), + columns: vec!["email".to_string()], + }, + IndexInfo { + name: "idx_products_name".to_string(), + table_name: "products".to_string(), + index_type: "BTREE".to_string(), + columns: vec!["name".to_string()], + }, + ]; + let result = QueryResult::IndexList(indices); + + let output = formatter.format(&result).unwrap(); + + let expected = " List of indices + Name | Type | Table +-------------------+--------+---------- + idx_users_email | IVF_PQ | users + idx_products_name | BTREE | products +(2 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_csv_escaping() { + let formatter = ResultFormatter::new(OutputFormat::Csv); + let schema = Arc::new(Schema::new(vec![Field::new("text", DataType::Utf8, false)])); + + let array = StringArray::from(vec!["simple", "with,comma", "with\"quote", "with\nnewline"]); + + let batch = RecordBatch::try_new(schema, vec![Arc::new(array) as ArrayRef]).unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + assert!(output.contains("simple")); + assert!(output.contains("\"with,comma\"")); + assert!(output.contains("\"with\"\"quote\"")); + assert!(output.contains("\"with\nnewline\"")); + } + + #[test] + fn test_csv_preserves_scalar_values() { + let long = "µ".repeat(300); + let binary = vec![0xab; 100]; + let batch = RecordBatch::try_from_iter(vec![ + ( + "long", + Arc::new(StringArray::from(vec![long.as_str()])) as ArrayRef, + ), + ( + "large", + Arc::new(arrow_array::LargeStringArray::from(vec![long.as_str()])), + ), + ( + "view", + Arc::new(arrow_array::StringViewArray::from(vec![long.as_str()])), + ), + ("small", Arc::new(Float64Array::from(vec![0.000123]))), + ("f32", Arc::new(Float32Array::from(vec![0.00693]))), + ( + "f64", + Arc::new(Float64Array::from(vec![1.2345678901234567])), + ), + ("literal_null", Arc::new(StringArray::from(vec!["NULL"]))), + ("null", Arc::new(StringArray::from(vec![None::<&str>]))), + ("empty", Arc::new(StringArray::from(vec![""]))), + ( + "binary", + Arc::new(BinaryArray::from(vec![binary.as_slice()])), + ), + ( + "decimal", + Arc::new( + arrow_array::Decimal128Array::from(vec![123456789012345678901234567890_i128]) + .with_precision_and_scale(30, 10) + .unwrap(), + ), + ), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + + let row = csv::Reader::from_reader(output.as_slice()) + .records() + .next() + .unwrap() + .unwrap(); + for index in 0..3 { + assert_eq!(&row[index], long); + } + assert_eq!(row[3].parse::().unwrap(), 0.000123); + assert_eq!( + row[4].parse::().unwrap().to_bits(), + 0.00693_f32.to_bits() + ); + assert_eq!( + row[5].parse::().unwrap().to_bits(), + 1.2345678901234567_f64.to_bits() + ); + assert_eq!(&row[6], "NULL"); + assert_eq!(&row[7], CSV_NULL_VALUE); + assert_eq!(&row[8], ""); + assert!(String::from_utf8(output) + .unwrap() + .contains(",NULL,\\N,\"\",")); + assert_eq!(&row[9], "ab".repeat(100)); + assert_eq!(&row[10], "12345678901234567890.1234567890"); + } + + #[test] + fn test_csv_preserves_nested_values() { + use arrow_array::builder::{ListBuilder, StringBuilder}; + use arrow_array::types::{Float16Type, Float32Type, UInt8Type}; + use arrow_array::Array; + + let mut tags = ListBuilder::new(StringBuilder::new()); + for value in [ + Some("a,b"), + Some("\"quoted\""), + Some("NULL"), + Some(""), + None, + ] { + tags.values().append_option(value); + } + tags.append(true); + let tags = tags.finish(); + let vector = FixedSizeListArray::from_iter_primitive::( + [Some( + (0..12) + .map(|i| Some(i as f32 + 0.000123)) + .collect::>(), + )], + 12, + ); + let small = ListArray::from_iter_primitive::([Some(vec![ + Some(half::f16::from_f32(0.00693)), + None, + ])]); + let bytes = ListArray::from_iter_primitive::([Some(vec![ + Some(0), + Some(255), + None, + ])]); + let multivector = ListArray::new( + Arc::new(Field::new("item", vector.data_type().clone(), true)), + arrow_buffer::OffsetBuffer::new(vec![0, 1].into()), + Arc::new(vector.clone()), + None, + ); + let special = ListArray::from_iter_primitive::([Some(vec![ + Some(f32::NAN), + Some(f32::INFINITY), + Some(f32::NEG_INFINITY), + None, + ])]); + let nested = arrow_array::StructArray::from(vec![( + Arc::new(Field::new("tags", tags.data_type().clone(), true)), + { + let mut values = ListBuilder::new(StringBuilder::new()); + values.values().append_value("NULL"); + values.values().append_null(); + values.append(true); + Arc::new(values.finish()) as ArrayRef + }, + )]); + let batch = RecordBatch::try_from_iter(vec![ + ("tags", Arc::new(tags) as ArrayRef), + ("vector", Arc::new(vector)), + ("f16", Arc::new(small)), + ("bytes", Arc::new(bytes)), + ("multivector", Arc::new(multivector)), + ("struct", Arc::new(nested)), + ("special", Arc::new(special)), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let row = csv::Reader::from_reader(output.as_slice()) + .records() + .next() + .unwrap() + .unwrap(); + let values: Vec = row + .iter() + .map(|cell| serde_json::from_str(cell).unwrap()) + .collect(); + assert_eq!( + values[0], + serde_json::json!(["a,b", "\"quoted\"", "NULL", "", null]) + ); + assert_eq!(values[1].as_array().unwrap().len(), 12); + for (index, value) in values[1].as_array().unwrap().iter().enumerate() { + assert_eq!(value.as_f64().unwrap() as f32, index as f32 + 0.000123); + } + assert_eq!( + values[2][0].as_f64().unwrap() as f32, + half::f16::from_f32(0.00693).to_f32() + ); + assert!(values[2][1].is_null()); + assert_eq!(values[3], serde_json::json!([0, 255, null])); + assert_eq!(values[4], serde_json::json!([values[1]])); + assert_eq!(values[5], serde_json::json!({"tags": ["NULL", null]})); + assert_eq!(values[6], serde_json::json!(["NaN", "inf", "-inf", null])); + } + + #[test] + fn test_csv_distinguishes_nulls_from_empty_values() { + use arrow_array::types::{Float64Type, Int8Type}; + let dictionary = arrow_array::DictionaryArray::::try_new( + Int8Array::from(vec![Some(0), Some(1), None]), + Arc::new(StringArray::from(vec![None, Some("")])), + ) + .unwrap(); + let lists = ListArray::from_iter_primitive::([ + None, + Some(vec![]), + Some(vec![None]), + ]); + let batch = RecordBatch::try_from_iter(vec![ + ("null", Arc::new(arrow_array::NullArray::new(3)) as ArrayRef), + ("dictionary", Arc::new(dictionary)), + ("list", Arc::new(lists)), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + assert_eq!( + String::from_utf8(output).unwrap(), + "null,dictionary,list\n\\N,\\N,\\N\n\\N,\"\",[]\n\\N,\\N,[null]\n" + ); + } + + #[test] + fn test_csv_preserves_single_column_null_rows() { + let original = vec![ + Some("before"), + None, + Some(""), + Some("NULL"), + Some(r"\N"), + Some(r"\\N"), + Some(r"\path"), + Some("after"), + ]; + let batch = RecordBatch::try_from_iter(vec![( + "v", + Arc::new(StringArray::from(original.clone())) as ArrayRef, + )]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let rows = csv::Reader::from_reader(output.as_slice()) + .records() + .collect::, _>>() + .unwrap(); + assert_eq!(rows.len(), 8); + let values: Vec<_> = rows.iter().map(|row| &row[0]).collect(); + assert_eq!( + values, + ["before", r"\N", "", "NULL", r"\\N", r"\\\N", r"\\path", "after"] + ); + let decoded: Vec<_> = values + .iter() + .map(|&value| { + if value == CSV_NULL_VALUE { + None + } else if value.starts_with(r"\\") { + Some(&value[1..]) + } else { + Some(value) + } + }) + .collect(); + assert_eq!(decoded, original); + } + + #[test] + fn test_csv_preserves_nested_dictionary_nulls() { + use arrow_array::types::Int8Type; + use arrow_array::{Array, DictionaryArray, StructArray}; + + let dictionary = DictionaryArray::::try_new( + Int8Array::from(vec![Some(0), Some(1), None]), + Arc::new(StringArray::from(vec![None, Some("")])), + ) + .unwrap(); + let field = Arc::new(Field::new("item", dictionary.data_type().clone(), true)); + let list = ListArray::new( + field.clone(), + arrow_buffer::OffsetBuffer::new(vec![0, 3].into()), + Arc::new(dictionary.clone()), + None, + ); + let structs = StructArray::from(vec![(field, Arc::new(dictionary) as ArrayRef)]); + let struct_list = ListArray::new( + Arc::new(Field::new("item", structs.data_type().clone(), true)), + arrow_buffer::OffsetBuffer::new(vec![0, 3].into()), + Arc::new(structs), + None, + ); + let encoded_list = + DictionaryArray::::try_new(Int8Array::from(vec![0]), Arc::new(list.clone())) + .unwrap(); + let batch = RecordBatch::try_from_iter(vec![ + ("list", Arc::new(list) as ArrayRef), + ("structs", Arc::new(struct_list)), + ("encoded_list", Arc::new(encoded_list)), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let row = csv::Reader::from_reader(output.as_slice()) + .records() + .next() + .unwrap() + .unwrap(); + assert_eq!(&row[0], r#"[null,"",null]"#); + assert_eq!(&row[1], r#"[{"item":null},{"item":""},{"item":null}]"#); + assert_eq!(&row[2], r#"[null,"",null]"#); + } + + #[test] + fn test_csv_escapes_headers_and_carriage_returns_across_batches() { + let batch = RecordBatch::try_from_iter(vec![ + ( + "with,comma", + Arc::new(StringArray::from(vec!["with\rcarriage return"])) as ArrayRef, + ), + ( + "with\"quote", + Arc::new(StringArray::from(vec!["with\"quote"])), + ), + ( + "with\nnewline", + Arc::new(StringArray::from(vec!["with\nnewline"])), + ), + ]) + .unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Csv) + .format_record_batches(&[batch.slice(0, 0), batch.clone(), batch], &mut output) + .unwrap(); + let mut reader = csv::Reader::from_reader(output.as_slice()); + assert_eq!( + reader.headers().unwrap(), + &csv::StringRecord::from(vec!["with,comma", "with\"quote", "with\nnewline"]) + ); + let rows = reader + .records() + .collect::, _>>() + .unwrap(); + assert_eq!(rows.len(), 2); + for row in rows { + assert_eq!( + row, + csv::StringRecord::from(vec![ + "with\rcarriage return", + "with\"quote", + "with\nnewline" + ]) + ); + } + } + + #[test] + fn test_table_preserves_small_float_precision() { + let batch = arrow_array::record_batch!(("small", Float64, [0.000123, 0.00693])).unwrap(); + let mut output = Vec::new(); + ResultFormatter::new(OutputFormat::Table) + .with_terminal_width(200) + .format_record_batches(&[batch], &mut output) + .unwrap(); + let output = String::from_utf8(output).unwrap(); + assert!(output.contains("0.000123")); + assert!(output.contains("0.00693")); + } + + #[test] + fn test_format_bytes() { + assert_eq!(format_bytes(0), "0 B"); + assert_eq!(format_bytes(1023), "1023 B"); + assert_eq!(format_bytes(1024), "1.0 KB"); + assert_eq!(format_bytes(1536), "1.5 KB"); + assert_eq!(format_bytes(1024 * 1024), "1.0 MB"); + assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB"); + } + + #[test] + fn test_format_data_type() { + assert_eq!(format_data_type(&DataType::Boolean), "BOOLEAN"); + assert_eq!(format_data_type(&DataType::Int32), "INT"); + assert_eq!(format_data_type(&DataType::Float64), "DOUBLE"); + assert_eq!(format_data_type(&DataType::Utf8), "TEXT"); + assert_eq!( + format_data_type(&DataType::FixedSizeList( + Arc::new(Field::new("item", DataType::Float32, true)), + 128 + )), + "FLOAT[128]" + ); + } + + #[test] + fn test_sql_result_dml_insert() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let dml = DmlResult::new("foo", DmlOperation::Insert, 1, 3); + let result = QueryResult::SqlResult(SqlResult::Dml(dml)); + + let output = formatter.format(&result).unwrap(); + assert_eq!(output, "INSERT 1 row(s), version 3\n"); + } + + #[test] + fn test_sql_result_dml_delete() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let dml = DmlResult::new("bar", DmlOperation::Delete, 0, 4); + let result = QueryResult::SqlResult(SqlResult::Dml(dml)); + + let output = formatter.format(&result).unwrap(); + assert_eq!(output, "DELETE 0 row(s), version 4\n"); + } + + #[test] + fn test_sql_result_success() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let result = QueryResult::SqlResult(SqlResult::Success); + + let output = formatter.format(&result).unwrap(); + assert_eq!(output, "Success\n"); + } + + #[test] + fn test_table_info_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("email", DataType::Utf8, false), + Field::new( + "created_at", + DataType::Timestamp(arrow_schema::TimeUnit::Microsecond, None), + false, + ), + Field::new("score", DataType::Float64, true), + ])); + + let table_info = TableInfo { + name: "users".to_string(), + schema, + row_count: Some(1500), + size_bytes: Some(2 * 1024 * 1024), // 2 MB + num_indices: Some(3), + num_fragments: Some(2), + }; + + let result = QueryResult::TableInfo(table_info); + let output = formatter.format(&result).unwrap(); + + let expected = " Table \"users\" + Column | Type | Nullable +------------+-----------+---------- + id | INT | + email | TEXT | + created_at | TIMESTAMP | + score | DOUBLE | YES + +Rows: 1500 +Size: 2.0 MB +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_data_type_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table); + + struct TestCase { + name: &'static str, + field: Field, + data: ArrayRef, + expected_values: Vec<&'static str>, + } + + let test_cases = vec![ + TestCase { + name: "timestamp", + field: Field::new( + "ts", + DataType::Timestamp(arrow_schema::TimeUnit::Microsecond, None), + false, + ), + data: Arc::new(arrow_array::TimestampMicrosecondArray::from(vec![ + 1609459200000000, // 2021-01-01 00:00:00 UTC + 1625097600000000, // 2021-07-01 00:00:00 UTC + ])) as ArrayRef, + expected_values: vec!["2021-01-01", "2021-07-01"], + }, + TestCase { + name: "date", + field: Field::new("date", DataType::Date64, false), + data: Arc::new(arrow_array::Date64Array::from(vec![ + 1622505600000, // 2021-06-01 + 1622592000000, // 2021-06-02 + ])) as ArrayRef, + expected_values: vec!["2021-06-01", "2021-06-02"], + }, + TestCase { + name: "largeutf8", + field: Field::new("text", DataType::LargeUtf8, false), + data: Arc::new(arrow_array::LargeStringArray::from(vec![ + "Hello, World!", + "Large UTF-8 String", + ])) as ArrayRef, + expected_values: vec!["Hello, World!", "Large UTF-8 String"], + }, + TestCase { + name: "utf8view", + field: Field::new("view", DataType::Utf8View, false), + data: Arc::new(arrow_array::StringViewArray::from(vec![ + "View String 1", + "View String 2", + ])) as ArrayRef, + expected_values: vec!["View String 1", "View String 2"], + }, + TestCase { + name: "struct", + field: Field::new( + "data", + DataType::Struct( + vec![ + Field::new("name", DataType::Utf8, false), + Field::new("age", DataType::Int32, false), + ] + .into(), + ), + false, + ), + data: Arc::new(arrow_array::StructArray::from(vec![ + ( + Arc::new(Field::new("name", DataType::Utf8, false)), + Arc::new(StringArray::from(vec!["Alice", "Bob"])) as ArrayRef, + ), + ( + Arc::new(Field::new("age", DataType::Int32, false)), + Arc::new(Int32Array::from(vec![30, 25])) as ArrayRef, + ), + ])) as ArrayRef, + expected_values: vec!["{name: Alice, age: 30}", "{name: Bob, age: 25}"], + }, + ]; + + for test_case in test_cases { + let schema = Arc::new(Schema::new(vec![test_case.field])); + let batch = RecordBatch::try_new(schema, vec![test_case.data]).unwrap(); + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + for expected in test_case.expected_values { + assert!( + output.contains(expected), + "Test case '{}' failed: expected output to contain '{}', but got:\n{}", + test_case.name, + expected, + output + ); + } + } + } + + #[test] + fn marked_columns_render_in_full() { + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(500); + let long_string = format!("j1_{}", "a".repeat(300)); + + let schema = Arc::new(Schema::new(vec![ + Field::new("job_id", DataType::Utf8, false), + Field::new("state", DataType::Utf8, false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(StringArray::from(vec![long_string.as_str()])) as ArrayRef, + Arc::new(StringArray::from(vec![long_string.as_str()])) as ArrayRef, + ], + ) + .unwrap(); + + let marked = mark_no_truncate(SqlResult::Query(vec![batch]), &["job_id"]); + let output = formatter.format(&QueryResult::SqlResult(marked)).unwrap(); + + assert!( + output.contains(&long_string), + "a marked column must render in full: {output}" + ); + assert!( + output.contains("...(303 chars)"), + "an unmarked column must still be abbreviated: {output}" + ); + } + + fn job_ids(result: &SqlResult) -> Vec { + let SqlResult::Query(batches) = result else { + panic!("expected a query result"); + }; + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + + #[test] + fn taking_rows_cuts_across_batch_boundaries() { + let first = arrow_array::record_batch!(("job_id", Int32, [1, 2, 3])).unwrap(); + let second = arrow_array::record_batch!(("job_id", Int32, [4, 5, 6])).unwrap(); + let batches = vec![first, second]; + + assert_eq!(row_count(&SqlResult::Query(batches.clone())), 6); + + // A cut inside the second batch keeps the first whole and slices the + // second; a limit at or past the total is a no-op. + let capped = take_rows(SqlResult::Query(batches.clone()), 4); + assert_eq!(job_ids(&capped), vec![1, 2, 3, 4]); + assert_eq!( + job_ids(&take_rows(SqlResult::Query(batches.clone()), 6)), + vec![1, 2, 3, 4, 5, 6] + ); + assert_eq!( + job_ids(&take_rows(SqlResult::Query(batches), 99)), + vec![1, 2, 3, 4, 5, 6] + ); + } + + #[test] + fn taking_rows_leaves_non_query_results_alone() { + assert!(matches!( + take_rows(SqlResult::Success, 0), + SqlResult::Success + )); + assert_eq!(row_count(&SqlResult::Success), 0); + } + + #[test] + fn test_string_elision() { + let formatter = ResultFormatter::new(OutputFormat::Table); + + // Create a long string that should be elided + let long_string = "a".repeat(100); + let short_string = "short string"; + + let schema = Arc::new(Schema::new(vec![ + Field::new("short", DataType::Utf8, false), + Field::new("long", DataType::Utf8, false), + Field::new("long_large", DataType::LargeUtf8, false), + ])); + + let short_array = StringArray::from(vec![short_string]); + let long_array = StringArray::from(vec![long_string.as_str()]); + let long_large_array = arrow_array::LargeStringArray::from(vec![long_string.as_str()]); + + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(short_array) as ArrayRef, + Arc::new(long_array) as ArrayRef, + Arc::new(long_large_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + // Short string should appear in full + assert!(output.contains(short_string)); + + // Long strings should be truncated with char count + assert!(output.contains("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...(100 chars)")); + assert!(!output.contains(&long_string)); // Full string should not appear + } + + #[test] + fn test_string_truncation_with_multibyte_utf8() { + let formatter = ResultFormatter::new(OutputFormat::Table); + + // The en-dash '–' is 3 bytes in UTF-8. Place it so byte index 50 falls + // inside the character, which would panic with naive &value[..50]. + // 48 ASCII bytes + '–' (3 bytes) + padding = well over 50 bytes + let multibyte_string = format!("{}{}", "x".repeat(48), "–".repeat(20)); + + let schema = Arc::new(Schema::new(vec![ + Field::new("text", DataType::Utf8, false), + Field::new("text_large", DataType::LargeUtf8, false), + Field::new("text_view", DataType::Utf8View, false), + ])); + + let utf8_array = StringArray::from(vec![multibyte_string.as_str()]); + let large_array = arrow_array::LargeStringArray::from(vec![multibyte_string.as_str()]); + let view_array = arrow_array::StringViewArray::from(vec![multibyte_string.as_str()]); + + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(utf8_array) as ArrayRef, + Arc::new(large_array) as ArrayRef, + Arc::new(view_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + // Should not panic, and should contain truncation indicator + // 48 ASCII chars + 20 en-dashes = 68 chars total + assert!(output.contains("...(68 chars)")); + // The truncated prefix should end at a char boundary (48 x's, not mid en-dash) + assert!(output.contains(&"x".repeat(48))); + } + + #[test] + fn test_struct_formatting() { + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(200); + + // Create a struct with multiple fields + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "user_info", + DataType::Struct( + vec![ + Field::new("name", DataType::Utf8, false), + Field::new("age", DataType::Int32, false), + Field::new("email", DataType::Utf8, true), + ] + .into(), + ), + false, + ), + ])); + + let id_array = Int32Array::from(vec![1, 2]); + let name_array = StringArray::from(vec!["Alice", "Bob"]); + let age_array = Int32Array::from(vec![30, 25]); + let email_array = StringArray::from(vec![Some("alice@example.com"), None]); + + let struct_array = arrow_array::StructArray::from(vec![ + ( + Arc::new(Field::new("name", DataType::Utf8, false)), + Arc::new(name_array) as ArrayRef, + ), + ( + Arc::new(Field::new("age", DataType::Int32, false)), + Arc::new(age_array) as ArrayRef, + ), + ( + Arc::new(Field::new("email", DataType::Utf8, true)), + Arc::new(email_array) as ArrayRef, + ), + ]); + + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(id_array) as ArrayRef, + Arc::new(struct_array) as ArrayRef, + ], + ) + .unwrap(); + + let result = QueryResult::SqlResult(SqlResult::Query(vec![batch])); + let output = formatter.format(&result).unwrap(); + + // Check the exact literal output for proper struct formatting + let expected = " id | user_info +----+-------------------------------------------------- + 1 | {name: Alice, age: 30, email: alice@example.com} + 2 | {name: Bob, age: 25, email: NULL} +(2 rows) +"; + + assert_eq!(output, expected); + } + + #[test] + fn test_index_list_detailed_formatting() { + // Pin a wide terminal so the table renders columnar ("hotdog") rather + // than auto-expanding ("hamburger") in a narrow terminal — keeps the + // golden output independent of the ambient terminal width. + let formatter = ResultFormatter::new(OutputFormat::Table).with_terminal_width(200); + let indices = vec![ + ( + IndexInfo { + name: "idx_embeddings".to_string(), + table_name: "documents".to_string(), + index_type: "IVF_PQ".to_string(), + columns: vec!["embedding".to_string()], + }, + Some(IndexStats { + num_indexed_rows: 10000, + num_unindexed_rows: 500, + distance_type: Some("L2".to_string()), + }), + ), + ( + IndexInfo { + name: "idx_created_at".to_string(), + table_name: "documents".to_string(), + index_type: "BTREE".to_string(), + columns: vec!["created_at".to_string()], + }, + None, + ), + ]; + let result = QueryResult::IndexListDetailed(indices); + + let output = formatter.format(&result).unwrap(); + + let expected = " List of relations + Name | Type | Distance | Indexed Rows | Unindexed Rows | Table +----------------+--------+----------+--------------+----------------+----------- + idx_embeddings | IVF_PQ | L2 | 10000 | 500 | documents + idx_created_at | BTREE | | | | documents +(2 rows) +"; + + assert_eq!(output, expected); + } +} diff --git a/rust/lancedb/cli/src/lib.rs b/rust/lancedb/cli/src/lib.rs new file mode 100644 index 000000000..46a32122e --- /dev/null +++ b/rust/lancedb/cli/src/lib.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +pub mod auth; +pub mod cli; +pub mod client; +pub mod dml_result; +pub mod formatter; +pub mod mocks; +pub mod profile; +pub mod server_config; +pub mod sql_executor; +pub mod table_writer; + +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +pub use cli::{run, Args, Commands}; +pub(crate) fn format_host_port(host: &str, port: impl std::fmt::Display) -> String { + match host.parse::() { + Ok(std::net::IpAddr::V6(_)) => format!("[{host}]:{port}"), + _ => format!("{host}:{port}"), + } +} + +pub(crate) fn lancedb_client_config( + tls: &server_config::TlsOptions, + authentication: &server_config::Authentication, +) -> Option { + if tls == &server_config::TlsOptions::default() + && matches!(authentication, server_config::Authentication::ApiKey(_)) + { + return None; + } + let mut config = lancedb::remote::ClientConfig::default(); + if tls != &server_config::TlsOptions::default() { + config.tls_config = Some(lancedb::remote::TlsConfig { + ssl_ca_cert: tls.ca_cert.clone(), + cert_file: tls.client_cert.clone(), + key_file: tls.client_key.clone(), + ..Default::default() + }); + } + if !matches!(authentication, server_config::Authentication::ApiKey(_)) { + config.header_provider = Some(std::sync::Arc::new(authentication.clone())); + } + Some(config) +} + +static BUILD_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); +/// Set the version displayed by shared command handlers when embedded in another binary. +pub fn set_build_version(version: &'static str) { + let _ = BUILD_VERSION.set(version); +} +pub fn build_version() -> &'static str { + BUILD_VERSION.get().copied().unwrap_or(VERSION) +} diff --git a/rust/lancedb/cli/src/main.rs b/rust/lancedb/cli/src/main.rs new file mode 100644 index 000000000..01f65e386 --- /dev/null +++ b/rust/lancedb/cli/src/main.rs @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use clap::Parser; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let _ = rustls::crypto::ring::default_provider().install_default(); + lancedb_cli::run(lancedb_cli::Args::parse()).await +} diff --git a/rust/lancedb/cli/src/mocks.rs b/rust/lancedb/cli/src/mocks.rs new file mode 100644 index 000000000..ac8a66e7b --- /dev/null +++ b/rust/lancedb/cli/src/mocks.rs @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/// Mock implementations for testing +#[cfg(test)] +pub mod test_mocks { + use crate::sql_executor::{SqlQueryExecutor, SqlResult}; + use anyhow::Result; + use arrow_array::RecordBatch; + use arrow_schema::{DataType, Field, Schema}; + use async_trait::async_trait; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + /// Mock SQL executor for testing + pub struct MockSqlExecutor { + pub is_connected: bool, + pub queries: Arc>>, + pub query_results: HashMap>, + /// URLs passed to `connect`, in call order. + pub connected_urls: Arc>>, + } + + impl Default for MockSqlExecutor { + fn default() -> Self { + Self::new() + } + } + + impl MockSqlExecutor { + pub fn new() -> Self { + Self { + is_connected: false, + queries: Arc::new(Mutex::new(Vec::new())), + query_results: HashMap::new(), + connected_urls: Arc::new(Mutex::new(Vec::new())), + } + } + + pub fn set_query_result(&mut self, query: &str, result: Vec) { + self.query_results.insert(query.to_string(), result); + } + + pub fn get_executed_queries(&self) -> Vec { + self.queries.lock().unwrap().clone() + } + + pub fn get_connected_urls(&self) -> Vec { + self.connected_urls.lock().unwrap().clone() + } + } + + #[async_trait] + impl SqlQueryExecutor for MockSqlExecutor { + async fn execute_query(&mut self, query: &str) -> Result { + self.queries.lock().unwrap().push(query.to_string()); + + if let Some(result) = self.query_results.get(query) { + Ok(SqlResult::Query(result.clone())) + } else { + // Return empty result by default + Ok(SqlResult::Query(vec![])) + } + } + + async fn is_connected(&self) -> bool { + self.is_connected + } + + fn connection_info(&self) -> Option { + if self.is_connected { + Some("Mock SQL connection".to_string()) + } else { + None + } + } + + async fn connect(&mut self, server_url: &str) -> Result<()> { + self.connected_urls + .lock() + .unwrap() + .push(server_url.to_string()); + self.is_connected = true; + Ok(()) + } + + fn set_database(&mut self, _database: String) { + // Mock implementation - no-op + } + } + + /// Helper function to create a simple test schema + pub fn create_test_schema() -> Arc { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("name", DataType::Utf8, false), + Field::new("value", DataType::Float64, true), + ])) + } + + /// Helper function to create test RecordBatch + pub fn create_test_batch() -> RecordBatch { + use arrow_array::{Float64Array, Int64Array, StringArray}; + + let id_array = Int64Array::from(vec![1, 2, 3]); + let name_array = StringArray::from(vec!["Alice", "Bob", "Charlie"]); + let value_array = Float64Array::from(vec![Some(10.5), None, Some(20.0)]); + + RecordBatch::try_new( + create_test_schema(), + vec![ + Arc::new(id_array), + Arc::new(name_array), + Arc::new(value_array), + ], + ) + .unwrap() + } +} diff --git a/rust/lancedb/cli/src/profile.rs b/rust/lancedb/cli/src/profile.rs new file mode 100644 index 000000000..55e854c68 --- /dev/null +++ b/rust/lancedb/cli/src/profile.rs @@ -0,0 +1,494 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::borrow::Cow; +use std::io::{self, Write}; + +use anyhow::{anyhow, Result}; +use clap::{Args, Subcommand}; +use rustyline::highlight::Highlighter; +use rustyline::{Editor, Helper}; + +use crate::server_config::{Config, Profile}; + +#[derive(Args, Debug)] +pub struct ProfileArgs { + #[command(subcommand)] + pub command: ProfileCommand, +} + +/// The settable fields of a profile, shared by `create` and `edit`. +/// +/// `create` writes them all; `edit` applies only the ones that were passed. +#[derive(Args, Debug, Default)] +pub struct ProfileFields { + /// SQL server URL (Flight SQL endpoint), as host:port or grpc(s)://host:port + #[arg(long)] + pub sql_server_url: Option, + + /// HTTP server URL (REST endpoint), as host:port or http(s)://host:port + #[arg(long)] + pub http_server_url: Option, + + /// API key for authentication + #[arg(long, conflicts_with = "oidc_access_token_file")] + pub api_key: Option, + + /// Path to a file containing an OIDC access token + #[arg(long, value_name = "PATH", conflicts_with = "api_key")] + pub oidc_access_token_file: Option, + + /// Default database name + #[arg(long, short)] + pub database: Option, + + /// Azure storage account name for Azure-backed databases + #[arg(long)] + pub azure_storage_account_name: Option, + + /// Path to a PEM CA certificate trusted in addition to the platform roots + #[arg(long, value_name = "PATH")] + pub ca_cert: Option, + + /// Path to a PEM client certificate presented for mTLS + #[arg(long, value_name = "PATH")] + pub client_cert: Option, + + /// Path to the PKCS#8 PEM private key for the client certificate + #[arg(long, value_name = "PATH")] + pub client_key: Option, +} + +impl ProfileFields { + /// Whether any field was supplied, which is what makes `create` + /// non-interactive. Destructured so a new field cannot be forgotten here. + fn any_set(&self) -> bool { + let Self { + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + } = self; + [ + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + ] + .iter() + .any(|field| field.is_some()) + } +} + +impl From<&ProfileFields> for Profile { + fn from(fields: &ProfileFields) -> Self { + Self { + sql_server_url: fields.sql_server_url.clone(), + http_server_url: fields.http_server_url.clone(), + api_key: fields.api_key.clone(), + oidc_access_token_file: fields.oidc_access_token_file.clone(), + oidc: None, + database: fields.database.clone(), + azure_storage_account_name: fields.azure_storage_account_name.clone(), + ca_cert: fields.ca_cert.clone(), + client_cert: fields.client_cert.clone(), + client_key: fields.client_key.clone(), + } + } +} + +#[derive(Subcommand, Debug)] +pub enum ProfileCommand { + /// List all configured profiles + List, + + /// Show details of a specific profile + Show { + /// Name of the profile to show (uses default if not specified) + name: Option, + }, + + /// Create a new profile (interactive by default) + Create { + /// Name for the new profile + name: String, + + #[command(flatten)] + fields: ProfileFields, + }, + + /// Set the default profile + #[command(name = "set")] + SetDefault { + /// Name of the profile to set as default + name: String, + }, + + /// Delete a profile + Delete { + /// Name of the profile to delete + name: String, + }, + + /// Edit an existing profile + Edit { + /// Name of the profile to edit + name: String, + + #[command(flatten)] + fields: ProfileFields, + }, +} + +pub async fn run_profile_command(args: ProfileArgs) -> Result<()> { + match args.command { + ProfileCommand::List => list_profiles(), + ProfileCommand::Show { name } => show_profile(name), + ProfileCommand::Create { name, fields } => { + // If any flags are provided, use non-interactive mode + if fields.any_set() { + create_profile(&name, Profile::from(&fields)) + } else { + create_profile_interactive(&name) + } + } + ProfileCommand::SetDefault { name } => set_default_profile(&name), + ProfileCommand::Delete { name } => delete_profile(&name), + ProfileCommand::Edit { name, fields } => edit_profile(&name, Profile::from(&fields)), + } +} + +fn list_profiles() -> Result<()> { + let config = Config::load_default()?; + let default_profile = config.default_profile.as_deref().unwrap_or("local"); + + println!("Configured profiles:"); + + // Always show "local" as it's built-in + let is_default = default_profile == "local"; + let default_marker = if is_default { "*" } else { " " }; + let in_config = if config.profiles.contains_key("local") { + "" + } else { + " [built-in]" + }; + println!(" {} local{}", default_marker, in_config); + + // Show configured profiles + let mut profile_names: Vec<_> = config.profiles.keys().collect(); + profile_names.sort(); + + for name in profile_names { + if name == "local" { + continue; // Already shown above + } + let is_default = default_profile == name; + let default_marker = if is_default { "*" } else { " " }; + println!(" {} {}", default_marker, name); + } + + if config.profiles.is_empty() + || (config.profiles.len() == 1 && config.profiles.contains_key("local")) + { + println!(); + println!("No custom profiles configured. Use 'lancedb profile create ' to add one."); + } + + Ok(()) +} + +fn show_profile(name: Option) -> Result<()> { + let config = Config::load_default()?; + let profile_name = name + .as_deref() + .or(config.default_profile.as_deref()) + .unwrap_or("local"); + + let profile = config.get_profile(Some(profile_name)); + let is_builtin = !config.profiles.contains_key(profile_name) && profile_name == "local"; + + let builtin_marker = if is_builtin { " [built-in]" } else { "" }; + println!("Profile: {}{}", profile_name, builtin_marker); + println!( + " sql_server_url: {}", + profile.sql_server_url.as_deref().unwrap_or("") + ); + println!( + " http_server_url: {}", + profile.http_server_url.as_deref().unwrap_or("") + ); + println!( + " api_key: {}", + profile + .api_key + .as_ref() + .map(|_| "********") + .unwrap_or("") + ); + println!( + " oidc_access_token_file: {}", + profile + .oidc_access_token_file + .as_deref() + .unwrap_or("") + ); + if let Some(oidc) = &profile.oidc { + println!(" oidc: {}", toml::to_string(oidc)?); + } + println!( + " database: {}", + profile.database.as_deref().unwrap_or("") + ); + println!( + " azure_storage_account_name: {}", + profile + .azure_storage_account_name + .as_deref() + .unwrap_or("") + ); + println!( + " ca_cert: {}", + profile.ca_cert.as_deref().unwrap_or("") + ); + println!( + " client_cert: {}", + profile.client_cert.as_deref().unwrap_or("") + ); + println!( + " client_key: {}", + profile.client_key.as_deref().unwrap_or("") + ); + + Ok(()) +} + +fn create_profile(name: &str, profile: Profile) -> Result<()> { + let mut config = Config::load_default()?; + + if config.profiles.contains_key(name) { + return Err(anyhow!( + "Profile '{}' already exists. Use 'lancedb profile edit {}' to modify it.", + name, + name + )); + } + + config.set_profile(name, profile); + config.save_default()?; + + println!("Created profile '{}'", name); + Ok(()) +} + +fn create_profile_interactive(name: &str) -> Result<()> { + let mut config = Config::load_default()?; + + if config.profiles.contains_key(name) { + return Err(anyhow!( + "Profile '{}' already exists. Use 'lancedb profile edit {}' to modify it.", + name, + name + )); + } + + println!("Creating profile '{}'", name); + println!("Press Enter to skip optional fields."); + println!(); + + let sql_server_url = + prompt_optional("SQL server URL (host:port, or grpcs://host:port for TLS)")?; + let http_server_url = + prompt_optional("HTTP server URL (host:port, or https://host:port for TLS)")?; + let api_key = prompt_secret("API key")?; + let oidc_access_token_file = if api_key.is_none() { + prompt_optional("OIDC access token file")? + } else { + None + }; + let database = prompt_optional("Default database")?; + let azure_storage_account_name = prompt_optional("Azure storage account name")?; + let ca_cert = prompt_optional("CA certificate path (PEM, for a private CA)")?; + let client_cert = prompt_optional("Client certificate path (PEM, for mTLS)")?; + let client_key = prompt_optional("Client key path (PKCS#8 PEM, for mTLS)")?; + + let profile = Profile { + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + oidc: None, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + }; + config.set_profile(name, profile); + config.save_default()?; + + println!(); + println!("Created profile '{}'", name); + Ok(()) +} + +fn set_default_profile(name: &str) -> Result<()> { + let mut config = Config::load_default()?; + + // Verify profile exists (or is built-in "local") + if name != "local" && !config.profiles.contains_key(name) { + return Err(anyhow!( + "Profile '{}' does not exist. Use 'lancedb profile list' to see available profiles.", + name + )); + } + + // Persist the addresses when localhost is explicitly selected, so a later + // default SQL invocation can distinguish this choice from an unset endpoint. + if name == "local" && !config.profiles.contains_key(name) { + config.set_profile(name, Profile::local_default()); + } + config.set_default_profile(name); + config.save_default()?; + + println!("Set '{}' as the default profile", name); + Ok(()) +} + +fn delete_profile(name: &str) -> Result<()> { + if name == "local" { + return Err(anyhow!("Cannot delete the built-in 'local' profile")); + } + + let mut config = Config::load_default()?; + + if !config.profiles.contains_key(name) { + return Err(anyhow!("Profile '{}' does not exist", name)); + } + + config.remove_profile(name); + + // If we deleted the default profile, reset to "local" + if config.default_profile.as_deref() == Some(name) { + config.set_default_profile("local"); + println!("Default profile reset to 'local'"); + } + + config.save_default()?; + + println!("Deleted profile '{}'", name); + Ok(()) +} + +fn edit_profile(name: &str, updates: Profile) -> Result<()> { + let mut config = Config::load_default()?; + + // Get existing profile or create from built-in + let mut profile = if config.profiles.contains_key(name) { + config.profiles.get(name).cloned().unwrap() + } else if name == "local" { + Profile::local_default() + } else { + return Err(anyhow!( + "Profile '{}' does not exist. Use 'lancedb profile create {}' to create it.", + name, + name + )); + }; + + // Update only the fields that were provided + let Profile { + sql_server_url, + http_server_url, + api_key, + oidc_access_token_file, + oidc, + database, + azure_storage_account_name, + ca_cert, + client_cert, + client_key, + } = updates; + profile.sql_server_url = sql_server_url.or(profile.sql_server_url); + profile.http_server_url = http_server_url.or(profile.http_server_url); + if let Some(api_key) = api_key { + profile.oidc = None; + profile.api_key = Some(api_key); + profile.oidc_access_token_file = None; + } else if let Some(oidc_access_token_file) = oidc_access_token_file { + profile.oidc = None; + profile.api_key = None; + profile.oidc_access_token_file = Some(oidc_access_token_file); + } + if let Some(oidc) = oidc { + profile.api_key = None; + profile.oidc_access_token_file = None; + profile.oidc = Some(oidc); + } + profile.database = database.or(profile.database); + profile.azure_storage_account_name = + azure_storage_account_name.or(profile.azure_storage_account_name); + profile.ca_cert = ca_cert.or(profile.ca_cert); + profile.client_cert = client_cert.or(profile.client_cert); + profile.client_key = client_key.or(profile.client_key); + + config.set_profile(name, profile); + config.save_default()?; + + println!("Updated profile '{}'", name); + Ok(()) +} + +fn prompt_optional(field: &str) -> Result> { + print!("{}: ", field); + io::stdout().flush()?; + + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + + let value = input.trim(); + if value.is_empty() { + Ok(None) + } else { + Ok(Some(value.to_string())) + } +} + +fn prompt_secret(field: &str) -> Result> { + struct MaskHelper; + impl Highlighter for MaskHelper { + fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> { + Cow::Owned("*".repeat(line.len())) + } + fn highlight_char(&self, _line: &str, _pos: usize, _forced: bool) -> bool { + true + } + } + impl rustyline::completion::Completer for MaskHelper { + type Candidate = String; + } + impl rustyline::hint::Hinter for MaskHelper { + type Hint = String; + } + impl rustyline::validate::Validator for MaskHelper {} + impl Helper for MaskHelper {} + + let mut editor = Editor::new()?; + editor.set_helper(Some(MaskHelper)); + let input = editor.readline(&format!("{}: ", field))?; + let value = input.trim(); + if value.is_empty() { + Ok(None) + } else { + Ok(Some(value.to_string())) + } +} diff --git a/rust/lancedb/cli/src/server_config.rs b/rust/lancedb/cli/src/server_config.rs new file mode 100644 index 000000000..eb483c44e --- /dev/null +++ b/rust/lancedb/cli/src/server_config.rs @@ -0,0 +1,1310 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use anyhow::{anyhow, bail, Context, Result}; +use clap::Args; +use directories::UserDirs; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::fs; +use std::io::Write; +#[cfg(unix)] +use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +/// The default profile name used when no profile is specified +pub const DEFAULT_PROFILE: &str = "local"; + +/// Port assumed for a Flight SQL address that carries neither scheme nor port. +pub const DEFAULT_SQL_PORT: u16 = 10025; + +/// Port assumed for a REST address that carries neither scheme nor port. +pub const DEFAULT_HTTP_PORT: u16 = 10024; + +const DEFAULT_API_KEY: &str = "sk_localtest"; +const API_KEY_ENV: &str = "LANCEDB_API_KEY"; +const OIDC_ACCESS_TOKEN_ENV: &str = "LANCEDB_OIDC_ACCESS_TOKEN"; +const OIDC_ACCESS_TOKEN_FILE_ENV: &str = "LANCEDB_OIDC_ACCESS_TOKEN_FILE"; + +/// Authentication material selected for a CLI connection. +#[derive(Clone, PartialEq, Eq)] +pub enum Authentication { + ApiKey(String), + OidcAccessToken(String), + OidcAccessTokenFile(PathBuf), + ManagedOidc(std::sync::Arc), +} + +impl std::fmt::Debug for Authentication { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::ApiKey(_) => f.write_str("ApiKey()"), + Self::OidcAccessToken(_) => f.write_str("OidcAccessToken()"), + Self::OidcAccessTokenFile(path) => { + f.debug_tuple("OidcAccessTokenFile").field(path).finish() + } + Self::ManagedOidc(session) => f.debug_tuple("ManagedOidc").field(session).finish(), + } + } +} + +/// Transport scheme of a server address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scheme { + Http, + Https, +} + +impl Scheme { + pub fn as_str(&self) -> &'static str { + match self { + Self::Http => "http", + Self::Https => "https", + } + } + + /// Port to use when the address names this scheme but no port. + fn default_port(&self) -> u16 { + match self { + Self::Http => 80, + Self::Https => 443, + } + } +} + +impl std::fmt::Display for Scheme { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +/// A server address split into the parts needed to rebuild a connection URL. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Endpoint { + pub scheme: Scheme, + /// Host without IPv6 brackets, as it would appear in a certificate. + pub host: String, + pub port: u16, +} + +impl Endpoint { + /// `host:port`, bracketing IPv6 literals. + pub fn host_port(&self) -> String { + crate::format_host_port(&self.host, self.port) + } + + /// Full `scheme://host:port` URL. + pub fn url(&self) -> String { + format!("{}://{}", self.scheme, self.host_port()) + } + + pub fn is_tls(&self) -> bool { + self.scheme == Scheme::Https + } +} + +impl std::fmt::Display for Endpoint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.url()) + } +} + +/// Parse a user-supplied REST address into scheme, host, and port. +/// +/// An explicit `https://` prefix is how a user asks for TLS; without a scheme +/// the address is assumed to be plaintext. `default_port` applies only when the +/// address names neither a scheme nor a port, so `https://host` still resolves +/// to 443 rather than to a LanceDB-specific default. +pub fn parse_endpoint(addr: &str, default_port: u16) -> Result { + parse_endpoint_with_schemes(addr, default_port, &["http", "https"]) +} + +/// Parse a user-supplied Flight SQL address, which additionally accepts the +/// gRPC scheme names. `grpc://` and `grpcs://` are aliases for `http://` and +/// `https://`: gRPC runs over the same HTTP/2 transport, and only the TLS +/// distinction reaches the connection. +pub fn parse_grpc_endpoint(addr: &str, default_port: u16) -> Result { + parse_endpoint_with_schemes(addr, default_port, &["http", "https", "grpc", "grpcs"]) +} + +fn parse_endpoint_with_schemes( + addr: &str, + default_port: u16, + accepted: &[&str], +) -> Result { + let addr = addr.trim(); + + let (scheme, rest, scheme_was_explicit) = match addr.split_once("://") { + Some((scheme, rest)) => { + let scheme = scheme.to_ascii_lowercase(); + if !accepted.contains(&scheme.as_str()) { + bail!( + "Unsupported scheme '{scheme}' in server address '{addr}'; expected one of {}", + accepted.join(", ") + ); + } + let scheme = match scheme.as_str() { + "https" | "grpcs" => Scheme::Https, + _ => Scheme::Http, + }; + (scheme, rest, true) + } + None => (Scheme::Http, addr, false), + }; + + // Drop any path, query, or fragment: only the authority is dialed. + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + if authority.is_empty() { + bail!("Server address '{addr}' is missing a host"); + } + + let (host, port) = split_host_port(authority, addr)?; + let port = port.unwrap_or(if scheme_was_explicit { + scheme.default_port() + } else { + default_port + }); + + Ok(Endpoint { scheme, host, port }) +} + +/// Split an authority into host and optional port, accepting bracketed IPv6 +/// (`[::1]:10025`) and bare IPv6 literals (`::1`). +fn split_host_port(authority: &str, addr: &str) -> Result<(String, Option)> { + let parse_port = |port: &str| -> Result { + port.parse::() + .with_context(|| format!("Invalid port '{port}' in server address '{addr}'")) + }; + + if let Some(rest) = authority.strip_prefix('[') { + let (host, rest) = rest + .split_once(']') + .ok_or_else(|| anyhow!("Unterminated IPv6 address in server address '{addr}'"))?; + let port = match rest { + "" => None, + _ => Some(parse_port(rest.strip_prefix(':').ok_or_else(|| { + anyhow!("Expected ':port' after IPv6 address in server address '{addr}'") + })?)?), + }; + return Ok((host.to_string(), port)); + } + + // More than one colon means a bare IPv6 literal; a port would require brackets. + match authority.split_once(':') { + Some((host, port)) if !port.contains(':') => { + Ok((host.to_string(), Some(parse_port(port)?))) + } + _ => Ok((authority.to_string(), None)), + } +} + +/// Client-side TLS material, shared by every transport the CLI dials. +/// +/// The two settings are independent: `ca_cert` decides whether the client +/// trusts the *server's* certificate, while `client_cert`/`client_key` are what +/// the client presents so the *server* can authenticate it (mTLS). A deployment +/// using a private CA for both directions needs both. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TlsOptions { + /// PEM CA certificate trusted in addition to the platform roots. + pub ca_cert: Option, + /// PEM client certificate presented for mTLS. + pub client_cert: Option, + /// PKCS#8 PEM private key for `client_cert`. + pub client_key: Option, +} + +impl TlsOptions { + /// The client certificate and key, read from disk. `None` when no client + /// identity is configured. + pub fn read_client_identity(&self) -> Result, Vec)>> { + let (Some(cert), Some(key)) = (&self.client_cert, &self.client_key) else { + return Ok(None); + }; + let cert_pem = fs::read(cert) + .with_context(|| format!("Failed to read client certificate '{cert}'"))?; + let key_pem = + fs::read(key).with_context(|| format!("Failed to read client key '{key}'"))?; + Ok(Some((cert_pem, key_pem))) + } + + /// The CA certificate, read from disk. + pub fn read_ca_cert(&self) -> Result>> { + let Some(ca_cert) = &self.ca_cert else { + return Ok(None); + }; + let pem = fs::read(ca_cert) + .with_context(|| format!("Failed to read CA certificate '{ca_cert}'"))?; + Ok(Some(pem)) + } +} + +/// Resolved connection settings with guaranteed values. +/// +/// This is returned by `ConnectionArgs::resolve()` after applying +/// the precedence rules: CLI/env args > profile > defaults. +#[derive(Debug, Clone)] +pub struct ResolvedConnection { + pub sql_server_url: String, + pub http_server_url: String, + pub database: String, + pub authentication: Authentication, + pub azure_storage_account_name: Option, + pub tls: TlsOptions, + pub profile_name: String, +} + +/// Common connection arguments that can be embedded in command structs. +/// +/// Use `#[command(flatten)]` to embed these in your command's args struct. +#[derive(Args, Debug, Clone, Default)] +pub struct ConnectionArgs { + /// Connection profile to use (from ~/.lancedb/config.toml) + #[arg(short = 'p', long, value_name = "PROFILE")] + pub profile: Option, + + /// SQL Server URL (Flight SQL endpoint), as host:port or grpc(s)://host:port - overrides profile + #[arg(long, value_name = "URL")] + pub sql_server_url: Option, + + /// HTTP Server URL, as host:port or http(s)://host:port - overrides profile + #[arg(long, value_name = "URL")] + pub http_server_url: Option, + + /// Database name - overrides profile + #[arg(short = 'd', long)] + pub database: Option, + + /// API key - overrides profile and authentication environment variables + /// + /// Without explicit credential flags, environment precedence is LANCEDB_API_KEY, + /// LANCEDB_OIDC_ACCESS_TOKEN, then LANCEDB_OIDC_ACCESS_TOKEN_FILE. + #[arg(long, conflicts_with = "oidc_access_token_file")] + pub api_key: Option, + + /// File containing an OIDC access token - overrides profile and authentication environment variables + #[arg(long, value_name = "PATH", conflicts_with = "api_key")] + pub oidc_access_token_file: Option, + + /// Azure storage account name - overrides profile + #[arg(long, env = "AZURE_STORAGE_ACCOUNT_NAME")] + pub azure_storage_account_name: Option, + + /// Path to a PEM CA certificate that signed the server's TLS certificate, + /// trusted in addition to the platform roots - overrides profile + #[arg(long, value_name = "PATH", env = "LANCEDB_CA_CERT")] + pub ca_cert: Option, + + /// Path to a PEM client certificate to present for mTLS; requires + /// --client-key - overrides profile + #[arg(long, value_name = "PATH", env = "LANCEDB_CLIENT_CERT")] + pub client_cert: Option, + + /// Path to the PKCS#8 PEM private key for --client-cert - overrides profile + #[arg(long, value_name = "PATH", env = "LANCEDB_CLIENT_KEY")] + pub client_key: Option, +} + +/// The database a connection uses when none is configured: the system username. +pub fn default_database_name() -> String { + std::env::var("USER") + .or_else(|_| std::env::var("USERNAME")) + .unwrap_or_else(|_| "default".to_string()) +} + +impl ConnectionArgs { + /// Resolve connection settings from profile with a custom default database. + /// + /// Precedence: CLI/env args > profile > defaults + pub fn resolve(&self, default_database: Option<&str>) -> Result { + let config = Config::load_default()?; + self.resolve_with_config(&config, default_database) + } + + /// Resolve SQL only when an endpoint was supplied by a flag or saved + /// profile. The built-in localhost endpoint requires `--profile local`. + pub(crate) fn resolve_sql(&self) -> Result> { + self.resolve_sql_with_config(&Config::load_default()?) + } + + fn resolve_sql_with_config(&self, config: &Config) -> Result> { + let profile_name = self + .profile + .as_deref() + .or(config.default_profile.as_deref()) + .unwrap_or(DEFAULT_PROFILE); + let endpoint = self.sql_server_url.as_deref().or_else(|| { + config + .profiles + .get(profile_name) + .and_then(|profile| profile.sql_server_url.as_deref()) + }); + if let Some(endpoint) = endpoint { + if endpoint.trim().is_empty() { + bail!("Flight SQL endpoint cannot be empty"); + } + } else if self.profile.as_deref() != Some(DEFAULT_PROFILE) { + return Ok(None); + } + self.resolve_with_config(config, None).map(Some) + } + + fn resolve_with_config( + &self, + config: &Config, + default_database: Option<&str>, + ) -> Result { + // Determine the effective profile name + let profile_name = self + .profile + .clone() + .or_else(|| config.default_profile.clone()) + .unwrap_or_else(|| DEFAULT_PROFILE.to_string()); + + let profile = config.get_profile(self.profile.as_deref()); + let authentication = self.resolve_authentication(&profile, &profile_name)?; + + let sql_server_url = self + .sql_server_url + .clone() + .or(profile.sql_server_url) + .unwrap_or_else(|| "localhost:10025".to_string()); + + let http_server_url = self + .http_server_url + .clone() + .or(profile.http_server_url) + .unwrap_or_else(|| "localhost:10024".to_string()); + + let database = self + .database + .clone() + .or(profile.database) + .unwrap_or_else(|| { + default_database + .map(|s| s.to_string()) + .unwrap_or_else(default_database_name) + }); + + let azure_storage_account_name = self + .azure_storage_account_name + .clone() + .or(profile.azure_storage_account_name); + + // A client certificate is unusable without its key, so resolve the pair + // together rather than letting one side come from the profile and the + // other from a flag. + let (client_cert, client_key) = match (&self.client_cert, &self.client_key) { + (None, None) => (profile.client_cert, profile.client_key), + (cert, key) => (cert.clone(), key.clone()), + }; + if client_cert.is_some() != client_key.is_some() { + bail!("--client-cert and --client-key must be provided together"); + } + + let tls = TlsOptions { + ca_cert: self.ca_cert.clone().or(profile.ca_cert), + client_cert, + client_key, + }; + + Ok(ResolvedConnection { + sql_server_url, + http_server_url, + database, + authentication, + azure_storage_account_name, + tls, + profile_name, + }) + } + + fn resolve_authentication( + &self, + profile: &Profile, + profile_name: &str, + ) -> Result { + self.resolve_authentication_with_env(profile, profile_name, |name| std::env::var_os(name)) + } + + fn resolve_authentication_with_env( + &self, + profile: &Profile, + profile_name: &str, + getenv: impl Fn(&str) -> Option, + ) -> Result { + if self.api_key.is_some() && self.oidc_access_token_file.is_some() { + bail!("--api-key and --oidc-access-token-file are mutually exclusive"); + } + profile.validate_authentication()?; + + if let Some(api_key) = &self.api_key { + return Ok(Authentication::ApiKey(nonempty_secret(api_key, "API key")?)); + } + if let Some(path) = &self.oidc_access_token_file { + return Ok(Authentication::OidcAccessTokenFile(path.into())); + } + if let Some(api_key) = getenv(API_KEY_ENV) { + return Ok(Authentication::ApiKey(nonempty_os_secret( + api_key, + API_KEY_ENV, + )?)); + } + if let Some(token) = getenv(OIDC_ACCESS_TOKEN_ENV) { + return Ok(Authentication::OidcAccessToken(nonempty_os_secret( + token, + OIDC_ACCESS_TOKEN_ENV, + )?)); + } + if let Some(path) = getenv(OIDC_ACCESS_TOKEN_FILE_ENV) { + let path = path + .into_string() + .map_err(|_| anyhow!("{OIDC_ACCESS_TOKEN_FILE_ENV} is not valid UTF-8"))?; + return Ok(Authentication::OidcAccessTokenFile(path.into())); + } + if let Some(api_key) = &profile.api_key { + return Ok(Authentication::ApiKey(nonempty_secret(api_key, "API key")?)); + } + if let Some(path) = &profile.oidc_access_token_file { + return Ok(Authentication::OidcAccessTokenFile(path.into())); + } + if let Some(oidc) = &profile.oidc { + return Ok(Authentication::ManagedOidc(std::sync::Arc::new( + crate::auth::ManagedOidc::for_profile(profile_name, oidc.clone())?, + ))); + } + Ok(Authentication::ApiKey(DEFAULT_API_KEY.to_string())) + } +} + +fn nonempty_secret(value: &str, description: &str) -> Result { + if value.is_empty() { + bail!("{description} cannot be empty"); + } + Ok(value.to_string()) +} + +fn nonempty_os_secret(value: std::ffi::OsString, name: &str) -> Result { + let value = value + .into_string() + .map_err(|_| anyhow!("{name} is not valid UTF-8"))?; + nonempty_secret(&value, name) +} + +/// A connection profile for the LanceDB CLI +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct Profile { + /// SQL server URL (Flight SQL endpoint) + #[serde(skip_serializing_if = "Option::is_none")] + pub sql_server_url: Option, + /// HTTP server URL (REST endpoint) + #[serde(skip_serializing_if = "Option::is_none")] + pub http_server_url: Option, + /// API key for authentication + #[serde(skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Path to a file containing an OIDC access token. + #[serde(skip_serializing_if = "Option::is_none")] + pub oidc_access_token_file: Option, + /// Managed OAuth authentication using the LanceDB SDK. + #[serde(skip_serializing_if = "Option::is_none")] + pub oidc: Option, + /// Default database name + #[serde(skip_serializing_if = "Option::is_none")] + pub database: Option, + /// Azure storage account name for Azure-backed databases + #[serde(skip_serializing_if = "Option::is_none")] + pub azure_storage_account_name: Option, + /// Path to a PEM CA certificate trusted in addition to the platform roots + #[serde(skip_serializing_if = "Option::is_none")] + pub ca_cert: Option, + /// Path to a PEM client certificate presented for mTLS + #[serde(skip_serializing_if = "Option::is_none")] + pub client_cert: Option, + /// Path to the PKCS#8 PEM private key for `client_cert` + #[serde(skip_serializing_if = "Option::is_none")] + pub client_key: Option, +} + +impl Profile { + pub(crate) fn validate_authentication(&self) -> Result<()> { + if self.api_key.is_some() && self.oidc_access_token_file.is_some() { + bail!("profile cannot specify both api_key and oidc_access_token_file"); + } + if self.oidc.is_some() && (self.api_key.is_some() || self.oidc_access_token_file.is_some()) + { + bail!("profile cannot combine oidc with api_key or oidc_access_token_file"); + } + Ok(()) + } + + /// Create the built-in profile for a local SQL/HTTP deployment. + pub fn local_default() -> Self { + Self { + sql_server_url: Some("localhost:10025".to_string()), + http_server_url: Some("localhost:10024".to_string()), + api_key: None, + oidc_access_token_file: None, + oidc: None, + database: None, + azure_storage_account_name: None, + ca_cert: None, + client_cert: None, + client_key: None, + } + } +} + +/// Configuration file structure for ~/.lancedb/config.toml +#[derive(Debug, Serialize, Deserialize)] +pub struct Config { + /// Data directory for LanceDB server + #[serde(skip_serializing_if = "Option::is_none")] + pub data_dir: Option, + + /// Default profile name to use when none is specified + #[serde(skip_serializing_if = "Option::is_none")] + pub default_profile: Option, + + /// Named connection profiles + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub profiles: HashMap, +} + +impl Default for Config { + fn default() -> Self { + Self { + data_dir: None, + default_profile: Some(DEFAULT_PROFILE.to_string()), + profiles: HashMap::new(), + } + } +} + +fn create_config_directory(path: &Path) -> Result<()> { + let mut builder = fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + builder.mode(0o700); + builder + .create(path) + .with_context(|| format!("Failed to create config directory: {:?}", path)) +} + +impl Config { + /// The database a client uses without `--database`: the default profile's, else the username. + pub fn default_database(&self) -> String { + self.get_profile(None) + .database + .unwrap_or_else(default_database_name) + } + + /// Get the default config file path (~/.lancedb/config.toml) + pub fn default_config_path() -> Result { + let user_dirs = + UserDirs::new().ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))?; + + let config_dir = user_dirs.home_dir().join(".lancedb"); + Ok(config_dir.join("config.toml")) + } + + /// Get the default data directory path (~/.lancedb/databases) + pub fn default_data_dir() -> Result { + let user_dirs = + UserDirs::new().ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))?; + + let data_dir = user_dirs.home_dir().join(".lancedb").join("databases"); + Ok(data_dir.to_string_lossy().to_string()) + } + + /// Load config from the default location, or return default config if not found + pub fn load_default() -> Result { + let config_path = Self::default_config_path()?; + + if !config_path.exists() { + return Ok(Self::default()); + } + + Self::load_from_path(&config_path) + } + + /// Load config from the default location, returning None if not found + pub fn load_default_optional() -> Result> { + let config_path = Self::default_config_path()?; + + if !config_path.exists() { + return Ok(None); + } + + Self::load_from_path(&config_path).map(Some) + } + + /// Load config from a specific path + pub fn load_from_path(path: &Path) -> Result { + let (config, unused) = Self::load_from_path_impl(path)?; + for unused_key in unused { + println!( + "While parsing {}, ignored unused configuration key: {}", + path.to_string_lossy(), + unused_key + ); + } + Ok(config) + } + + /// Load config and collect unused keys. Parse errors include a location + /// when available, without source text, values, or the original parser cause. + pub fn load_from_path_impl(path: &Path) -> Result<(Self, Vec)> { + let contents = fs::read_to_string(path) + .with_context(|| format!("Failed to read config file: {:?}", path))?; + + let mut unused = Vec::new(); + match serde_ignored::deserialize(toml::de::Deserializer::new(&contents), |path| { + unused.push(path.to_string()) + }) { + Err(err) => { + // Both Display and message() can contain credentials. Keep only + // the numeric location, and never attach the parser as a cause. + let location = err + .span() + .and_then(|span| contents.get(..span.start)) + .map(|prefix| { + let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1; + let column = prefix.rsplit('\n').next().unwrap_or("").chars().count() + 1; + format!(" at line {line}, column {column}") + }) + .unwrap_or_default(); + bail!( + "Failed to parse config file: {path:?}{location}: invalid TOML or configuration value" + ) + } + Ok(config) => Ok((config, unused)), + } + } + + /// Save config to the default location. On Unix, restrict the app-owned + /// directory to mode 0700, including when it already exists. + pub fn save_default(&self) -> Result<()> { + let config_path = Self::default_config_path()?; + #[cfg(unix)] + { + let parent = config_path.parent().context("Config path has no parent")?; + create_config_directory(parent)?; + fs::set_permissions(parent, fs::Permissions::from_mode(0o700)) + .with_context(|| format!("Failed to restrict config directory: {:?}", parent))?; + } + self.save_to_path(&config_path) + } + + /// Atomically replace config at a specific path. On Unix, the new file is + /// mode 0600, even when replacing a permissive file. Newly created parent + /// directories are private; existing custom parent directories are unchanged. + pub fn save_to_path(&self, path: &Path) -> Result<()> { + let contents = toml::to_string_pretty(self).context("Failed to serialize config")?; + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + create_config_directory(parent)?; + + // tempfile creates Unix files with mode 0600 from the outset. Set it + // explicitly before writing secrets so an owner-masking umask also works. + let mut file = tempfile::NamedTempFile::new_in(parent) + .with_context(|| format!("Failed to create private config file in {:?}", parent))?; + #[cfg(unix)] + file.as_file() + .set_permissions(fs::Permissions::from_mode(0o600)) + .with_context(|| format!("Failed to restrict config file: {:?}", path))?; + file.write_all(contents.as_bytes()) + .with_context(|| format!("Failed to write config file: {:?}", path))?; + file.persist(path) + .map_err(|error| error.error) + .with_context(|| format!("Failed to replace config file: {:?}", path))?; + + Ok(()) + } + + /// Get a profile by name, falling back to built-in "local" profile + pub fn get_profile(&self, name: Option<&str>) -> Profile { + let profile_name = name + .map(|s| s.to_string()) + .or_else(|| self.default_profile.clone()) + .unwrap_or_else(|| DEFAULT_PROFILE.to_string()); + + self.profiles + .get(&profile_name) + .cloned() + .unwrap_or_else(|| { + if profile_name == DEFAULT_PROFILE { + Profile::local_default() + } else { + Profile::default() + } + }) + } + + /// Add or update a profile + pub fn set_profile(&mut self, name: &str, profile: Profile) { + self.profiles.insert(name.to_string(), profile); + } + + /// Remove a profile + pub fn remove_profile(&mut self, name: &str) -> Option { + self.profiles.remove(name) + } + + /// List all profile names + pub fn list_profiles(&self) -> Vec<&str> { + self.profiles.keys().map(|s| s.as_str()).collect() + } + + /// Set the default profile name + pub fn set_default_profile(&mut self, name: &str) { + self.default_profile = Some(name.to_string()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[test] + fn sql_resolution_does_not_invent_an_endpoint() { + let args = ConnectionArgs { + api_key: Some("test-key".into()), + http_server_url: Some("http://api.example.com".into()), + ..Default::default() + }; + let mut config = Config::default(); + assert!(args.resolve_sql_with_config(&config).unwrap().is_none()); + config.set_profile("cloud", Profile::default()); + config.set_default_profile("cloud"); + assert!(args.resolve_sql_with_config(&config).unwrap().is_none()); + + let local = ConnectionArgs { + profile: Some("local".into()), + ..args + }; + assert_eq!( + local + .resolve_sql_with_config(&config) + .unwrap() + .unwrap() + .sql_server_url, + "localhost:10025" + ); + } + + #[test] + fn sql_resolution_uses_a_saved_endpoint_or_an_explicit_override() { + let args = ConnectionArgs { + api_key: Some("test-key".into()), + ..Default::default() + }; + let mut config = Config::default(); + config.set_profile( + "cloud", + Profile { + sql_server_url: Some("grpcs://sql.example.com:10025".into()), + ..Default::default() + }, + ); + config.set_default_profile("cloud"); + assert_eq!( + args.resolve_sql_with_config(&config) + .unwrap() + .unwrap() + .sql_server_url, + "grpcs://sql.example.com:10025" + ); + let override_args = ConnectionArgs { + sql_server_url: Some("localhost:12345".into()), + ..args + }; + assert_eq!( + override_args + .resolve_sql_with_config(&config) + .unwrap() + .unwrap() + .sql_server_url, + "localhost:12345" + ); + } + + #[test] + fn sql_resolution_rejects_an_empty_configured_endpoint() { + let args = ConnectionArgs { + sql_server_url: Some(" ".into()), + ..Default::default() + }; + let error = args + .resolve_sql_with_config(&Config::default()) + .unwrap_err(); + assert!(error + .to_string() + .contains("Flight SQL endpoint cannot be empty")); + } + + #[test] + fn test_parse_endpoint_defaults_to_plaintext() { + let endpoint = parse_endpoint("localhost:10024", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(endpoint.scheme, Scheme::Http); + assert_eq!(endpoint.url(), "http://localhost:10024"); + assert!(!endpoint.is_tls()); + } + + #[test] + fn test_parse_endpoint_applies_default_port_without_scheme() { + let endpoint = parse_endpoint("localhost", DEFAULT_SQL_PORT).unwrap(); + assert_eq!(endpoint.url(), "http://localhost:10025"); + } + + #[test] + fn test_parse_endpoint_preserves_https() { + let endpoint = parse_endpoint("https://db.example.com:8443", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(endpoint.scheme, Scheme::Https); + assert_eq!(endpoint.url(), "https://db.example.com:8443"); + assert!(endpoint.is_tls()); + } + + #[test] + fn test_parse_endpoint_scheme_implies_standard_port() { + assert_eq!( + parse_endpoint("https://db.example.com", DEFAULT_HTTP_PORT) + .unwrap() + .url(), + "https://db.example.com:443" + ); + assert_eq!( + parse_endpoint("http://db.example.com", DEFAULT_HTTP_PORT) + .unwrap() + .url(), + "http://db.example.com:80" + ); + } + + #[test] + fn test_parse_endpoint_ignores_trailing_path() { + let endpoint = parse_endpoint("https://db.example.com:8443/", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(endpoint.url(), "https://db.example.com:8443"); + } + + #[test] + fn test_parse_endpoint_ipv6() { + let bracketed = parse_endpoint("https://[fd00::1]:8443", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(bracketed.host, "fd00::1"); + assert_eq!(bracketed.url(), "https://[fd00::1]:8443"); + + // A bare IPv6 literal has no port; the default applies. + let bare = parse_endpoint("::1", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(bare.host, "::1"); + assert_eq!(bare.url(), "http://[::1]:10024"); + + let bracketed_no_port = parse_endpoint("[::1]", DEFAULT_HTTP_PORT).unwrap(); + assert_eq!(bracketed_no_port.url(), "http://[::1]:10024"); + } + + #[test] + fn test_parse_grpc_endpoint_maps_grpc_schemes() { + // grpc:// is plaintext HTTP/2; grpcs:// is the TLS form. + assert_eq!( + parse_grpc_endpoint("grpc://lancedb-query-node:10025", DEFAULT_SQL_PORT) + .unwrap() + .url(), + "http://lancedb-query-node:10025" + ); + let secure = + parse_grpc_endpoint("grpcs://sql.example.com:10025", DEFAULT_SQL_PORT).unwrap(); + assert!(secure.is_tls()); + assert_eq!(secure.url(), "https://sql.example.com:10025"); + } + + #[test] + fn test_parse_endpoint_rejects_invalid_addresses() { + // gRPC schemes belong to the Flight SQL address only. + assert!(parse_endpoint("grpc://localhost:10025", DEFAULT_SQL_PORT).is_err()); + assert!(parse_endpoint("ftp://localhost:10025", DEFAULT_SQL_PORT).is_err()); + assert!(parse_grpc_endpoint("ftp://localhost:10025", DEFAULT_SQL_PORT).is_err()); + assert!(parse_endpoint("localhost:notaport", DEFAULT_SQL_PORT).is_err()); + assert!(parse_endpoint("https://", DEFAULT_HTTP_PORT).is_err()); + assert!(parse_endpoint("[::1:10024", DEFAULT_HTTP_PORT).is_err()); + } + + #[test] + fn config_parse_errors_do_not_expose_credentials_or_parser_causes() { + let dir = tempdir().unwrap(); + let path = dir.path().join("config.toml"); + for (contents, secret, location) in [ + ( + "[profiles.cloud]\napi_key = \"sk_test_private\",\n", + "sk_test_private", + "line 2, column 28", + ), + ( + "[profiles.cloud]\r\napi_key = \"sk_test_prívate\",\r\n", + "sk_test_prívate", + "line 2, column 28", + ), + ( + "[profiles.cloud.oidc]\nflow = \"sk_test_private\"\n", + "sk_test_private", + "line 2, column 8", + ), + ] { + fs::write(&path, contents).unwrap(); + let err = Config::load_from_path_impl(&path).unwrap_err(); + for diagnostic in [ + format!("{err}"), + format!("{err:#}"), + format!("{err:?}"), + format!("{err:#?}"), + ] { + assert!(!diagnostic.contains(secret)); + assert!(!diagnostic.contains("api_key =")); + assert!(diagnostic.contains("Failed to parse config file")); + assert!(diagnostic.contains("invalid TOML or configuration value")); + assert!(diagnostic.contains(location), "{diagnostic}"); + assert!(diagnostic.contains("config.toml")); + } + assert_eq!(err.chain().count(), 1); + assert!(err.downcast_ref::().is_none()); + } + } + + #[test] + fn test_save_and_load_config() { + let dir = tempdir().unwrap(); + let config_path = dir.path().join("config.toml"); + + let mut config = Config { + data_dir: Some("/test/data".to_string()), + ..Config::default() + }; + config.set_profile( + "test", + Profile { + sql_server_url: Some("http://test.example.com".to_string()), + http_server_url: Some("http://test.example.com".to_string()), + api_key: Some("test-key".to_string()), + database: Some("testdb".to_string()), + azure_storage_account_name: Some("teststorageacct".to_string()), + ..Profile::default() + }, + ); + + // Save config + config.save_to_path(&config_path).unwrap(); + + // Load config + let loaded = Config::load_from_path(&config_path).unwrap(); + assert_eq!(loaded.data_dir, config.data_dir); + assert!(loaded.profiles.contains_key("test")); + assert_eq!( + loaded + .profiles + .get("test") + .unwrap() + .azure_storage_account_name, + Some("teststorageacct".to_string()) + ); + } + + #[cfg(unix)] + #[test] + fn config_saves_are_private_without_changing_custom_parent_modes() { + let dir = tempdir().unwrap(); + let parent = dir.path().join("custom"); + let path = parent.join("config.toml"); + let mut config = Config::default(); + config.set_profile( + "cloud", + Profile { + api_key: Some("initial-key".into()), + ..Profile::default() + }, + ); + config.save_to_path(&path).unwrap(); + assert_eq!( + fs::metadata(&parent).unwrap().permissions().mode() & 0o777, + 0o700 + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + + fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + config.profiles.get_mut("cloud").unwrap().api_key = Some("updated-key".into()); + config.save_to_path(&path).unwrap(); + + assert_eq!( + fs::metadata(&parent).unwrap().permissions().mode() & 0o777, + 0o755 + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + Config::load_from_path(&path) + .unwrap() + .get_profile(Some("cloud")) + .api_key + .as_deref(), + Some("updated-key") + ); + } + + #[test] + fn test_config_serialization() { + let config = Config { + data_dir: Some("/test/data".to_string()), + ..Config::default() + }; + + let serialized = toml::to_string_pretty(&config).unwrap(); + println!("Config TOML output:\n{}", serialized); + assert!(serialized.contains("data_dir = \"/test/data\"")); + + let deserialized: Config = toml::from_str(&serialized).unwrap(); + assert_eq!(deserialized.data_dir, config.data_dir); + } + + #[test] + fn test_profile_management() { + let mut config = Config::default(); + + // Test default profile (local) + let profile = config.get_profile(None); + assert_eq!(profile.sql_server_url, Some("localhost:10025".to_string())); + + // Add a custom profile + config.set_profile( + "production", + Profile { + sql_server_url: Some("http://sql.example.com".to_string()), + http_server_url: Some("http://api.example.com".to_string()), + api_key: Some("prod-key".to_string()), + database: Some("proddb".to_string()), + azure_storage_account_name: Some("prodstorageacct".to_string()), + ..Profile::default() + }, + ); + + // Get custom profile + let prod_profile = config.get_profile(Some("production")); + assert_eq!( + prod_profile.sql_server_url, + Some("http://sql.example.com".to_string()) + ); + assert_eq!(prod_profile.api_key, Some("prod-key".to_string())); + assert_eq!( + prod_profile.azure_storage_account_name, + Some("prodstorageacct".to_string()) + ); + + // Set as default + config.set_default_profile("production"); + let default_profile = config.get_profile(None); + assert_eq!( + default_profile.sql_server_url, + Some("http://sql.example.com".to_string()) + ); + + // List profiles + let profiles = config.list_profiles(); + assert!(profiles.contains(&"production")); + + // Remove profile + config.remove_profile("production"); + assert!(!config.profiles.contains_key("production")); + } + + #[test] + fn test_backward_compatible_config() { + // Test that old config format (just data_dir) still loads + let old_config = r#"data_dir = "/old/data/path""#; + let config: Config = toml::from_str(old_config).unwrap(); + assert_eq!(config.data_dir, Some("/old/data/path".to_string())); + assert!(config.profiles.is_empty()); + } + + #[test] + fn test_full_config_format() { + let full_config = r#" +data_dir = "/data/lancedb" +default_profile = "dev" + +[profiles.dev] +sql_server_url = "http://localhost:8080" +http_server_url = "http://localhost:8081" +database = "devdb" +unknown_config_key = "blah" + +[profiles.prod] +sql_server_url = "http://sql.prod.example.com" +http_server_url = "http://api.prod.example.com" +api_key = "secret-key" +database = "proddb" +azure_storage_account_name = "prodstorageacct" +"#; + let dir = tempdir().unwrap(); + let config_path = dir.path().join("config.toml"); + fs::write(&config_path, full_config).unwrap(); + let (config, unused) = Config::load_from_path_impl(&config_path).unwrap(); + assert_eq!(vec!["profiles.dev.unknown_config_key"], unused); + assert_eq!(config.data_dir, Some("/data/lancedb".to_string())); + assert_eq!(config.default_profile, Some("dev".to_string())); + assert_eq!(config.profiles.len(), 2); + + let dev = config.get_profile(Some("dev")); + assert_eq!( + dev.sql_server_url, + Some("http://localhost:8080".to_string()) + ); + assert_eq!(dev.api_key, None); + + let prod = config.get_profile(Some("prod")); + assert_eq!(prod.api_key, Some("secret-key".to_string())); + assert_eq!( + prod.azure_storage_account_name, + Some("prodstorageacct".to_string()) + ); + } + + #[test] + fn authentication_resolution_follows_flag_env_profile_order() { + let dir = tempdir().unwrap(); + let flag_token = dir.path().join("flag-token"); + let env_token = dir.path().join("env-token"); + fs::write(&flag_token, "flag-oidc\n").unwrap(); + fs::write(&env_token, "env-file-oidc\n").unwrap(); + + let profile = Profile { + api_key: Some("profile-api-key".to_string()), + ..Profile::default() + }; + let args = ConnectionArgs { + api_key: Some("flag-api-key".to_string()), + ..ConnectionArgs::default() + }; + let all_env = |name: &str| match name { + API_KEY_ENV => Some("env-api-key".into()), + OIDC_ACCESS_TOKEN_ENV => Some("env-oidc".into()), + OIDC_ACCESS_TOKEN_FILE_ENV => Some(env_token.as_os_str().to_owned()), + _ => None, + }; + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, all_env) + .unwrap(), + Authentication::ApiKey("flag-api-key".to_string()) + ); + + let args = ConnectionArgs { + oidc_access_token_file: Some(flag_token.to_string_lossy().into_owned()), + ..ConnectionArgs::default() + }; + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, all_env) + .unwrap(), + Authentication::OidcAccessTokenFile(flag_token.clone()) + ); + + let args = ConnectionArgs::default(); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, all_env) + .unwrap(), + Authentication::ApiKey("env-api-key".to_string()) + ); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |name| match name { + OIDC_ACCESS_TOKEN_ENV => Some("env-oidc".into()), + OIDC_ACCESS_TOKEN_FILE_ENV => Some(env_token.as_os_str().to_owned()), + _ => None, + }) + .unwrap(), + Authentication::OidcAccessToken("env-oidc".to_string()) + ); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |name| match name { + OIDC_ACCESS_TOKEN_FILE_ENV => Some(env_token.as_os_str().to_owned()), + _ => None, + }) + .unwrap(), + Authentication::OidcAccessTokenFile(env_token.clone()) + ); + assert_eq!( + args.resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |_| None) + .unwrap(), + Authentication::ApiKey("profile-api-key".to_string()) + ); + assert_eq!( + args.resolve_authentication_with_env(&Profile::default(), DEFAULT_PROFILE, |_| None) + .unwrap(), + Authentication::ApiKey(DEFAULT_API_KEY.to_string()) + ); + } + + #[test] + fn profile_cannot_contain_two_authentication_methods() { + let profile = Profile { + api_key: Some("sk_test".to_string()), + oidc_access_token_file: Some("token-file".to_string()), + ..Profile::default() + }; + let err = ConnectionArgs::default() + .resolve_authentication_with_env(&profile, DEFAULT_PROFILE, |_| None) + .unwrap_err(); + assert_eq!( + err.to_string(), + "profile cannot specify both api_key and oidc_access_token_file" + ); + } + #[test] + fn native_oidc_profile_and_credential_overrides() { + let config: Config = toml::from_str( + r#" +[profiles.automation.oidc] +flow = "client_credentials" +issuer_url = "https://identity.example.com" +client_id = "automation-client" +scopes = ["lancedb"] +client_secret_file = "/run/secrets/lancedb" +"#, + ) + .unwrap(); + let profile = config.get_profile(Some("automation")); + let args = ConnectionArgs::default(); + assert!(matches!( + args.resolve_authentication_with_env(&profile, "automation", |_| None) + .unwrap(), + Authentication::ManagedOidc(_) + )); + let oidc = args + .resolve_authentication_with_env(&profile, "automation", |name| { + (name == OIDC_ACCESS_TOKEN_ENV).then(|| "external-token".into()) + }) + .unwrap(); + assert_eq!( + oidc, + Authentication::OidcAccessToken("external-token".into()) + ); + let key = args + .resolve_authentication_with_env(&profile, "automation", |name| match name { + API_KEY_ENV => Some("api-key".into()), + OIDC_ACCESS_TOKEN_ENV => Some("external-token".into()), + _ => None, + }) + .unwrap(); + assert_eq!(key, Authentication::ApiKey("api-key".into())); + let invalid = Profile { + api_key: Some("key".into()), + ..profile + }; + assert!(args + .resolve_authentication_with_env(&invalid, "automation", |_| None) + .is_err()); + } +} diff --git a/rust/lancedb/cli/src/sql_executor.rs b/rust/lancedb/cli/src/sql_executor.rs new file mode 100644 index 000000000..87559d88e --- /dev/null +++ b/rust/lancedb/cli/src/sql_executor.rs @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use crate::dml_result::DmlResult; +use anyhow::Result; +use arrow_array::RecordBatch; +use async_trait::async_trait; + +#[async_trait] +pub trait SqlQueryExecutor: Send + Sync { + /// Execute a SQL query and return a structured result. + async fn execute_query(&mut self, query: &str) -> Result; + + /// Check if the executor is connected and ready + async fn is_connected(&self) -> bool; + + /// Get the connection info for display purposes + fn connection_info(&self) -> Option; + + /// Connect to the server. `server_url` may carry an `http://` or `https://` + /// scheme; a bare `host:port` is treated as plaintext. + async fn connect(&mut self, server_url: &str) -> Result<()>; + + /// Set the current database + fn set_database(&mut self, database: String); +} + +/// Result of a SQL execution +#[derive(Debug)] +pub enum SqlResult { + /// Query returned data + Query(Vec), + /// DML result (INSERT, DELETE, UPDATE) + Dml(DmlResult), + /// DDL statement (CREATE, DROP, etc.) completed + Success, +} + +impl From> for SqlResult { + fn from(batches: Vec) -> Self { + match batches.first().and_then(DmlResult::try_from_batch) { + Some(dml) => Self::Dml(dml), + None => Self::Query(batches), + } + } +} + +/// SQL execution through the public SDK's asynchronous query lifecycle. +pub struct SdkSqlExecutor { + connection: Option, + server_url: String, + database: String, + authentication: crate::server_config::Authentication, + tls: crate::server_config::TlsOptions, +} + +impl SdkSqlExecutor { + pub fn new_with_authentication( + server_url: String, + authentication: crate::server_config::Authentication, + ) -> Self { + Self { + connection: None, + server_url, + database: "test".into(), + authentication, + tls: Default::default(), + } + } + + pub fn new_with_api_key(server_url: String, api_key: String) -> Self { + Self::new_with_authentication( + server_url, + crate::server_config::Authentication::ApiKey(api_key), + ) + } + + pub fn with_tls(mut self, tls: crate::server_config::TlsOptions) -> Self { + self.tls = tls; + self + } +} + +#[async_trait] +impl SqlQueryExecutor for SdkSqlExecutor { + async fn execute_query(&mut self, query: &str) -> Result { + use futures::TryStreamExt; + let connection = self + .connection + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Flight SQL client not connected"))?; + let mut builder = connection.execute_query_async(query); + if let Ok(namespace) = std::env::var("LANCEDB_NAMESPACE_PATH") { + builder = builder.default_namespace_path(namespace.split('$')); + } + let query = builder.execute().await?; + let batches: Vec = query.reader().await?.try_collect().await?; + Ok(batches.into()) + } + + async fn is_connected(&self) -> bool { + self.connection.is_some() + } + + fn connection_info(&self) -> Option { + self.connection + .as_ref() + .map(|_| format!("Connected to {}", self.server_url)) + } + + async fn connect(&mut self, server_url: &str) -> Result<()> { + use crate::server_config::{parse_grpc_endpoint, Authentication, DEFAULT_SQL_PORT}; + self.connection = None; + self.server_url = server_url.to_owned(); + let endpoint = parse_grpc_endpoint(server_url, DEFAULT_SQL_PORT)?.url(); + let mut builder = lancedb::connect(&format!("db://{}", self.database)) + .region("self-hosted") + .sql_host_override(&endpoint); + builder = match &self.authentication { + Authentication::ApiKey(key) => builder.api_key(key), + _ => builder.api_key(""), + }; + let mut config = + crate::lancedb_client_config(&self.tls, &self.authentication).unwrap_or_default(); + // Preserve the CLI's bounded startup probe, including the TLS handshake. + config.timeout_config.connect_timeout = Some(std::time::Duration::from_secs(5)); + builder = builder.client_config(config); + let connection = builder.execute().await?; + connection.check_sql_connection().await?; + self.connection = Some(connection); + Ok(()) + } + + fn set_database(&mut self, database: String) { + if self.database != database { + self.connection = None; + } + self.database = database; + } +} diff --git a/rust/lancedb/cli/src/table_writer.rs b/rust/lancedb/cli/src/table_writer.rs new file mode 100644 index 000000000..bcd146d1b --- /dev/null +++ b/rust/lancedb/cli/src/table_writer.rs @@ -0,0 +1,380 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/* +MIT License + +Copyright (c) Foxglove Technologies Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +// Ported from +// https://github.com/foxglove/foxglove-cli/blob/main/foxglove/util/tablewriter/tablewriter.go + +use std::io::{self, Write}; +use std::process::Command; +use unicode_width::UnicodeWidthStr; + +pub struct TableWriter; + +impl TableWriter { + pub fn print_table( + writer: &mut W, + headers: &[String], + data: &[Vec], + term_width: Option, + ) -> io::Result<()> { + let term_width = term_width.unwrap_or_else(get_terminal_width); + let table_width = compute_hotdog_table_width(headers, data); + + if term_width < table_width { + Self::print_hamburger(writer, term_width, headers, data) + } else { + Self::print_hotdog(writer, headers, data) + } + } + + pub fn print_table_with_title( + writer: &mut W, + title: &str, + headers: &[String], + data: &[Vec], + term_width: Option, + ) -> io::Result<()> { + let term_width = term_width.unwrap_or_else(get_terminal_width); + let table_width = compute_hotdog_table_width(headers, data); + + if term_width < table_width { + // For hamburger mode, just print the title normally + writeln!(writer, "{}", title)?; + Self::print_hamburger(writer, term_width, headers, data) + } else { + // For hotdog mode, center the title over the table + let title_padding = if table_width > title.width() { + (table_width - title.width()) / 2 + } else { + 0 + }; + writeln!(writer, "{}{}", " ".repeat(title_padding), title)?; + Self::print_hotdog(writer, headers, data) + } + } + + /// Prints table in horizontal "hotdog" format (PostgreSQL style) + fn print_hotdog( + writer: &mut W, + headers: &[String], + data: &[Vec], + ) -> io::Result<()> { + let cell_widths = compute_hotdog_cell_widths(headers, data); + let column_alignments = compute_column_alignments(data); + + // Write headers + write!(writer, " ")?; + for (i, header) in headers.iter().enumerate() { + if i > 0 { + write!(writer, " | ")?; + } + let padding = cell_widths[i] - header.width(); + write!(writer, "{}{}", header, " ".repeat(padding))?; + } + writeln!(writer)?; + + // Write separator with + at junctions + write!(writer, "-")?; // Leading edge + for (i, &width) in cell_widths.iter().enumerate() { + write!(writer, "{}", "-".repeat(width))?; + if i < cell_widths.len() - 1 { + write!(writer, "-+-")?; // Junction between columns + } + } + writeln!(writer, "-")?; // Trailing edge + + // Write data rows + for row in data { + write!(writer, " ")?; + for (i, col) in row.iter().enumerate() { + if i > 0 { + write!(writer, " | ")?; + } + let padding = cell_widths[i] - col.width(); + + // Right-align numeric columns, left-align others + if i < column_alignments.len() && column_alignments[i] { + write!(writer, "{}{}", " ".repeat(padding), col)?; + } else { + write!(writer, "{}{}", col, " ".repeat(padding))?; + } + } + writeln!(writer)?; + } + + Ok(()) + } + + /// Prints table in vertical "hamburger" format (psql expanded display style) + fn print_hamburger( + writer: &mut W, + term_width: usize, + headers: &[String], + data: &[Vec], + ) -> io::Result<()> { + let mut max_header_width = 0; + let mut max_record_width = 0; + + // Compute max header width + for header in headers { + if header.width() > max_header_width { + max_header_width = header.width(); + } + } + + // Compute max record width (cap at reasonable limit) + const MAX_VALUE_DISPLAY_WIDTH: usize = 80; // Reasonable max for value display + for row in data { + for col in row { + let col_width = col.width().min(MAX_VALUE_DISPLAY_WIDTH); + if col_width > max_record_width { + max_record_width = col_width; + } + } + } + + // Ensure sufficient room for record headers + let longest_record_header = format!("-[ RECORD {} ]", data.len()); + if longest_record_header.len() > max_header_width { + max_header_width = longest_record_header.len(); + } + + // Calculate right dash extent - aim for a reasonable width + let desired_dash_extent = 60; // Reasonable default width for dashes + let mut dashes_right_extent = desired_dash_extent.min(max_record_width + 15); + let max_allowed_extent = term_width.saturating_sub(max_header_width + 3); // +3 for "+-" and space + if dashes_right_extent > max_allowed_extent { + dashes_right_extent = max_allowed_extent; + } + let right_dashes = "-".repeat(dashes_right_extent); + + // Print records + for (i, row) in data.iter().enumerate() { + let record_header = format!("-[ RECORD {} ]", i + 1); + let header_line = format!( + "{}{}+{}", + record_header, + "-".repeat(max_header_width - record_header.len()), + right_dashes + ); + writeln!(writer, "{}", header_line)?; + + for (j, col) in row.iter().enumerate() { + writeln!( + writer, + "{}{}| {}", + headers[j], + " ".repeat(max_header_width - headers[j].width()), + col + )?; + } + } + + Ok(()) + } +} + +fn compute_hotdog_cell_widths(headers: &[String], data: &[Vec]) -> Vec { + let mut cell_widths = vec![0; headers.len()]; + + // Initialize with header widths + for (i, header) in headers.iter().enumerate() { + cell_widths[i] = header.width(); + } + + // Check data column widths + for row in data { + for (i, col) in row.iter().enumerate() { + if i < cell_widths.len() && cell_widths[i] < col.width() { + cell_widths[i] = col.width(); + } + } + } + + cell_widths +} + +fn compute_hotdog_table_width(headers: &[String], data: &[Vec]) -> usize { + let cell_widths = compute_hotdog_cell_widths(headers, data); + // Account for " | " separators between columns (3 chars each) + leading space + trailing space + let separator_width = if headers.len() > 1 { + (headers.len() - 1) * 3 + } else { + 0 + }; + 2 + cell_widths.iter().sum::() + separator_width +} + +fn compute_column_alignments(data: &[Vec]) -> Vec { + if data.is_empty() { + return vec![]; + } + + let num_cols = data[0].len(); + let mut is_numeric = vec![true; num_cols]; + + // Check each column to see if all non-empty values are numeric + for col_idx in 0..num_cols { + for row in data { + if col_idx < row.len() && !row[col_idx].is_empty() { + let value = &row[col_idx]; + // Check if the value is numeric (integer or float) + // Also handle NULL values + if value != "NULL" && !is_numeric_value(value) { + is_numeric[col_idx] = false; + break; + } + } + } + } + + is_numeric +} + +fn is_numeric_value(s: &str) -> bool { + // Try to parse as integer or float + s.parse::().is_ok() || s.parse::().is_ok() +} + +fn get_terminal_width() -> usize { + if let Ok(output) = Command::new("stty").arg("size").output() { + if let Ok(output_str) = String::from_utf8(output.stdout) { + let parts: Vec<&str> = output_str.split_whitespace().collect(); + if parts.len() >= 2 { + if let Ok(cols) = parts[1].parse::() { + return cols; + } + } + } + } + + // Fallback: try termsize crate + if let Some(size) = termsize::get() { + return size.cols as usize; + } + + // Final fallback + 80 +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn test_print_hotdog() { + let mut output = Cursor::new(Vec::new()); + let headers = vec!["ID".to_string(), "Name".to_string(), "Age".to_string()]; + let data = vec![ + vec!["1".to_string(), "Alice".to_string(), "30".to_string()], + vec!["2".to_string(), "Bob".to_string(), "25".to_string()], + vec!["3".to_string(), "Charlie".to_string(), "35".to_string()], + ]; + + TableWriter::print_hotdog(&mut output, &headers, &data).unwrap(); + let result = String::from_utf8(output.into_inner()).unwrap(); + assert_eq!(result, expected_output()); + } + + #[test] + fn test_unicode_table_padding_uses_terminal_columns() { + let headers = vec!["µ".to_string(), "Type".to_string()]; + let data = vec![ + vec!["µ".to_string(), "TEXT".to_string()], + vec!["漢".to_string(), "TEXT".to_string()], + vec!["e\u{301}".to_string(), "TEXT".to_string()], + ]; + let mut output = Vec::new(); + TableWriter::print_table(&mut output, &headers, &data, Some(11)).unwrap(); + assert_eq!( + String::from_utf8(output).unwrap(), + " µ | Type\n----+------\n µ | TEXT\n 漢 | TEXT\n e\u{301} | TEXT\n" + ); + } + + fn expected_output() -> String { + let mut output = String::new(); + output.push_str(" ID | Name | Age\n"); + output.push_str("----+---------+-----\n"); + output.push_str(" 1 | Alice | 30\n"); + output.push_str(" 2 | Bob | 25\n"); + output.push_str(" 3 | Charlie | 35\n"); + output + } + + #[test] + fn test_print_hamburger() { + let mut output = Cursor::new(Vec::new()); + let headers = vec!["ID".to_string(), "Name".to_string(), "Age".to_string()]; + let data = vec![ + vec!["1".to_string(), "Alice".to_string(), "30".to_string()], + vec!["2".to_string(), "Bob".to_string(), "25".to_string()], + vec!["3".to_string(), "Charlie".to_string(), "35".to_string()], + ]; + + // Test with a narrow terminal width + TableWriter::print_hamburger(&mut output, 80, &headers, &data).unwrap(); + let result = String::from_utf8(output.into_inner()).unwrap(); + assert_eq!(result, expected_hamburger_output()); + } + + fn expected_hamburger_output() -> String { + let mut output = String::new(); + output.push_str("-[ RECORD 1 ]+----------------------\n"); + output.push_str("ID | 1\n"); + output.push_str("Name | Alice\n"); + output.push_str("Age | 30\n"); + output.push_str("-[ RECORD 2 ]+----------------------\n"); + output.push_str("ID | 2\n"); + output.push_str("Name | Bob\n"); + output.push_str("Age | 25\n"); + output.push_str("-[ RECORD 3 ]+----------------------\n"); + output.push_str("ID | 3\n"); + output.push_str("Name | Charlie\n"); + output.push_str("Age | 35\n"); + output + } + + #[test] + fn test_print_table_with_title() { + let mut output = Cursor::new(Vec::new()); + let headers = vec!["ID".to_string(), "Name".to_string()]; + let data = vec![ + vec!["1".to_string(), "Alice".to_string()], + vec!["2".to_string(), "Bob".to_string()], + ]; + + TableWriter::print_table_with_title(&mut output, "User List", &headers, &data, Some(200)) + .unwrap(); + let result = String::from_utf8(output.into_inner()).unwrap(); + + // Should center the title and print hotdog format + let expected = " User List\n ID | Name \n----+-------\n 1 | Alice\n 2 | Bob \n"; + assert_eq!(result, expected); + } +} diff --git a/rust/lancedb/cli/tests/command_surface.rs b/rust/lancedb/cli/tests/command_surface.rs new file mode 100644 index 000000000..9d2f9c50e --- /dev/null +++ b/rust/lancedb/cli/tests/command_surface.rs @@ -0,0 +1,339 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::process::Command; + +#[test] +fn an_unconfigured_default_sql_invocation_prints_usage() { + use lancedb_cli::server_config::{Config, Profile}; + + for has_http_profile in [false, true] { + let home = tempfile::tempdir().unwrap(); + if has_http_profile { + let mut config = Config::default(); + config.set_profile( + "cloud", + Profile { + http_server_url: Some("http://api.example.com".into()), + ..Default::default() + }, + ); + config.set_default_profile("cloud"); + config + .save_to_path(&home.path().join(".lancedb/config.toml")) + .unwrap(); + } + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .env("HOME", home.path()) + .env("LANCEDB_API_KEY", "secret-that-must-not-appear") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("Usage:"), "{stdout}"); + assert!( + stdout.contains("No Flight SQL endpoint is configured"), + "{stdout}" + ); + assert!(!stdout.contains("secret-that-must-not-appear")); + assert!( + output.stderr.is_empty(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + if !has_http_profile { + assert!(!home.path().join(".lancedb").exists()); + } + } +} + +#[test] +fn invalid_config_diagnostics_do_not_print_credentials() { + for (contents, location) in [ + ( + "[profiles.cloud]\napi_key = \"sk_test_private\",\n", + "line 2, column 28", + ), + ( + "[profiles.cloud.oidc]\nflow = \"sk_test_private\"\n", + "line 2, column 8", + ), + ] { + let home = tempfile::tempdir().unwrap(); + let config_dir = home.path().join(".lancedb"); + std::fs::create_dir(&config_dir).unwrap(); + std::fs::write(config_dir.join("config.toml"), contents).unwrap(); + for args in [vec!["profile", "list"], vec!["sql"], vec![]] { + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(args) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains("sk_test_private")); + assert!(!stderr.contains("api_key =")); + assert!(stderr.contains("Failed to parse config file"), "{stderr}"); + assert!(stderr.contains("invalid TOML or configuration value")); + assert!(stderr.contains(location), "{stderr}"); + assert!(stderr.contains("config.toml")); + assert!(output.stdout.is_empty()); + } + } +} + +#[test] +fn explicit_sql_requests_require_a_configured_endpoint() { + for args in [ + vec!["sql"], + vec!["--command", "SELECT 1"], + vec!["--file", "queries.sql"], + vec!["--profile", "missing"], + ] { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(&args) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!(!output.status.success(), "{args:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("No Flight SQL endpoint is configured"), + "{args:?}: {stderr}" + ); + assert!(stderr.contains("--sql-server-url"), "{stderr}"); + assert!(stderr.contains("--profile local"), "{stderr}"); + assert!(!home.path().join(".lancedb").exists()); + } +} + +#[test] +fn selecting_local_as_default_persists_its_endpoint() { + use lancedb_cli::server_config::{Config, Profile}; + + for existing_endpoint in [None, Some("localhost:12345")] { + let home = tempfile::tempdir().unwrap(); + let path = home.path().join(".lancedb/config.toml"); + if let Some(endpoint) = existing_endpoint { + let mut config = Config::default(); + config.set_profile( + "local", + Profile { + sql_server_url: Some(endpoint.into()), + ..Default::default() + }, + ); + config.save_to_path(&path).unwrap(); + } + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(["profile", "set", "local"]) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let config = Config::load_from_path(&path).unwrap(); + assert_eq!(config.default_profile.as_deref(), Some("local")); + assert_eq!( + config + .profiles + .get("local") + .unwrap() + .sql_server_url + .as_deref(), + Some(existing_endpoint.unwrap_or("localhost:10025")) + ); + } +} + +#[test] +fn help_lists_commands_without_creating_configuration() { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .arg("--help") + .env("HOME", home.path()) + .env("LANCEDB_API_KEY", "secret-that-must-not-appear") + .output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.contains("Usage:")); + for command in ["auth", "profile", "sql"] { + assert!(stdout.contains(command)); + } + for command in ["acl", "load", "job"] { + assert!(!stdout.contains(&format!(" {command} ")), "{stdout}"); + } + assert!(!stdout.contains("secret-that-must-not-appear")); + assert!(!home.path().join(".lancedb").exists()); +} + +#[test] +fn excluded_commands_and_mixed_sql_options_are_rejected() { + for args in [ + vec!["server"], + vec!["management"], + vec!["job", "--help"], + vec!["job", "list", "--help"], + vec!["job", "usage"], + vec!["acl"], + vec!["acl", "--help"], + vec!["acl", "list"], + vec!["acl", "add"], + vec!["acl", "delete"], + vec!["load"], + vec!["load", "--help"], + vec!["load", "--source", "lance", "--dataset", "data.lance"], + vec!["--command", "SELECT 1", "profile", "list"], + vec!["--file", "queries.sql", "profile", "list"], + vec!["profile", "list", "--command", "SELECT 1"], + vec!["profile", "list", "--file", "queries.sql"], + ] { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(&args) + .env("HOME", home.path()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2), "{args:?}"); + assert!(output.stdout.is_empty(), "{args:?}"); + assert!(!home.path().join(".lancedb").exists(), "{args:?}"); + } +} + +#[test] +fn sql_options_do_not_appear_in_other_subcommand_help() { + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(["profile", "--help"]) + .output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + for option in ["--command", "--file", "--format", "--sql-server-url"] { + assert!(!stdout.contains(option), "{stdout}"); + } +} + +#[test] +fn sql_environment_options_do_not_change_profile_commands() { + let home = tempfile::tempdir().unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(["profile", "list"]) + .env("HOME", home.path()) + .env("LANCEDB_CA_CERT", "/not-used-by-profile/ca.pem") + .env("LANCEDB_CLIENT_CERT", "/not-used-by-profile/client.pem") + .env("LANCEDB_CLIENT_KEY", "/not-used-by-profile/key.pem") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("Configured profiles:"), "{stdout}"); +} + +#[test] +fn profile_updates_preserve_enterprise_data_directory() { + use lancedb_cli::server_config::{Config, Profile}; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + "data_dir = '/enterprise/data'\ndefault_profile = 'local'\n", + ) + .unwrap(); + let mut config = Config::load_from_path(&path).unwrap(); + config.set_profile( + "cloud", + Profile { + database: Some("analytics".into()), + ..Default::default() + }, + ); + config.save_to_path(&path).unwrap(); + let saved = Config::load_from_path(&path).unwrap(); + assert_eq!(saved.data_dir.as_deref(), Some("/enterprise/data")); + assert_eq!( + saved.get_profile(Some("cloud")).database.as_deref(), + Some("analytics") + ); +} + +#[cfg(unix)] +#[test] +fn api_key_profiles_are_private_under_permissive_umasks_and_after_edits() { + use lancedb_cli::server_config::Config; + use std::fs; + use std::os::unix::fs::PermissionsExt; + + for mask in ["022", "000"] { + let home = tempfile::tempdir().unwrap(); + let config_dir = home.path().join(".lancedb"); + let path = config_dir.join("config.toml"); + let run = |command: &str, key: &str| { + // Set umask only in the child, leaving other test threads unaffected. + let output = Command::new("/bin/sh") + .args([ + "-c", + r#"umask "$1"; shift; exec "$@""#, + "profile-permissions", + mask, + env!("CARGO_BIN_EXE_lancedb"), + "profile", + command, + "cloud", + "--api-key", + key, + "--database", + "analytics", + ]) + .env("HOME", home.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{command} under umask {mask}: {}", + String::from_utf8_lossy(&output.stderr) + ); + }; + let assert_private = || { + assert_eq!( + fs::metadata(&config_dir).unwrap().permissions().mode() & 0o777, + 0o700, + "config directory under umask {mask}" + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600, + "config file under umask {mask}" + ); + }; + + run("create", "initial-key"); + assert_private(); + + fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o755)).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + run("edit", "replacement-key"); + assert_private(); + let saved = Config::load_from_path(&path).unwrap(); + assert_eq!( + saved.get_profile(Some("cloud")).api_key.as_deref(), + Some("replacement-key") + ); + assert_eq!( + saved.get_profile(Some("cloud")).database.as_deref(), + Some("analytics") + ); + } +} diff --git a/rust/lancedb/cli/tests/flight_sql_tls.rs b/rust/lancedb/cli/tests/flight_sql_tls.rs new file mode 100644 index 000000000..40c34409c --- /dev/null +++ b/rust/lancedb/cli/tests/flight_sql_tls.rs @@ -0,0 +1,643 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! End-to-end TLS and SQL file-execution coverage for the Flight SQL transport. +//! +//! A throwaway CA signs a server certificate for `127.0.0.1`, a real Flight +//! server serves it over TLS, and the CLI's executor connects with the CA +//! supplied through `--ca-cert`. The negative cases prove verification is +//! genuinely happening rather than being skipped. + +use std::net::SocketAddr; +use std::pin::Pin; + +use arrow_array::{Int32Array, RecordBatch}; +use arrow_flight::encode::FlightDataEncoderBuilder; +use arrow_flight::flight_service_server::{FlightService, FlightServiceServer}; +use arrow_flight::sql::{Any, CommandStatementQuery}; +use arrow_flight::{ + Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo, + HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, +}; +use arrow_schema::{DataType, Field, Schema}; +use futures::{Stream, TryStreamExt}; +use lancedb_cli::server_config::TlsOptions; +use lancedb_cli::sql_executor::SdkSqlExecutor as FlightSqlExecutor; +use lancedb_cli::sql_executor::{SqlQueryExecutor, SqlResult}; +use prost::Message; +use std::sync::{Arc, Mutex}; +use tokio::net::TcpListener; +use tokio_stream::wrappers::TcpListenerStream; +use tonic::transport::{Identity, Server, ServerTlsConfig}; +use tonic::{Request, Response, Status, Streaming}; + +/// The single column the stub server returns, asserted by the tests. +const ANSWER: i32 = 42; + +/// tonic's server-side TLS needs a process-level rustls crypto provider; unlike +/// the client path it has no built-in fallback. +fn init_crypto_provider() { + static INIT: std::sync::Once = std::sync::Once::new(); + INIT.call_once(|| { + let _ = rustls::crypto::ring::default_provider().install_default(); + }); +} + +type BoxStream = Pin> + Send + 'static>>; + +/// Minimal Flight service: enough for `execute_query` to complete a round trip. +/// Everything the CLI does not call is left unimplemented on purpose. +#[derive(Clone, Default)] +struct StubFlightService { + queries: Option>>>, +} + +/// The SDK wraps a Flight SQL command in a ticket's field 2. +#[derive(Clone, PartialEq, Message)] +struct CommandTicket { + #[prost(bytes = "vec", tag = "2")] + command: Vec, +} + +impl StubFlightService { + fn batch() -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new( + "answer", + DataType::Int32, + false, + )])); + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![ANSWER]))]).unwrap() + } +} + +#[tonic::async_trait] +impl FlightService for StubFlightService { + type HandshakeStream = BoxStream; + type ListFlightsStream = BoxStream; + type DoGetStream = BoxStream; + type DoPutStream = BoxStream; + type DoExchangeStream = BoxStream; + type DoActionStream = BoxStream; + type ListActionsStream = BoxStream; + + async fn get_flight_info( + &self, + _request: Request, + ) -> Result, Status> { + let endpoint = FlightEndpoint::new().with_ticket(Ticket::new("stub")); + Ok(Response::new(FlightInfo::new().with_endpoint(endpoint))) + } + + async fn do_get( + &self, + request: Request, + ) -> Result, Status> { + if let Some(queries) = &self.queries { + let ticket = CommandTicket::decode(request.into_inner().ticket).unwrap(); + let command = Any::decode(ticket.command.as_slice()) + .unwrap() + .unpack::() + .unwrap() + .unwrap(); + queries.lock().unwrap().push(command.query); + } + let batch = Self::batch(); + let stream = FlightDataEncoderBuilder::new() + .build(futures::stream::once(async move { Ok(batch) })) + .map_err(|err| Status::internal(err.to_string())); + Ok(Response::new(Box::pin(stream))) + } + + async fn handshake( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented("handshake")) + } + + async fn list_flights( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("list_flights")) + } + + async fn poll_flight_info( + &self, + _request: Request, + ) -> Result, Status> { + let endpoint = FlightEndpoint::new().with_ticket(Ticket::new("stub")); + let info = FlightInfo::new() + .with_endpoint(endpoint) + .try_with_schema(&Self::batch().schema()) + .unwrap(); + Ok(Response::new(PollInfo { + info: Some(info), + flight_descriptor: None, + progress: Some(1.0), + expiration_time: None, + })) + } + + async fn get_schema( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("get_schema")) + } + + async fn do_put( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented("do_put")) + } + + async fn do_exchange( + &self, + _request: Request>, + ) -> Result, Status> { + Err(Status::unimplemented("do_exchange")) + } + + async fn do_action( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("do_action")) + } + + async fn list_actions( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented("list_actions")) + } +} + +/// A CA plus the server and client certificates it signed. The server +/// certificate is valid for `127.0.0.1`. +struct TestCerts { + ca_pem: String, + server_cert_pem: String, + server_key_pem: String, + client_cert_pem: String, + client_key_pem: String, +} + +fn generate_certs() -> TestCerts { + use rcgen::{BasicConstraints, CertificateParams, IsCa, KeyPair, PKCS_ECDSA_P256_SHA256}; + + let mut ca_params = CertificateParams::new(vec!["Test CA".to_string()]); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + ca_params.key_pair = Some(KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap()); + let ca_cert = rcgen::Certificate::from_params(ca_params).unwrap(); + + // The SANs must cover the address the client dials, or the handshake fails + // hostname verification even with the right CA. + let mut server_params = + CertificateParams::new(vec!["localhost".to_string(), "127.0.0.1".to_string()]); + server_params.key_pair = Some(KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap()); + let server_cert = rcgen::Certificate::from_params(server_params).unwrap(); + + let mut client_params = CertificateParams::new(vec!["test-client".to_string()]); + client_params.key_pair = Some(KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap()); + let client_cert = rcgen::Certificate::from_params(client_params).unwrap(); + + TestCerts { + ca_pem: ca_cert.serialize_pem().unwrap(), + server_cert_pem: server_cert.serialize_pem_with_signer(&ca_cert).unwrap(), + server_key_pem: server_cert.serialize_private_key_pem(), + client_cert_pem: client_cert.serialize_pem_with_signer(&ca_cert).unwrap(), + client_key_pem: client_cert.serialize_private_key_pem(), + } +} + +/// Start the stub Flight server over TLS on an ephemeral port. The server stops +/// when the returned shutdown sender is dropped. +async fn start_tls_server(certs: &TestCerts) -> (SocketAddr, tokio::sync::oneshot::Sender<()>) { + start_server(certs, false).await +} + +/// Same, but the server demands a client certificate signed by the test CA. +async fn start_mtls_server(certs: &TestCerts) -> (SocketAddr, tokio::sync::oneshot::Sender<()>) { + start_server(certs, true).await +} + +async fn start_server( + certs: &TestCerts, + require_client_cert: bool, +) -> (SocketAddr, tokio::sync::oneshot::Sender<()>) { + init_crypto_provider(); + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let addr = listener.local_addr().unwrap(); + + let identity = Identity::from_pem(&certs.server_cert_pem, &certs.server_key_pem); + let mut tls = ServerTlsConfig::new().identity(identity); + if require_client_cert { + tls = tls.client_ca_root(tonic::transport::Certificate::from_pem(&certs.ca_pem)); + } + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + + tokio::spawn(async move { + Server::builder() + .tls_config(tls) + .unwrap() + .add_service(FlightServiceServer::new(StubFlightService::default())) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }) + .await + .unwrap(); + }); + + (addr, shutdown_tx) +} + +fn write_pem(dir: &tempfile::TempDir, name: &str, contents: &str) -> String { + let path = dir.path().join(name); + std::fs::write(&path, contents).unwrap(); + path.to_str().unwrap().to_string() +} + +/// Exercise argument parsing, file reading, script execution, and SQL transport. +/// The stub records SQL without executing it against a database. +async fn run_sql_cli(args: &[&str], script: Option<&str>) -> (std::process::Output, Vec) { + let queries = Arc::new(Mutex::new(Vec::new())); + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let sql_endpoint = format!("http://{}", listener.local_addr().unwrap()); + let service = StubFlightService { + queries: Some(queries.clone()), + }; + let sql_server = tokio::spawn(async move { + Server::builder() + .add_service(FlightServiceServer::new(service)) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let http_endpoint = format!("http://{}", listener.local_addr().unwrap()); + let app = + axum::Router::new().fallback(|| async { axum::Json(serde_json::json!({"tables": []})) }); + let http_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("script.sql"); + if let Some(script) = script { + std::fs::write(&path, script).unwrap(); + } + let mut config = lancedb_cli::server_config::Config::default(); + config.set_profile( + "test", + lancedb_cli::server_config::Profile { + sql_server_url: Some(sql_endpoint), + http_server_url: Some(http_endpoint), + database: Some("test".into()), + api_key: Some("test-key".into()), + ..Default::default() + }, + ); + config.set_default_profile("test"); + config + .save_to_path(&dir.path().join(".lancedb/config.toml")) + .unwrap(); + let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_lancedb")) + .args(args) + .current_dir(dir.path()) + .stdin(std::process::Stdio::null()) + .env("HOME", dir.path()) + .env("XDG_DATA_HOME", dir.path().join("data")) + .env("XDG_CONFIG_HOME", dir.path().join("config")) + .env_remove("LANCEDB_API_KEY") + .env_remove("LANCEDB_OIDC_ACCESS_TOKEN") + .env_remove("LANCEDB_OIDC_ACCESS_TOKEN_FILE") + .env_remove("LANCEDB_CA_CERT") + .env_remove("LANCEDB_CLIENT_CERT") + .env_remove("LANCEDB_CLIENT_KEY") + .output() + .await + .unwrap(); + sql_server.abort(); + http_server.abort(); + let recorded = queries.lock().unwrap().clone(); + (output, recorded) +} + +async fn run_sql_file(script: &str) -> (std::process::Output, Vec) { + run_sql_cli( + &["sql", "--file", "script.sql", "--format", "json"], + Some(script), + ) + .await +} + +#[tokio::test] +async fn no_subcommand_opens_the_sql_shell() { + for args in [vec![], vec!["sql"]] { + let (output, queries) = run_sql_cli(&args, None).await; + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("LanceDB CLI v"), "{stdout}"); + assert!( + stdout.contains("Type \\? for help or \\q to quit"), + "{stdout}" + ); + assert!(queries.is_empty()); + } +} + +#[tokio::test] +async fn sql_options_work_with_and_without_the_subcommand() { + for prefix in [vec![], vec!["sql"]] { + let mut args = prefix.clone(); + args.extend(["--command", "SELECT 42", "--format", "json"]); + let (output, queries) = run_sql_cli(&args, None).await; + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(queries, ["SELECT 42"]); + let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(value, serde_json::json!([{"answer": ANSWER}])); + + let mut args = prefix; + args.extend(["--file", "script.sql", "--format", "json"]); + let (output, queries) = run_sql_cli(&args, Some("SELECT 'semi;colon';")).await; + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(queries, ["SELECT 'semi;colon'"]); + } +} + +#[tokio::test] +async fn sql_files_preserve_comments_and_quoted_semicolons() { + for (script, expected) in [ + ( + "SHOW JOBS; CANCEL JOB 'job-123';", + vec!["SHOW JOBS", "CANCEL JOB 'job-123'"], + ), + ( + "SELECT 1 -- documentation; DELETE FROM customers\n;", + vec!["SELECT 1 -- documentation; DELETE FROM customers"], + ), + ( + "SELECT 1 /* documentation; DELETE FROM customers */; SELECT 2;", + vec![ + "SELECT 1 /* documentation; DELETE FROM customers */", + "SELECT 2", + ], + ), + ( + "/* outer; /* nested; DELETE FROM customers */ still a comment; */ SELECT 3;", + vec!["/* outer; /* nested; DELETE FROM customers */ still a comment; */ SELECT 3"], + ), + ( + "SELECT 1 /*! ; DELETE FROM customers */;", + vec!["SELECT 1 /*! ; DELETE FROM customers */"], + ), + ( + r#"SELECT 'it''s; unchanged', "col;""name", `back;``tick`; SELECT 'next'"#, + vec![ + r#"SELECT 'it''s; unchanged', "col;""name", `back;``tick`"#, + "SELECT 'next'", + ], + ), + ( + "SELECT $$text; -- still text$$, $tag$more; /* text */$tag$; SELECT 3;", + vec![ + "SELECT $$text; -- still text$$, $tag$more; /* text */$tag$", + "SELECT 3", + ], + ), + ( + r"SELECT E'it\'s; unchanged'; SELECT 2;", + vec![r"SELECT E'it\'s; unchanged'", "SELECT 2"], + ), + ( + "SELECT 'text; -- still a string /* not a comment */'; SELECT 2;", + vec![ + "SELECT 'text; -- still a string /* not a comment */'", + "SELECT 2", + ], + ), + ( + "SELECT 'café; 🦀';\r\n-- comment; DELETE FROM customers\r\nSELECT 2; ;", + vec![ + "SELECT 'café; 🦀'", + "-- comment; DELETE FROM customers\r\nSELECT 2", + ], + ), + ( + "; -- documentation; DELETE FROM customers\n; /* comment; SELECT 2 */; ;", + vec![], + ), + ] { + let (output, queries) = run_sql_file(script).await; + assert!( + output.status.success(), + "script {script:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(queries, expected, "script: {script:?}"); + } +} + +#[tokio::test] +async fn sql_files_with_unterminated_tokens_submit_no_statements() { + for script in [ + "SELECT 1; SELECT 'unterminated; DELETE FROM customers", + "SELECT 1; SELECT \"unterminated; DELETE FROM customers", + "SELECT 1; SELECT `unterminated; DELETE FROM customers", + "SELECT 1; SELECT $tag$unterminated; DELETE FROM customers", + "SELECT 1; /* unterminated; DELETE FROM customers", + ] { + let (output, queries) = run_sql_file(script).await; + assert!(!output.status.success(), "script: {script:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Failed to tokenize SQL script"), + "unexpected error: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + queries.is_empty(), + "submitted SQL for {script:?}: {queries:?}" + ); + } +} + +#[tokio::test] +async fn ca_cert_enables_a_tls_flight_sql_query() { + let certs = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let ca_path = write_pem(&dir, "ca.pem", &certs.ca_pem); + let (addr, _shutdown) = start_tls_server(&certs).await; + + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(ca_path), + ..TlsOptions::default() + }); + + executor + .connect(&format!("https://{addr}")) + .await + .expect("TLS connect with the signing CA should succeed"); + assert!(executor.is_connected().await); + + let result = executor + .execute_query("SELECT 1") + .await + .expect("query over TLS should succeed"); + match result { + SqlResult::Query(batches) => { + let rows: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + assert_eq!(rows, vec![ANSWER]); + } + other => panic!("expected a query result, got {other:?}"), + } +} + +#[tokio::test] +async fn tls_connect_fails_without_the_signing_ca() { + let certs = generate_certs(); + let (addr, _shutdown) = start_tls_server(&certs).await; + + // No CA configured: the server's certificate chains to a CA that is not in + // the platform trust store, so verification must reject it. + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()); + + assert!( + executor.connect(&format!("https://{addr}")).await.is_err(), + "an untrusted server certificate must not be accepted" + ); + assert!(!executor.is_connected().await); +} + +#[tokio::test] +async fn tls_connect_fails_with_an_unrelated_ca() { + let certs = generate_certs(); + // A second, unrelated CA: right file shape, wrong signer. + let other = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let unrelated_ca = write_pem(&dir, "other-ca.pem", &other.ca_pem); + let (addr, _shutdown) = start_tls_server(&certs).await; + + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(unrelated_ca), + ..TlsOptions::default() + }); + + assert!( + executor.connect(&format!("https://{addr}")).await.is_err(), + "a certificate signed by a different CA must not be accepted" + ); +} + +#[tokio::test] +async fn a_missing_ca_cert_file_is_reported() { + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some("/nonexistent/ca.pem".to_string()), + ..TlsOptions::default() + }); + + let err = executor + .connect("https://127.0.0.1:1") + .await + .expect_err("a missing CA file must fail loudly"); + assert!( + err.to_string().contains("/nonexistent/ca.pem"), + "error should name the missing file, got: {err}" + ); +} + +#[tokio::test] +async fn a_client_certificate_satisfies_an_mtls_server() { + let certs = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let ca_path = write_pem(&dir, "ca.pem", &certs.ca_pem); + let cert_path = write_pem(&dir, "client.pem", &certs.client_cert_pem); + let key_path = write_pem(&dir, "client-key.pem", &certs.client_key_pem); + let (addr, _shutdown) = start_mtls_server(&certs).await; + + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(ca_path), + client_cert: Some(cert_path), + client_key: Some(key_path), + }); + + executor + .connect(&format!("https://{addr}")) + .await + .expect("mTLS connect with a CA-signed client certificate should succeed"); + executor + .execute_query("SELECT 1") + .await + .expect("query over mTLS should succeed"); +} + +#[tokio::test] +async fn an_mtls_server_rejects_a_client_with_no_certificate() { + let certs = generate_certs(); + let dir = tempfile::tempdir().unwrap(); + let ca_path = write_pem(&dir, "ca.pem", &certs.ca_pem); + let (addr, _shutdown) = start_mtls_server(&certs).await; + + // Trusts the server, but presents no identity of its own. + let mut executor = FlightSqlExecutor::new_with_api_key(String::new(), "sk_test".to_string()) + .with_tls(TlsOptions { + ca_cert: Some(ca_path), + ..TlsOptions::default() + }); + + // TLS 1.3 sends the client certificate after the client considers the + // handshake done, so the rejection can surface at connect or at the first + // request. Either way the exchange must not succeed. + let rejected = match executor.connect(&format!("https://{addr}")).await { + Err(_) => true, + Ok(()) => executor.execute_query("SELECT 1").await.is_err(), + }; + assert!( + rejected, + "an mTLS server must reject a client with no certificate" + ); +} + +#[tokio::test] +async fn a_client_certificate_without_its_key_is_rejected_at_resolve() { + use lancedb_cli::server_config::ConnectionArgs; + + let args = ConnectionArgs { + client_cert: Some("/tmp/client.pem".to_string()), + ..ConnectionArgs::default() + }; + let err = args + .resolve(None) + .expect_err("a client certificate without a key must be rejected"); + assert!( + err.to_string().contains("--client-key"), + "error should name the missing flag, got: {err}" + ); +} diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 065eb3084..20bb0b360 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -528,6 +528,12 @@ impl Connection { ExecuteQueryAsyncBuilder::new(self.internal.clone(), query.into()) } + /// Establish the remote SQL transport without executing a statement. + /// This checks connectivity and TLS; authentication is checked by subsequent requests. + pub async fn check_sql_connection(&self) -> Result<()> { + self.internal.check_sql_connection().await + } + /// Describe a submitted SQL query by its connection-scoped id. /// /// This performs one bounded status poll using state retained by this diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 939861b88..54d51c24f 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -579,6 +579,12 @@ pub trait Database: async fn resume_job(&self, _job_id: &str) -> Result { job_op_not_supported("resume_job") } + /// Establish the SQL transport without executing a statement. + async fn check_sql_connection(&self) -> Result<()> { + Err(crate::Error::NotSupported { + message: "SQL is not supported by this database".into(), + }) + } /// Start executing a SQL statement on a LanceDB Distributed database. async fn execute_query_async( &self, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 5c27587dc..0e88a7432 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -92,6 +92,7 @@ impl TerminalResult { } } + #[cfg(feature = "remote")] pub(crate) fn remote(value: Option, request_id: String) -> Self { Self { value, @@ -242,6 +243,7 @@ impl Job<()> { /// A handle whose record the caller has already fetched, so the detail /// accessors answer without a second round trip. + #[cfg(feature = "remote")] pub(crate) fn opened(handle: Box, description: JobDescription) -> Self { let job = Self::new(handle); { diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 4f97c16e8..5c85d0792 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1357,6 +1357,16 @@ impl Database for RemoteDatabase { }) } + async fn check_sql_connection(&self) -> Result<()> { + self.sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".into(), + })? + .check_connection() + .await + } + async fn execute_query_async(&self, request: ExecuteQueryRequest) -> Result { let client = self .sql_client diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 207a0cbec..880f61045 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -170,6 +170,13 @@ impl std::fmt::Debug for SqlClient { } impl SqlClient { + pub(super) async fn check_connection(&self) -> Result<()> { + self.inner + .connection(&Uuid::new_v4().to_string()) + .await + .map(|_| ()) + } + pub(super) fn new( database: String, database_prefix: Option, @@ -1428,7 +1435,18 @@ async fn connect_channel( tokio::time::timeout(connect_timeout, endpoint.connect()) .await .map_err(|_| sql_error(request_id, "SQL connection timed out"))? - .map_err(|err| sql_error(request_id, err)) + .map_err(|err| { + // tonic's Display only says "transport error"; preserve the source chain + // so callers can distinguish DNS, refused connections, and TLS failures. + let mut message = err.to_string(); + let mut source = std::error::Error::source(&err); + while let Some(error) = source { + message.push_str(": "); + message.push_str(&error.to_string()); + source = error.source(); + } + sql_error(request_id, message) + }) } fn tls_config(config: Option<&TlsConfig>) -> Result { From 03c7d1f199af35972f9fbfba52ef907cede33b0b Mon Sep 17 00:00:00 2001 From: alexcastgonz <82875882+pcbeingused333@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:03:32 -0400 Subject: [PATCH 179/180] fix(python): add the missing f prefix to the permutation split error (#4709) --- python/python/lancedb/permutation.py | 2 +- python/python/tests/test_permutation.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 0788cb5cb..b70c96979 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -641,7 +641,7 @@ class Permutation: if split is not None: if permutation_table is None: raise ValueError( - "Cannot create a permutation on split `{split}`" + f"Cannot create a permutation on split `{split}`" " because no permutation table is provided" ) if isinstance(split, str): diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 50ca53061..bc5c1649c 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -1404,3 +1404,10 @@ def test_permutation_over_remote_table(): ] assert_server_safe_row_id_requests(server) + + +def test_from_tables_split_without_permutation_table(mem_db): + tbl = mem_db.create_table("test_table", pa.table({"id": range(10)})) + + with pytest.raises(ValueError, match="permutation on split `train` because no"): + Permutation.from_tables(tbl, split="train") From d5013459eb4c7beb84d80bc2c26720d58f347611 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Thu, 29 Oct 2026 14:14:09 -0700 Subject: [PATCH 180/180] chore: update lance dependency to v15.0.0-beta.6 (#4742) Updates Rust and Java Lance dependencies to [v15.0.0-beta.6](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.6), pins Python tests to published pylance 15.0.0b6, and refreshes both lockfiles. Aligns Arrow 59, DataFusion 55, and PyO3 0.29; adapts execution plans and MemWAL directory handling, updates the ABI metadata test, and removes the obsolete Lance Arrow patch now fixed upstream. Validation: workspace clippy with all features/tests and warnings denied, cargo fmt, Python/CI Ruff checks, uv lock check, 16 CI-script tests, and targeted Python regressions (54 passed, 28 skipped); repository-wide Ruff retains existing documentation-example failures, and the upstream macOS wheel build failed while Linux and Windows wheels are published. --------- Co-authored-by: Daniel Rammer Co-authored-by: Claude Opus 5.5 --- .github/workflows/rust.yml | 2 +- Cargo.lock | 2666 +++++++++-------- Cargo.toml | 74 +- java/pom.xml | 2 +- nodejs/__test__/table.test.ts | 3 +- python/Cargo.toml | 8 +- python/pyproject.toml | 2 +- python/python/lancedb/table.py | 3 +- python/python/tests/test_fts.py | 2 +- python/python/tests/test_package_metadata.py | 6 +- python/python/tests/test_table.py | 1 + python/uv.lock | 14 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- rust/lancedb/src/materialized_view/refresh.rs | 2 + rust/lancedb/src/query.rs | 10 + rust/lancedb/src/remote/table/insert.rs | 20 + rust/lancedb/src/table.rs | 4 +- rust/lancedb/src/table/computed_columns.rs | 8 +- rust/lancedb/src/table/datafusion.rs | 35 +- rust/lancedb/src/table/datafusion/insert.rs | 10 + .../src/table/datafusion/scannable_exec.rs | 10 + .../table/datafusion/udtf/duplicate_pairs.rs | 10 + .../src/table/datafusion/udtf/vector_query.rs | 10 + rust/lancedb/src/table/merge.rs | 161 +- rust/lancedb/src/table/merge/lsm.rs | 134 +- rust/lancedb/src/table/query.rs | 4 +- rust/lancedb/src/table/query/lsm.rs | 67 +- rust/lancedb/src/table/refresh.rs | 7 +- 29 files changed, 1913 insertions(+), 1366 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 9b24a1f77..f65123f78 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -381,7 +381,7 @@ jobs: runs-on: ubuntu-24.04 strategy: matrix: - msrv: ["1.94.0"] # This should match up with rust-version in Cargo.toml + msrv: ["1.95.0"] # This should match up with rust-version in Cargo.toml env: # Need up-to-date compilers for kernels CC: clang-18 diff --git a/Cargo.lock b/Cargo.lock index a58fa195a..bf7b12213 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,7 +23,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "cipher", "cpufeatures 0.2.17", ] @@ -34,7 +34,7 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "const-random", "getrandom 0.3.4", "once_cell", @@ -44,9 +44,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.5" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" dependencies = [ "memchr", ] @@ -68,9 +68,9 @@ checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" [[package]] name = "alloc-stdlib" -version = "0.2.4" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" dependencies = [ "alloc-no-stdlib", ] @@ -92,9 +92,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "android_system_properties" -version = "0.1.6" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" dependencies = [ "libc", ] @@ -172,11 +172,11 @@ dependencies = [ [[package]] name = "ar_archive_writer" -version = "0.5.3" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" +checksum = "7eb93bbb63b9c227414f6eb3a0adfddca591a8ce1e9b60661bb08969b87e340b" dependencies = [ - "object 0.39.1", + "object", ] [[package]] @@ -197,6 +197,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "argminmax" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "088a9c28ca36500c581f9f54b63460492d2b4f71e1e61d176e8fb79565109b01" +dependencies = [ + "num-traits", +] + [[package]] name = "array-init-cursor" version = "0.2.1" @@ -211,15 +220,15 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.8" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "arrow" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cfdd0833e32a9874d2b55089333ad310c0be208aafa277385ce2461dec90be3" +checksum = "3f04e0a89cc175eaf3740282537851e6fd9d7276f97730b9d0ea2859c11a85df" dependencies = [ "arrow-arith", "arrow-array", @@ -239,9 +248,9 @@ dependencies = [ [[package]] name = "arrow-arith" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a41203398f0eaa6f7ec8e62c0da742a21abf282c148fc157f6c35c90e29981a" +checksum = "157943c720919e8f5b6731407ce5cd4c9a5ef47a75bf10edaf24b7081b5763ef" dependencies = [ "arrow-array", "arrow-buffer", @@ -253,9 +262,9 @@ dependencies = [ [[package]] name = "arrow-array" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae33dad492b7df00a217563a7b0ef2874df68a0deea1b1a3acf628152f7f7a69" +checksum = "72b5b1682924f11ecf6929689c16cbc69efbb6dd141b06ad98ee1cb10d858c43" dependencies = [ "ahash", "arrow-buffer", @@ -265,6 +274,7 @@ dependencies = [ "chrono-tz 0.10.4", "half", "hashbrown 0.17.1", + "libc", "num-complex", "num-integer", "num-traits", @@ -272,21 +282,21 @@ dependencies = [ [[package]] name = "arrow-buffer" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9552f96391c005e6ab449fa941420935e7e062489b12b8b1b08879b2163f5b5" +checksum = "b5d687afc6c927965a8a759f3b68de91933d9dfa2e1bb6e156bac84b85665e92" dependencies = [ "bytes", "half", - "num-bigint", + "num-bigint 0.5.1", "num-traits", ] [[package]] name = "arrow-cast" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a8a327c9649f30d8406995f27642b68df354713cca3baaaf100f076f18d5f34" +checksum = "3f23c3379feede42135ef27ca60e67f6e643cd4343ae74e4c8b16c83f55afd85" dependencies = [ "arrow-array", "arrow-buffer", @@ -295,7 +305,7 @@ dependencies = [ "arrow-schema", "arrow-select", "atoi", - "base64 0.22.1", + "base64 0.23.1", "chrono", "comfy-table", "half", @@ -306,9 +316,9 @@ dependencies = [ [[package]] name = "arrow-csv" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af0dd6d90d1955e9f9a014c1e563ee8aeffc21909085d25623e1da44d96eca26" +checksum = "85b1984628b091b8319b3c305fce21d04f9e9b2578bb733b0d0108462ae1d698" dependencies = [ "arrow-array", "arrow-cast", @@ -321,9 +331,9 @@ dependencies = [ [[package]] name = "arrow-data" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b24852db04738907e06c04ea61e42fe7fda962a34513022dc0d0e754fb7976b" +checksum = "bb0a031c7ff5e2bdb443117054fb466af1d4df5b7f0ecbe197713dc8b113b1ba" dependencies = [ "arrow-buffer", "arrow-schema", @@ -334,9 +344,9 @@ dependencies = [ [[package]] name = "arrow-flight" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2dbe34824c639e43136af8f106992792ab456540d54b880bc320a3192502d2e" +checksum = "43f998a8cc9ffdc37731b66c0414dccf4f4f11a03d9136d383ef10f95181cd7d" dependencies = [ "arrow-arith", "arrow-array", @@ -349,11 +359,10 @@ dependencies = [ "arrow-schema", "arrow-select", "arrow-string", - "base64 0.22.1", + "base64 0.23.1", "bytes", "futures", "once_cell", - "paste", "prost", "prost-types", "tonic", @@ -362,9 +371,9 @@ dependencies = [ [[package]] name = "arrow-ipc" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29a908a11fcfb3fb2f6730f4ac15e367bc644e419155e96238f68cf3adde572b" +checksum = "f5dd1afadda2eb821aaf851bb4c0adef60c30cc0f1a29bd02fb99dd07fb9f58d" dependencies = [ "arrow-array", "arrow-buffer", @@ -372,15 +381,15 @@ dependencies = [ "arrow-schema", "arrow-select", "flatbuffers", - "lz4_flex", + "lz4_flex 0.14.0", "zstd 0.13.3", ] [[package]] name = "arrow-json" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a96aed3931c076adee39ec2a40d8219fc7f09e79bcdaca1df16272993e1e14" +checksum = "e2bc4d56a0dad84cc51c5812ccff48b642047a1f3be80349cd84318983e79edb" dependencies = [ "arrow-array", "arrow-buffer", @@ -390,7 +399,7 @@ dependencies = [ "arrow-select", "chrono", "half", - "indexmap 2.14.2", + "indexmap 2.14.0", "itoa", "lexical-core", "memchr", @@ -403,9 +412,9 @@ dependencies = [ [[package]] name = "arrow-ord" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63a083ec750f5c043f02946b4baf05fcdbb55f4560a3277055caca5cc99f3eb0" +checksum = "561b8209faa2cd489764b7fd07d7cb9e8d274d78048c38de59f77c41140cb834" dependencies = [ "arrow-array", "arrow-buffer", @@ -416,9 +425,9 @@ dependencies = [ [[package]] name = "arrow-pyarrow" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ffb9be5a873590f825aef50df20e0f8dff5fd42a77058e28bbe7bd44bb53dec" +checksum = "ba037102b3f52163f96db970209ada931c2a6f46c4607d3170950d075db68773" dependencies = [ "arrow-array", "arrow-data", @@ -428,9 +437,9 @@ dependencies = [ [[package]] name = "arrow-row" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "514ba0ef0d4c5896202dae736251ce415abb43a950bed570fb7981b8716c0e4c" +checksum = "0d8c68b87a569f92b90c46cb0a09d86bd9609ddc9b1bf1fc5a503c8c6907c14e" dependencies = [ "arrow-array", "arrow-buffer", @@ -441,20 +450,20 @@ dependencies = [ [[package]] name = "arrow-schema" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21ca356ad6425cecb6eb7b28e4f659f1ee7880fbb1a16127de7dd62901efee9e" +checksum = "e87acb0c6bf6237fca7a50d7b51e801c98a18a5fe6f3bb34f7d77b85ca165388" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "serde_core", "serde_json", ] [[package]] name = "arrow-select" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c58da39eb3d8350ad4a549e5c2bc49284dac554016c69829310350f1731b0aad" +checksum = "c844141958d805b47d1208e0d12aac53fcf388ce8011639fe82aa492adde0bb4" dependencies = [ "ahash", "arrow-array", @@ -466,9 +475,9 @@ dependencies = [ [[package]] name = "arrow-string" -version = "58.4.0" +version = "59.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6789b388467525e3271326b6b4915666ecfdf5142aef09779445c954b67543c" +checksum = "bc130892b1a9552da77971924b390e06cf375d1f7e4344a7b7b40ca4426fa470" dependencies = [ "arrow-array", "arrow-buffer", @@ -495,9 +504,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.51" +version = "0.4.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970" +checksum = "e79b3f8a79cccc2898f31920fc69f304859b3bd567490f75ebf51ae1c792a9ac" dependencies = [ "compression-codecs", "compression-core", @@ -537,7 +546,7 @@ dependencies = [ "bytes", "derive_builder", "futures", - "rand 0.8.8", + "rand 0.8.6", "reqwest 0.12.28", "reqwest-eventsource", "secrecy", @@ -552,13 +561,13 @@ dependencies = [ [[package]] name = "async-recursion" -version = "1.2.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -569,7 +578,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.3", ] [[package]] @@ -583,12 +592,9 @@ dependencies = [ [[package]] name = "asyncband" -version = "0.7.4" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d2050892d4691cf110586070786712b504985a4d37ed64a9cd8a402718e1706" -dependencies = [ - "hashbrown 0.17.1", -] +checksum = "f2d85fd3d291fabcc40c7232c92c280ec1754fd7b5d7ea769f143222143e179a" [[package]] name = "atoi" @@ -613,15 +619,15 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.5.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-config" -version = "1.12.0" +version = "1.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8d7b388a9fc3a6db15a5ec778c38b354eff1364882c94d08e0252f7a47dcaa4" +checksum = "50f156acdd2cf55f5aa53ee416c4ac851cf1222694506c0b1f78c85695e9ca9d" dependencies = [ "aws-credential-types", "aws-runtime", @@ -633,14 +639,13 @@ dependencies = [ "aws-smithy-json", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", "hex", "http 1.5.0", - "sha1 0.10.7", + "sha1 0.10.6", "time", "tokio", "tracing", @@ -650,9 +655,9 @@ dependencies = [ [[package]] name = "aws-credential-types" -version = "1.3.0" +version = "1.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93964ffdaf57857f544be3666a5f57570bb699e934700f11b49708f61bb556e" +checksum = "8f20799b373a1be121fe3005fba0c2090af9411573878f224df44b42727fcaf7" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", @@ -686,9 +691,9 @@ dependencies = [ [[package]] name = "aws-runtime" -version = "1.9.4" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25b43ad47adc2517efe3d706559d94b97e50e80e0321b3cadbc9f77cee88adcd" +checksum = "5dcd93c82209ac7413532388067dce79be5a8780c1786e5fae3df22e4dee2864" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -714,11 +719,10 @@ dependencies = [ [[package]] name = "aws-sdk-bedrockruntime" -version = "1.145.0" +version = "1.130.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aed4de4a98241f9dd95ddad4223755b7afc3327d0a148a2a29286c95ef64db5e" +checksum = "3e2f7bca252e3c5c8f0ed12c5501bf8b0fbadb937cd9fdd71a0ebd9d7526540f" dependencies = [ - "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -729,7 +733,6 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -743,11 +746,10 @@ dependencies = [ [[package]] name = "aws-sdk-dynamodb" -version = "1.126.0" +version = "1.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84916ddc26951545be16e11fe45277e2d2561b9d0f2d0538274fb750c09b3eae" +checksum = "fc418346e3cb248c7d59e642acbcb06488b7c7cd2ba6ebc79e8003f618c60099" dependencies = [ - "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -756,7 +758,6 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -765,16 +766,14 @@ dependencies = [ "http 1.5.0", "regex-lite", "tracing", - "url", ] [[package]] name = "aws-sdk-kms" -version = "1.120.0" +version = "1.106.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6b0fe38fee2ba5b6cd24d32d08365b314ae1adea123649e061a7eb6300b6f5b" +checksum = "2336350f96efcf9c2552b7fdb4dd07a0c1fef11f22b28fb020a9e33e7925cf9d" dependencies = [ - "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -783,7 +782,6 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -796,11 +794,10 @@ dependencies = [ [[package]] name = "aws-sdk-s3" -version = "1.148.0" +version = "1.132.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a61c1db3987ab6c8740fb87f248864687d50549401115244a84f02c3047b2d5" +checksum = "5575840a3a6b11f6011463ebe359320dfe5b67babb5e9b06fed6ddf809a9ab40" dependencies = [ - "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -812,7 +809,6 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", @@ -823,21 +819,20 @@ dependencies = [ "http 0.2.12", "http 1.5.0", "http-body 1.1.0", - "lru 0.18.5", + "lru", "percent-encoding", "regex-lite", - "sha2 0.11.1", + "sha2 0.11.0", "tracing", "url", ] [[package]] name = "aws-sdk-sso" -version = "1.111.0" +version = "1.98.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65700d75f6da78c89a61a49f1539979400a4609d3329376b1dc2133d7a1b2b90" +checksum = "d69c77aafa20460c68b6b3213c84f6423b6e76dbf89accd3e1789a686ffd9489" dependencies = [ - "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -846,7 +841,6 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -859,11 +853,10 @@ dependencies = [ [[package]] name = "aws-sdk-ssooidc" -version = "1.113.0" +version = "1.100.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb1147c254af7b6cee3ace90ae7da6f21366ce9a9b899035fa8a0fdf586eb75a" +checksum = "1c7e7b09346d5ca22a2a08267555843a6a0127fb20d8964cb6ecfb8fdb190225" dependencies = [ - "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -872,7 +865,6 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", @@ -885,11 +877,10 @@ dependencies = [ [[package]] name = "aws-sdk-sts" -version = "1.116.0" +version = "1.103.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "035c7392e751d20bf1060d625d023587eb14099646110a9cff7c697bfe4b253a" +checksum = "c2249b81a2e73a8027c41c378463a81ec39b8510f184f2caab87de912af0f49b" dependencies = [ - "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -899,7 +890,6 @@ dependencies = [ "aws-smithy-query", "aws-smithy-runtime", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", @@ -912,9 +902,9 @@ dependencies = [ [[package]] name = "aws-sigv4" -version = "1.5.3" +version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31d955e76ff96acd555bf06fa0fa6d5bf9335fa84ae7c64481b20ae61d231f70" +checksum = "68dc0b907359b120170613b5c09ccc61304eac3998ff6274b97d93ee6490115a" dependencies = [ "aws-credential-types", "aws-smithy-eventstream", @@ -922,7 +912,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "bytes", - "crypto-bigint", + "crypto-bigint 0.5.5", "form_urlencoded", "hex", "hmac 0.13.0", @@ -930,7 +920,8 @@ dependencies = [ "http 1.5.0", "p256", "percent-encoding", - "sha2 0.11.1", + "ring", + "sha2 0.11.0", "subtle", "time", "tracing", @@ -939,9 +930,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "1.3.1" +version = "1.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" +checksum = "2ffcaf626bdda484571968400c326a244598634dc75fd451325a54ad1a59acfc" dependencies = [ "futures-util", "pin-project-lite", @@ -950,9 +941,9 @@ dependencies = [ [[package]] name = "aws-smithy-checksums" -version = "0.65.0" +version = "0.64.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67ecd999972b58e67cab052f5129906c08c25883bd0788ceefc55ef97d61307" +checksum = "10efbbcec1e044b81600e2fc562a391951d291152d95b482d5b7e7132299d762" dependencies = [ "aws-smithy-http", "aws-smithy-types", @@ -965,15 +956,15 @@ dependencies = [ "md-5", "pin-project-lite", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.0", "tracing", ] [[package]] name = "aws-smithy-eventstream" -version = "0.61.4" +version = "0.60.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80c2051c2f1016fb8e6548dd07b8bc2ac9c3fe583721444b92f515e856d31609" +checksum = "faf09d74e5e32f76b8762da505a3cd59303e367a664ca67295387baa8c1d7548" dependencies = [ "aws-smithy-types", "bytes", @@ -982,9 +973,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.64.0" +version = "0.63.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37843d9add67c3aff5856f409c6dc315d3cdff60f9c0cb5b670dab1e9920306d" +checksum = "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231" dependencies = [ "aws-smithy-eventstream", "aws-smithy-runtime-api", @@ -1004,9 +995,9 @@ dependencies = [ [[package]] name = "aws-smithy-http-client" -version = "1.4.2" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd25384a4e437aa8d8f339afad4b69e786b936a7cb10db668a7aaf66717b1a8" +checksum = "5c3ef8931ad1c98aa6a55b4256f847f3116090819844e0dd41ea682cac5dd2d3" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", @@ -1028,9 +1019,9 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.63.1" +version = "0.62.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3385d469edbe8b60cc72002784652b5efca39178192aa9cc4b44c9875c6bdc18" +checksum = "701a947f4797e52a911e114a898667c746c39feea467bbd1abd7b3721f702ffa" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-schema", @@ -1039,31 +1030,28 @@ dependencies = [ [[package]] name = "aws-smithy-observability" -version = "0.3.0" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c" +checksum = "a06c2315d173edbf1920da8ba3a7189695827002e4c0fc961973ab1c54abca9c" dependencies = [ "aws-smithy-runtime-api", ] [[package]] name = "aws-smithy-query" -version = "0.62.1" +version = "0.60.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1d1d71f6562be974caa85442ecd90194c40fdb5df045f182a6c2e872ce95056" +checksum = "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd" dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", - "aws-smithy-xml", "urlencoding", ] [[package]] name = "aws-smithy-runtime" -version = "1.14.2" +version = "1.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3296253d3a91b3f938a3f2bcce4daebadcb4aa4228153fcec90f9d23532b4484" +checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -1087,9 +1075,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api" -version = "1.16.2" +version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d881a7b7ad179fd6611680c9de89f716fb00ab40299a9a7b8c6913e8f7511a8" +checksum = "9db177daa6ba8afb9ee1aefcf548c907abcf52065e394ee11a92780057fe0e8c" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", @@ -1105,20 +1093,20 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api-macros" -version = "1.1.0" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "221eaa237ddf1ca79b60d1372aad77e47f9c0ea5b3ce5099da8c61d027dc77b3" +checksum = "8d7396fd9500589e62e460e987ecb671bad374934e55ec3b5f498cc7a8a8a7b7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "aws-smithy-schema" -version = "0.2.1" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8f395d93304280b64b7632fea798d177e74897fe7f063416ce627cd6fa24829" +checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", @@ -1153,26 +1141,22 @@ dependencies = [ [[package]] name = "aws-smithy-xml" -version = "0.62.1" +version = "0.60.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b932c8d6dc127fc980eecd78f8694ae9b9551b69a93a7def2a199c1c0033daf" +checksum = "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3" dependencies = [ - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", "xmlparser", ] [[package]] name = "aws-types" -version = "1.6.0" +version = "1.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "209f3a6d82a6e9e5f94abbed94c7a26e1c052341002bf57a5fb5481f625896fc" +checksum = "2f4bbcaa9304ea40902d3d5f42a0428d1bd895a2b0f6999436fb279ffddc58ac" dependencies = [ "aws-credential-types", "aws-smithy-async", "aws-smithy-runtime-api", - "aws-smithy-schema", "aws-smithy-types", "rustc_version", "tracing", @@ -1295,7 +1279,7 @@ dependencies = [ "getrandom 0.2.17", "instant", "pin-project-lite", - "rand 0.8.8", + "rand 0.8.6", "tokio", ] @@ -1317,19 +1301,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" dependencies = [ "addr2line", - "cfg-if", + "cfg-if 1.0.4", "libc", - "miniz_oxide 0.8.9", - "object 0.37.3", + "miniz_oxide", + "object", "rustc-demangle", "windows-link", ] [[package]] name = "base16ct" -version = "0.2.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" [[package]] name = "base64" @@ -1373,13 +1357,13 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bigdecimal" -version = "0.4.11" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653" +checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695" dependencies = [ "autocfg", "libm", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", ] @@ -1407,15 +1391,15 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.13.2" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" [[package]] name = "bitvec" -version = "1.1.1" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" dependencies = [ "funty", "radium", @@ -1434,15 +1418,16 @@ dependencies = [ [[package]] name = "blake3" -version = "1.8.7" +version = "1.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce" dependencies = [ + "arrayref", "arrayvec", "cc", - "cfg-if", + "cfg-if 1.0.4", "constant_time_eq", - "cpufeatures 0.3.1", + "cpufeatures 0.3.0", ] [[package]] @@ -1456,9 +1441,9 @@ dependencies = [ [[package]] name = "block-buffer" -version = "0.12.1" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be" dependencies = [ "hybrid-array", ] @@ -1504,26 +1489,26 @@ dependencies = [ [[package]] name = "bstr" -version = "1.13.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" dependencies = [ "memchr", "regex-automata", - "serde_core", + "serde", ] [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" [[package]] name = "bytecheck" -version = "0.8.3" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26333eeac754f0ad8a6bcd0eb0ac012156302e4e16b852b72ee399aea4f12c29" +checksum = "0caa33a2c0edca0419d15ac723dff03f1956f7978329b1e3b5fdaaaed9d3ca8b" dependencies = [ "bytecheck_derive", "ptr_meta", @@ -1533,13 +1518,13 @@ dependencies = [ [[package]] name = "bytecheck_derive" -version = "0.8.3" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46d07918caa9eeaaf06b7873925c53a61daac173539b4f7715090745e44e4e69" +checksum = "89385e82b5d1821d2219e0b095efa2cc1f246cbf99080f3be46a1a85c0d392d9" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -1559,13 +1544,13 @@ dependencies = [ [[package]] name = "bytemuck_derive" -version = "1.12.1" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -1601,14 +1586,14 @@ dependencies = [ "gemm", "half", "libm", - "memmap2 0.9.12", + "memmap2 0.9.10", "num-traits", "num_cpus", "rand 0.9.5", "rand_distr 0.5.1", "rayon", "safetensors", - "thiserror 2.0.21", + "thiserror 2.0.18", "yoke", "zip", ] @@ -1626,7 +1611,7 @@ dependencies = [ "rayon", "safetensors", "serde", - "thiserror 2.0.21", + "thiserror 2.0.18", ] [[package]] @@ -1665,9 +1650,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.10.0" +version = "1.2.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" dependencies = [ "find-msvc-tools", "jobserver", @@ -1686,9 +1671,15 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.5" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" @@ -1698,9 +1689,9 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" [[package]] name = "cfg_aliases" -version = "0.2.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chacha20" @@ -1708,8 +1699,8 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", + "cfg-if 1.0.4", + "cpufeatures 0.3.0", "rand_core 0.10.1", ] @@ -1798,9 +1789,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.7" +version = "4.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" dependencies = [ "clap_builder", "clap_derive", @@ -1808,9 +1799,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.7" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" dependencies = [ "anstream", "anstyle", @@ -1820,21 +1811,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.7" +version = "4.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] name = "clap_lex" -version = "1.1.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" [[package]] name = "clipboard-win" @@ -1877,9 +1868,9 @@ dependencies = [ [[package]] name = "combine" -version = "4.6.9" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" dependencies = [ "bytes", "memchr", @@ -1898,9 +1889,9 @@ dependencies = [ [[package]] name = "compression-codecs" -version = "0.4.46" +version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe" +checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf" dependencies = [ "compression-core", "flate2", @@ -1909,9 +1900,9 @@ dependencies = [ [[package]] name = "compression-core" -version = "0.4.34" +version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" +checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" [[package]] name = "concurrent-queue" @@ -1975,9 +1966,9 @@ checksum = "18f12cc9948ed9604230cdddc7c86e270f9401ccbe3c2e98a4378c5e7632212f" [[package]] name = "const_panic" -version = "0.2.17" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9603f79528ece8163c496f8932121cb36cfe46259e9c907bb3d8205139d7caa3" +checksum = "e262cdaac42494e3ae34c43969f9cdeb7da178bdb4b66fa6a1ea2edb4c8ae652" dependencies = [ "typewit", ] @@ -2023,12 +2014,6 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - [[package]] name = "countio" version = "0.3.0" @@ -2044,7 +2029,7 @@ version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", ] [[package]] @@ -2058,30 +2043,47 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.3.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" dependencies = [ "libc", ] [[package]] -name = "crc-fast" -version = "1.10.0" +name = "crc" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5" +checksum = "9710d3b3739c2e349eb44fe848ad0b7c8cb1e42bd87ee49371df2f7acaf3e675" dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crc-fast" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fd92aca2c6001b1bf5ba0ff84ee74ec8501b52bbef0cac80bf25a6c1d87a83d" +dependencies = [ + "crc", "digest 0.10.7", + "rustversion", "spin 0.10.1", ] [[package]] name = "crc32fast" -version = "1.5.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", ] [[package]] @@ -2122,18 +2124,18 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.17" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.8" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -2141,18 +2143,18 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.21" +version = "0.9.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-queue" -version = "0.3.14" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" dependencies = [ "crossbeam-utils", ] @@ -2169,9 +2171,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.23" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crossterm" @@ -2179,11 +2181,11 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "crossterm_winapi", "document-features", "parking_lot", - "rustix 1.1.5", + "rustix 1.1.4", "winapi", ] @@ -2204,9 +2206,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-bigint" -version = "0.5.5" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" dependencies = [ "generic-array", "rand_core 0.6.4", @@ -2214,6 +2216,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -2226,9 +2238,9 @@ dependencies = [ [[package]] name = "crypto-common" -version = "0.2.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ "hybrid-array", ] @@ -2256,9 +2268,9 @@ dependencies = [ [[package]] name = "ctor" -version = "1.0.13" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +checksum = "2d83cb7e7a873830708d6b02a78cd36a592c6fa14bf267b68725103b85c0d77f" dependencies = [ "link-section", "linktime-proc-macro", @@ -2266,9 +2278,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.6" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" +checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" dependencies = [ "cmov", ] @@ -2310,7 +2322,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -2323,7 +2335,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.9", + "syn 3.0.3", ] [[package]] @@ -2334,7 +2346,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core 0.20.11", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -2345,7 +2357,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core 0.24.1", "quote", - "syn 3.0.9", + "syn 3.0.3", ] [[package]] @@ -2354,7 +2366,7 @@ version = "6.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "crossbeam-utils", "hashbrown 0.14.5", "lock_api", @@ -2364,9 +2376,9 @@ dependencies = [ [[package]] name = "datafusion" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "754ef4e8f073922a26f5b23133b9db4829342362b09be0bc94309cf261c2f098" +checksum = "4cd5317db77ba6bca25c761a8091b9d294a9f4188e4f9dcd0243e6a57de862ac" dependencies = [ "arrow", "arrow-schema", @@ -2397,8 +2409,8 @@ dependencies = [ "datafusion-session", "datafusion-sql", "futures", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", "parking_lot", @@ -2411,9 +2423,9 @@ dependencies = [ [[package]] name = "datafusion-catalog" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06afd1e38dd27bbb1258685a1fc6524df6aff4e07b25b393a47de59635178d99" +checksum = "f35d36794509b7bfcbf90e11a1b5e4d047123c34610105e2e80a2048351cdb2f" dependencies = [ "arrow", "async-trait", @@ -2427,7 +2439,7 @@ dependencies = [ "datafusion-physical-plan", "datafusion-session", "futures", - "itertools 0.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", "parking_lot", @@ -2436,9 +2448,9 @@ dependencies = [ [[package]] name = "datafusion-catalog-listing" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0668fb32c12065ec242be0e5b4bc62bd7a06a0be3ecd83791ef877e4be67e02" +checksum = "a6454bfb7f43b83942e2ca2576fd09342eedbd0d323e1eef72c3c8e4d57d7203" dependencies = [ "arrow", "async-trait", @@ -2452,16 +2464,17 @@ dependencies = [ "datafusion-physical-expr-common", "datafusion-physical-plan", "futures", - "itertools 0.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", + "percent-encoding", ] [[package]] name = "datafusion-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca43b263cdff57042cfa8fb817fb3469f4878933380dccff25f5e793580abbf9" +checksum = "d26626e12b224b83351239465dcd00f72d47b02fb5e5b65a643e2dc8ed37f687" dependencies = [ "arrow", "arrow-ipc", @@ -2470,10 +2483,11 @@ dependencies = [ "foldhash 0.2.0", "half", "hashbrown 0.17.1", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", "libc", "log", + "num-traits", "object_store 0.13.2", "sqlparser 0.62.0", "tokio", @@ -2483,9 +2497,9 @@ dependencies = [ [[package]] name = "datafusion-common-runtime" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f0ba2b864792bdca4d76c59a1de0ab6e1b61946596b9936888dbd6360035f2" +checksum = "a106420cbfa980f242c22243ae9a6cce661d4d86ce96cff87dacabf7754a4470" dependencies = [ "futures", "log", @@ -2494,9 +2508,9 @@ dependencies = [ [[package]] name = "datafusion-datasource" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b840a8bce0bcbf5afad02946d438591e7c373f7afccaf3d874c04485772514dd" +checksum = "210aa1e9525e9454f2399dbb8b0b95510145bd8c1fdc35de74e9ccbf81bcb699" dependencies = [ "arrow", "async-trait", @@ -2513,7 +2527,7 @@ dependencies = [ "datafusion-session", "futures", "glob", - "itertools 0.14.0", + "itertools 0.15.0", "log", "object_store 0.13.2", "parking_lot", @@ -2524,9 +2538,9 @@ dependencies = [ [[package]] name = "datafusion-datasource-arrow" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a24cc0b9cf6e367f27f27406eff13abf48a11b72446aaa40b3105c0ded5c17d9" +checksum = "65b1b041688cad707fa103c3e7f4c6d89b3134ebf67da0129070dad3381851eb" dependencies = [ "arrow", "arrow-ipc", @@ -2541,16 +2555,16 @@ dependencies = [ "datafusion-physical-plan", "datafusion-session", "futures", - "itertools 0.14.0", + "itertools 0.15.0", "object_store 0.13.2", "tokio", ] [[package]] name = "datafusion-datasource-csv" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1abe56b2a7a2d1d6de5117dd1a203181e267f28529faa5da546947621b697d7" +checksum = "2a7b34e253c4fa5251f174977af910a2f2ec831ec39dbbb56b29ce505cff278b" dependencies = [ "arrow", "async-trait", @@ -2571,9 +2585,9 @@ dependencies = [ [[package]] name = "datafusion-datasource-json" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3e467f0611ad7bdd5aad17c63c9bb6182d04e5282e5496d897ea2b49c024ba" +checksum = "1663338f43be6a5746473008e2d0fbde282577ddf0bae90d6c7386e988d71b29" dependencies = [ "arrow", "async-trait", @@ -2594,19 +2608,20 @@ dependencies = [ [[package]] name = "datafusion-doc" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69bb69d8769e34f76839c960dbde24c1ac0c885a79b6c3c2287bdc56ec67891" +checksum = "0c2569c2e74a34fcae3a369ab3912d61e41a062592510f11e31b1dae2725ecdc" [[package]] name = "datafusion-execution" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8eac0a09bc8d263f52025cad9e001da4d8138d633fa288edda4d06b1772eae6" +checksum = "39cfdd5ac0769d1e74a885450e49fde8f63ca7ab41eb479a068564aaea80b837" dependencies = [ "arrow", "arrow-buffer", "async-trait", + "bytes", "dashmap", "datafusion-common", "datafusion-expr", @@ -2615,16 +2630,19 @@ dependencies = [ "log", "object_store 0.13.2", "parking_lot", + "pin-project-lite", "rand 0.9.5", "tempfile", + "tokio", + "tokio-util", "url", ] [[package]] name = "datafusion-expr" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eeb14d374767ee0fc62dc79a5ba8bcf8a63c14e993c7d992d0e63adfa23d77d3" +checksum = "86560fd7df4dda924f5474b588c56e7ae8e96dcf158c7327c9cfe9daff448ec5" dependencies = [ "arrow", "arrow-schema", @@ -2636,33 +2654,34 @@ dependencies = [ "datafusion-functions-aggregate-common", "datafusion-functions-window-common", "datafusion-physical-expr-common", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", + "serde", "serde_json", "sqlparser 0.62.0", ] [[package]] name = "datafusion-expr-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7b19a8c95522bee8cbb313d74263b85e355d2b52f42e67ef5694bf5de9e9356" +checksum = "e82e313cf655cf6bc2dce6cbd23bcb0d20236a54a1b09c436615e4bac4d8c49f" dependencies = [ "arrow", "datafusion-common", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", ] [[package]] name = "datafusion-functions" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f64c983bbbdcb729d921a2b2ac3375598719b5cc0c30345ad664936f3176fc7" +checksum = "939ae2771da8a3fdc23ab4de610ae8fef9515476626b49d96d0d5c782b105771" dependencies = [ "arrow", "arrow-buffer", - "base64 0.22.1", + "base64 0.23.1", "blake2", "blake3", "chrono", @@ -2675,22 +2694,22 @@ dependencies = [ "datafusion-macros", "datafusion-physical-expr-common", "hex", - "itertools 0.14.0", + "itertools 0.15.0", "log", "md-5", "memchr", "num-traits", "rand 0.9.5", "regex", - "sha2 0.11.1", + "sha2 0.11.0", "uuid", ] [[package]] name = "datafusion-functions-aggregate" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89bc17041e424a47ed062f43df24d84aab8b57c4c3221e5c1a5eef46d6c5718b" +checksum = "fd6c3aee9f2bc65716787d651e023743a90b4efbc57a2f679f036632e16fb110" dependencies = [ "arrow", "datafusion-common", @@ -2701,17 +2720,17 @@ dependencies = [ "datafusion-macros", "datafusion-physical-expr", "datafusion-physical-expr-common", - "foldhash 0.2.0", "half", + "hashbrown 0.17.1", "log", "num-traits", ] [[package]] name = "datafusion-functions-aggregate-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97dd2a9e865c6108059f5b37b77934f84b50bfb108f837bd0e5c9536e03f0545" +checksum = "988b5d3dfb4939d81c2f9fab267063610fe52a843620f2fa6cb2a1598e43369c" dependencies = [ "arrow", "datafusion-common", @@ -2721,9 +2740,9 @@ dependencies = [ [[package]] name = "datafusion-functions-nested" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75f0bdfeef16d96417b9632ef855645376b242e9006a126dfd0bedfc54a93f5f" +checksum = "08149d433a97c9ea3cdf80de06480ab5c7f5453485f1e452d5b3583c81d5c0dd" dependencies = [ "arrow", "arrow-ord", @@ -2738,7 +2757,7 @@ dependencies = [ "datafusion-macros", "datafusion-physical-expr-common", "hashbrown 0.17.1", - "itertools 0.14.0", + "itertools 0.15.0", "itoa", "log", "memchr", @@ -2746,9 +2765,9 @@ dependencies = [ [[package]] name = "datafusion-functions-table" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4e4941673c917819616877e9993da4503e4f4739812be0bc32c5356184c6383" +checksum = "2c767567cce2782d4d0bdfa55fab010aaba0bdbe533509e9e0b9a6a3ee29ed59" dependencies = [ "arrow", "async-trait", @@ -2762,9 +2781,9 @@ dependencies = [ [[package]] name = "datafusion-functions-window" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12dd2e16c12b84b6f6b41b19f55b366dd1c46876bb35b86896c6349067379e8d" +checksum = "0a311c1f558d1f792f1f631c3670da12ee72a20fbf5d6ca151325d66191c03c1" dependencies = [ "arrow", "datafusion-common", @@ -2779,9 +2798,9 @@ dependencies = [ [[package]] name = "datafusion-functions-window-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cdc5e4b6f8b6ef823cc1c761f85088ad4c884fe8df64df3cbcc6b2b84698441" +checksum = "fffd54b8acf6ecef284cc0677e01e1b8c71be64fec50612ba00a0ff0d9b41a52" dependencies = [ "datafusion-common", "datafusion-physical-expr-common", @@ -2789,20 +2808,20 @@ dependencies = [ [[package]] name = "datafusion-macros" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a3614234dd93578c92428cb4f408e020874f0d2b7e6c90c928d9d28b5df2ceb" +checksum = "14d6df9763c8fb968b2417d797aef4c55ac2e4a895aaef38c72c16a287aa4a40" dependencies = [ "datafusion-doc", "quote", - "syn 2.0.119", + "syn 3.0.3", ] [[package]] name = "datafusion-optimizer" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0635620b050b81bb92764e99250868f654e2cd5ad1bece413283b3f73c83179" +checksum = "acfb8cea6e05e2e75bae183340cf7d53cccb3db0449e2f1fbc07654d980fd19f" dependencies = [ "arrow", "chrono", @@ -2810,8 +2829,8 @@ dependencies = [ "datafusion-expr", "datafusion-expr-common", "datafusion-physical-expr", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", "log", "regex", "regex-syntax", @@ -2819,11 +2838,12 @@ dependencies = [ [[package]] name = "datafusion-physical-expr" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cabf7a86eb70b816729e33c81bf7767c936ee1226f607a114f5dac2decac8d0" +checksum = "9f002cef849e10c0597a217ec7891c2796c0f8b42d739f5d24abc24496373406" dependencies = [ "arrow", + "arrow-schema", "datafusion-common", "datafusion-expr", "datafusion-expr-common", @@ -2831,8 +2851,8 @@ dependencies = [ "datafusion-physical-expr-common", "half", "hashbrown 0.17.1", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", "parking_lot", "petgraph", "tokio", @@ -2840,9 +2860,9 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-adapter" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de222e04f7e6744501555a54ab0abe26bfdfebee380af79a9bdc175704246859" +checksum = "82761522c4536e7059d3b185cd99f10525c2bf48f1bd26a0a57e73e19eadc0fb" dependencies = [ "arrow", "datafusion-common", @@ -2850,31 +2870,31 @@ dependencies = [ "datafusion-functions", "datafusion-physical-expr", "datafusion-physical-expr-common", - "itertools 0.14.0", + "itertools 0.15.0", ] [[package]] name = "datafusion-physical-expr-common" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d0d0057fc5a502d45c870cb6d47c66eb7bdd5edb1bd71ad6f3f724975ac2a8" +checksum = "f8c5c67aa252886f4d6b331c8114797f5b140464e774c4da36889269a1bf1bd8" dependencies = [ "arrow", "chrono", "datafusion-common", "datafusion-expr-common", "hashbrown 0.17.1", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", "parking_lot", "pin-project", ] [[package]] name = "datafusion-physical-optimizer" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86046eed10950c5f9aaed9acfd148e9bd2e1dfdfe4f9aef607d1447b271e4183" +checksum = "f1a49dd3a76e4879012682c59dc3735282e60640c97483546a4113564a60bf8f" dependencies = [ "arrow", "datafusion-common", @@ -2885,14 +2905,15 @@ dependencies = [ "datafusion-physical-expr-common", "datafusion-physical-plan", "datafusion-pruning", - "itertools 0.14.0", + "datafusion-session", + "itertools 0.15.0", ] [[package]] name = "datafusion-physical-plan" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bc84da934c903407ba297971ebcc020c4c1a38aafd765d6c144c76eff3fa6a1" +checksum = "b1451d6817e5ac0dd21819b19949d1c420ab51d748f55dd9a96ecb5418a24c97" dependencies = [ "arrow", "arrow-data", @@ -2900,6 +2921,7 @@ dependencies = [ "arrow-ord", "arrow-schema", "async-trait", + "bytes", "datafusion-common", "datafusion-common-runtime", "datafusion-execution", @@ -2912,20 +2934,22 @@ dependencies = [ "futures", "half", "hashbrown 0.17.1", - "indexmap 2.14.2", - "itertools 0.14.0", + "indexmap 2.14.0", + "itertools 0.15.0", "log", "num-traits", "parking_lot", "pin-project-lite", + "serde", + "serde_json", "tokio", ] [[package]] name = "datafusion-pruning" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb63eeac6de19be40f487b65dd84e546195f783c5a9928618e0c4f2a3569b0d7" +checksum = "f11f0dbe2b5a642f6106e44de8bbd6654fa7220ca14f32313d4efd5514a86968" dependencies = [ "arrow", "datafusion-common", @@ -2939,10 +2963,11 @@ dependencies = [ [[package]] name = "datafusion-session" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f961d209177f91bd014db5cbb2c33b7d28a2597b9003e77f17aeb712964315a" +checksum = "62dc5ce37a5ce1ff5362949776829aded2529a11dbaa13d24b0ffa6a059e106a" dependencies = [ + "arrow-schema", "async-trait", "datafusion-common", "datafusion-execution", @@ -2953,9 +2978,9 @@ dependencies = [ [[package]] name = "datafusion-sql" -version = "54.1.0" +version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1d71cb454da682b2af7488e1fc1ddd72ee1b28f19297b8ccad73f0a21ee9a69" +checksum = "816c224a0ef5469a32a562b5d4830544f714f97c5f50142109286d40a288c7db" dependencies = [ "arrow", "bigdecimal", @@ -2963,7 +2988,7 @@ dependencies = [ "datafusion-common", "datafusion-expr", "datafusion-functions-nested", - "indexmap 2.14.2", + "indexmap 2.14.0", "log", "regex", "sqlparser 0.62.0", @@ -2986,9 +3011,9 @@ dependencies = [ [[package]] name = "defmt" -version = "1.2.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -2996,23 +3021,33 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.2.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] name = "defmt-parser" -version = "1.1.0" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" dependencies = [ - "thiserror 2.0.21", + "thiserror 2.0.18", +] + +[[package]] +name = "der" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" +dependencies = [ + "const-oid 0.9.6", + "zeroize", ] [[package]] @@ -3028,10 +3063,11 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.9" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" dependencies = [ + "powerfmt", "serde_core", ] @@ -3053,7 +3089,7 @@ dependencies = [ "darling 0.20.11", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -3063,7 +3099,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -3084,9 +3120,9 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer 0.12.1", + "block-buffer 0.12.0", "const-oid 0.10.2", - "crypto-common 0.2.2", + "crypto-common 0.2.1", "ctutils", ] @@ -3128,7 +3164,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.3", + "redox_users 0.5.2", "windows-sys 0.61.2", ] @@ -3138,19 +3174,19 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "objc2", ] [[package]] name = "displaydoc" -version = "0.2.7" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -3200,49 +3236,46 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9" [[package]] -name = "earcutr" -version = "0.4.3" +name = "earcut" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79127ed59a85d7687c409e9978547cffb7dc79675355ed22da6b66fd5f6ead01" +checksum = "88459a2a8e3a514b6e6de38cf3aaa9250a894cb098f74a932db77fcc8341b6d0" dependencies = [ - "itertools 0.11.0", "num-traits", ] [[package]] name = "ecdsa" -version = "0.16.9" +version = "0.14.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" dependencies = [ - "der", - "digest 0.10.7", + "der 0.6.1", "elliptic-curve", "rfc6979", - "signature", - "spki", + "signature 1.6.4", ] [[package]] name = "either" -version = "1.19.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "elliptic-curve" -version = "0.13.8" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" dependencies = [ "base16ct", - "crypto-bigint", + "crypto-bigint 0.4.9", + "der 0.6.1", "digest 0.10.7", "ff", "generic-array", "group", - "pem-rfc7468", - "pkcs8", + "pkcs8 0.9.0", "rand_core 0.6.4", "sec1", "subtle", @@ -3257,23 +3290,18 @@ checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" [[package]] name = "encoding_rs" -version = "0.8.42" +version = "0.8.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", + "cfg-if 1.0.4", ] [[package]] name = "encoding_rs_io" -version = "0.1.8" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fba3fe847045ecff794b9c138293a80db914678c453ad63fbf0c6a9eb6e00b22" +checksum = "1cc3c5651fb62ab8aa3103998dade57efdd028544bd300516baa31840c252a83" dependencies = [ "encoding_rs", ] @@ -3293,7 +3321,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -3305,7 +3333,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -3348,14 +3376,14 @@ checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "equivalent" -version = "1.0.3" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" @@ -3390,10 +3418,11 @@ checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" [[package]] name = "event-listener" -version = "5.4.2" +version = "5.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" dependencies = [ + "concurrent-queue", "parking", "pin-project-lite", ] @@ -3444,15 +3473,15 @@ checksum = "95765f67b4b18863968b4a1bd5bb576f732b29a4a28c7cd84c09fa3e2875f33c" [[package]] name = "fast-float2" -version = "0.2.4" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" +checksum = "f8eb564c5c7423d25c886fb561d1e4ee69f72354d16918afa32c08811f6b6a55" [[package]] name = "fastrand" -version = "2.5.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" [[package]] name = "fd-lock" @@ -3460,16 +3489,16 @@ version = "4.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" dependencies = [ - "cfg-if", - "rustix 1.1.5", + "cfg-if 1.0.4", + "rustix 1.1.4", "windows-sys 0.59.0", ] [[package]] name = "ff" -version = "0.13.1" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" dependencies = [ "rand_core 0.6.4", "subtle", @@ -3477,9 +3506,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.15" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" [[package]] name = "findshlibs" @@ -3505,19 +3534,18 @@ version = "25.12.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "rustc_version", ] [[package]] name = "flate2" -version = "1.1.10" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", + "miniz_oxide", ] [[package]] @@ -3534,9 +3562,9 @@ dependencies = [ [[package]] name = "float_next_after" -version = "1.0.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" +checksum = "37007738a80ea34f969af54a3390dd72cacdef654974cfd449c9f6f72dbaac10" [[package]] name = "fnv" @@ -3594,7 +3622,7 @@ checksum = "643b47d510032a01e5af70dca288b0c5ec531646c1a8392e793fb5b0c13bef30" dependencies = [ "anyhow", "bytes", - "cfg-if", + "cfg-if 1.0.4", "foyer-tokio", "mixtrics", "parking_lot", @@ -3619,7 +3647,7 @@ checksum = "ae51f5089f3d9025ae77f17ea66d2489ac0f82fbb1d91462807bea174d486d82" dependencies = [ "anyhow", "asyncband", - "bitflags 2.13.2", + "bitflags 2.11.1", "datasketches", "equivalent", "foyer-common", @@ -3647,9 +3675,9 @@ dependencies = [ [[package]] name = "frostem" -version = "1.20260821.8" +version = "1.20260804.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e2488a10218a17366ce6bd38b6d081b4387a9548d350029db9feddc9bb44d6d" +checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" [[package]] name = "fs4" @@ -3657,7 +3685,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.4", "windows-sys 0.59.0", ] @@ -3669,8 +3697,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "rand 0.9.5", @@ -3693,9 +3721,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" dependencies = [ "futures-channel", "futures-core", @@ -3708,9 +3736,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" dependencies = [ "futures-core", "futures-sink", @@ -3718,15 +3746,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" [[package]] name = "futures-executor" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" dependencies = [ "futures-core", "futures-task", @@ -3735,44 +3763,44 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" [[package]] name = "futures-macro" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] name = "futures-sink" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" [[package]] name = "futures-task" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" [[package]] name = "futures-timer" -version = "3.0.4" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" [[package]] name = "futures-util" -version = "0.3.34" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ "futures-channel", "futures-core", @@ -3787,9 +3815,12 @@ dependencies = [ [[package]] name = "gearhash" -version = "0.1.4" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616e8f476a586f1b078d9eece21f7a071f27997e709e2b471f5697deea53bda9" +checksum = "c8cf82cf76cd16485e56295a1377c775ce708c9f1a0be6b029076d60a245d213" +dependencies = [ + "cfg-if 0.1.10", +] [[package]] name = "gemm" @@ -3912,12 +3943,12 @@ dependencies = [ [[package]] name = "generator" -version = "0.8.11" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37" +checksum = "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9" dependencies = [ "cc", - "cfg-if", + "cfg-if 1.0.4", "libc", "log", "rustversion", @@ -3933,24 +3964,26 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", - "zeroize", ] [[package]] name = "geo" -version = "0.31.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fc1a1678e54befc9b4bcab6cd43b8e7f834ae8ea121118b0fd8c42747675b4a" +checksum = "30eb1fdc57c1e5cfd11826fe0caec4b9dc7901f3758263bb506228d88c8d9e9a" dependencies = [ - "earcutr", + "earcut", "float_next_after", "geo-types", "geographiclib-rs", "i_overlay", "log", "num-traits", + "rand 0.10.1", + "rand_pcg", "robust", "rstar", + "sif-itree", "spade", ] @@ -3965,23 +3998,23 @@ dependencies = [ [[package]] name = "geo-types" -version = "0.7.20" +version = "0.7.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "777d18aa0f12f8b285331cd867133ee14422b3f023f6d388034c47d43e28786a" +checksum = "94776032c45f950d30a13af6113c2ad5625316c9abfbccee4dd5a6695f8fe0f5" dependencies = [ "approx", "num-traits", "rayon", "rstar", "serde", - "thiserror 2.0.21", + "spade", ] [[package]] name = "geoarrow-array" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dafe7b7de3fab1a8b7099fd6a6434ca955fa65065f9c19f0f8a133693f3c2b0e" +checksum = "d3e4cb9aceb3985c450742846920af226c3d37249f8d6e70a96cb8fb2aa1c1f7" dependencies = [ "arrow-array", "arrow-buffer", @@ -3995,9 +4028,9 @@ dependencies = [ [[package]] name = "geoarrow-expr-geo" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e4a62ac19c86827c6ec81ea584594b3ee96db5a8119b9774d3466c6b373c434" +checksum = "4d0e3db05f5b28dc0a7e4df1fa507cbfcb08c79098620c306c556d7b030a9dbe" dependencies = [ "arrow-array", "arrow-buffer", @@ -4009,9 +4042,9 @@ dependencies = [ [[package]] name = "geoarrow-schema" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d4a7edb2a1d87024a93805332a9c8184a0354836271d42c0d18cf628a5e3cd0" +checksum = "6ec8b1c883eac8a4f163bfd59c4cbfcc4d857948b7a7a9b38482e537482354c5" dependencies = [ "arrow-schema", "geo-traits", @@ -4022,9 +4055,9 @@ dependencies = [ [[package]] name = "geodatafusion" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fecbdd00d0fff2b04635c1b1e4129c217908f0c2d17539e0a2275308afce2552" +checksum = "6ec9c5155e8679cb1b78e5fd020c17163adf72a032a1bb42b86e10b08cc7a2ae" dependencies = [ "arrow-arith", "arrow-array", @@ -4066,7 +4099,7 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "js-sys", "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -4079,7 +4112,7 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "libc", "r-efi 5.3.0", "wasip2", @@ -4087,15 +4120,17 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.3" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", + "wasip2", + "wasip3", "wasm-bindgen", ] @@ -4122,14 +4157,14 @@ checksum = "53010ccb100b96a67bc32c0175f0ed1426b31b655d562898e57325f81c023ac0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "glob" -version = "0.3.4" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "gloo-timers" @@ -4161,11 +4196,11 @@ dependencies = [ "io-uring", "itoa", "libc", - "lru 0.16.4", + "lru", "prost", "rand 0.9.5", "serde", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tokio-stream", "tonic", @@ -4177,9 +4212,9 @@ dependencies = [ [[package]] name = "group" -version = "0.13.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" dependencies = [ "ff", "rand_core 0.6.4", @@ -4188,9 +4223,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.20" +version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27" dependencies = [ "atomic-waker", "bytes", @@ -4198,7 +4233,7 @@ dependencies = [ "futures-core", "futures-sink", "http 1.5.0", - "indexmap 2.14.2", + "indexmap 2.14.0", "slab", "tokio", "tokio-util", @@ -4212,7 +4247,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "bytemuck", - "cfg-if", + "cfg-if 1.0.4", "crunchy", "num-traits", "rand 0.9.5", @@ -4309,9 +4344,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.5.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" [[package]] name = "hex" @@ -4336,7 +4371,7 @@ dependencies = [ "reqwest 0.12.28", "serde", "serde_json", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "ureq", "windows-sys 0.60.2", @@ -4344,9 +4379,9 @@ dependencies = [ [[package]] name = "hf-xet" -version = "1.7.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f24754aef4f6c3d57bc4a0dc2648ca74487050eda01c361b3eefa11feeafd662" +checksum = "c237ef4fb0ce1962a5117f8bd8c74454b41629826a9df17d14a1840ca18f0754" dependencies = [ "anyhow", "async-trait", @@ -4355,7 +4390,7 @@ dependencies = [ "more-asserts", "serde", "serde_json", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tokio-util", "tokio_with_wasm", @@ -4400,7 +4435,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "libc", "windows-link", ] @@ -4449,9 +4484,9 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.5" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ "bytes", "futures-core", @@ -4474,24 +4509,24 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "humantime" -version = "2.4.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" +checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[package]] name = "hybrid-array" -version = "0.4.15" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da" dependencies = [ "typenum", ] [[package]] name = "hyper" -version = "1.12.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" dependencies = [ "atomic-waker", "bytes", @@ -4511,9 +4546,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.10" +version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ "http 1.5.0", "hyper", @@ -4523,7 +4558,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.11", + "webpki-roots 1.0.10", ] [[package]] @@ -4557,17 +4592,16 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.21" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64 0.23.1", + "base64 0.22.1", "bytes", "futures-channel", "futures-util", "http 1.5.0", "http-body 1.1.0", - "httparse", "hyper", "ipnet", "libc", @@ -4592,24 +4626,27 @@ dependencies = [ [[package]] name = "i_float" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "010025c2c532c8d82e42d0b8bb5184afa449fa6f06c709ea9adcb16c49ae405b" +checksum = "813145bb0ad5b60f55cbbf3c74cdceda1c0a9d253b35c4cc36ae0df7887cb78f" dependencies = [ "libm", ] [[package]] name = "i_key_sort" -version = "0.6.0" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9190f86706ca38ac8add223b2aed8b1330002b5cdbbce28fb58b10914d38fc27" +checksum = "d73d122b937fca067feb0ad74f62388920272b27c356d4df2d0cfdd59e044cf0" +dependencies = [ + "rayon", +] [[package]] name = "i_overlay" -version = "4.0.7" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413183068e6e0289e18d7d0a1f661b81546e6918d5453a44570b9ab30cbed1b3" +checksum = "8dd314b4668e2b3a12508f2e125558c82a6c0a8636fa5107a900f79ce414e450" dependencies = [ "i_float", "i_key_sort", @@ -4620,18 +4657,18 @@ dependencies = [ [[package]] name = "i_shape" -version = "1.14.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ea154b742f7d43dae2897fcd5ead86bc7b5eefcedd305a7ebf9f69d44d61082" +checksum = "bfa9eac533d7509a8ab87672b60ac610c17240f9ea4851d26227689fdfe349c8" dependencies = [ "i_float", ] [[package]] name = "i_tree" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35e6d558e6d4c7b82bc51d9c771e7a927862a161a7d87bf2b0541450e0e20915" +checksum = "4804bdc1dc124eb7e1aa9e144ecc04096bcf787a10a15fa44af682b51f0f6cce" [[package]] name = "iana-time-zone" @@ -4659,9 +4696,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" dependencies = [ "displaydoc", "potential_utf", @@ -4672,10 +4709,25 @@ dependencies = [ ] [[package]] -name = "icu_locale_core" -version = "2.4.0" +name = "icu_locale" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +checksum = "d5a396343c7208121dc86e35623d3dfe19814a7613cfd14964994cdc9c9a2e26" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" dependencies = [ "displaydoc", "litemap", @@ -4686,30 +4738,16 @@ dependencies = [ ] [[package]] -name = "icu_locale_fallback" -version = "2.4.0" +name = "icu_locale_data" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" -dependencies = [ - "icu_locale_core", - "icu_locale_fallback_data", - "icu_provider", - "potential_utf", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locale_fallback_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" +checksum = "d5fdcc9ac77c6d74ff5cf6e65ef3181d6af32003b16fce3a77fb451d2f695993" [[package]] name = "icu_normalizer" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -4721,17 +4759,16 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" [[package]] name = "icu_properties" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" dependencies = [ - "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -4742,15 +4779,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" [[package]] name = "icu_provider" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" dependencies = [ "displaydoc", "icu_locale_core", @@ -4765,26 +4802,30 @@ dependencies = [ [[package]] name = "icu_segmenter" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +checksum = "5c0794db0b1a86193ac9c48768d0e6c52c54448e0870ad87907d456ee0dac964" dependencies = [ "icu_collections", - "icu_locale_fallback", + "icu_locale", "icu_provider", "icu_segmenter_data", "potential_utf", - "smallvec", "utf8_iter", - "zerotrie", "zerovec", ] [[package]] name = "icu_segmenter_data" -version = "2.4.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" +checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" [[package]] name = "ident_case" @@ -4826,9 +4867,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.2" +version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", "hashbrown 0.17.1", @@ -4856,7 +4897,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "232929e1d75fe899576a3d5c7416ad0d88dbfbb3c3d6aa00873a7408a50ddb88" dependencies = [ "ahash", - "indexmap 2.14.2", + "indexmap 2.14.0", "is-terminal", "itoa", "log", @@ -4883,25 +4924,25 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", ] [[package]] name = "io-uring" -version = "0.7.15" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" +checksum = "4d09b98f7eace8982db770e4408e7470b028ce513ac28fecdc6bf4c30fe92b62" dependencies = [ - "bitflags 2.13.2", - "cfg-if", + "bitflags 2.11.1", + "cfg-if 1.0.4", "libc", ] [[package]] name = "ipnet" -version = "2.12.2" +version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" [[package]] name = "is-terminal" @@ -4979,31 +5020,32 @@ checksum = "9028f49264629065d057f340a86acb84867925865f73bbf8d47b4d149a7e88b8" [[package]] name = "jieba-macros" -version = "0.10.4" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "455f837e9d0255b68a712200db247c68fdad4941b72471b76bfa61c3b0c1f79f" +checksum = "46adade69b634535a8f495cf87710ed893cff53e1dbc9dd750c2ab81c5defb82" dependencies = [ "phf_codegen 0.13.1", ] [[package]] name = "jieba-rs" -version = "0.10.4" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6a8bbb0f77ee810f0689a30b7cec56b875751ef4ec2e74fd995613dc52b3ae1" +checksum = "11b53580aaa8ec8b713da271da434f8947409242c537a9ab3f7b76bdbb19e8a9" dependencies = [ "bytecount", "cedarwood", "jieba-macros", "phf 0.13.1", + "regex", "rustc-hash", ] [[package]] name = "jiff" -version = "0.2.38" +version = "0.2.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" dependencies = [ "defmt", "jiff-core", @@ -5020,31 +5062,30 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.1" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" dependencies = [ "defmt", - "log", ] [[package]] name = "jiff-static" -version = "0.2.38" +version = "0.2.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" dependencies = [ "jiff-core", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "jiff-tzdb" -version = "0.1.9" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" +checksum = "c900ef84826f1338a557697dc8fc601df9ca9af4ac137c7fb61d4c6f2dfd3076" [[package]] name = "jiff-tzdb-platform" @@ -5061,13 +5102,13 @@ version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "combine", "jni-macros", "jni-sys", "log", "simd_cesu8", - "thiserror 2.0.21", + "thiserror 2.0.18", "walkdir", "windows-link", ] @@ -5082,7 +5123,7 @@ dependencies = [ "quote", "rustc_version", "simd_cesu8", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -5101,27 +5142,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" dependencies = [ "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "jobserver" -version = "0.1.35" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" dependencies = [ - "getrandom 0.4.3", + "getrandom 0.3.4", "libc", ] [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "futures-util", + "once_cell", "wasm-bindgen", ] @@ -5153,8 +5195,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arc-swap", "arrow", @@ -5218,7 +5260,7 @@ dependencies = [ "semver", "serde", "serde_json", - "snafu 0.9.2", + "snafu 0.9.0", "tokio", "tokio-stream", "tokio-util", @@ -5229,7 +5271,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.3" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5250,8 +5293,8 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" -version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "59.0.0" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5264,8 +5307,8 @@ dependencies = [ [[package]] name = "lance-arrow-stats" -version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "59.0.0" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-schema", @@ -5274,8 +5317,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrayref", "crunchy", @@ -5285,8 +5328,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5312,7 +5355,7 @@ dependencies = [ "rand 0.9.5", "roaring", "serde_json", - "snafu 0.9.2", + "snafu 0.9.0", "tempfile", "tokio", "tokio-util", @@ -5323,8 +5366,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5356,8 +5399,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5382,8 +5425,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5400,18 +5443,18 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "lance-encoding" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-arith", "arrow-array", @@ -5445,8 +5488,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-arith", "arrow-array", @@ -5478,8 +5521,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "geo-traits", "geo-types", @@ -5491,8 +5534,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arc-swap", "arrow", @@ -5568,8 +5611,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-schema", @@ -5592,8 +5635,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5613,6 +5656,7 @@ dependencies = [ "log", "metrics", "moka", + "nix 0.31.3", "object_store 0.14.2", "object_store_opendal", "opendal", @@ -5632,12 +5676,13 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", ] [[package]] name = "lance-jsonb" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "byteorder", "ethnum", @@ -5646,7 +5691,7 @@ dependencies = [ "jiff", "nom 8.0.0", "num-traits", - "ordered-float 5.5.1", + "ordered-float 5.3.0", "serde", "serde_json", "zmij", @@ -5654,9 +5699,10 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ + "argminmax 0.7.1", "arrow-array", "arrow-schema", "cc", @@ -5669,8 +5715,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "async-trait", @@ -5679,13 +5725,13 @@ dependencies = [ "lance-namespace-reqwest-client", "serde", "serde_json", - "snafu 0.9.2", + "snafu 0.9.0", ] [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arc-swap", "arrow", @@ -5739,8 +5785,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5754,8 +5800,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow", "arrow-array", @@ -5776,6 +5822,7 @@ dependencies = [ "lance-io", "lance-select", "log", + "num-traits", "object_store 0.14.2", "prost", "prost-build", @@ -5786,7 +5833,7 @@ dependencies = [ "semver", "serde", "serde_json", - "snafu 0.9.2", + "snafu 0.9.0", "tokio", "tracing", "url", @@ -5795,8 +5842,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "arrow-array", "arrow-schema", @@ -5809,8 +5856,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.3#2e22bb984d6cc6f5990f188cabb0b586b7bb51bc" +version = "15.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.6#d28b9cfb2f82ddb4ba9cdca5882aea41ad829d9d" dependencies = [ "frostem", "icu_segmenter", @@ -6033,13 +6080,19 @@ dependencies = [ [[package]] name = "lazy_static" -version = "1.5.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" dependencies = [ "spin 0.9.9", ] +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + [[package]] name = "lexical-core" version = "1.0.6" @@ -6109,7 +6162,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "windows-link", ] @@ -6121,18 +6174,18 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.25" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" dependencies = [ "libc", ] [[package]] name = "libsais-rs" -version = "0.2.2" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00777f770949ecbe5524eb6630699a501c9c27e4d18493705a7dad49c9bdfbd1" +checksum = "40fe164dbd47ea0c20e78a121c980ef673326905f1d4fba55e3645a20ef6717f" dependencies = [ "rayon", ] @@ -6179,7 +6232,7 @@ dependencies = [ "encoding_rs_io", "glob", "log", - "memmap2 0.9.12", + "memmap2 0.9.10", "num_cpus", "once_cell", "regex", @@ -6188,20 +6241,20 @@ dependencies = [ "serde_json", "strum", "strum_macros 0.28.0", - "thiserror 2.0.21", + "thiserror 2.0.18", ] [[package]] name = "link-section" -version = "0.19.3" +version = "0.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39c29a617ce3df32c08497bdc1ab6e2376e0b17948ac166a2fbe5977c5954cd9" +checksum = "5ee1a0d6e252afe82e7bc2db42fba60e02ddf3b1accaf8cb21d96e34ba61f3d4" [[package]] name = "linktime-proc-macro" -version = "0.2.3" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e57c38c1e860fd37c604281cdfb1dd2216977fd76a50f85ba2f388ef3219616" +checksum = "348d0075b1fc163b26d72a7f75fc5141daf2fd1bdf128d873cbaf6785d495bdf" [[package]] name = "linux-raw-sys" @@ -6217,15 +6270,15 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.3" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "litrs" -version = "1.0.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" [[package]] name = "lock_api" @@ -6248,7 +6301,7 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "generator", "scoped-tls", "tracing", @@ -6264,20 +6317,11 @@ dependencies = [ "hashbrown 0.16.1", ] -[[package]] -name = "lru" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" -dependencies = [ - "hashbrown 0.17.1", -] - [[package]] name = "lru-slab" -version = "0.1.3" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" [[package]] name = "lz4" @@ -6307,6 +6351,15 @@ dependencies = [ "twox-hash", ] +[[package]] +name = "lz4_flex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" +dependencies = [ + "twox-hash", +] + [[package]] name = "lzma-sys" version = "0.1.20" @@ -6320,19 +6373,19 @@ dependencies = [ [[package]] name = "macro_rules_attribute" -version = "0.2.3" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" +checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520" dependencies = [ "macro_rules_attribute-proc_macro", - "pastey", + "paste", ] [[package]] name = "macro_rules_attribute-proc_macro" -version = "0.2.3" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" +checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30" [[package]] name = "matchers" @@ -6357,9 +6410,9 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" [[package]] name = "matrixmultiply" -version = "0.3.11" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08" dependencies = [ "autocfg", "num_cpus", @@ -6374,10 +6427,20 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "digest 0.11.3", ] +[[package]] +name = "mea" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c709842c4ce65cb91e2666ad5319dfc1efc3af0d34f02075eddca9000d9f8afb" +dependencies = [ + "hashbrown 0.17.1", + "slab", +] + [[package]] name = "memchr" version = "2.8.3" @@ -6395,9 +6458,9 @@ dependencies = [ [[package]] name = "memmap2" -version = "0.9.12" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3" dependencies = [ "libc", "stable_deref_trait", @@ -6432,7 +6495,7 @@ dependencies = [ "crossbeam-epoch", "crossbeam-utils", "hashbrown 0.15.5", - "indexmap 2.14.2", + "indexmap 2.14.0", "metrics", "ordered-float 4.6.0", "quanta", @@ -6469,15 +6532,6 @@ name = "miniz_oxide" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" dependencies = [ "adler2", "simd-adler32", @@ -6485,9 +6539,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.4" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -6496,9 +6550,9 @@ dependencies = [ [[package]] name = "mixtrics" -version = "0.2.6" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dd94ebec15e61a36cd63b1e8816c83434e42926962cd21ee6e4db898d4d4f05" +checksum = "2c46b5adfb7a3ae4996d327a5bdc90e78fec025806dd312bdbe6f07a755e0ec9" dependencies = [ "itertools 0.15.0", "parking_lot", @@ -6543,7 +6597,7 @@ checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -6580,12 +6634,6 @@ dependencies = [ "target-features", ] -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - [[package]] name = "munge" version = "0.4.7" @@ -6603,7 +6651,7 @@ checksum = "4568f25ccbd45ab5d5603dc34318c1ec56b117531781260002151b8530a9f931" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -6627,7 +6675,7 @@ version = "3.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a746ad50efbfb632ade1de4025519a477decbbd798cea1a6ac41d7c44f80083" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "chrono", "ctor", "futures", @@ -6658,7 +6706,7 @@ dependencies = [ "napi-derive-backend", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.3", ] [[package]] @@ -6671,7 +6719,7 @@ dependencies = [ "proc-macro2", "quote", "semver", - "syn 3.0.9", + "syn 3.0.3", ] [[package]] @@ -6737,7 +6785,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" dependencies = [ "bitflags 1.3.2", - "cfg-if", + "cfg-if 1.0.4", "libc", ] @@ -6747,8 +6795,8 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" dependencies = [ - "bitflags 2.13.2", - "cfg-if", + "bitflags 2.11.1", + "cfg-if 1.0.4", "cfg_aliases 0.1.1", "libc", ] @@ -6759,9 +6807,9 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "cfg_aliases 0.2.2", + "bitflags 2.11.1", + "cfg-if 1.0.4", + "cfg_aliases 0.2.1", "libc", ] @@ -6819,9 +6867,19 @@ dependencies = [ [[package]] name = "num-bigint" -version = "0.4.8" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" dependencies = [ "num-integer", "num-traits", @@ -6838,7 +6896,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand 0.8.8", + "rand 0.8.6", "smallvec", "zeroize", ] @@ -6855,9 +6913,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.2.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" [[package]] name = "num-format" @@ -6871,19 +6929,20 @@ dependencies = [ [[package]] name = "num-integer" -version = "0.1.47" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" dependencies = [ "num-traits", ] [[package]] name = "num-iter" -version = "0.1.46" +version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" dependencies = [ + "autocfg", "num-integer", "num-traits", ] @@ -6894,7 +6953,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", ] @@ -6938,7 +6997,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -6957,7 +7016,7 @@ dependencies = [ "chrono", "getrandom 0.2.17", "http 1.5.0", - "rand 0.8.8", + "rand 0.8.6", "serde", "serde_json", "serde_path_to_error", @@ -6968,9 +7027,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.5" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" dependencies = [ "objc2-encode", ] @@ -6981,7 +7040,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "objc2", "objc2-foundation", ] @@ -6992,7 +7051,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "dispatch2", "objc2", ] @@ -7009,7 +7068,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "objc2", "objc2-core-foundation", ] @@ -7024,17 +7083,6 @@ dependencies = [ "objc2-core-foundation", ] -[[package]] -name = "objc2-open-directory" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb82bed227edf5201dfedf072bba4015a33d3d4a98519837295a90f0a23f676d" -dependencies = [ - "objc2", - "objc2-core-foundation", - "objc2-foundation", -] - [[package]] name = "objc2-system-configuration" version = "0.3.2" @@ -7053,15 +7101,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "object" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" -dependencies = [ - "memchr", -] - [[package]] name = "object_store" version = "0.13.2" @@ -7079,7 +7118,7 @@ dependencies = [ "itertools 0.14.0", "parking_lot", "percent-encoding", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tracing", "url", @@ -7114,13 +7153,13 @@ dependencies = [ "parking_lot", "percent-encoding", "quick-xml 0.41.0", - "rand 0.10.3", + "rand 0.10.1", "reqwest 0.13.5", "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tracing", "url", @@ -7132,9 +7171,9 @@ dependencies = [ [[package]] name = "object_store_opendal" -version = "0.60.5" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bd9da6291f93eb19b7987dac17617de0131760a6ba97a4cd8d6b1a07fa89783" +checksum = "c479bcc317f0ed98972b7184e0f9cc1bea83a07f60cdade96d7207a48ebfb779" dependencies = [ "async-trait", "asyncband", @@ -7171,7 +7210,7 @@ version = "6.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "libc", "once_cell", "onig_sys", @@ -7195,9 +7234,9 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "opendal" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46081824c74bac9f68f0bc4408077f77b0e315c006514719c97af1c2227ac2d2" +checksum = "9fe43e16d96bed57937eb7c4a28559bf4c5fc4a3951656505d1fdd4f856349b4" dependencies = [ "ctor", "opendal-core", @@ -7218,9 +7257,9 @@ dependencies = [ [[package]] name = "opendal-core" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d5a635dfea36a7a0c3bbb2ca34c97af17f98dd69b0cdf31a1d436a346e0a12" +checksum = "de4566a412776e3f65d53dd9fceced5b432a0a9c9a1e8d50ccf58823795e5c5b" dependencies = [ "anyhow", "asyncband", @@ -7232,7 +7271,7 @@ dependencies = [ "log", "md-5", "percent-encoding", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-core", "serde", "serde_json", @@ -7244,9 +7283,9 @@ dependencies = [ [[package]] name = "opendal-http-transport-reqwest" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc025e163c43993e30cf1829a30b791934e5b0f7cd4d7e03acc902a9efb7e8f5" +checksum = "f772ce6c137ab43647726116d505a649a88d41928fcd813438eb30b02312bcbb" dependencies = [ "bytes", "futures", @@ -7258,9 +7297,9 @@ dependencies = [ [[package]] name = "opendal-layer-concurrent-limit" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06b44bdf694cccb7d90515b3eac6623975a2813abf4f5c438b4949a329d6a45b" +checksum = "3734c648617e5ad724d49175dde8323550624f9614f50e9e81b7aafae30b1734" dependencies = [ "asyncband", "futures", @@ -7270,9 +7309,9 @@ dependencies = [ [[package]] name = "opendal-layer-logging" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520d3de5d246c82a246c431ef0f52b8d2f091c7c49a3fd7a6f0ff519b1e7725f" +checksum = "0a8daab5a91eac76f94516e7c71e677195c9221840ce8f5e71815e3fc8207742" dependencies = [ "log", "opendal-core", @@ -7280,9 +7319,9 @@ dependencies = [ [[package]] name = "opendal-layer-retry" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a02c59479b047878f4a0f269f23c847f24d67d1ff19f2b20fdd5a3bceefd451" +checksum = "eb8e22cb1f86ef9af771a8947d3ccf380c8f5b76236f628314dd41c9ba73331a" dependencies = [ "backon", "log", @@ -7291,9 +7330,9 @@ dependencies = [ [[package]] name = "opendal-layer-timeout" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afffa0cf8a6690b3b44cc510816ba675638eb236699a7d449e44ac3344bafd36" +checksum = "08ac6c77fe0d1b18e0064a02c19b98dbebcab78bf5e7753ad1f3abbc18850ff4" dependencies = [ "opendal-core", "tokio", @@ -7301,9 +7340,9 @@ dependencies = [ [[package]] name = "opendal-service-azblob" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b674507cd2f764f6b40d5f88d284bb293c519d76e8aa0103987f970da412eeac" +checksum = "c6cf31b02e7b44191d97c07254eea109b5da9c17210a29e478c8d0dc26dffb1f" dependencies = [ "base64 0.23.1", "bytes", @@ -7311,20 +7350,20 @@ dependencies = [ "log", "opendal-core", "opendal-service-azure-common", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-azure-storage", "reqsign-core", "reqsign-file-read-tokio", "serde", - "sha2 0.11.1", + "sha2 0.11.0", "uuid", ] [[package]] name = "opendal-service-azdls" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afeb287cf2b03ab8d99d77a8e9687e908eb7898e2da1af6ccd00590c7095cae6" +checksum = "354f4a8d26f0fb7639f5c4ad3a924d7c75625830f69550b8c807c080ea0df8bc" dependencies = [ "asyncband", "base64 0.23.1", @@ -7333,7 +7372,7 @@ dependencies = [ "log", "opendal-core", "opendal-service-azure-common", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-azure-storage", "reqsign-core", "reqsign-file-read-tokio", @@ -7343,9 +7382,9 @@ dependencies = [ [[package]] name = "opendal-service-azure-common" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdf9c9d0bfd1fa3638eec485c7f3448252cbb5a81774a2aa7abadc3e4f1ea43e" +checksum = "8107324c3f3cb9970fe20526c2c341b7c5769acbd4699bab73bd525f5fd63d62" dependencies = [ "http 1.5.0", "opendal-core", @@ -7353,15 +7392,15 @@ dependencies = [ [[package]] name = "opendal-service-cos" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "423127c9e81b1ef4253883743ea6696c06dfad0fa6dcb1247887039919e53772" +checksum = "feb737e6609b4fd42e4773b7b2d8d05031b63cd0df46c7ba68ddd64bae1dd3f3" dependencies = [ "bytes", "http 1.5.0", "log", "opendal-core", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-core", "reqsign-file-read-tokio", "reqsign-tencent-cos", @@ -7370,9 +7409,9 @@ dependencies = [ [[package]] name = "opendal-service-gcs" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9e5197fce0cd5929db9129a7e71e503841aa20bea4f1dcc54ab097a5f3652e9" +checksum = "3d80eca6f9227bdf65d43e5b8d5fe75dca8cfab1da07571442a0420400847bea" dependencies = [ "async-trait", "bytes", @@ -7380,7 +7419,7 @@ dependencies = [ "log", "opendal-core", "percent-encoding", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-core", "reqsign-file-read-tokio", "reqsign-google", @@ -7392,9 +7431,9 @@ dependencies = [ [[package]] name = "opendal-service-goosefs" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ca356f23424fa0129367c3eca426eb3ec0c3cfaf628bb2972fa597f8bd10805" +checksum = "2134aca0ef64dbff844cb1e608d28833f2a1b34b884e7d6b307416e966694e9f" dependencies = [ "asyncband", "bytes", @@ -7406,9 +7445,9 @@ dependencies = [ [[package]] name = "opendal-service-hf" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32c1a4076d933180b66b57a0f305e48f2de1a72b50648114cb9943a8bc9e28b8" +checksum = "0a0cba627efaee637746804b74bc2c2b2b207fe214307e1e2ba31b49aad708a3" dependencies = [ "asyncband", "bytes", @@ -7423,15 +7462,15 @@ dependencies = [ [[package]] name = "opendal-service-oss" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30e973fcebfa413432c024c41d65fad8034b22c065250c587e0c3a70f1a27eb6" +checksum = "a0ebfa355b1d4edb0e5b2a5b86d8de9f811fae1d7baca6d65246b230b2afc0bd" dependencies = [ "bytes", "http 1.5.0", "log", "opendal-core", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-aliyun-oss", "reqsign-core", "reqsign-file-read-tokio", @@ -7440,9 +7479,9 @@ dependencies = [ [[package]] name = "opendal-service-s3" -version = "0.59.5" +version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0932321e27c712a30ef72db56b12f31e41e9f0d2d3841d63a91bc8075cd8f0ef" +checksum = "2942f2d8d3d4953c0e8d07cd1244879628d084948e48ce6b6d808c5938f7858d" dependencies = [ "base64 0.23.1", "bytes", @@ -7451,7 +7490,7 @@ dependencies = [ "log", "md-5", "opendal-core", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-aws-v4", "reqsign-core", "reqsign-file-read-tokio", @@ -7465,8 +7504,8 @@ version = "0.10.81" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" dependencies = [ - "bitflags 2.13.2", - "cfg-if", + "bitflags 2.11.1", + "cfg-if 1.0.4", "foreign-types", "libc", "openssl-macros", @@ -7481,14 +7520,14 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "openssl-probe" -version = "0.2.2" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] name = "openssl-sys" @@ -7519,9 +7558,9 @@ dependencies = [ [[package]] name = "ordered-float" -version = "5.5.1" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +checksum = "b7d950ca161dc355eaf28f82b11345ed76c6e1f6eb1f4f4479e0323b9e2fbd0e" dependencies = [ "num-traits", ] @@ -7553,13 +7592,12 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" [[package]] name = "p256" -version = "0.13.2" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" dependencies = [ "ecdsa", "elliptic-curve", - "primeorder", "sha2 0.10.9", ] @@ -7595,7 +7633,7 @@ version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "libc", "redox_syscall", "smallvec", @@ -7623,12 +7661,6 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" -[[package]] -name = "pastey" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" - [[package]] name = "path_abs" version = "0.5.1" @@ -7661,16 +7693,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "pem" -version = "4.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" -dependencies = [ - "base64 0.23.1", - "serde_core", -] - [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -7700,7 +7722,7 @@ checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset", "hashbrown 0.15.5", - "indexmap 2.14.2", + "indexmap 2.14.0", "serde", ] @@ -7759,7 +7781,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ "phf_shared 0.11.3", - "rand 0.8.8", + "rand 0.8.6", ] [[package]] @@ -7816,7 +7838,7 @@ checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -7827,9 +7849,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pin-utils" -version = "0.1.1" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkcs1" @@ -7837,9 +7859,9 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" dependencies = [ - "der", - "pkcs8", - "spki", + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", ] [[package]] @@ -7850,11 +7872,21 @@ checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" dependencies = [ "aes", "cbc", - "der", + "der 0.7.10", "pbkdf2", "scrypt", "sha2 0.10.9", - "spki", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" +dependencies = [ + "der 0.6.1", + "spki 0.6.0", ] [[package]] @@ -7863,17 +7895,17 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", + "der 0.7.10", "pkcs5", "rand_core 0.6.4", - "spki", + "spki 0.7.3", ] [[package]] name = "pkg-config" -version = "0.3.34" +version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" [[package]] name = "planus" @@ -8000,14 +8032,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "465f70d3e96b6d0b1a43c358ba451286b8c8bd56696feff020d65702aa33e35c" dependencies = [ "ahash", - "bitflags 2.13.2", + "bitflags 2.11.1", "bytemuck", "chrono", "chrono-tz 0.8.6", "comfy-table", "either", "hashbrown 0.14.5", - "indexmap 2.14.2", + "indexmap 2.14.0", "num-traits", "once_cell", "polars-arrow", @@ -8015,7 +8047,7 @@ dependencies = [ "polars-error", "polars-row", "polars-utils", - "rand 0.8.8", + "rand 0.8.6", "rand_distr 0.4.3", "rayon", "regex", @@ -8074,7 +8106,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89b2632b1af668e2058d5f8f916d8fbde3cac63d03ae29a705f598e41dcfeb7f" dependencies = [ "ahash", - "bitflags 2.13.2", + "bitflags 2.11.1", "glob", "once_cell", "polars-arrow", @@ -8097,7 +8129,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "efdbdb4d9a92109bc2e0ce8e17af5ae8ab643bb5b7ee9d1d74f0aeffd1fbc95f" dependencies = [ "ahash", - "argminmax", + "argminmax 0.6.3", "base64 0.21.7", "bytemuck", "chrono", @@ -8105,7 +8137,7 @@ dependencies = [ "either", "hashbrown 0.14.5", "hex", - "indexmap 2.14.2", + "indexmap 2.14.0", "memchr", "num-traits", "polars-arrow", @@ -8214,7 +8246,7 @@ dependencies = [ "polars-error", "polars-lazy", "polars-plan", - "rand 0.8.8", + "rand 0.8.6", "serde", "serde_json", "sqlparser 0.39.0", @@ -8249,7 +8281,7 @@ dependencies = [ "ahash", "bytemuck", "hashbrown 0.14.5", - "indexmap 2.14.2", + "indexmap 2.14.0", "num-traits", "once_cell", "polars-error", @@ -8263,24 +8295,24 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.15.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" [[package]] name = "portable-atomic-util" -version = "0.2.8" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" dependencies = [ "portable-atomic", ] [[package]] name = "potential_utf" -version = "0.1.6" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" dependencies = [ "serde_core", "writeable", @@ -8289,9 +8321,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "pprof" @@ -8301,7 +8333,7 @@ checksum = "afad4d4df7b31280028245f152d5a575083e2abb822d05736f5e47653e77689f" dependencies = [ "aligned-vec", "backtrace", - "cfg-if", + "cfg-if 1.0.4", "findshlibs", "inferno", "libc", @@ -8323,7 +8355,7 @@ checksum = "38a01da47675efa7673b032bf8efd8214f1917d89685e07e395ab125ea42b187" dependencies = [ "aligned-vec", "backtrace", - "cfg-if", + "cfg-if 1.0.4", "findshlibs", "inferno", "libc", @@ -8334,7 +8366,7 @@ dependencies = [ "spin 0.10.1", "symbolic-demangle", "tempfile", - "thiserror 2.0.21", + "thiserror 2.0.18", ] [[package]] @@ -8353,16 +8385,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ "proc-macro2", - "syn 2.0.119", -] - -[[package]] -name = "primeorder" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" -dependencies = [ - "elliptic-curve", + "syn 2.0.117", ] [[package]] @@ -8371,14 +8394,14 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.17+spec-1.1.0", + "toml_edit 0.25.11+spec-1.1.0", ] [[package]] name = "proc-macro2" -version = "1.0.107" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] @@ -8395,9 +8418,9 @@ dependencies = [ [[package]] name = "prost-build" -version = "0.14.4" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" +checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ "heck 0.5.0", "itertools 0.14.0", @@ -8408,7 +8431,7 @@ dependencies = [ "prost", "prost-types", "regex", - "syn 2.0.119", + "syn 2.0.117", "tempfile", ] @@ -8422,23 +8445,23 @@ dependencies = [ "itertools 0.14.0", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "prost-types" -version = "0.14.4" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" +checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" dependencies = [ "prost", ] [[package]] name = "psm" -version = "0.1.32" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +checksum = "645dbe486e346d9b5de3ef16ede18c26e6c70ad97418f4874b8b1889d6e761ea" dependencies = [ "ar_archive_writer", "cc", @@ -8446,32 +8469,32 @@ dependencies = [ [[package]] name = "ptr_meta" -version = "0.3.2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743da816b98c921cdbe8628ef7381b76f25ecf4da599fc80aca90eae7ef70cc0" +checksum = "0b9a0cf95a1196af61d4f1cbdab967179516d9a4a4312af1f31948f8f6224a79" dependencies = [ "ptr_meta_derive", ] [[package]] name = "ptr_meta_derive" -version = "0.3.2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0" +checksum = "7347867d0a7e1208d93b46767be83e2b8f978c3dad35f775ac8d8847551d6fe1" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] name = "pulp" -version = "0.22.3" +version = "0.22.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +checksum = "2e205bb30d5b916c55e584c22201771bcf2bad9aabd5d4127f38387140c38632" dependencies = [ "bytemuck", - "cfg-if", + "cfg-if 1.0.4", "libm", "num-complex", "paste", @@ -8483,15 +8506,15 @@ dependencies = [ [[package]] name = "pulp-wasm-simd-flag" -version = "0.1.1" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" +checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" [[package]] name = "pyo3" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12" +checksum = "700d18fa267b73b9b521fd7e13580e2f446916f176cacee1ab63fcc8191f1655" dependencies = [ "chrono", "libc", @@ -8505,9 +8528,9 @@ dependencies = [ [[package]] name = "pyo3-async-runtimes" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e7364a95bf00e8377bbf9b0f09d7ff9715a29d8fcf93b47d1a967363b973178" +checksum = "b3ef68daa7316a3fac65e5e18b2203f010346de1c1c53456811a2624673ab046" dependencies = [ "futures-channel", "futures-util", @@ -8520,29 +8543,29 @@ dependencies = [ [[package]] name = "pyo3-async-runtimes-macros" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c23399970eea9c31d0ac84cee4a9d8dd05f89b1da2f4dd5bb44b32a3f66db4f8" +checksum = "faf75ff3922e6830adcaa30f3a359ce861326f6161f16a13d97adb40ba6a744a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "pyo3-build-config" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" +checksum = "7b3fc0c4d08f6bb10e71fe39dfb9e2f59c6eb6854e22ec8092f50c69a4499adb" dependencies = [ "target-lexicon", ] [[package]] name = "pyo3-ffi" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" +checksum = "dfc0b8e19df29aad7086cf977bb0c2a2f143e30567eb113e9cf72b62ca698330" dependencies = [ "libc", "pyo3-build-config", @@ -8550,27 +8573,26 @@ dependencies = [ [[package]] name = "pyo3-macros" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813" +checksum = "6100e8a4b5eba53afaa5ed078364851a0b2499c553a44c31026b929049b49dc6" dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "pyo3-macros-backend" -version = "0.28.3" +version = "0.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb" +checksum = "6143877a16e82b5a727b7127ff4cd86858a24a28d745d72f43e6f227c7b1bdb3" dependencies = [ "heck 0.5.0", "proc-macro2", - "pyo3-build-config", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -8616,16 +8638,6 @@ dependencies = [ "serde", ] -[[package]] -name = "quick-xml" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "quick_cache" version = "0.6.24" @@ -8640,19 +8652,19 @@ dependencies = [ [[package]] name = "quinn" -version = "0.11.12" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" dependencies = [ "bytes", - "cfg_aliases 0.2.2", + "cfg_aliases 0.2.1", "pin-project-lite", "quinn-proto", "quinn-udp", "rustc-hash", "rustls", "socket2", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tracing", "web-time", @@ -8666,16 +8678,16 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", - "getrandom 0.4.3", + "getrandom 0.4.2", "lru-slab", - "rand 0.10.3", + "rand 0.10.1", "rand_pcg", "ring", "rustc-hash", "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.21", + "thiserror 2.0.18", "tinyvec", "tracing", "web-time", @@ -8683,23 +8695,23 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.16" +version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" dependencies = [ - "cfg_aliases 0.2.2", + "cfg_aliases 0.2.1", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] name = "quote" -version = "1.0.47" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] @@ -8734,18 +8746,18 @@ dependencies = [ [[package]] name = "rancor" -version = "0.1.3" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b534442d0fcdb55d66f373d9cac6d33b6293a2335bc2136dbd06ce0e87d2572" +checksum = "a063ea72381527c2a0561da9c80000ef822bdd7c3241b1cc1b12100e3df081ee" dependencies = [ "ptr_meta", ] [[package]] name = "rand" -version = "0.8.8" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", "rand_chacha 0.3.1", @@ -8764,12 +8776,12 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.3" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ "chacha20", - "getrandom 0.4.3", + "getrandom 0.4.2", "rand_core 0.10.1", ] @@ -8824,7 +8836,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" dependencies = [ "num-traits", - "rand 0.8.8", + "rand 0.8.6", ] [[package]] @@ -8865,15 +8877,15 @@ dependencies = [ "brotli", "once_cell", "paste", - "rand 0.8.8", + "rand 0.8.6", "unicase", ] [[package]] name = "rangemap" -version = "1.8.0" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" +checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68" [[package]] name = "rapidhash" @@ -8890,7 +8902,7 @@ version = "11.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", ] [[package]] @@ -8936,7 +8948,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48406db8ac1f3cbc7dcdb56ec355343817958a356ff430259bb07baf7607e1e1" dependencies = [ - "pem 3.0.6", + "pem", "ring", "time", "yasna", @@ -8965,7 +8977,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" dependencies = [ "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -8983,7 +8995,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", ] [[package]] @@ -8999,32 +9011,33 @@ dependencies = [ [[package]] name = "redox_users" -version = "0.5.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ + "getrandom 0.2.17", "libredox", - "thiserror 2.0.21", + "thiserror 2.0.18", ] [[package]] name = "ref-cast" -version = "1.0.27" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.27" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -9041,9 +9054,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad" dependencies = [ "aho-corasick", "memchr", @@ -9070,18 +9083,18 @@ checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" [[package]] name = "rend" -version = "0.5.4" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "663ba70707f96e871406fe10d68128412e619b06d1d47cb91c3a4c6501176240" +checksum = "cadadef317c2f20755a64d7fdc48f9e7178ee6b0e1f7fce33fa60f1d68a276e6" dependencies = [ "bytecheck", ] [[package]] name = "reqsign-aliyun-oss" -version = "3.2.0" +version = "3.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cf3d65d37ac910073d921c1cc58c3e4e6c963795c6062eee196e6d19054dde" +checksum = "a5e6d659fcdbca6fe2d7ef109c2e28499b7be80501f1bb86c10caf5ec8ac1219" dependencies = [ "anyhow", "form_urlencoded", @@ -9096,9 +9109,9 @@ dependencies = [ [[package]] name = "reqsign-aws-core" -version = "3.2.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38c902d8ec745bd9eadd1abbcbe227f4c1fc2926b2ec8929f89234af3114500" +checksum = "bac4749b7dfa7bfaccd01eb03e9dc795ed37e3f20d6f0f38e2c67ee85ad6bc86" dependencies = [ "bytes", "form_urlencoded", @@ -9106,7 +9119,7 @@ dependencies = [ "http 1.5.0", "log", "percent-encoding", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-core", "rust-ini", "serde", @@ -9117,14 +9130,14 @@ dependencies = [ [[package]] name = "reqsign-aws-v4" -version = "3.3.1" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "906bfd028f96bfe73fdb892ce26f3b3f99b4f30feb9bd024be58bd6657f68b2b" +checksum = "ff250f0fd0b913fbd565e405acc553da0f13bde30bfb5403178c9d0313cdc15f" dependencies = [ "bytes", "http 1.5.0", "log", - "quick-xml 0.42.0", + "quick-xml 0.41.0", "reqsign-aws-core", "reqsign-core", "serde", @@ -9132,18 +9145,17 @@ dependencies = [ [[package]] name = "reqsign-azure-storage" -version = "3.3.0" +version = "3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7260e6c1d89422ba62d624a32c491b561386fb364ac4bf0959c740e34b251a2e" +checksum = "2824e7da3c2cc42ac3406c674eb57c89127fdcd97f3a73c608cfc680505ea134" dependencies = [ "anyhow", - "asyncband", "base64 0.23.1", "bytes", "form_urlencoded", "http 1.5.0", "log", - "pem 4.0.0", + "pem", "percent-encoding", "reqsign-core", "rsa", @@ -9154,33 +9166,34 @@ dependencies = [ [[package]] name = "reqsign-core" -version = "3.3.2" +version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85fed85c436b6b920e4b36310f699a77771a91e38ae483df48447bd7d162671c" +checksum = "ff052daffb0599681c50f85c59e7236438976efe991ab864edd9f3b235501a0f" dependencies = [ "anyhow", - "asyncband", "base64 0.23.1", "bytes", + "futures", "hex", "hmac 0.13.0", "http 1.5.0", "jiff", "log", + "mea", "percent-encoding", "rsa", "serde", "serde_json", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.0", "windows-sys 0.61.2", ] [[package]] name = "reqsign-file-read-tokio" -version = "3.0.7" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "586a8e198057773f9616901fd723a4bc186812b9765bc0f20368661d6169d906" +checksum = "b3235df90a6bca681aa47dd86f2393d122a6d77042aa8a7c81e218cd45c5bfc0" dependencies = [ "anyhow", "reqsign-core", @@ -9189,9 +9202,9 @@ dependencies = [ [[package]] name = "reqsign-google" -version = "3.2.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719e55931cc81b8dcd69f95f0a2def55617cb76cb3aa2f8c439e10682e46fa10" +checksum = "272a5813571885c1455ffe106f0c768577e6ce69313446d4476e8d41dcf6ac5a" dependencies = [ "bytes", "form_urlencoded", @@ -9208,9 +9221,9 @@ dependencies = [ [[package]] name = "reqsign-tencent-cos" -version = "3.0.7" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a98625e0f3eab846348b7524f1f5b5c97ffc348002845463520be371b7ab7cd" +checksum = "764629c90f7c3566a6d4e4641ebab9acd604ce02e16eda4d37c7d7e79e16ed90" dependencies = [ "anyhow", "http 1.5.0", @@ -9260,14 +9273,14 @@ dependencies = [ "tokio-rustls", "tokio-util", "tower", - "tower-http 0.6.11", + "tower-http 0.6.10", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.11", + "webpki-roots 1.0.10", ] [[package]] @@ -9305,7 +9318,7 @@ dependencies = [ "tokio-rustls", "tokio-util", "tower", - "tower-http 0.6.11", + "tower-http 0.6.10", "tower-service", "url", "wasm-bindgen", @@ -9332,26 +9345,27 @@ dependencies = [ [[package]] name = "reqwest-middleware" -version = "0.5.2" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bc3f1384cffa4f274dad2d4ddd73aed32fed8f786d96c6be8aa4e5fd3c3b58" +checksum = "199dda04a536b532d0cc04d7979e39b1c763ea749bf91507017069c00b96056f" dependencies = [ "anyhow", "async-trait", "http 1.5.0", "reqwest 0.13.5", - "thiserror 2.0.21", + "thiserror 2.0.18", "tower-service", ] [[package]] name = "rfc6979" -version = "0.4.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" dependencies = [ + "crypto-bigint 0.4.9", "hmac 0.12.1", - "subtle", + "zeroize", ] [[package]] @@ -9370,7 +9384,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", - "cfg-if", + "cfg-if 1.0.4", "getrandom 0.2.17", "libc", "untrusted 0.9.0", @@ -9379,14 +9393,14 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.8.18" +version = "0.8.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9776093b7ca170454ab1406954f7b7d97a57c51dc6c0642957fb2ef25c2d399" +checksum = "815cc8a37159a463064825246cadb07961e25cd9885908606f6d08a98d8f8874" dependencies = [ "bytecheck", "bytes", "hashbrown 0.17.1", - "indexmap 2.14.2", + "indexmap 2.14.0", "munge", "ptr_meta", "rancor", @@ -9398,13 +9412,13 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.8.18" +version = "0.8.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c25ef604ac7dd839d44d64648952ea23c97866f124ff671b0ed2cf3ad9bb06e" +checksum = "c0ed1a78a1b19d184b0daa629dd9a024573173ec7d485b287cb369fb3607cc1c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -9435,11 +9449,11 @@ dependencies = [ "num-integer", "num-traits", "pkcs1", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", "sha2 0.10.9", - "signature", - "spki", + "signature 2.2.0", + "spki 0.7.3", "subtle", "zeroize", ] @@ -9473,7 +9487,7 @@ version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "glob", "proc-macro-crate", "proc-macro2", @@ -9481,7 +9495,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.119", + "syn 2.0.117", "unicode-ident", ] @@ -9491,21 +9505,21 @@ version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "ordered-multimap", ] [[package]] name = "rustc-demangle" -version = "0.1.28" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" +checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" [[package]] name = "rustc-hash" -version = "2.1.3" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" [[package]] name = "rustc_version" @@ -9522,7 +9536,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "errno", "libc", "linux-raw-sys 0.4.15", @@ -9531,11 +9545,11 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "errno", "libc", "linux-raw-sys 0.12.1", @@ -9560,9 +9574,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.5" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -9572,9 +9586,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" dependencies = [ "web-time", "zeroize", @@ -9582,9 +9596,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier" -version = "0.7.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", @@ -9603,9 +9617,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier-android" -version = "0.2.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" @@ -9621,9 +9635,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.23" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "rustyline" @@ -9631,8 +9645,8 @@ version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7803e8936da37efd9b6d4478277f4b2b9bb5cdb37a113e8d63222e58da647e63" dependencies = [ - "bitflags 2.13.2", - "cfg-if", + "bitflags 2.11.1", + "cfg-if 1.0.4", "clipboard-win", "fd-lock", "home", @@ -9699,9 +9713,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.30" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" dependencies = [ "windows-sys 0.61.2", ] @@ -9720,9 +9734,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.3" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" dependencies = [ "dyn-clone", "ref-cast", @@ -9755,14 +9769,14 @@ dependencies = [ [[package]] name = "sec1" -version = "0.7.3" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" dependencies = [ "base16ct", - "der", + "der 0.6.1", "generic-array", - "pkcs8", + "pkcs8 0.9.0", "subtle", "zeroize", ] @@ -9783,7 +9797,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -9839,7 +9853,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.3", ] [[package]] @@ -9859,7 +9873,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "foldhash 0.2.0", - "indexmap 2.14.2", + "indexmap 2.14.0", "itoa", "memchr", "serde", @@ -9889,13 +9903,13 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.21" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -9930,10 +9944,10 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.14.2", + "indexmap 2.14.0", "jiff", "schemars 0.9.0", - "schemars 1.2.3", + "schemars 1.2.1", "serde_core", "serde_json", "serde_with_macros", @@ -9949,7 +9963,7 @@ dependencies = [ "darling 0.24.1", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.3", ] [[package]] @@ -9958,7 +9972,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" dependencies = [ - "indexmap 2.14.2", + "indexmap 2.14.0", "itoa", "ryu", "serde", @@ -9987,16 +10001,16 @@ checksum = "94e153fc76e1c6a068703d6d29c508a0b15c061c4b7e43da59cc097bc342673c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "sha1" -version = "0.10.7" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "cpufeatures 0.2.17", "digest 0.10.7", ] @@ -10007,8 +10021,8 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", + "cfg-if 1.0.4", + "cpufeatures 0.3.0", "digest 0.11.3", ] @@ -10024,19 +10038,19 @@ version = "0.10.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "cpufeatures 0.2.17", "digest 0.10.7", ] [[package]] name = "sha2" -version = "0.11.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", + "cfg-if 1.0.4", + "cpufeatures 0.3.0", "digest 0.11.3", ] @@ -10062,9 +10076,15 @@ dependencies = [ [[package]] name = "shlex" -version = "2.0.1" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "sif-itree" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7f45b8998ced5134fb1d75732c77842a3e888f19c1ff98481822e8fbfbf930b" [[package]] name = "signal-hook-registry" @@ -10076,6 +10096,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "1.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "signature" version = "2.2.0" @@ -10101,15 +10131,15 @@ dependencies = [ [[package]] name = "simd-adler32" -version = "0.3.10" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" [[package]] name = "simd_cesu8" -version = "1.2.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" dependencies = [ "rustc_version", "simdutf8", @@ -10123,15 +10153,15 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" -version = "1.0.4" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" [[package]] name = "sketches-ddsketch" -version = "0.3.2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45f82fa313d625dd72aaa65ec0c9f8c95407add0510c1bef3c18ea7257ec34ce" +checksum = "0c6f73aeb92d671e0cc4dca167e59b2deb6387c375391bc99ee743f326994a2b" [[package]] name = "slab" @@ -10141,9 +10171,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.4" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "smartstring" @@ -10167,11 +10197,11 @@ dependencies = [ [[package]] name = "snafu" -version = "0.9.2" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e45cb604038abb7b926b679887b3226d8d0f23874b66623625a0454be425a4b7" +checksum = "d1d4bced6a69f90b2056c03dcff2c4737f98d6fb9e0853493996e1d253ca29c6" dependencies = [ - "snafu-derive 0.9.2", + "snafu-derive 0.9.0", ] [[package]] @@ -10183,26 +10213,26 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "snafu-derive" -version = "0.9.2" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "287f59010008f0d7cf5e3b03196d666c1acc46c8d3e9cf34c28a1a7157601e72" +checksum = "54254b8531cafa275c5e096f62d48c81435d1015405a91198ddb11e967301d40" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "socket2" -version = "0.6.5" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", "windows-sys 0.61.2", @@ -10246,6 +10276,16 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spki" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" +dependencies = [ + "base64ct", + "der 0.6.1", +] + [[package]] name = "spki" version = "0.7.3" @@ -10253,7 +10293,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", - "der", + "der 0.7.10", ] [[package]] @@ -10295,7 +10335,7 @@ checksum = "a6dd45d8fc1c79299bfbb7190e42ccbbdf6a5f52e4a6ad98d92357ea965bd289" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -10306,12 +10346,12 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stacker" -version = "0.1.25" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +checksum = "640c8cdd92b6b12f5bcb1803ca3bbf5ab96e5e6b6b96b9ab77dabe9e880b3190" dependencies = [ "cc", - "cfg-if", + "cfg-if 1.0.4", "libc", "psm", "windows-sys 0.61.2", @@ -10347,9 +10387,9 @@ checksum = "e51f1e89f093f99e7432c491c382b88a6860a5adbe6bf02574bf0a08efff1978" [[package]] name = "stop-words" -version = "0.10.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1ed527ae13a020ac2404e32746ecee62d632aafe64f8e0df2bb3545ae96f6d1" +checksum = "d68df56303396bcfb639455b3c166804aeb7994005010aab5e9e8a1277b8871d" dependencies = [ "serde_json", ] @@ -10406,7 +10446,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -10418,7 +10458,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -10434,7 +10474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "332615d90111d8eeaf86a84dc9bbe9f65d0d8c5cf11b4caccedc37754eb0dcfd" dependencies = [ "debugid", - "memmap2 0.9.12", + "memmap2 0.9.10", "stable_deref_trait", "uuid", ] @@ -10469,9 +10509,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.119" +version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", @@ -10480,9 +10520,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" dependencies = [ "proc-macro2", "quote", @@ -10500,13 +10540,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.14.0" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -10515,7 +10555,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "byteorder", "enum-as-inner", "libc", @@ -10529,7 +10569,7 @@ version = "0.30.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "core-foundation-sys", "libc", "ntapi", @@ -10539,16 +10579,15 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.39.6" +version = "0.38.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" +checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" dependencies = [ "libc", "memchr", "ntapi", "objc2-core-foundation", "objc2-io-kit", - "objc2-open-directory", "windows 0.62.2", ] @@ -10558,7 +10597,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -10604,9 +10643,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.4.2", "once_cell", - "rustix 1.1.5", + "rustix 1.1.4", "windows-sys 0.61.2", ] @@ -10639,7 +10678,7 @@ checksum = "c26ef8b00e4d382e59f6a8ddb3cd790b3a5bb29f21a358a9a69ea2f29f13f27b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -10648,7 +10687,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "944ad38adcbb71eaa682c56bceeb079e4ca82b4b3edc2a0fde5cb297b77dac8d" dependencies = [ - "syn 2.0.119", + "syn 2.0.117", "test-log-core", ] @@ -10663,11 +10702,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.21" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ - "thiserror-impl 2.0.21", + "thiserror-impl 2.0.18", ] [[package]] @@ -10678,18 +10717,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] name = "thiserror-impl" -version = "2.0.21" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -10703,20 +10742,21 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.10" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", ] [[package]] name = "time" -version = "0.3.55" +version = "0.3.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", + "itoa", "num-conv", "powerfmt", "serde_core", @@ -10726,15 +10766,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.9" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] name = "time-macros" -version = "0.2.32" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" dependencies = [ "num-conv", "time-core", @@ -10751,9 +10791,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.5" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" dependencies = [ "displaydoc", "serde_core", @@ -10772,9 +10812,18 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.13.3" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokenizers" @@ -10794,7 +10843,7 @@ dependencies = [ "monostate", "onig", "paste", - "rand 0.8.8", + "rand 0.8.6", "rayon", "rayon-cond", "regex", @@ -10827,13 +10876,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.7.2" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -10848,20 +10897,20 @@ dependencies = [ [[package]] name = "tokio-retry" -version = "0.3.2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a129d95275ebf4c493ec53bf0f8cd95f5ac161bc4f381700809a54f595d4470" +checksum = "40f644c762e9d396831ae2f8935c954b0d758c4532e924bead0f666d0c1c8640" dependencies = [ "pin-project-lite", - "rand 0.10.3", + "rand 0.10.1", "tokio", ] [[package]] name = "tokio-rustls" -version = "0.26.6" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" dependencies = [ "rustls", "tokio", @@ -10869,9 +10918,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.19" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" dependencies = [ "futures-core", "pin-project-lite", @@ -10881,14 +10930,13 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.20" +version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" dependencies = [ "bytes", "futures-core", "futures-sink", - "libc", "pin-project-lite", "tokio", ] @@ -10914,7 +10962,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d01145a2c788d6aae4cd653afec1e8332534d7d783d01897cefcafe4428de992" dependencies = [ "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -10940,9 +10988,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.2+spec-1.1.0" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" dependencies = [ "serde_core", ] @@ -10953,7 +11001,7 @@ version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap 2.14.2", + "indexmap 2.14.0", "serde", "serde_spanned", "toml_datetime 0.6.11", @@ -10963,23 +11011,23 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.17+spec-1.1.0" +version = "0.25.11+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" dependencies = [ - "indexmap 2.14.2", - "toml_datetime 1.1.2+spec-1.1.0", + "indexmap 2.14.0", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", - "winnow 1.0.4", + "winnow 1.0.3", ] [[package]] name = "toml_parser" -version = "1.1.5+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ - "winnow 1.0.4", + "winnow 1.0.3", ] [[package]] @@ -11038,7 +11086,7 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap 2.14.2", + "indexmap 2.14.0", "pin-project-lite", "slab", "sync_wrapper", @@ -11055,7 +11103,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ - "bitflags 2.13.2", + "bitflags 2.11.1", "bytes", "http 1.5.0", "http-body 1.1.0", @@ -11068,12 +11116,12 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.11" +version = "0.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +checksum = "68d6fdd9f81c2819c9a8b0e0cd91660e7746a8e6ea2ba7c6b2b057985f6bcb51" dependencies = [ "async-compression", - "bitflags 2.13.2", + "bitflags 2.11.1", "bytes", "futures-core", "futures-util", @@ -11121,7 +11169,7 @@ checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" dependencies = [ "crossbeam-channel", "symlink", - "thiserror 2.0.21", + "thiserror 2.0.18", "time", "tracing-subscriber", ] @@ -11134,7 +11182,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -11197,24 +11245,24 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "twox-hash" -version = "2.1.5" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" +checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c" dependencies = [ - "rand 0.10.3", + "rand 0.9.5", ] [[package]] name = "typed-path" -version = "0.12.4" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" [[package]] name = "typenum" -version = "1.20.1" +version = "1.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" [[package]] name = "typewit" @@ -11224,27 +11272,27 @@ checksum = "214ca0b2191785cbc06209b9ca1861e048e39b5ba33574b3cedd58363d5bb5f6" [[package]] name = "unicase" -version = "2.10.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" [[package]] name = "unicode-blocks" -version = "0.1.10" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "328edfd6d0bb91a22e592bed3a3b54c7b1f5c92a517f5a7aca24a2caef10c363" +checksum = "6b12e05d9e06373163a9bb6bb8c263c261b396643a99445fe6b9811fd376581b" [[package]] name = "unicode-ident" -version = "1.0.27" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-normalization" -version = "0.1.26" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" dependencies = [ "tinyvec", ] @@ -11269,9 +11317,9 @@ dependencies = [ [[package]] name = "unicode-segmentation" -version = "1.13.3" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" [[package]] name = "unicode-width" @@ -11285,6 +11333,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + [[package]] name = "unicode_categories" version = "0.1.1" @@ -11371,7 +11425,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ - "getrandom 0.4.3", + "getrandom 0.4.2", "js-sys", "serde_core", "sha1_smol", @@ -11414,9 +11468,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" dependencies = [ "try-lock", ] @@ -11438,11 +11492,20 @@ dependencies = [ [[package]] name = "wasip2" -version = "1.0.4+wasi-0.2.12" +version = "1.0.3+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" dependencies = [ - "wit-bindgen", + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", ] [[package]] @@ -11456,11 +11519,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "once_cell", "rustversion", "wasm-bindgen-macro", @@ -11469,20 +11532,19 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.79" +version = "0.4.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" dependencies = [ "js-sys", - "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11490,26 +11552,48 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap 2.14.0", + "wasm-encoder", + "wasmparser", +] + [[package]] name = "wasm-streams" version = "0.4.2" @@ -11537,10 +11621,22 @@ dependencies = [ ] [[package]] -name = "web-sys" -version = "0.3.106" +name = "wasmparser" +version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags 2.11.1", + "hashbrown 0.15.5", + "indexmap 2.14.0", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" dependencies = [ "js-sys", "wasm-bindgen", @@ -11574,9 +11670,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.11" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] @@ -11587,14 +11683,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.11", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.11" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -11613,9 +11709,9 @@ dependencies = [ [[package]] name = "whoami" -version = "2.1.3" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +checksum = "998767ef88740d1f5b0682a9c53c24431453923962269c2db68ee43788c5a40d" dependencies = [ "libc", "libredox", @@ -11737,7 +11833,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -11748,7 +11844,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -12047,9 +12143,9 @@ dependencies = [ [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" dependencies = [ "memchr", ] @@ -12060,6 +12156,15 @@ version = "0.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -12067,10 +12172,89 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] -name = "wkb" -version = "0.9.3" +name = "wit-bindgen-core" +version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04ab2f2845abe967a213998446345a1a6fc9a8f318cd88f668a8e507861d13bc" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck 0.5.0", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck 0.5.0", + "indexmap 2.14.0", + "prettyplease", + "syn 2.0.117", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.117", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags 2.11.1", + "indexmap 2.14.0", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap 2.14.0", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "wkb" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a120b336c7ad17749026d50427c23d838ecb50cd64aaea6254b5030152f890a9" dependencies = [ "byteorder", "geo-traits", @@ -12093,9 +12277,9 @@ dependencies = [ [[package]] name = "writeable" -version = "0.6.4" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" [[package]] name = "wyz" @@ -12108,21 +12292,20 @@ dependencies = [ [[package]] name = "xet-client" -version = "1.7.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15500e5fc9e17be15224f9e34cb07d41fb2805d9dbbf7bd3507c982fd1eb3efd" +checksum = "c3b8da8cc70aa2e3c500c0400e012df82c656ab9fca47f9f939fffc5afd89aca" dependencies = [ "anyhow", "async-trait", "base64 0.22.1", "bytes", - "chrono", "crc32fast", "futures", "http 1.5.0", "hyper", "more-asserts", - "rand 0.10.3", + "rand 0.10.1", "redb", "reqwest 0.13.5", "reqwest-middleware", @@ -12131,14 +12314,13 @@ dependencies = [ "serde_repr", "statrs", "tempfile", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tokio-retry", "tokio_with_wasm", "tracing", "url", "urlencoding", - "uuid", "web-time", "xet-core-structures", "xet-runtime", @@ -12146,9 +12328,9 @@ dependencies = [ [[package]] name = "xet-core-structures" -version = "1.7.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5080d5803c8bf15fa56ef934050a46b225801bad3ea4cb8bb3c46c5c37976516" +checksum = "73503c223783dccc864abde22115e09d12f190448a0baf58ab2c54bc709e2f99" dependencies = [ "async-trait", "base64 0.22.1", @@ -12158,17 +12340,17 @@ dependencies = [ "countio", "futures", "futures-util", - "getrandom 0.4.3", + "getrandom 0.4.2", "heapify", "itertools 0.14.0", - "lz4_flex", + "lz4_flex 0.13.1", "more-asserts", - "rand 0.10.3", + "rand 0.10.1", "regex", "safe-transmute", "serde", "static_assertions", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tokio-util", "tracing", @@ -12179,9 +12361,9 @@ dependencies = [ [[package]] name = "xet-data" -version = "1.7.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1287a1657fb67de846030f6605a9960dcdad401c467b490657e6e909d2e0d1c0" +checksum = "c89052ec5dec2187cad30b86af92cc24fd61c4a57a795f1ff7ff5f38d49184eb" dependencies = [ "anyhow", "async-trait", @@ -12191,12 +12373,12 @@ dependencies = [ "http 1.5.0", "itertools 0.14.0", "more-asserts", - "rand 0.10.3", + "rand 0.10.1", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.0", "tempfile", - "thiserror 2.0.21", + "thiserror 2.0.18", "tokio", "tokio-util", "tokio_with_wasm", @@ -12211,9 +12393,9 @@ dependencies = [ [[package]] name = "xet-runtime" -version = "1.7.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "921953c885ce83e02b21e8d26444b75c78c9e83076699ced08d5c6fc1cdb48ac" +checksum = "af5c60d5eed38ab4c576f4421bae835e7bd07631fb381705605529d2015c106b" dependencies = [ "anyhow", "async-trait", @@ -12231,13 +12413,13 @@ dependencies = [ "more-asserts", "oneshot", "pin-project", - "rand 0.10.3", + "rand 0.10.1", "reqwest 0.13.5", "serde", "serde_json", "shellexpand", - "sysinfo 0.39.6", - "thiserror 2.0.21", + "sysinfo 0.38.4", + "thiserror 2.0.18", "tokio", "tokio-util", "tokio_with_wasm", @@ -12272,9 +12454,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.4" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -12283,34 +12465,34 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.4" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.63" +version = "0.8.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.63" +version = "0.8.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 2.0.117", ] [[package]] @@ -12324,27 +12506,27 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.8" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", "synstructure", ] [[package]] name = "zeroize" -version = "1.9.1" +version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" [[package]] name = "zerotrie" -version = "0.2.5" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" dependencies = [ "displaydoc", "yoke", @@ -12354,9 +12536,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.9" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" dependencies = [ "serde", "yoke", @@ -12366,13 +12548,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.7" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 2.0.117", ] [[package]] @@ -12382,22 +12564,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" dependencies = [ "crc32fast", - "indexmap 2.14.2", + "indexmap 2.14.0", "memchr", "typed-path", ] -[[package]] -name = "zlib-rs" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" - [[package]] name = "zmij" -version = "1.0.23" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" [[package]] name = "zstd" @@ -12405,7 +12581,7 @@ version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" dependencies = [ - "zstd-safe 7.3.0", + "zstd-safe 7.2.4", ] [[package]] @@ -12419,9 +12595,9 @@ dependencies = [ [[package]] name = "zstd-safe" -version = "7.3.0" +version = "7.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" dependencies = [ "zstd-sys", ] diff --git a/Cargo.toml b/Cargo.toml index 343813b65..ce5a5edae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,52 +16,52 @@ repository = "https://github.com/lancedb/lancedb" description = "Serverless, low-latency vector database for AI applications" keywords = ["lancedb", "lance", "database", "vector", "search"] categories = ["database-implementations"] -rust-version = "1.94.0" +rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.3", default-features = false, "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.3", default-features = false, "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.3", default-features = false, "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { version = "=15.0.0-beta.3", path = "python/vendor/lance-arrow" } +lance = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.6", default-features = false, "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.6", "tag" = "v15.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" # Note that this one does not include pyarrow -arrow = { version = "58.0.0", optional = false } -arrow-array = "58.0.0" -arrow-buffer = "58.0.0" -arrow-data = "58.0.0" -arrow-ipc = "58.0.0" -arrow-ord = "58.0.0" -arrow-schema = "58.0.0" -arrow-select = "58.0.0" -arrow-cast = "58.0.0" -arrow-flight = { version = "58.0.0", features = ["flight-sql-experimental"] } +arrow = { version = "59.2.0", optional = false } +arrow-array = "59.2.0" +arrow-buffer = "59.2.0" +arrow-data = "59.2.0" +arrow-ipc = "59.2.0" +arrow-ord = "59.2.0" +arrow-schema = "59.2.0" +arrow-select = "59.2.0" +arrow-cast = "59.2.0" +arrow-flight = { version = "59.2.0", features = ["flight-sql-experimental"] } async-trait = "0" # Smithy JSON 0.63 requires the pre-1.7 Document representation; allow the MSRV pin. aws-smithy-types = ">=1.3.6, <1.7" base64 = "0.22" bytes = "1" -datafusion = { version = "54.0.0", default-features = false } -datafusion-catalog = "54.0.0" -datafusion-common = { version = "54.0.0", default-features = false } -datafusion-execution = "54.0.0" -datafusion-expr = "54.0.0" -datafusion-functions = "54.0.0" -datafusion-physical-plan = "54.0.0" -datafusion-physical-expr = "54.0.0" -datafusion-sql = "54.0.0" +datafusion = { version = "55.0.0", default-features = false } +datafusion-catalog = "55.0.0" +datafusion-common = { version = "55.0.0", default-features = false } +datafusion-execution = "55.0.0" +datafusion-expr = "55.0.0" +datafusion-functions = "55.0.0" +datafusion-physical-plan = "55.0.0" +datafusion-physical-expr = "55.0.0" +datafusion-sql = "55.0.0" env_logger = "0.11" half = { "version" = "2.7.1", default-features = false, features = [ "num-traits", @@ -94,10 +94,6 @@ tracing = "0.1" uuid = { version = "1.7.0", features = ["v4", "v7"] } chrono = { version = "0.4", default-features = false, features = ["clock"] } -[patch."https://github.com/lance-format/lance.git"] -# Carry the offset-safe validity fix until it is available in a Lance release. -lance-arrow = { path = "python/vendor/lance-arrow" } - [patch.crates-io] # Lance v14.0.0-beta.18 requires multipart write modes from this upstream revision. object_store = { git = "https://github.com/apache/arrow-rs-object-store.git", rev = "c10758c207c0103355f940f0c736fb8ecb157b04" } diff --git a/java/pom.xml b/java/pom.xml index aa5be0b95..2bccd2510 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.3 + 15.0.0-beta.6 2.18.11 false 2.30.0 diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index c98292fd4..b41d98767 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -1731,12 +1731,13 @@ describe("When creating an index", () => { config: Index.ivfFlat({ numPartitions: 2, targetPartitionSize: 100 }), }); + // Lance records the target size the partition count implies: 300 rows / 2. const indices = await tbl.listIndices(); expect( (indices[0].indexDetails as Record)[ "target_partition_size" ], - ).toBeUndefined(); + ).toBe(150); }); it("should allow me to replace (or not) an existing index", async () => { diff --git a/python/Cargo.toml b/python/Cargo.toml index 07b7f2e39..0695180cd 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -8,7 +8,7 @@ license.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true -rust-version = "1.94.0" +rust-version = "1.95.0" [lib] name = "_lancedb" @@ -30,9 +30,9 @@ env_logger.workspace = true log.workspace = true # Maturin enables extension-module mode for Python builds. Keeping it out of # Cargo features lets Rust unit tests link against libpython. -pyo3 = { version = "0.28", features = ["abi3-py310", "chrono", "uuid"] } +pyo3 = { version = "0.29", features = ["abi3-py310", "chrono", "uuid"] } chrono.workspace = true -pyo3-async-runtimes = { version = "0.28", features = [ +pyo3-async-runtimes = { version = "0.29", features = [ "attributes", "tokio-runtime", ] } @@ -46,7 +46,7 @@ uuid.workspace = true libc = "0.2" [build-dependencies] -pyo3-build-config = { version = "0.28", features = ["abi3-py310"] } +pyo3-build-config = "0.29" [features] default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"] diff --git a/python/pyproject.toml b/python/pyproject.toml index f71eac182..1a6c64cee 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow<25", "pyarrow-stubs>=16.0", - "pylance==15.0.0b3", + "pylance==15.0.0b6", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index be42dc802..b68f15912 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -5921,7 +5921,8 @@ class AsyncTable: """Remove the RTEWriteSpec from this table. Reverts to the standard `merge_insert` write path. Errors if no spec - is currently set. + is currently set, or if the RTE still holds rows that have not been + merged into the base table, since removing it would drop them. """ await self._inner.disable_rte() diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 486c1ce62..6714f35d9 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -386,7 +386,7 @@ def test_custom_stop_words_list(table): assert [token.text for token in tokens] == ["the", "data"] empty_tokens = ldb.tokenize("the lance data", stem=False, custom_stop_words=[]) assert [token.text for token in empty_tokens] == ["the", "lance", "data"] - with pytest.raises(TypeError, match=r"custom_stop_words.*int"): + with pytest.raises(TypeError, match=r"'int' object is not an instance of 'str'"): ldb.tokenize( "the lance data", custom_stop_words=["lance", 42], diff --git a/python/python/tests/test_package_metadata.py b/python/python/tests/test_package_metadata.py index 27def814f..58f4e7267 100644 --- a/python/python/tests/test_package_metadata.py +++ b/python/python/tests/test_package_metadata.py @@ -32,8 +32,10 @@ def test_pyo3_abi_matches_minimum_supported_python(): expected_abi = f"abi3-py{major}{minor}" configured_abis = re.findall(r'"(abi3-py\d+)"', cargo_manifest) - assert configured_abis == [expected_abi, expected_abi], ( - "the pyo3 runtime and build ABI features must both match requires-python" + # PyO3 0.29 configures the ABI through the runtime dependency; its + # build-config crate no longer exposes ABI features. + assert configured_abis == [expected_abi], ( + "the pyo3 runtime ABI feature must match requires-python" ) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 375eec40c..f4efb1787 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1417,6 +1417,7 @@ def test_branches_preserve_namespace(tmp_path): "lance" ) # namespace_path routes through lance's DirectoryNamespace db = lancedb.connect(tmp_path) + db.create_namespace(["ns1"]) table = db.create_table("t", [{"id": 1}], namespace_path=["ns1"]) assert table.namespace == ["ns1"] diff --git a/python/uv.lock b/python/uv.lock index 3158220dd..9101dba74 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2007,7 +2007,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b3" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b6" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -3938,7 +3938,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b3" +version = "15.0.0b6" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -3948,12 +3948,10 @@ dependencies = [ { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1ttHFr/pylance-15.0.0b3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:aaca475121cef79ada6fc19e2e2b54860e411cc8291f9ffa5643500264513086" }, - { url = "https://pypi.fury.io/lance-format/-/ver_19DzNz/pylance-15.0.0b3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5632f269b9e138b9ed3e5c7b788dfe27e04debab9d0f4c72be468f56d4a0d45a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_20XdL/pylance-15.0.0b3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bdc92d7dc4d38323452543f71e61b493c3cfb5129dade33175f478e394b1959" }, - { url = "https://pypi.fury.io/lance-format/-/ver_YBklr/pylance-15.0.0b3-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:6fcaced6f675f027979e1928284e104ae45eb8282d7c1eb0e51e4a5b92b93392" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1HLHhZ/pylance-15.0.0b3-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f19240f3ccd621b746062fd2825e9340b99131c2cbda7ed5b226b6f7871b73f4" }, - { url = "https://pypi.fury.io/lance-format/-/ver_24P9Ax/pylance-15.0.0b3-cp310-abi3-win_amd64.whl", hash = "sha256:3f964e4ed093b6f170601d40772fcd3525fd73d15fd56eb30d884a446668d602" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2jARvj/pylance-15.0.0b6-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:88bd0646118c57e1c0a3118d04162323a74ebea28578f362977c927cdcb0f0c9" }, + { url = "https://pypi.fury.io/lance-format/-/ver_28yD6d/pylance-15.0.0b6-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:66613ecb88dcb8e02f0cd21d241987018d924b9f587cef4015bf7ea1815ab44f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1Us94M/pylance-15.0.0b6-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d0765efab1f21b4697207ab75b9d391f1962813afb08e78db794eeea280c0bcc" }, + { url = "https://pypi.fury.io/lance-format/-/ver_ccoue/pylance-15.0.0b6-cp310-abi3-win_amd64.whl", hash = "sha256:f21eb48c6ec5d2269bb1817b2c0bb036956383d05033fb54278c4df64251ead4" }, ] [[package]] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 264c0be4d..64252f772 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -47,7 +47,7 @@ lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lind lance-table = { workspace = true } lance-linalg = { workspace = true } lance-encoding = { workspace = true } -lance-arrow = { "version" = "=15.0.0-beta.3", "tag" = "v15.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { workspace = true } lance-namespace = { workspace = true } lance-namespace-impls = { workspace = true } metrics = { workspace = true, optional = true } diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 426df0a1f..df9291647 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -17,7 +17,7 @@ anyhow.workspace = true arrow-array.workspace = true arrow-buffer.workspace = true arrow-cast.workspace = true -arrow-json = "58.0.0" +arrow-json = "59.2.0" arrow-schema.workspace = true async-trait.workspace = true clap = { version = "4.5.13", features = ["derive", "env"] } diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 9f7e3eb1f..1072b7684 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -254,6 +254,7 @@ async fn replace_fragments(dataset: Dataset, stream: SendableRecordBatchStream) update_mode: None, inserted_rows_filter: Some(inserted_rows_filter), updated_fragment_offsets: None, + mem_wal_dir_id: None, }, None, )) @@ -663,6 +664,7 @@ mod tests { update_mode: None, inserted_rows_filter: Some(filter), updated_fragment_offsets: None, + mem_wal_dir_id: None, }, None, )) diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 70684e84f..f48d98a90 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -1862,6 +1862,16 @@ impl DisplayAs for TakeRestoreExec { } impl ExecutionPlan for TakeRestoreExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "TakeRestoreExec" } diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index 8a735fa03..ebae823e1 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -589,6 +589,16 @@ impl DisplayAs for RemoteWriteExec { } impl ExecutionPlan for RemoteWriteExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { Self::static_name() } @@ -1149,6 +1159,16 @@ mod tests { } impl ExecutionPlan for ErroringExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "ErroringExec" } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 6ae31fd9e..173ddc815 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2075,7 +2075,9 @@ impl Table { /// Remove the [`RTEWriteSpec`] from this table, reverting to the standard /// `merge_insert` write path. /// - /// Errors if no spec is currently set. + /// Errors if no spec is currently set, or if the RTE still holds rows that + /// have not been merged into the base table, since removing it would drop + /// them. pub async fn disable_rte(&self) -> Result<()> { self.inner.disable_rte().await } diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 09a751d7a..f2ec6dc4a 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -3576,9 +3576,8 @@ mod tests { assert!(matches!(err, Error::NotSupported { .. }), "declare won"); } - /// The gate's reproducer: after catch-up activation, an LSM write, and - /// unset, retained SSTable rows survive without a live spec. The catch-up - /// flag is the durable marker; declaration refuses on it. + /// Rows written through the RTE keep the spec installed, since + /// `disable_rte` refuses while they are unmerged, so declaration refuses. #[tokio::test] #[cfg_attr( not(feature = "experimental-functions"), @@ -3622,7 +3621,8 @@ mod tests { .execute(Box::new(RecordBatchIterator::new(vec![Ok(batch)], schema))) .await .unwrap(); - table.disable_rte().await.unwrap(); + // The RTE holds the written rows, so unsetting it is refused. + table.disable_rte().await.unwrap_err(); let err = add_computed(&table, &[("doubled".into(), "value * 2".into())]) .await diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 8f187d465..81df7d300 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -104,6 +104,16 @@ impl DisplayAs for MetadataEraserExec { } impl ExecutionPlan for MetadataEraserExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "MetadataEraserExec" } @@ -157,8 +167,21 @@ impl ExecutionPlan for MetadataEraserExec { ) } - fn partition_statistics(&self, partition: Option) -> DataFusionResult> { - self.input.partition_statistics(partition) + fn child_stats_requests( + &self, + partition: Option, + ) -> Vec { + vec![datafusion_physical_plan::statistics::ChildStats::At( + partition, + )] + } + + fn statistics_from_inputs( + &self, + input_stats: &[Arc], + _args: &datafusion_physical_plan::statistics::StatisticsArgs, + ) -> DataFusionResult> { + Ok(input_stats[0].clone()) } fn supports_limit_pushdown(&self) -> bool { @@ -1398,7 +1421,9 @@ pub mod tests { assert_eq!(physical_plan.name(), "MetadataEraserExec"); - let partition_stats = physical_plan.partition_statistics(None).unwrap(); + let partition_stats = datafusion_physical_plan::statistics::StatisticsContext::new() + .compute(physical_plan.as_ref(), &Default::default()) + .unwrap(); assert!(matches!(partition_stats.num_rows, Precision::Exact(10))); } @@ -1492,7 +1517,9 @@ pub mod tests { .await .unwrap(); - let rewired = foo.with_new_children(vec![tbl2.clone()]).unwrap(); + let rewired = + datafusion_physical_plan::replace_children_if_necessary(foo, vec![tbl2.clone()]) + .unwrap(); assert_eq!(rewired.schema(), tbl2.schema()); } } diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index b9bd2396e..ec1e603d2 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -141,6 +141,16 @@ impl DisplayAs for InsertExec { } impl ExecutionPlan for InsertExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { Self::static_name() } diff --git a/rust/lancedb/src/table/datafusion/scannable_exec.rs b/rust/lancedb/src/table/datafusion/scannable_exec.rs index b3a4cc536..dd9f5e681 100644 --- a/rust/lancedb/src/table/datafusion/scannable_exec.rs +++ b/rust/lancedb/src/table/datafusion/scannable_exec.rs @@ -62,6 +62,16 @@ impl DisplayAs for ScannableExec { } impl ExecutionPlan for ScannableExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "ScannableExec" } diff --git a/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs b/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs index 20de93148..06f9ba6d9 100644 --- a/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs +++ b/rust/lancedb/src/table/datafusion/udtf/duplicate_pairs.rs @@ -507,6 +507,16 @@ impl DisplayAs for DuplicatePairsExec { } impl ExecutionPlan for DuplicatePairsExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "DuplicatePairsExec" } diff --git a/rust/lancedb/src/table/datafusion/udtf/vector_query.rs b/rust/lancedb/src/table/datafusion/udtf/vector_query.rs index 543a59589..6b59a623b 100644 --- a/rust/lancedb/src/table/datafusion/udtf/vector_query.rs +++ b/rust/lancedb/src/table/datafusion/udtf/vector_query.rs @@ -373,6 +373,16 @@ impl DisplayAs for VectorDedupExec { } impl ExecutionPlan for VectorDedupExec { + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion_common::Result< + datafusion_common::tree_node::TreeNodeRecursion, + >, + ) -> datafusion_common::Result { + Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue) + } fn name(&self) -> &str { "VectorDedupExec" } diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index a066a4d6d..2d26e1c02 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -1453,6 +1453,132 @@ mod lsm_tests { ); } + /// Another process re-initializing the MemWAL retires this process's + /// cached writer: its rows are not read, and the next write opens a + /// writer for the new MemWAL. + /// + /// `disable_rte` refuses while the writer holds rows, so the MemWAL index + /// is dropped through Lance directly, standing in for a write that lands + /// after that check. The writer's rows are lost to the base table either + /// way; what this pins is that they are not served from a directory the + /// index no longer names. + #[tokio::test] + async fn lsm_writer_of_a_retired_mem_wal_is_replaced() { + use lance::index::DatasetIndexExt; + + let dir = tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let conn = connect(uri) + .read_consistency_interval(std::time::Duration::ZERO) + .execute() + .await + .unwrap(); + let table = conn + .create_table("t", id_value_reader(vec![1, 2, 3])) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + lsm_upsert(&table, vec![4, 5]).await; + let retired_dir_id = mem_wal_dir_id(&table).await; + + let mut dataset = lance::Dataset::open(&table.uri().await.unwrap()) + .await + .unwrap(); + dataset + .drop_index(lance_index::mem_wal::MEM_WAL_INDEX_NAME) + .await + .unwrap(); + let other = connect(uri) + .execute() + .await + .unwrap() + .open_table("t") + .execute() + .await + .unwrap(); + other.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + let dir_id = mem_wal_dir_id(&table).await; + assert_ne!(dir_id, retired_dir_id); + + let ids = || async { + let rows = collect_id_value(table.query().execute().await.unwrap()).await; + rows.into_iter().map(|(id, _)| id).collect::>() + }; + assert_eq!(ids().await, vec![1, 2, 3]); + + lsm_upsert(&table, vec![6]).await; + assert_eq!(ids().await, vec![1, 2, 3, 6]); + let native = table.as_native().unwrap(); + assert!( + native + .dataset + .shard_writer() + .read_snapshot(&dir_id) + .await + .unwrap() + .is_some(), + "the write opened a writer for the new MemWAL" + ); + } + + /// `disable_rte` refuses while the MemWAL holds rows the base table does + /// not, since a MemWAL installed later would not read them. + #[tokio::test] + async fn lsm_disable_is_refused_while_rows_are_unmerged() { + let dir = tempdir().unwrap(); + let table = id_value_table(&dir).await; + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + lsm_upsert(&table, vec![4, 5]).await; + + let err = table.disable_rte().await.unwrap_err(); + assert!( + err.to_string() + .contains("not been merged into the base table"), + "unexpected error: {err}" + ); + assert_eq!( + table.get_rte_spec().await.unwrap(), + Some(RTEWriteSpec::unsharded()) + ); + let rows = collect_id_value(table.query().execute().await.unwrap()).await; + assert_eq!( + rows.into_iter().map(|(id, _)| id).collect::>(), + vec![1, 2, 3, 4, 5] + ); + } + + /// Rows another process's writer has acknowledged but not flushed are in + /// its WAL only, and still refuse `disable_rte`. + #[tokio::test] + async fn lsm_disable_is_refused_while_another_writer_holds_rows() { + let dir = tempdir().unwrap(); + let table = id_value_table(&dir).await; + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + lsm_upsert(&table, vec![4, 5]).await; + + let other = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap() + .open_table("t") + .execute() + .await + .unwrap(); + let err = other.disable_rte().await.unwrap_err(); + assert!( + err.to_string().contains("0 SSTable(s) not merged") + && !err.to_string().contains(" 0 WAL entry(ies) not flushed"), + "unexpected error: {err}" + ); + let rows = collect_id_value(table.query().execute().await.unwrap()).await; + assert_eq!( + rows.into_iter().map(|(id, _)| id).collect::>(), + vec![1, 2, 3, 4, 5] + ); + } + #[tokio::test] async fn base_table_adapter_use_rte_false_scans_the_base_only() { use crate::table::datafusion::BaseTableAdapter; @@ -1728,9 +1854,10 @@ mod lsm_tests { /// A spec is replaced by unsetting it and setting the new one. /// - /// `disable_rte` drains the open writer, so the rows it held - /// survive the replacement, and the writer the next write opens builds its - /// MemTables from the new set. + /// The writer the next write opens builds its MemTables from the new set. + /// Unsetting is refused while the MemWAL holds unmerged rows (see + /// `lsm_disable_is_refused_while_rows_are_unmerged`), so nothing is + /// written before the replacement. #[tokio::test] async fn lsm_spec_is_replaced_by_unsetting_it_first() { use crate::index::Index; @@ -1745,13 +1872,11 @@ mod lsm_tests { .unwrap(); let fts_index = table.list_indices().await.unwrap()[0].name.clone(); - // Installed maintaining nothing, then written to: the writer opens with - // no FTS index. + // Installed maintaining nothing. table .enable_rte(RTEWriteSpec::unsharded().with_maintained_indexes(Vec::new())) .await .unwrap(); - upsert_text(&table, vec![(99, "zebra")]).await; // Setting over an installed spec is refused; unset, then set. let err = table @@ -2269,7 +2394,7 @@ mod lsm_tests { .unwrap() .dataset .shard_writer() - .read_snapshot() + .read_snapshot(&mem_wal_dir_id(&table).await) .await .unwrap() .expect("the merge opened a writer"); @@ -2288,6 +2413,20 @@ mod lsm_tests { assert_sstables_answer_through_region_bitmap(&table, vec![10, 11]).await; } + /// The `dir_id` of the table's current MemWAL, read from storage. + async fn mem_wal_dir_id(table: &Table) -> String { + use lance::dataset::mem_wal::DatasetMemWalExt; + + lance::Dataset::open(&table.uri().await.unwrap()) + .await + .unwrap() + .mem_wal_index_details() + .await + .unwrap() + .expect("the table has a MemWAL") + .dir_id + } + /// The SSTables each shard's manifest publishes. async fn published_sstables(table: &Table) -> Vec { use lance::dataset::mem_wal::ShardManifestStore; @@ -2296,13 +2435,15 @@ mod lsm_tests { let (store, base) = lance_io::object_store::ObjectStore::from_uri(&uri) .await .unwrap(); - let mem_wal = std::path::Path::new(&uri).join("_mem_wal"); + let dir_id = mem_wal_dir_id(table).await; + let mem_wal = std::path::Path::new(&uri) + .join(lance::dataset::mem_wal::util::mem_wal_dir_name(&dir_id)); let mut sstables = Vec::new(); for shard in std::fs::read_dir(&mem_wal).unwrap() { let Ok(shard_id) = shard.unwrap().file_name().to_string_lossy().parse() else { continue; }; - let manifest = ShardManifestStore::new(store.clone(), &base, shard_id, 2) + let manifest = ShardManifestStore::new(store.clone(), &base, &dir_id, shard_id, 2) .latest() .await .unwrap() @@ -2417,7 +2558,7 @@ mod lsm_tests { .unwrap() .dataset .shard_writer() - .read_snapshot() + .read_snapshot(&mem_wal_dir_id(&table).await) .await .unwrap() .expect("the merge opened a writer"); diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index 1596679de..e32b1a289 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -30,8 +30,8 @@ use datafusion_physical_plan::SendableRecordBatchStream; use futures::TryStreamExt; use lance::Dataset; use lance::dataset::mem_wal::{ - DatasetMemWalExt, ShardWriter, ShardWriterConfig, evaluate_sharding_spec, - validate_maintained_indexes_with, + DatasetMemWalExt, ShardManifestStore, ShardWriter, ShardWriterConfig, WalTailer, + evaluate_sharding_spec, validate_maintained_indexes_with, }; use lance::index::DatasetIndexExt; use lance_core::datatypes::Schema as LanceSchema; @@ -197,7 +197,9 @@ fn index_name_list(indices: &[IndexConfig]) -> String { /// Remove the [`RTEWriteSpec`] from the table by dropping the MemWAL index. /// /// Any cached shard writers are drained and closed first. Errors if no spec is -/// currently set. +/// currently set, or if the MemWAL still holds rows that have not been merged +/// into the base table: dropping the index would orphan them, since a MemWAL +/// installed later gets a new directory. #[allow(clippy::redundant_pub_crate)] pub(crate) async fn disable_rte(table: &NativeTable) -> Result<()> { table.dataset.ensure_mutable()?; @@ -214,6 +216,9 @@ pub(crate) async fn disable_rte(table: &NativeTable) -> Result<()> { table.dataset.shard_writer().drain_and_close().await?; let mut dataset = (*table.dataset.get().await?).clone(); + if let Some(details) = dataset.mem_wal_index_details().await? { + ensure_mem_wal_merged(&dataset, &details).await?; + } dataset .drop_index(lance_index::mem_wal::MEM_WAL_INDEX_NAME) .await?; @@ -221,6 +226,67 @@ pub(crate) async fn disable_rte(table: &NativeTable) -> Result<()> { Ok(()) } +/// Error if any shard of the MemWAL holds rows the base table does not: an +/// SSTable past the shard's compaction watermark, or a WAL entry past the +/// position its flushed SSTables cover. +/// +/// Reading the WAL tip catches rows a live writer in another process has +/// acknowledged but not flushed. A write that lands after this check is not +/// caught. +async fn ensure_mem_wal_merged(dataset: &Dataset, details: &MemWalIndexDetails) -> Result<()> { + let store = dataset.object_store(None).await?; + let base_path = dataset.branch_location().path; + let scan_batch_size = ShardWriterConfig::default().manifest_scan_batch_size; + + let mut pending = Vec::new(); + for shard_id in dataset.list_mem_wal_latest_shard_ids().await? { + // First occurrence per shard, as Lance's `compacted_generation_for_shard`. + let compacted = details + .compacted_sstables + .iter() + .find(|entry| entry.shard_id == shard_id) + .map_or(0, |entry| entry.generation); + let manifest = ShardManifestStore::new( + store.clone(), + &base_path, + &details.dir_id, + shard_id, + scan_batch_size, + ) + .latest() + .await?; + let (unmerged, flushed_through) = manifest.map_or((0, 0), |manifest| { + let unmerged = manifest + .sstables + .iter() + .filter(|sstable| sstable.generation > compacted) + .count(); + (unmerged, manifest.replay_after_wal_entry_position) + }); + let wal_tip = WalTailer::new(store.clone(), base_path.clone(), &details.dir_id, shard_id) + .next_position() + .await? + .saturating_sub(1); + let unflushed = wal_tip.saturating_sub(flushed_through); + if unmerged > 0 || unflushed > 0 { + pending.push(format!( + "shard {shard_id}: {unmerged} SSTable(s) not merged, {unflushed} WAL entry(ies) not flushed" + )); + } + } + if pending.is_empty() { + return Ok(()); + } + Err(Error::InvalidInput { + message: format!( + "disable_rte: the RTE holds rows that have not been merged into the base \ + table and would be lost if it were removed ({}); disable_rte is only \ + allowed before any rows have been written through the RTE", + pending.join("; ") + ), + }) +} + // ============================================================================= // get_rte_spec // ============================================================================= @@ -351,12 +417,17 @@ impl std::fmt::Debug for ShardWriterCache { } struct ShardWriterEntry { + /// The `dir_id` of the MemWAL the writer was opened for. Another process + /// can drop and re-initialize the MemWAL under this one, leaving the cached + /// writer bound to a directory the index no longer names. + dir_id: String, inner: RwLock>, } impl ShardWriterEntry { fn new(writer: ShardWriter) -> Self { Self { + dir_id: writer.config().dir_id.clone(), inner: RwLock::new(Some(writer)), } } @@ -420,37 +491,57 @@ impl ShardWriterCache { /// Return the cached writer, opening one for `shard_id` with `config` if /// the slot is empty. Errors if a writer is already open for a *different* /// shard — the caller must close it first. + /// + /// A cached writer opened for a MemWAL other than `dir_id` is retired and + /// replaced: the MemWAL it wrote to was dropped by another process, so its + /// rows are no longer part of the table and its commits would be fenced. async fn writer_for_shard( &self, dataset: &Dataset, + dir_id: &str, shard_id: Uuid, config: ShardWriterConfig, ) -> Result> { { let guard = self.slot.read().await; - if let Some((cached, entry)) = guard.as_ref() { + if let Some((cached, entry)) = guard.as_ref() + && entry.dir_id == dir_id + { check_shard_match(*cached, shard_id)?; return Ok(entry.clone()); } } let mut guard = self.slot.write().await; // Re-check: another caller may have opened the writer meanwhile. - if let Some((cached, entry)) = guard.as_ref() { + if let Some((cached, entry)) = guard.as_ref() + && entry.dir_id == dir_id + { check_shard_match(*cached, shard_id)?; return Ok(entry.clone()); } - let writer = dataset + let retired = guard.take(); + let opened = dataset .mem_wal_writer(shard_id, config) .await - .map_err(|e| Error::Runtime { - message: format!( - "merge_insert: failed to open RTE shard writer for shard {}: {}", - shard_id, e - ), - })?; - let entry = Arc::new(ShardWriterEntry::new(writer)); - *guard = Some((shard_id, entry.clone())); - Ok(entry) + .map(|writer| Arc::new(ShardWriterEntry::new(writer))); + if let Ok(entry) = &opened { + *guard = Some((shard_id, entry.clone())); + } + drop(guard); + if let Some((retired_shard, retired)) = retired + && let Err(error) = retired.close().await + { + log::warn!( + "the MemWAL was re-initialized, and the writer this process held for \ + shard {retired_shard} of the retired MemWAL could not be closed: {error}" + ); + } + opened.map_err(|e| Error::Runtime { + message: format!( + "merge_insert: failed to open RTE shard writer for shard {}: {}", + shard_id, e + ), + }) } /// Install `dataset`'s maintained index set on the cached writer, if one is @@ -505,10 +596,12 @@ impl ShardWriterCache { /// Snapshot the cached writer's shard for the RTE read path: its shard id, /// authoritative in-memory manifest, and active + frozen memtable refs. /// Returns `None` when no writer is currently cached (e.g. nothing has been - /// written this session, or the writer was closed). + /// written this session, or the writer was closed), or when the cached + /// writer belongs to a MemWAL other than `dir_id`. #[allow(clippy::redundant_pub_crate)] pub(crate) async fn read_snapshot( &self, + dir_id: &str, ) -> Result< Option<( Uuid, @@ -523,6 +616,10 @@ impl ShardWriterCache { let Some((shard_id, entry)) = cached else { return Ok(None); }; + // A writer for a retired MemWAL holds no rows of the current one. + if entry.dir_id != dir_id { + return Ok(None); + } // Capture memtables before the manifest. If a flush interleaves, dedup // tolerates the same rows appearing in both a memtable and a freshly // flushed generation, but would drop rows present in neither. Manifest @@ -576,6 +673,8 @@ enum LsmMode { #[allow(clippy::redundant_pub_crate)] pub(crate) struct LsmPlan { mode: LsmMode, + /// The `dir_id` of the MemWAL the write targets. + dir_id: String, writer_config_defaults: HashMap, } @@ -644,6 +743,7 @@ pub(crate) async fn lsm_dispatch_decision( let mode = resolve_lsm_mode(&details)?; Ok(LsmDispatch::Lsm(LsmPlan { mode, + dir_id: details.dir_id, writer_config_defaults: details.writer_config_defaults, })) } @@ -745,7 +845,7 @@ pub(crate) async fn execute_lsm_merge_insert( let writer = table .dataset .shard_writer() - .writer_for_shard(dataset.as_ref(), shard_id, config) + .writer_for_shard(dataset.as_ref(), &plan.dir_id, shard_id, config) .await?; writer.put(batches).await?; diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index dbb3dbc68..2f5c75766 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -27,7 +27,7 @@ use datafusion_physical_plan::PhysicalExpr; use datafusion_physical_plan::projection::ProjectionExec; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::union::UnionExec; -use datafusion_physical_plan::{ExecutionPlan, with_new_children_if_necessary}; +use datafusion_physical_plan::{ExecutionPlan, replace_children_if_necessary}; use lance::dataset::mem_wal::DatasetMemWalExt; use lance::dataset::scanner::DatasetRecordBatchStream; use lance::dataset::scanner::Scanner; @@ -740,7 +740,7 @@ fn replace_ann_branches( .cloned() .map(|child| replace_ann_branches(child, internal_ann_plans, normalized_l2_indices)) .collect::>>()?; - Ok(with_new_children_if_necessary(public_plan, children)?) + Ok(replace_children_if_necessary(public_plan, children)?) } fn scale_distance_column( diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 7af52e572..d348a6668 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -120,12 +120,11 @@ pub(super) async fn create_lsm_plan( } else { plain_plan( &ds_ref, + &details, &query, pk_columns.clone(), snapshots, in_memory, - limit, - offset, ) .await? }; @@ -304,8 +303,13 @@ async fn build_read_context( let mut snapshots: Vec = Vec::new(); for shard_id in shard_ids { - let manifest_store = - ShardManifestStore::new(store.clone(), &base_path, shard_id, scan_batch_size); + let manifest_store = ShardManifestStore::new( + store.clone(), + &base_path, + &details.dir_id, + shard_id, + scan_batch_size, + ); if let Some(manifest) = manifest_store.latest().await? { snapshots.push(snapshot_from_manifest(shard_id, &manifest, &exclude)); } @@ -324,8 +328,11 @@ async fn build_read_context( // Override the active shard with the cached writer's in-memory view. let mut in_memory: HashMap = HashMap::new(); if !wal_only - && let Some((shard_id, manifest, memtables)) = - table.dataset.shard_writer().read_snapshot().await? + && let Some((shard_id, manifest, memtables)) = table + .dataset + .shard_writer() + .read_snapshot(&details.dir_id) + .await? { if let Some(manifest) = manifest { let snapshot = snapshot_from_manifest(shard_id, &manifest, &exclude); @@ -384,12 +391,14 @@ fn as_i64(value: Option) -> Option { /// scanner's `create_plan`. fn base_scanner( dataset: &Dataset, + dir_id: &str, query: &VectorQueryRequest, pk_columns: Vec, snapshots: Vec, in_memory: HashMap, ) -> Result { - let mut scanner = LsmScanner::new(Arc::new(dataset.clone()), snapshots, pk_columns); + let mut scanner = LsmScanner::new(Arc::new(dataset.clone()), snapshots, pk_columns) + .with_mem_wal_dir_id(dir_id); for (shard_id, memtables) in in_memory { scanner = scanner.with_in_memory_memtables(shard_id, memtables); } @@ -435,15 +444,21 @@ fn enrich_filter_error(error: DataFusionError, schema: &ArrowSchema, context: &s /// The plain scan applies limit and offset inside the planner. async fn plain_plan( dataset: &Dataset, + details: &MemWalIndexDetails, query: &VectorQueryRequest, pk_columns: Vec, snapshots: Vec, in_memory: HashMap, - limit: Option, - offset: Option, ) -> Result> { - let scanner = base_scanner(dataset, query, pk_columns, snapshots, in_memory)? - .limit(as_i64(limit), as_i64(offset))?; + let scanner = base_scanner( + dataset, + &details.dir_id, + query, + pk_columns, + snapshots, + in_memory, + )? + .limit(as_i64(query.base.limit), as_i64(query.base.offset))?; Ok(scanner.create_plan().await?) } @@ -491,10 +506,17 @@ async fn fts_plan( }); } - let scanner = base_scanner(dataset, query, pk_columns, snapshots, in_memory)? - .with_overfetch_factor(LSM_OVERFETCH_FACTOR) - .full_text_search(fts)? - .limit(as_i64(limit), as_i64(offset))?; + let scanner = base_scanner( + dataset, + &details.dir_id, + query, + pk_columns, + snapshots, + in_memory, + )? + .with_overfetch_factor(LSM_OVERFETCH_FACTOR) + .full_text_search(fts)? + .limit(as_i64(limit), as_i64(offset))?; Ok(scanner.create_plan().await?) } @@ -740,10 +762,17 @@ async fn vector_plan( // Guard `k` to at least 1 so a degenerate `limit(0)` is trimmed by `limit` // below rather than rejected by `nearest`. let k = limit.unwrap_or(DEFAULT_TOP_K).max(1); - let mut scanner = base_scanner(dataset, query, pk_columns, snapshots, in_memory)? - .with_overfetch_factor(LSM_OVERFETCH_FACTOR) - .nearest(&column, query_vector.as_ref(), k)? - .distance_metric(distance_type.into()); + let mut scanner = base_scanner( + dataset, + &details.dir_id, + query, + pk_columns, + snapshots, + in_memory, + )? + .with_overfetch_factor(LSM_OVERFETCH_FACTOR) + .nearest(&column, query_vector.as_ref(), k)? + .distance_metric(distance_type.into()); if let Some(nprobes) = query.nprobes { scanner = if query.maximum_nprobes == Some(0) { scanner.minimum_nprobes(nprobes) diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index a3f313ba7..19accc2c2 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -1805,8 +1805,8 @@ mod tests { assert!(matches!(err, Error::NotSupported { .. })); } - /// After catch-up activation and unset, no spec remains but the catch-up - /// flag still marks retained SSTable rows; refresh refuses on the flag. + /// Rows written through the RTE keep the spec installed, since + /// `disable_rte` refuses while they are unmerged, so refresh refuses. #[tokio::test] #[cfg_attr( not(feature = "experimental-functions"), @@ -1849,7 +1849,8 @@ mod tests { ))) .await .unwrap(); - table.disable_rte().await.unwrap(); + // The RTE holds the written rows, so unsetting it is refused. + table.disable_rte().await.unwrap_err(); super::super::computed_columns::add_foreign_kind(&table, "doubled", "sql").await; let err = table.refresh_column("doubled").await.unwrap_err();