From deb8834b5a098713ae15e4233604d181dc8aafd3 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 10:36:11 +0800 Subject: [PATCH 001/203] fix: expose stable row IDs in Function errors (#4841) Function error records expose physical row locations, which can change when a table is compacted. Expose the server-provided optional stable `row_id` through Rust and Python so callers can locate the same row after compaction. Document stable-ID retries and retain physical addresses for tables without stable row IDs. Older server responses continue to deserialize with `row_id=None`. The Python remote response test and Rust remote deserialization test passed on verification SDK `4e1725fa352035e2079dfd235b8271cd05adf433`, including decoding a legacy response without the new field. This branch applies the same SDK patch to current main; intervening main changes leave the affected error types and assertions unchanged. Formatting and lint checks passed after correcting the retry examples to use the `table.name` property. In a separate Linux server experiment, a real skipped Function row retained `_rowid=506` after compaction changed its physical address. The SDK field requires a server that emits stable row IDs; this PR does not change server dependencies. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/table.py | 60 +++++++++++++++++++++++---- python/python/tests/test_remote_db.py | 2 + python/src/table.rs | 2 + rust/lancedb/src/function.rs | 7 ++++ rust/lancedb/src/remote/table.rs | 7 +++- rust/lancedb/src/table.rs | 4 ++ 7 files changed, 73 insertions(+), 10 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 02d9c9e87..351933ed5 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1006,6 +1006,7 @@ class FunctionErrorRecord: job_id: str fragment_id: int row_offset: Optional[int] + row_id: Optional[int] row_address: Optional[int] column: str function: str diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 23bc25b97..4724776a1 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3301,9 +3301,31 @@ class Table(ABC): ``records``, ``fragments`` and ``truncated``, the last saying whether the listing stopped at its limit. - Each record identifies its row with ``fragment_id``, ``row_offset`` - and the physical ``row_address`` (``(fragment_id << 32) | - row_offset``). To retry the recorded rows, collect the non-null + Each record identifies its row with ``fragment_id``, ``row_offset``, + the physical ``row_address`` (``(fragment_id << 32) | + row_offset``), and, when the table uses stable row IDs, the stable + ``row_id`` read from the refresh's pinned table version. Prefer + ``row_id`` for retries: compaction and rewrite can change the + physical fields, while a stable row ID survives them. + + To retry the recorded rows with stable row IDs: + + .. code-block:: python + + errors = table.function_errors(column="embedding") + row_ids = sorted( + record.row_id + for record in errors.records + if record.row_id is not None + ) + if row_ids: + row_id_list = ", ".join(str(row_id) for row_id in row_ids) + database.execute_query( + f"REFRESH COLUMN embedding ON {table.name} " + f"WHERE _rowid IN ({row_id_list})" + ) + + For a table without stable row IDs, collect the non-null physical addresses before the table is compacted or rewritten and run the SQL refresh: @@ -3318,7 +3340,7 @@ class Table(ABC): if addresses: address_list = ", ".join(str(address) for address in addresses) database.execute_query( - f"REFRESH COLUMN embedding ON {table.name()} " + f"REFRESH COLUMN embedding ON {table.name} " f"WHERE _rowaddr IN ({address_list})" ) @@ -7786,9 +7808,31 @@ class AsyncTable: ``records``, ``fragments`` and ``truncated``, the last saying whether the listing stopped at its limit. - Each record identifies its row with ``fragment_id``, ``row_offset`` - and the physical ``row_address`` (``(fragment_id << 32) | - row_offset``). To retry the recorded rows, collect the non-null + Each record identifies its row with ``fragment_id``, ``row_offset``, + the physical ``row_address`` (``(fragment_id << 32) | + row_offset``), and, when the table uses stable row IDs, the stable + ``row_id`` read from the refresh's pinned table version. Prefer + ``row_id`` for retries: compaction and rewrite can change the + physical fields, while a stable row ID survives them. + + To retry the recorded rows with stable row IDs: + + .. code-block:: python + + errors = await table.function_errors(column="embedding") + row_ids = sorted( + record.row_id + for record in errors.records + if record.row_id is not None + ) + if row_ids: + row_id_list = ", ".join(str(row_id) for row_id in row_ids) + await database.execute_query( + f"REFRESH COLUMN embedding ON {table.name} " + f"WHERE _rowid IN ({row_id_list})" + ) + + For a table without stable row IDs, collect the non-null physical addresses before the table is compacted or rewritten and run the SQL refresh: @@ -7803,7 +7847,7 @@ class AsyncTable: if addresses: address_list = ", ".join(str(address) for address in addresses) await database.execute_query( - f"REFRESH COLUMN embedding ON {table.name()} " + f"REFRESH COLUMN embedding ON {table.name} " f"WHERE _rowaddr IN ({address_list})" ) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 1ee6d464b..8aec4d185 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2047,6 +2047,7 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): "job_id": "j-7", "fragment_id": 3, "row_offset": 9, + "row_id": 42, "row_address": 12884901897, "column": "embedding", "function": "embed", @@ -2098,6 +2099,7 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): assert errors.truncated is True assert [r.error_message for r in errors.records] == ["bad input 'x'"] assert errors.records[0].row_offset == 9 + assert errors.records[0].row_id == 42 assert errors.records[0].row_address == 12884901897 assert errors.records[0].function_version == "2" assert repr(errors.records[0]) == ( diff --git a/python/src/table.rs b/python/src/table.rs index 6ef524310..4ccc76f89 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -614,6 +614,7 @@ pub struct FunctionErrorRecord { pub job_id: String, pub fragment_id: u64, pub row_offset: Option, + pub row_id: Option, pub row_address: Option, pub column: String, pub function: String, @@ -653,6 +654,7 @@ impl From for FunctionErrorRecord { job_id: record.job_id, fragment_id: record.fragment_id, row_offset: record.row_offset, + row_id: record.row_id, row_address: record.row_address, column: record.column, function: record.function, diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 8933d0b37..ffa61f158 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1043,6 +1043,13 @@ pub struct FunctionErrorRecord { /// detail was capped and only the fragment summary remains. #[serde(default)] pub row_offset: Option, + /// Stable row identity at the table version the refresh read. + /// + /// Present only when that version used stable row IDs. It remains valid + /// across later compaction and rewrite, unlike `row_address`. `None` on + /// legacy tables and on records written before the server reported it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub row_id: Option, /// Portable physical row address, `(fragment_id << 32) | row_offset`. /// /// `None` when the record covers a fragment rather than one row, or when diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3b241dd3a..b95227db6 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11026,7 +11026,7 @@ mod tests { .status(200) .body( r#"{"records": [{"job_id": "j-7", "fragment_id": 3, "row_offset": 9, - "row_address": 12884901897, + "row_id": 42, "row_address": 12884901897, "column": "embedding", "function": "embed", "function_version": "2", "table_version": 11, "error_type": "ValueError", "error_message": "bad input 'x'", "created_at_millis": 1700000000000}], @@ -11052,6 +11052,7 @@ mod tests { job_id: "j-7".into(), fragment_id: 3, row_offset: Some(9), + row_id: Some(42), row_address: Some(12_884_901_897), column: "embedding".into(), function: "embed".into(), @@ -11073,7 +11074,8 @@ mod tests { ); assert!(errors.truncated); - // Servers before row_address omit it; the record still decodes. + // Servers before row_address or row_id omit them; the record still + // decodes. let legacy: FunctionErrorRecord = serde_json::from_value(serde_json::json!({ "job_id": "j-6", "fragment_id": 2, @@ -11087,6 +11089,7 @@ mod tests { "created_at_millis": 1_700_000_000_000_i64, })) .unwrap(); + assert!(legacy.row_id.is_none()); assert!(legacy.row_address.is_none()); // No filter sends no filter, and an empty listing reads as such. diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 6bc845580..1bd3a711a 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2141,6 +2141,10 @@ impl Table { /// capped. Filter by job or column through the request; a listing that /// hit its limit reports [`FunctionErrors::truncated`]. /// + /// A record carries a stable `row_id` when the refresh source used stable + /// row IDs. Prefer it over the physical `row_address` for retries: + /// compaction and rewrite can change the address. + /// /// LanceDB Enterprise only, and the caller needs read access /// to the table, since a message carries the value that failed. /// From 4396ed5c210d643ddfdb3cbf71a95b526080ef22 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 5 Nov 2026 11:16:30 +0800 Subject: [PATCH 002/203] chore: update lance dependency to v15.0.0-beta.10 (#4838) Update the Rust workspace Lance dependencies to [v15.0.0-beta.10](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.10), which contains the released MinHash signature scanning API needed by downstream consumers. Pin Python tests to the published `15.0.0b10` wheels, including macOS, and refresh both lockfiles. Java remains on beta.8. No SDK source compatibility changes were needed. All 25 Lance Git packages resolve to release commit `f56a08d40b5630ce1124535c4c3b1406d5ceedf1`; third-party package versions are unchanged. Validation on macOS ARM64 with pinned Rust 1.97.0: strict workspace Clippy with default and all features, Rust formatting, 32 CI-script tests, three count tests, one WAL/vector regression, and the Python lockfile check passed. The native test binary emitted a macOS compact-unwind size warning; both test commands completed successfully without changing linker settings. Downstream release and integrated Sophon acceptance remain separate. --- Cargo.lock | 129 ++++++++++++++++-------------------------- Cargo.toml | 30 +++++----- python/pyproject.toml | 4 +- python/uv.lock | 65 +++++---------------- 4 files changed, 81 insertions(+), 147 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9e23f1f65..65bcd8c5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3752,8 +3752,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5250,8 +5250,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arc-swap", "arrow", @@ -5306,7 +5306,6 @@ dependencies = [ "permutation", "pin-project", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rayon", @@ -5326,8 +5325,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5349,7 +5348,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5363,7 +5362,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "arrow-schema", @@ -5372,8 +5371,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrayref", "crunchy", @@ -5383,8 +5382,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5401,6 +5400,7 @@ dependencies = [ "libc", "libm", "log", + "metrics", "moka", "num_cpus", "object_store 0.14.2", @@ -5421,8 +5421,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow", "arrow-array", @@ -5447,15 +5447,14 @@ dependencies = [ "log", "pin-project", "prost", - "prost-build", "tokio", "tracing", ] [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow", "arrow-array", @@ -5480,8 +5479,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow", "arrow-array", @@ -5498,8 +5497,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "proc-macro2", "quote", @@ -5508,8 +5507,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-arith", "arrow-array", @@ -5533,7 +5532,6 @@ dependencies = [ "lz4", "num-traits", "prost", - "prost-build", "serde_json", "tokio", "tracing", @@ -5543,8 +5541,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,7 +5565,6 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "serde", "tokio", @@ -5576,8 +5573,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "geo-traits", "geo-types", @@ -5589,8 +5586,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arc-swap", "arrow", @@ -5647,7 +5644,6 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rand_distr 0.5.1", @@ -5666,8 +5662,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "arrow-schema", @@ -5690,8 +5686,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow", "arrow-array", @@ -5736,8 +5732,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "byteorder", "ethnum", @@ -5754,8 +5750,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5770,8 +5766,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow", "async-trait", @@ -5785,8 +5781,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arc-swap", "arrow", @@ -5840,8 +5836,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5855,8 +5851,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow", "arrow-array", @@ -5880,10 +5876,10 @@ dependencies = [ "num-traits", "object_store 0.14.2", "prost", - "prost-build", "prost-types", "rand 0.9.5", "rangemap", + "rayon", "roaring", "semver", "serde", @@ -5897,8 +5893,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "arrow-array", "arrow-schema", @@ -5911,8 +5907,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.9#025b3d93aded5a201508a50e20e031a031c63b66" +version = "15.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" dependencies = [ "frostem", "icu_segmenter", @@ -6662,12 +6658,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fafa6961cabd9c63bcd77a45d7e3b7f3b552b70417831fb0f56db717e72407e" -[[package]] -name = "multimap" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" - [[package]] name = "multiversion" version = "0.7.4" @@ -8471,25 +8461,6 @@ dependencies = [ "prost-derive", ] -[[package]] -name = "prost-build" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" -dependencies = [ - "heck 0.5.0", - "itertools 0.14.0", - "log", - "multimap", - "petgraph", - "prettyplease", - "prost", - "prost-types", - "regex", - "syn 2.0.117", - "tempfile", -] - [[package]] name = "prost-derive" version = "0.14.4" diff --git a/Cargo.toml b/Cargo.toml index ac10aab52..4ba74870e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.9", default-features = false, "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.9", default-features = false, "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.9", default-features = false, "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.9", "tag" = "v15.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.10", default-features = false, "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.10", default-features = false, "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.10", default-features = false, "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/python/pyproject.toml b/python/pyproject.toml index a8005f973..bd40b5828 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,9 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow<25", "pyarrow-stubs>=16.0", - # pylance 15.0.0b5+ has not published macOS wheels. - "pylance==15.0.0b9; sys_platform != 'darwin'", - "pylance==15.0.0b4; sys_platform == 'darwin'", + "pylance==15.0.0b10", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 2bc641cca..47d0b7773 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2055,8 +2055,7 @@ otel = [ { name = "opentelemetry-api" }, ] pylance = [ - { name = "pylance", version = "15.0.0b4", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform == 'darwin'" }, - { name = "pylance", version = "15.0.0b9", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform != 'darwin'" }, + { name = "pylance" }, ] siglip = [ { name = "pillow" }, @@ -2076,8 +2075,7 @@ tests = [ { name = "polars" }, { name = "pyarrow" }, { name = "pyarrow-stubs" }, - { name = "pylance", version = "15.0.0b4", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform == 'darwin'" }, - { name = "pylance", version = "15.0.0b9", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform != 'darwin'" }, + { name = "pylance" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-mock" }, @@ -2128,9 +2126,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 = "sys_platform == 'darwin' and extra == 'tests'", specifier = "==15.0.0b4" }, - { name = "pylance", marker = "sys_platform != 'darwin' and extra == 'tests'", specifier = "==15.0.0b9" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b10" }, { 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" }, @@ -4107,54 +4104,22 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b4" +version = "15.0.0b10" source = { registry = "https://pypi.fury.io/lance-format/" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.11.*' and sys_platform == 'darwin'", - "python_full_version < '3.11' and sys_platform == 'darwin'", -] dependencies = [ - { name = "lance-namespace", marker = "sys_platform == 'darwin'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform == 'darwin'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*' and sys_platform == 'darwin'" }, - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and sys_platform == 'darwin'" }, - { name = "pyarrow", marker = "sys_platform == 'darwin'" }, + { name = "lance-namespace" }, + { name = "numpy", version = "2.2.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.11.*'" }, + { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1Bbzay/pylance-15.0.0b4-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c948ac22105a0bd9f8314edb883edac421a64b059d992ea6d614773cd2fa2e65" }, -] - -[[package]] -name = "pylance" -version = "15.0.0b9" -source = { registry = "https://pypi.fury.io/lance-format/" } -resolution-markers = [ - "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version >= '3.14' and sys_platform == 'emscripten'", - "python_full_version >= '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", - "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version == '3.11.*' and sys_platform == 'linux'", - "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", - "python_full_version < '3.11' and sys_platform == 'linux'", - "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", -] -dependencies = [ - { name = "lance-namespace", marker = "sys_platform != 'darwin'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform != 'darwin'" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*' and sys_platform != 'darwin'" }, - { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and sys_platform != 'darwin'" }, - { name = "pyarrow", marker = "sys_platform != 'darwin'" }, -] -wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_11uz9g/pylance-15.0.0b9-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:749d4da73a22f5d33f6926387109dfaf814413d3bd1c36b974edf81ca040eb04" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Zl1Qd/pylance-15.0.0b9-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c49523c68122f4cb42fd310155af6f420f90559752f0735d1503c06f7f45629" }, - { url = "https://pypi.fury.io/lance-format/-/ver_23GhEu/pylance-15.0.0b9-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:78ff23c91b1b4113bae7715fd143af1fec732cdc0fd2429db6d3149de16d565a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1IKCVE/pylance-15.0.0b9-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ee8f71b7bdf16bb44305f961b6a2cf4a75f47f1db7d217955e2aca0020acdf05" }, - { url = "https://pypi.fury.io/lance-format/-/ver_10hNTp/pylance-15.0.0b9-cp310-abi3-win_amd64.whl", hash = "sha256:28f1f92c8af8072a7fdc6f4eca5a8814a54e457843e2ac7e0f00554da5152d90" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1aEUT6/pylance-15.0.0b10-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:fe34d42c5d58008a65f41acb659474c43848104414a2af94461454377c9f5276" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1YU4YL/pylance-15.0.0b10-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1042942b4df0ea42d263bf2e12ac2fa04e24ea49482f55349687df439686f614" }, + { url = "https://pypi.fury.io/lance-format/-/ver_LnRBy/pylance-15.0.0b10-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f0954e2a3855bc161a9ffebfcdf7f7086da3fa71ef1f3a92bd38212076963b08" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pjVe1/pylance-15.0.0b10-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:eb6bc476f79d4c1b786377ae8366afc1718f54a9314141e65c57ad0f47906df6" }, + { url = "https://pypi.fury.io/lance-format/-/ver_RENd/pylance-15.0.0b10-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4dc325458b5b959bc644487c2ade6cdbcc89c4bc14ee7bb7487d9e145426207c" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1I5wzV/pylance-15.0.0b10-cp310-abi3-win_amd64.whl", hash = "sha256:10226cf5c224c0a47d18d7a323ce64473026acd7a4f08e7c6a59e787ee93a73c" }, ] [[package]] From e73eb951899b7c30e7a81d956a94ea3a38ab5d13 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 11:25:51 +0800 Subject: [PATCH 003/203] fix: preserve FunctionVersion execution controls (#4856) Function catalog responses include `batch_size`, `row_timeout_seconds`, and `result_stability`, but the Rust and Python `FunctionVersion` models silently discarded them. Preserve these optional execution controls through decoding, typed access, and canonical serialization; versions without the fields retain their existing representation. The regression exercises raw SQL transport responses and public Python sync/async get/list paths. Live Sophon catalog acceptance remains pending under ENT-2073 and the related FunctionVersion round-trip requirement in ENT-2176. --- python/python/lancedb/functions.py | 17 +++++ .../tests/test_first_class_function_slice1.py | 16 ++++ .../tests/test_first_class_function_slice2.py | 75 +++++++++++++++++++ rust/lancedb/src/function.rs | 53 +++++++++++++ rust/lancedb/src/remote/sql_test.rs | 24 ++++++ 5 files changed, 185 insertions(+) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index ba2bbeba3..0257e4d7b 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -482,6 +482,10 @@ class FunctionVersion(_RemoteValue): ``gpu_class`` is the operator-defined GPU pool fixed into this Function version, or ``None`` when registration used the deployment default. + + ``batch_size``, ``row_timeout_seconds``, and ``result_stability`` retain + the execution controls reported by the catalog. They are ``None`` for + versions registered before the corresponding declaration. """ name: str @@ -497,6 +501,19 @@ class FunctionVersion(_RemoteValue): metadata: Mapping[str, str] disabled: bool gpu_class: Optional[str] = None + batch_size: Optional[int] = None + row_timeout_seconds: Optional[float] = None + result_stability: Optional[str] = None + + @field_validator("batch_size", mode="before") + @classmethod + def _validate_batch_size(cls, value): + return _validate_batch_size(value) + + @field_validator("row_timeout_seconds", mode="before") + @classmethod + def _validate_row_timeout(cls, value): + return _validate_row_timeout(value) def __call__(self, **arguments: Any) -> FunctionApplication: """Bind this exact version to named table columns. diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index cc4485133..980c11993 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -180,6 +180,22 @@ def test_function_version_exposes_registered_gpu_class(): assert json.loads(version.to_canonical_json())["gpu_class"] == "a10g" +def test_function_version_preserves_execution_controls(): + value = job_result("remote_function_job.json") + value.update( + batch_size=12, + row_timeout_seconds=8.0, + result_stability="input_and_context", + ) + version = FunctionVersion.from_json(json.dumps(value)) + encoded = json.loads(version.to_canonical_json()) + + assert encoded == value + assert type(encoded["batch_size"]) is int + assert type(encoded["row_timeout_seconds"]) is float + assert type(encoded["result_stability"]) is str + + 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 bb2e6f755..6df017cff 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -25,7 +25,9 @@ import pytest import lancedb from lancedb import BlobReader +from lancedb.db import AsyncConnection from lancedb.functions import ( + FunctionVersion, HuggingFaceModel, PythonRuntimeSpec, SecretBinding, @@ -37,6 +39,7 @@ from lancedb.functions import ( udf, ) from lancedb.secrets import EnvVarSecret +from lancedb.remote.db import RemoteDBConnection from utils import start_server_thread THRESHOLD = 20 @@ -1865,6 +1868,78 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path): db.drop_function("normalize_score", version=FUNCTION_VERSION) +class _RawFunctionCatalog: + def __init__(self, definition, *, encode=False): + self.definition = json.dumps(definition) if encode else definition + + async def get_function(self, _name, version, namespace_path): + return self.definition + + def list_functions(self, *, namespace_path=None, page_token=None, page_limit=None): + return self + + def __aiter__(self): + return self + + async def __anext__(self): + if self.definition is None: + raise StopAsyncIteration + definition, self.definition = self.definition, None + return definition + + def num_page_results(self): + return int(self.definition is not None) + + def page_token(self): + return None + + +def _assert_execution_control_encoding(version): + encoded = json.loads(version.to_canonical_json()) + assert type(encoded["batch_size"]) is int + assert type(encoded["row_timeout_seconds"]) is float + assert type(encoded["result_stability"]) is str + return encoded + + +@pytest.mark.asyncio +async def test_async_catalog_path_preserves_execution_controls(): + definition = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + definition.update( + batch_size=12, + row_timeout_seconds=8.0, + result_stability="input_and_context", + ) + connection = AsyncConnection(_RawFunctionCatalog(definition, encode=True)) + + exact = await connection.get_function("embed", version="1") + listed = [item async for item in connection.list_functions(page_limit=32)] + assert len(listed) == 1 + for version in [exact, *listed]: + assert _assert_execution_control_encoding(version) == definition + + +def test_sync_catalog_path_preserves_execution_controls(): + definition = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + definition.update( + batch_size=12, + row_timeout_seconds=8.0, + result_stability="input_and_context", + ) + connection = object.__new__(RemoteDBConnection) + connection._conn = _RawFunctionCatalog(FunctionVersion(**definition)) + + exact = connection.get_function("embed", version="1") + listed = list(connection.list_functions(page_limit=32)) + assert len(listed) == 1 + for version in [exact, *listed]: + assert _assert_execution_control_encoding(version) == definition + + @contextlib.contextmanager def _mock_remote_function_catalog(): state = {"requests": [], "version": None} diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index ffa61f158..96eb4de10 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -541,6 +541,31 @@ fn deserialize_object_version<'de, D: Deserializer<'de>>( } } +/// A positive, finite per-call deadline reported by the catalog. +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[serde(transparent)] +struct RowTimeoutSeconds(f64); + +impl Eq for RowTimeoutSeconds {} + +impl RowTimeoutSeconds { + fn get(self) -> f64 { + self.0 + } +} + +impl<'de> Deserialize<'de> for RowTimeoutSeconds { + fn deserialize>(deserializer: D) -> std::result::Result { + let seconds = f64::deserialize(deserializer)?; + if !seconds.is_finite() || seconds <= 0.0 { + return Err(de::Error::custom( + "row_timeout_seconds must be positive and finite", + )); + } + Ok(Self(seconds)) + } +} + /// One immutable Function object revision and its executable artifact. /// /// The Function is named by its parts, `name` and `namespace_path`, the way a @@ -570,6 +595,19 @@ pub struct FunctionVersion { /// Operator-defined GPU class declared at registration. #[serde(default, skip_serializing_if = "Option::is_none")] gpu_class: Option, + /// Default maximum rows in one callable batch. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_batch_size" + )] + batch_size: Option, + /// Per-call deadline in seconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + row_timeout_seconds: Option, + /// Result-stability value declared at registration. + #[serde(default, skip_serializing_if = "Option::is_none")] + result_stability: Option, } impl FunctionVersion { @@ -629,6 +667,21 @@ impl FunctionVersion { self.gpu_class.as_deref() } + /// Default maximum rows in one callable batch, when declared. + pub fn batch_size(&self) -> Option { + self.batch_size + } + + /// Per-call deadline in seconds, when declared. + pub fn row_timeout_seconds(&self) -> Option { + self.row_timeout_seconds.map(RowTimeoutSeconds::get) + } + + /// Result-stability value declared at registration, when present. + pub fn result_stability(&self) -> Option<&str> { + self.result_stability.as_deref() + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index b25ab4ddb..cbca4e9f6 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -2775,6 +2775,9 @@ async fn function_creation_and_description_use_sql_query_handles() { "secret_ref": {"name": "hf-prod"}, }]); let mut version_json: serde_json::Value = serde_json::from_str(VERSION).unwrap(); + version_json["batch_size"] = serde_json::json!(12); + version_json["row_timeout_seconds"] = serde_json::json!(8.0); + version_json["result_stability"] = serde_json::json!("input_and_context"); if with_models { let models = serde_json::json!([{ "repo": "sentence-transformers/all-MiniLM-L6-v2", @@ -2815,6 +2818,9 @@ async fn function_creation_and_description_use_sql_query_handles() { let created = job.wait().await.unwrap(); assert_eq!(created.name(), "embed"); assert_eq!(created.version(), "1"); + assert_eq!(created.batch_size(), Some(12)); + assert_eq!(created.row_timeout_seconds(), Some(8.0)); + assert_eq!(created.result_stability(), Some("input_and_context")); // Assert the actual SQL body, after the same native JSON decode used // by the Python binding, rather than only the Python declaration. { @@ -2831,6 +2837,9 @@ async fn function_creation_and_description_use_sql_query_handles() { let created_json: serde_json::Value = serde_json::from_str(&created.to_canonical_json().unwrap()).unwrap(); assert_eq!(created_json["image"].get("models"), expected_models); + assert_eq!(created_json["batch_size"], 12); + assert_eq!(created_json["row_timeout_seconds"], 8.0); + assert_eq!(created_json["result_stability"], "input_and_context"); assert_eq!( client.describe(id).await.unwrap().status, QueryStatus::Finished @@ -2840,17 +2849,32 @@ async fn function_creation_and_description_use_sql_query_handles() { .await .unwrap(); assert_eq!(described.name(), "embed"); + assert_eq!(described.batch_size(), Some(12)); + assert_eq!(described.row_timeout_seconds(), Some(8.0)); + assert_eq!(described.result_stability(), Some("input_and_context")); let described_json: serde_json::Value = serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap(); assert_eq!(described_json["image"].get("models"), expected_models); + assert_eq!(described_json["batch_size"], 12); + assert_eq!(described_json["row_timeout_seconds"], 8.0); + assert_eq!(described_json["result_stability"], "input_and_context"); let listed = db .list_functions(&["team".into()], Default::default()) .await .unwrap(); assert_eq!(listed.items.len(), 1); + assert_eq!(listed.items[0].batch_size(), Some(12)); + assert_eq!(listed.items[0].row_timeout_seconds(), Some(8.0)); + assert_eq!( + listed.items[0].result_stability(), + Some("input_and_context") + ); let listed_json: serde_json::Value = serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap(); assert_eq!(listed_json["image"].get("models"), expected_models); + assert_eq!(listed_json["batch_size"], 12); + assert_eq!(listed_json["row_timeout_seconds"], 8.0); + assert_eq!(listed_json["result_stability"], "input_and_context"); let seen = statements.lock().unwrap(); assert_eq!(seen[1], "DESCRIBE FUNCTION \"embed\" WITH (version = '1')"); shutdown.send(()).unwrap(); From d0b0efcd4775b6b6e522394841e30d3950ff4579 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 4 Nov 2026 20:25:14 -0800 Subject: [PATCH 004/203] style: increase Mermaid diagram font size and tone down dark-mode accent borders (#4828) ## Summary Follow-up to the Mermaid brand-theming PR, addressing review feedback: - Diagram text was hard to read at the previous 15px font size; bumped to 18px, light and dark alike. - The dark-mode orange accent border was brighter and more saturated than its fill or the default border, reading as too loud against the dark background. It now reuses the same muted orange already used for the light-mode accent border, which was fine as is. ## Companion change lancedb/sophon#9719 makes the same two changes across its own diagrams. Co-authored-by: Claude Sonnet 5 --- docs/web/basics/catalog.mdx | 4 ++-- docs/web/curation/blob-late-materialization.mdx | 6 +++--- docs/web/curation/distributed-shuffle.mdx | 6 +++--- docs/web/enterprise/adaptive-execution.mdx | 4 ++-- docs/web/enterprise/advanced-conflict-resolution.mdx | 12 ++++++------ docs/web/enterprise/checkpointing.mdx | 6 +++--- docs/web/enterprise/data-page-cache.mdx | 4 ++-- docs/web/enterprise/distributed-compaction.mdx | 6 +++--- docs/web/enterprise/distributed-indexing.mdx | 6 +++--- docs/web/enterprise/distributed-real-time-read.mdx | 6 +++--- docs/web/enterprise/distributed-real-time-write.mdx | 4 ++-- docs/web/enterprise/distributed-write.mdx | 6 +++--- docs/web/enterprise/gpu-refresh-execution.mdx | 6 +++--- docs/web/enterprise/horizontal-scaling.mdx | 12 ++++++------ docs/web/enterprise/intelligent-auto-maintenance.mdx | 6 +++--- docs/web/enterprise/realtime-engine-compaction.mdx | 10 +++++----- docs/web/enterprise/tiered-index-cache.mdx | 4 ++-- docs/web/governance/audit-log.mdx | 6 +++--- docs/web/training/training-cache.mdx | 6 +++--- 19 files changed, 60 insertions(+), 60 deletions(-) diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index f00060f25..1e95aeca4 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -53,7 +53,7 @@ a nested `search` namespace: %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD catalog["root catalog"] --> database["ai_data · database"] @@ -75,7 +75,7 @@ flowchart TD %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD catalog["root catalog"] --> database["ai_data · database"] diff --git a/docs/web/curation/blob-late-materialization.mdx b/docs/web/curation/blob-late-materialization.mdx index 86aff0e54..af6b335eb 100644 --- a/docs/web/curation/blob-late-materialization.mdx +++ b/docs/web/curation/blob-late-materialization.mdx @@ -26,7 +26,7 @@ the join has already settled which rows survive. "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph Naive["Naive: wide column read before filtering"] @@ -41,7 +41,7 @@ flowchart TB D2 --> D3["RemoteTake:
fetch the wide column,
once per surviving row"] end classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class D3 accent ``` @@ -54,7 +54,7 @@ flowchart TB "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph Naive["Naive: wide column read before filtering"] diff --git a/docs/web/curation/distributed-shuffle.mdx b/docs/web/curation/distributed-shuffle.mdx index 1a889f0d3..e834a463a 100644 --- a/docs/web/curation/distributed-shuffle.mdx +++ b/docs/web/curation/distributed-shuffle.mdx @@ -25,7 +25,7 @@ same worker regardless of which plan executor originally read them. "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph Stage1["Stage: scan"] @@ -47,7 +47,7 @@ flowchart LR EX --> PE3 EX --> PE4 classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class EX accent ``` @@ -60,7 +60,7 @@ flowchart LR "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR subgraph Stage1["Stage: scan"] diff --git a/docs/web/enterprise/adaptive-execution.mdx b/docs/web/enterprise/adaptive-execution.mdx index 4b51bf59c..3584cc191 100644 --- a/docs/web/enterprise/adaptive-execution.mdx +++ b/docs/web/enterprise/adaptive-execution.mdx @@ -44,7 +44,7 @@ invocation runs with more resources, fewer, or the same: %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR I["Invocation runs
wall time, CPU, memory, GPU measured"] --> D{"Saturated?"} @@ -66,7 +66,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR I["Invocation runs
wall time, CPU, memory, GPU measured"] --> D{"Saturated?"} diff --git a/docs/web/enterprise/advanced-conflict-resolution.mdx b/docs/web/enterprise/advanced-conflict-resolution.mdx index 3b3964bb5..6fcdbeed3 100644 --- a/docs/web/enterprise/advanced-conflict-resolution.mdx +++ b/docs/web/enterprise/advanced-conflict-resolution.mdx @@ -71,7 +71,7 @@ by a writer that can remap the tagged history eagerly. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Commit["Compaction commit
(defer_index_remap only)"] --> Tagged{"Table already
tagged with an FRI?"} @@ -84,7 +84,7 @@ flowchart TD V0 --> FRI[("Fragment reuse index")] Append --> FRI classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class FRI accent ``` @@ -96,7 +96,7 @@ flowchart TD %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Commit["Compaction commit
(defer_index_remap only)"] --> Tagged{"Table already
tagged with an FRI?"} @@ -145,7 +145,7 @@ that remap across all of them in one job instead of one per compaction. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD C1["Compaction job"] -->|appends transition| FRI["Fragment reuse index
(ledger of transitions)"] @@ -154,7 +154,7 @@ flowchart TD FRI -->|5 transitions or
1 day old| R["Remap catch-up job"] R -->|applies accumulated
transitions| IDX["Affected indexes,
physically remapped"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class FRI,R accent ``` @@ -166,7 +166,7 @@ flowchart TD %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD C1["Compaction job"] -->|appends transition| FRI["Fragment reuse index
(ledger of transitions)"] diff --git a/docs/web/enterprise/checkpointing.mdx b/docs/web/enterprise/checkpointing.mdx index 5fe82bbda..1569071d0 100644 --- a/docs/web/enterprise/checkpointing.mdx +++ b/docs/web/enterprise/checkpointing.mdx @@ -30,7 +30,7 @@ example) can have those side effects repeated for that part's rows. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Part started
event recorded"] --> E["Function executes"] @@ -42,7 +42,7 @@ flowchart LR S -. "worker dies here" .-> R["Next attempt reads the log,
sees no completion,
redoes only this part"] C -. "worker dies here" .-> R2["Next attempt reads the log,
sees this part done,
inherits it, moves on"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class R,R2 accent ``` @@ -54,7 +54,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Part started
event recorded"] --> E["Function executes"] diff --git a/docs/web/enterprise/data-page-cache.mdx b/docs/web/enterprise/data-page-cache.mdx index a4bfd61ae..55d40aef7 100644 --- a/docs/web/enterprise/data-page-cache.mdx +++ b/docs/web/enterprise/data-page-cache.mdx @@ -22,7 +22,7 @@ See [Architecture](/index#architecture). %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Read request
for a data page"] --> M{"In memory?"} @@ -42,7 +42,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Read request
for a data page"] --> M{"In memory?"} diff --git a/docs/web/enterprise/distributed-compaction.mdx b/docs/web/enterprise/distributed-compaction.mdx index 0c483865c..2219647d9 100644 --- a/docs/web/enterprise/distributed-compaction.mdx +++ b/docs/web/enterprise/distributed-compaction.mdx @@ -21,7 +21,7 @@ needed to decide who does what. See [Architecture](/index#architecture). %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR L["Lance's planner
splits fragments into
disjoint tasks"] --> R[("Job registry")] @@ -32,7 +32,7 @@ flowchart LR W2 --> C W3 --> C classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class R,C accent ``` @@ -44,7 +44,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR L["Lance's planner
splits fragments into
disjoint tasks"] --> R[("Job registry")] diff --git a/docs/web/enterprise/distributed-indexing.mdx b/docs/web/enterprise/distributed-indexing.mdx index b40e185df..10ba43055 100644 --- a/docs/web/enterprise/distributed-indexing.mdx +++ b/docs/web/enterprise/distributed-indexing.mdx @@ -21,7 +21,7 @@ from that model in parallel. See [Architecture](/index#architecture). %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Sample data"] --> T["Train shared IVF/PQ model
(vector index only)"] @@ -34,7 +34,7 @@ flowchart LR W2 --> C W3 --> C classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class R accent ``` @@ -46,7 +46,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Sample data"] --> T["Train shared IVF/PQ model
(vector index only)"] diff --git a/docs/web/enterprise/distributed-real-time-read.mdx b/docs/web/enterprise/distributed-real-time-read.mdx index 2adc267e8..c5175c5bd 100644 --- a/docs/web/enterprise/distributed-real-time-read.mdx +++ b/docs/web/enterprise/distributed-real-time-read.mdx @@ -24,7 +24,7 @@ so a query has to combine their results across the network instead. "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node
plans the query"] @@ -50,7 +50,7 @@ flowchart LR W2 --> U U --> R["Merged result"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class U accent ``` @@ -63,7 +63,7 @@ flowchart LR "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node
plans the query"] diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx index b07d6a64d..1f54f0cdb 100644 --- a/docs/web/enterprise/distributed-real-time-write.mdx +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -33,7 +33,7 @@ the underlying object storage; no pod talks to another one directly. "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node
hashes (db, table) to one WAL node"] @@ -64,7 +64,7 @@ flowchart LR "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", - "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node
hashes (db, table) to one WAL node"] diff --git a/docs/web/enterprise/distributed-write.mdx b/docs/web/enterprise/distributed-write.mdx index feda93a57..46624d04b 100644 --- a/docs/web/enterprise/distributed-write.mdx +++ b/docs/web/enterprise/distributed-write.mdx @@ -23,7 +23,7 @@ service is involved. See [Architecture](/index#architecture). %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Source
HuggingFace Parquet, or an
existing Lance dataset in
S3 / GCS / Azure"] @@ -40,7 +40,7 @@ flowchart LR PE2 --> Q PE3 --> Q classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class Q accent ``` @@ -52,7 +52,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR S["Source
HuggingFace Parquet, or an
existing Lance dataset in
S3 / GCS / Azure"] diff --git a/docs/web/enterprise/gpu-refresh-execution.mdx b/docs/web/enterprise/gpu-refresh-execution.mdx index 2c61c34f6..b9c7e6acc 100644 --- a/docs/web/enterprise/gpu-refresh-execution.mdx +++ b/docs/web/enterprise/gpu-refresh-execution.mdx @@ -23,7 +23,7 @@ from calling the Function directly, just a different caller. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR F["Function registered with
gpu=True, gpu_class"] --> A{"Who requests
a worker?"} @@ -32,7 +32,7 @@ flowchart LR D --> P["Same GPU-class placement,
same capacity-wait behavior"] R --> P classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class P accent ``` @@ -44,7 +44,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR F["Function registered with
gpu=True, gpu_class"] --> A{"Who requests
a worker?"} diff --git a/docs/web/enterprise/horizontal-scaling.mdx b/docs/web/enterprise/horizontal-scaling.mdx index 315dd350c..7ecb4c5a0 100644 --- a/docs/web/enterprise/horizontal-scaling.mdx +++ b/docs/web/enterprise/horizontal-scaling.mdx @@ -37,7 +37,7 @@ group it uses: "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph G0["Replica group 0"] @@ -62,7 +62,7 @@ flowchart TB TA -.-> G1 TB["Table B
group 2 only · RF 3"] -.-> G2 classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class TA,TB accent ``` @@ -75,7 +75,7 @@ flowchart TB "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TB subgraph G0["Replica group 0"] @@ -139,7 +139,7 @@ letting each table's read drift to a different group. "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node
routes to the lead group"] @@ -161,7 +161,7 @@ flowchart LR Q -. "only if group 0 has no healthy PE" .-> B0 Q -. "only if group 0 has no healthy PE" .-> B1 classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class Q accent ``` @@ -174,7 +174,7 @@ flowchart LR "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR Q["Query node
routes to the lead group"] diff --git a/docs/web/enterprise/intelligent-auto-maintenance.mdx b/docs/web/enterprise/intelligent-auto-maintenance.mdx index 800b867f6..4b52cc267 100644 --- a/docs/web/enterprise/intelligent-auto-maintenance.mdx +++ b/docs/web/enterprise/intelligent-auto-maintenance.mdx @@ -23,7 +23,7 @@ to. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR E["Table event notifications"] --> P @@ -35,7 +35,7 @@ flowchart LR P --> CL["Possible next step:
Cleanup"] P --> R["Possible next step:
Remap catch-up"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class P accent ``` @@ -47,7 +47,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR E["Table event notifications"] --> P diff --git a/docs/web/enterprise/realtime-engine-compaction.mdx b/docs/web/enterprise/realtime-engine-compaction.mdx index e42d113dc..5451111ad 100644 --- a/docs/web/enterprise/realtime-engine-compaction.mdx +++ b/docs/web/enterprise/realtime-engine-compaction.mdx @@ -82,7 +82,7 @@ instead. Either way, each pass: %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR A["Shard crosses a trigger
(count, bytes, or generation age)"] --> B["Per-pod trigger loop
or backpressure relief pass"] @@ -100,7 +100,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR A["Shard crosses a trigger
(count, bytes, or generation age)"] --> B["Per-pod trigger loop
or backpressure relief pass"] @@ -129,7 +129,7 @@ to flush. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Shard["Shard's per-shard latch"] --> Held{"Already held by
an in-progress pass?"} @@ -138,7 +138,7 @@ flowchart TD Held -->|yes, manual POST /v1/compact| Refuse["Refused outright,
never queued"] Held -->|yes, node drain| Wait["Wait for the current
pass to finish, don't skip"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class Shard accent ``` @@ -150,7 +150,7 @@ flowchart TD %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart TD Shard["Shard's per-shard latch"] --> Held{"Already held by
an in-progress pass?"} diff --git a/docs/web/enterprise/tiered-index-cache.mdx b/docs/web/enterprise/tiered-index-cache.mdx index 32737e25b..439c52df2 100644 --- a/docs/web/enterprise/tiered-index-cache.mdx +++ b/docs/web/enterprise/tiered-index-cache.mdx @@ -22,7 +22,7 @@ storage on every eviction. See [Architecture](/index#architecture). %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Index lookup"] --> M{"In memory?"} @@ -44,7 +44,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Index lookup"] --> M{"In memory?"} diff --git a/docs/web/governance/audit-log.mdx b/docs/web/governance/audit-log.mdx index 9533e346a..6e86f77b3 100644 --- a/docs/web/governance/audit-log.mdx +++ b/docs/web/governance/audit-log.mdx @@ -20,7 +20,7 @@ failure is logged; on success, the final successful check is logged. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Request arrives"] --> C["Authorization check"] @@ -30,7 +30,7 @@ flowchart LR L2 --> T T --> Q["SELECT ... FROM system.public.__audit_log"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class T accent ``` @@ -42,7 +42,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR R["Request arrives"] --> C["Authorization check"] diff --git a/docs/web/training/training-cache.mdx b/docs/web/training/training-cache.mdx index 14769d2f0..3f7e36877 100644 --- a/docs/web/training/training-cache.mdx +++ b/docs/web/training/training-cache.mdx @@ -24,7 +24,7 @@ consequence of connecting to Enterprise at all. %%{init: {"theme": "base", "themeVariables": { "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR DL["PyTorch DataLoader
/ StreamingDataset"] --> T["Enterprise-connected table"] @@ -34,7 +34,7 @@ flowchart LR C -->|miss| O[("Object storage")] O --> Fill["Fills the cache,
served"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#ff734a,stroke-width:1.5px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 class Fast accent ``` @@ -46,7 +46,7 @@ flowchart LR %%{init: {"theme": "base", "themeVariables": { "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "15px" + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR DL["PyTorch DataLoader
/ StreamingDataset"] --> T["Enterprise-connected table"] From b32afe97942c39979f8be4d8311eec79fe66e598 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 4 Nov 2026 20:25:17 -0800 Subject: [PATCH 005/203] docs: add an Introduction nav section with a dedicated Embedded vs Enterprise comparison (#4829) ## Summary - Adds a new top-level "Introduction" nav section before "Getting Started": LanceDB, LanceDB Embedded, LanceDB Enterprise, Embedded vs Enterprise. - Trims the landing page's combined Architecture/Embedded/Enterprise/Compare block down to a short pointer section (keeping its `#architecture` anchor), moving that content into two new pages: `basics/lancedb-embedded.mdx` and `basics/embedded-vs-enterprise.mdx`. - `basics/embedded-vs-enterprise.mdx` consolidates the feature-comparison table and the Enterprise overview's own comparison content (previously duplicated across multiple pages and, within this page, repeated across a dimension table, several narrative subsections, and a usage-differences list) into one comparison page with each section covering a distinct angle. - Repoints the `/enterprise` and `/enterprise/deployment` redirects at `/basics/embedded-vs-enterprise`, since the previous destination only resolves once the Enterprise overlay is applied and fails `rust/lancedb/src/docs.rs`'s link-resolution test against this repo's own `docs/web` tree. ## Companion change lancedb/sophon#9718 trims the Enterprise overview page to drop the content that moved here, and relocates its nav insertion into the new Introduction group. Co-authored-by: Claude Sonnet 5 --- docs/web/basics/embedded-vs-enterprise.mdx | 173 +++++++++++++++++++++ docs/web/basics/lancedb-embedded.mdx | 46 ++++++ docs/web/docs.json | 13 +- docs/web/index.mdx | 140 ++--------------- 4 files changed, 242 insertions(+), 130 deletions(-) create mode 100644 docs/web/basics/embedded-vs-enterprise.mdx create mode 100644 docs/web/basics/lancedb-embedded.mdx diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx new file mode 100644 index 000000000..6df5e5edb --- /dev/null +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -0,0 +1,173 @@ +--- +title: "Embedded vs Enterprise" +sidebarTitle: "Embedded vs Enterprise" +description: "A feature-by-feature comparison between LanceDB Embedded and LanceDB Enterprise." +icon: "scale-balanced" +keywords: ["embedded vs enterprise", "comparison", "oss vs enterprise"] +--- + +LanceDB Embedded runs in your application's process; your data can live on local disk or in object storage. +[LanceDB Enterprise](/enterprise/index) distributes query execution, indexing, maintenance and refresh work across +a cluster of many machines, outside your application. Both are built on the same [Lance](/basics/lance) columnar +file format, so moving data from one edition to the other does not require a data conversion step. See +[Architecture](/index#architecture) for how each one's components fit together. + +## How they differ {#how-they-differ} + +| Dimension | LanceDB Embedded | LanceDB Enterprise | What the difference means | +|:----------|:------------|:-------------------|:-------------------------| +| **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. | +| **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/search/vector-search#expected-performance) and [full-text search](/search/full-text-search#expected-performance) for representative measurements. | +| **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/enterprise/data-page-cache). | +| **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). | +| **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. | +| **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. | +| **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/curation) over SQL. See [SQL reference](/sql). | +| **Native vector dedup** | Not available | `dedupe()` / `duplicate_pairs()` | Index-partition deduplication as a SQL table function, with no full pairwise scan. See [DEDUPE](/sql/dql/dedupe). | +| **Materialized views** | Not available | Server-side, distributed compute | Enterprise derives and refreshes a table from a query as a background job. See [Materialized views](/feature-engineering/materialized-views). | + +## Compare features {#compare} + +| Area | Feature | Embedded | Enterprise | +| --- | --- | :-: | :-: | +| **Data Ingestion** | [Insert data](/ingestion/insert) | ✅ | ✅ | +| | [Merge](/ingestion/merge-insert) | ✅ | ✅ | +| | [RTE Write](/ingestion/realtime-write) | ✅ | ✅ | +| | [Distributed RTE Write](/enterprise/distributed-real-time-write) | ❌ | ✅ | +| | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ | +| | [Import Datasets](/ingestion/import) | ❌ | ✅ | +| | [Distributed Write](/enterprise/distributed-write) | ❌ | ✅ | +| **Semantic Search** | [Vector search](/search/vector-search) | ✅ | ✅ | +| | [Full-text search](/search/full-text-search) | ✅ | ✅ | +| | [Hybrid search](/search/hybrid-search) | ✅ | ✅ | +| | [Filtering](/search/filtering) | ✅ | ✅ | +| | [Reranking](/reranking) | ✅ | ✅ | +| | [Distributed search](/enterprise/distributed-search) | ❌ | ✅ | +| | [RTE Read](/search/realtime-read) | ✅ | ✅ | +| | [Distributed RTE Read](/enterprise/distributed-real-time-read) | ❌ | ✅ | +| | [Cache Prewarm](/enterprise/cache-prewarm) | ❌ | ✅ | +| **Data Curation** | [Inspect Datasets](/curation/inspect-datasets) | ❌ | ✅ | +| | [Statistical Sampling](/curation/statistical-sampling) | ❌ | ✅ | +| | [Selective Sampling](/curation/selective-sampling) | ✅ | ✅ | +| | [Aggregation and profiling](/curation/aggregate) | ❌ | ✅ | +| | [Joins](/curation/join) | ❌ | ✅ | +| | [Blob Late Materialization](/curation/blob-late-materialization) | ❌ | ✅ | +| | [Ranking and deduplication](/curation/windowing) | ❌ | ✅ | +| | [Near-duplicate detection](/curation/dedupe) | ❌ | ✅ | +| | [Chunking](/curation/chunking) | ❌ | ✅ | +| | [Changes since a version](/curation/changes) | ❌ | ✅ | +| | [GPU Function Execution](/curation/gpu-function-execution) | ❌ | ✅ | +| | [Slurm Scheduling](/curation/slurm-scheduling) | ❌ | ✅ | +| **Feature Engineering** | [Computed columns](/feature-engineering/add-computed-column) | ❌ | ✅ | +| | [Incremental Refresh](/enterprise/incremental-refresh) | ❌ | ✅ | +| | [Auto Refresh](/enterprise/auto-refresh) | ❌ | ✅ | +| | [Checkpointing](/enterprise/checkpointing) | ❌ | ✅ | +| | [Adaptive Execution](/enterprise/adaptive-execution) | ❌ | ✅ | +| | [GPU Refresh Execution](/enterprise/gpu-refresh-execution) | ❌ | ✅ | +| | [Slurm Scheduling](/enterprise/slurm-refresh-scheduling) | ❌ | ✅ | +| | [Refresh Materialized View](/feature-engineering/refresh-materialized-view) | ❌ | ✅ | +| | [Embedding registry](/embedding) | ✅ | ✅ | +| **Training** | [PyTorch data loader](/training/data-loading) | ✅ | ✅ | +| | [Training Cache](/training/training-cache) | ❌ | ✅ | +| | [Permutations](/training/permutation) | ✅ | ✅ | +| | [Distributed training](/training/distributed-training) | ✅ | ✅ | +| | [Observability](/training/observability) | ✅ | ✅ | +| | [Checkpointing](/training/checkpointing) | ✅ | ✅ | +| | [Resuming](/training/resuming) | ✅ | ✅ | +| **Management** | [Catalog](/management/catalog) | ❌ | ✅ | +| | [Database](/management/database) | ✅ | ✅ | +| | [Namespace](/management/namespace) | ✅ | ✅ | +| | [Table](/management/table) | ✅ | ✅ | +| | [Branches](/tables/branching) | ✅ | ✅ | +| | [View](/management/view) | ❌ | ✅ | +| | [Materialized view](/management/materialized-view) | ❌ | ✅ | +| | [Secret](/management/secret) | ❌ | ✅ | +| | [Function](/management/function) | ❌ | ✅ | +| | [Storage integration](/management/storage-integration) | ❌ | ✅ | +| **Maintenance** | [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance) | ❌ | ✅ | +| | [Vector Indexing](/indexing/vector-index) | ✅ | ✅ | +| | [FTS Indexing](/indexing/fts-index) | ✅ | ✅ | +| | [Scalar Indexing](/indexing/scalar-index) | ✅ | ✅ | +| | [Incremental Indexing](/indexing/incremental-indexing) | ✅ | ✅ | +| | [Distributed Indexing](/enterprise/distributed-indexing) | ❌ | ✅ | +| | [GPU Indexing](/indexing/gpu-indexing) | ✅ | ✅ | +| | [Compaction](/maintenance/compaction) | ✅ | ✅ | +| | [RTE Compaction](/enterprise/realtime-engine-compaction) | ❌ | ✅ | +| | [Garbage Collection](/maintenance/cleanup) | ✅ | ✅ | +| | [Distributed compaction](/enterprise/distributed-compaction) | ❌ | ✅ | +| | [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) | ❌ | ✅ | +| **Security** | [Authentication](/enterprise/authentication) | ❌ | ✅ | +| | [Authorization](/governance/authorization) | ❌ | ✅ | +| | [Audit Log](/governance/audit-log) | ❌ | ✅ | +| **Deployment** | [Horizontal Scaling](/enterprise/horizontal-scaling) | ❌ | ✅ | +| | [OpenTelemetry](/deployment/opentelemetry) | ✅ | ✅ | +| | [Kubernetes](/enterprise/deployment/kubernetes) | ❌ | ✅ | + +## Usage differences between Enterprise and Embedded {#usage-differences-between-enterprise-and-oss} + +The [quickstart](/quickstart) guide shows both LanceDB Embedded connections and Enterprise `db://...` +connections. Once connected to LanceDB, the table API is largely the same: create a table, search, +filter, evolve the schema, and store multimodal records. However, there are some semantic differences +worth understanding when your code is talking to LanceDB Enterprise. + +### 1\. Connection model {#1-connection-model} + +In LanceDB Enterprise, your app connects via a `db://...` URI and sends requests to the cluster API. +The cluster executes table operations on your behalf. Your code is coupled to a **managed service endpoint**, +whereas LanceDB Embedded is directly coupled to local or object-storage paths. + +### 2\. Returned table type {#2-returned-table-type} + +Connecting to an Enterprise table via `open_table(...)` returns a `RemoteTable`, unlike LanceDB Embedded, +which returns a `LanceTable`. `RemoteTable` is a catalog-backed table accessed through a server/cluster, +and does not support all the same methods as `LanceTable` (see below). + +### 3\. Materialization APIs {#3-materialization-apis} + +For Python users working with LanceDB Enterprise, `RemoteTable` does not support table-level +materialization methods like `table.to_arrow()` or `table.to_pandas()`. This protects users from +accidentally materializing tables that are too large to fit in memory. + +Instead, materialize results through query/search builders, for example +`table.search(...).limit(...).to_pandas()` for a vector or full-text search, or +`table.search().where(...).limit(...).to_arrow()` for a filtered scan. For quick previews, use +`table.head()`. + +### 4\. Maintenance lifecycle {#4-maintenance-lifecycle} + +In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to +existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with +async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger +it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and +`cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients +reject `optimize()` as not supported. + +That means maintenance is managed by platform behavior and cluster configuration, not by explicit +per-table maintenance calls in your application code. + +### 5\. Guardrails and limits {#5-guardrails-and-limits} + +Enterprise can enforce platform-level guardrails, such as index/table limits and safety checks around +operations like `merge_insert` when too many rows are unindexed. LanceDB Embedded mostly exposes +storage/format-level behavior, and you tune many lifecycle tasks yourself. + +This means an operation in LanceDB Enterprise can fail due to service-level policy, not just because +of local table shape or schema mismatch. + + +As a rule of thumb, all you need to remember is this: treat `db://...` as a network service boundary, +use query builders to fetch results, and otherwise interact with your tables as you would in LanceDB +Embedded. + + +## Which one should I use? {#which-one-should-i-use} + +[It's very simple to get started with LanceDB Embedded](/quickstart/): Get started with `pip install lancedb` and begin ingesting +your data and vectors into LanceDB. LanceDB Embedded (open source) makes sense when your dataset fits on one machine, traffic is still +modest, and your team is comfortable handling maintenance tasks such as compaction or reindexing itself. + +Move to LanceDB Enterprise when retrieval becomes shared infrastructure for your business: your data or traffic has +outgrown a single machine, you need private deployment options, or you want platform support for monitoring, security, +and large-scale feature workflows. + +If these sound like your use cases, [reach out to us](https://www.lancedb.com/contact) and we can help you scope your workload and arrange an Enterprise proof of concept. diff --git a/docs/web/basics/lancedb-embedded.mdx b/docs/web/basics/lancedb-embedded.mdx new file mode 100644 index 000000000..cd9c11fff --- /dev/null +++ b/docs/web/basics/lancedb-embedded.mdx @@ -0,0 +1,46 @@ +--- +title: "LanceDB Embedded" +sidebarTitle: "LanceDB Embedded" +description: "The open-source, embedded retrieval library that runs inside your application process." +icon: cube +keywords: ["embedded", "open source", "oss", "local", "sdk", "lancedb embedded"] +--- + +**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. It reads and writes tables on local disk or in object storage from inside your application +process, on the same [Lance](/basics/lance) format and table model that [LanceDB Enterprise](/enterprise/index) +builds on. + + + LanceDB Embedded architecture + + +## Why use LanceDB Embedded? {#why-use-lancedb-embedded} + +LanceDB Embedded fits local retrieval applications, notebooks, development, and single-node data pipelines, where +your application controls its own compute resources and [table maintenance](/maintenance/compaction). + +- **No infrastructure to run** -- the library runs inside your process. There is no server to deploy, configure, + or keep available. +- **Free and open source** -- `pip install lancedb` (or the TypeScript or Rust equivalent) and start reading and + writing tables, with no account or service to set up first. +- **Full local control** -- your application decides where table data lives, when maintenance such as compaction + and indexing runs, and how much compute each operation gets. +- **The same table format as Enterprise** -- Embedded and [Enterprise](/enterprise/index) share the same Lance + format and table model, so moving to a distributed deployment later does not require a data conversion step. + +## Get started {#get-started} + + + + Create a table, add data, and run your first search in a few lines of code. + + + Pick between the Python, TypeScript, and Rust SDKs. + + + +When your data or traffic outgrows a single machine, or you need managed infrastructure, private deployment, or +platform support, see [LanceDB Enterprise](/enterprise/index) and the +[feature-by-feature comparison](/basics/embedded-vs-enterprise). diff --git a/docs/web/docs.json b/docs/web/docs.json index 752d5e9ae..038edc4ce 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -41,7 +41,7 @@ }, { "source": "/enterprise", - "destination": "/#architecture" + "destination": "/basics/embedded-vs-enterprise" }, { "source": "/enterprise/intelligent-scheduling", @@ -89,7 +89,7 @@ }, { "source": "/enterprise/deployment", - "destination": "/#architecture" + "destination": "/basics/embedded-vs-enterprise" }, { "source": "/feature-engineering/data-evolution", @@ -370,9 +370,16 @@ "tab": "Documentation", "groups": [ { - "group": "Getting Started", + "group": "Introduction", "pages": [ "index", + "basics/lancedb-embedded", + "basics/embedded-vs-enterprise" + ] + }, + { + "group": "Getting Started", + "pages": [ "quickstart", "basics/sdk", "basics/sql", diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 84dca553b..8b290b97a 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -63,137 +63,23 @@ through the same table model, whether a workflow uses one table or several relat LanceDB ships as two offerings on the same [Lance](/basics/lance) format and table model, which stores table data, versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized -around that format. Start locally with Embedded, then move to Enterprise when your team needs distributed scale, +around that format: 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. - - - LanceDB Embedded architecture - - - LanceDB Enterprise architecture - - + + + An open-source, embedded retrieval library that runs inside your application process, with no separate + database server to deploy. + + + A distributed multimodal lakehouse service for production workloads that need managed infrastructure and + higher-throughput 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. It reads and writes tables on local disk or in object storage from inside your application -process. 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** is an exabyte-scale, distributed **multimodal lakehouse** service built on the -same table abstraction as Embedded, for search, curation, feature engineering, and high-throughput training data -access. Applications connect through a LanceDB SDK while the service plans and runs work across a fleet: query -serving, read execution and caching, indexing, and background maintenance scale as separate components, with -durable table data and index artifacts kept in object storage, independently of the machines serving requests. -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. See [Distributed search](/enterprise/distributed-search), -[distributed indexing](/enterprise/distributed-indexing), and the other architecture guides linked from the -comparison table below for how work divides across machines. - -Teams choose Enterprise to: - -- **Get new capabilities first** -- SQL, Functions, materialized views, and most other features documented - throughout these docs land in Enterprise first, often well before they reach Embedded, if they ever do. -- **Performance** -- cache frequently read table data near compute with the [Data Page Cache](/enterprise/data-page-cache), - and let [adaptive execution](/enterprise/adaptive-execution) size refresh and curation workers to the job instead - of guessing once. -- **Scale** -- add query-serving capacity by spreading a table across more [replica groups](/enterprise/horizontal-scaling) - as traffic grows, instead of upgrading one machine. -- **Fault tolerance** -- [replication](/enterprise/horizontal-scaling) keeps a table serving when a node fails, so - you lose latency to a warm-up, not an outage. -- **Multicloud deployment** -- bring LanceDB into your own cloud account, in the region your - [GPU capacity](/curation/gpu-function-execution) already lives, instead of moving data to it. -- **Simplify operations** -- [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance) runs - compaction, cleanup, and indexing in the background, with [OpenTelemetry](/deployment/opentelemetry) metrics and - traces instead of guesswork. - -[Reach out to us](https://www.lancedb.com/contact) to set up LanceDB Enterprise in your organization. Sharing a -format does not mean an Enterprise deployment automatically opens an existing Embedded database -- plan how to -move or connect your data. - -### Compare features {#compare} - -| Area | Feature | Embedded | Enterprise | -| --- | --- | :-: | :-: | -| **Data Ingestion** | [Insert data](/ingestion/insert) | ✅ | ✅ | -| | [Merge](/ingestion/merge-insert) | ✅ | ✅ | -| | [RTE Write](/ingestion/realtime-write) | ✅ | ✅ | -| | [Distributed RTE Write](/enterprise/distributed-real-time-write) | ❌ | ✅ | -| | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ | -| | [Import Datasets](/ingestion/import) | ❌ | ✅ | -| | [Distributed Write](/enterprise/distributed-write) | ❌ | ✅ | -| **Semantic Search** | [Vector search](/search/vector-search) | ✅ | ✅ | -| | [Full-text search](/search/full-text-search) | ✅ | ✅ | -| | [Hybrid search](/search/hybrid-search) | ✅ | ✅ | -| | [Filtering](/search/filtering) | ✅ | ✅ | -| | [Reranking](/reranking) | ✅ | ✅ | -| | [Distributed search](/enterprise/distributed-search) | ❌ | ✅ | -| | [RTE Read](/search/realtime-read) | ✅ | ✅ | -| | [Distributed RTE Read](/enterprise/distributed-real-time-read) | ❌ | ✅ | -| | [Cache Prewarm](/enterprise/cache-prewarm) | ❌ | ✅ | -| **Data Curation** | [Inspect Datasets](/curation/inspect-datasets) | ❌ | ✅ | -| | [Statistical Sampling](/curation/statistical-sampling) | ❌ | ✅ | -| | [Selective Sampling](/curation/selective-sampling) | ✅ | ✅ | -| | [Aggregation and profiling](/curation/aggregate) | ❌ | ✅ | -| | [Joins](/curation/join) | ❌ | ✅ | -| | [Blob Late Materialization](/curation/blob-late-materialization) | ❌ | ✅ | -| | [Ranking and deduplication](/curation/windowing) | ❌ | ✅ | -| | [Near-duplicate detection](/curation/dedupe) | ❌ | ✅ | -| | [Chunking](/curation/chunking) | ❌ | ✅ | -| | [Changes since a version](/curation/changes) | ❌ | ✅ | -| | [GPU Function Execution](/curation/gpu-function-execution) | ❌ | ✅ | -| | [Slurm Scheduling](/curation/slurm-scheduling) | ❌ | ✅ | -| **Feature Engineering** | [Computed columns](/feature-engineering/add-computed-column) | ❌ | ✅ | -| | [Incremental Refresh](/enterprise/incremental-refresh) | ❌ | ✅ | -| | [Auto Refresh](/enterprise/auto-refresh) | ❌ | ✅ | -| | [Checkpointing](/enterprise/checkpointing) | ❌ | ✅ | -| | [Adaptive Execution](/enterprise/adaptive-execution) | ❌ | ✅ | -| | [GPU Refresh Execution](/enterprise/gpu-refresh-execution) | ❌ | ✅ | -| | [Slurm Scheduling](/enterprise/slurm-refresh-scheduling) | ❌ | ✅ | -| | [Refresh Materialized View](/feature-engineering/refresh-materialized-view) | ❌ | ✅ | -| | [Embedding registry](/embedding) | ✅ | ✅ | -| **Training** | [PyTorch data loader](/training/data-loading) | ✅ | ✅ | -| | [Training Cache](/training/training-cache) | ❌ | ✅ | -| | [Permutations](/training/permutation) | ✅ | ✅ | -| | [Distributed training](/training/distributed-training) | ✅ | ✅ | -| | [Observability](/training/observability) | ✅ | ✅ | -| | [Checkpointing](/training/checkpointing) | ✅ | ✅ | -| | [Resuming](/training/resuming) | ✅ | ✅ | -| **Management** | [Catalog](/management/catalog) | ❌ | ✅ | -| | [Database](/management/database) | ✅ | ✅ | -| | [Namespace](/management/namespace) | ✅ | ✅ | -| | [Table](/management/table) | ✅ | ✅ | -| | [Branches](/tables/branching) | ✅ | ✅ | -| | [View](/management/view) | ❌ | ✅ | -| | [Materialized view](/management/materialized-view) | ❌ | ✅ | -| | [Secret](/management/secret) | ❌ | ✅ | -| | [Function](/management/function) | ❌ | ✅ | -| | [Storage integration](/management/storage-integration) | ❌ | ✅ | -| **Maintenance** | [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance) | ❌ | ✅ | -| | [Vector Indexing](/indexing/vector-index) | ✅ | ✅ | -| | [FTS Indexing](/indexing/fts-index) | ✅ | ✅ | -| | [Scalar Indexing](/indexing/scalar-index) | ✅ | ✅ | -| | [Incremental Indexing](/indexing/incremental-indexing) | ✅ | ✅ | -| | [Distributed Indexing](/enterprise/distributed-indexing) | ❌ | ✅ | -| | [GPU Indexing](/indexing/gpu-indexing) | ✅ | ✅ | -| | [Compaction](/maintenance/compaction) | ✅ | ✅ | -| | [RTE Compaction](/enterprise/realtime-engine-compaction) | ❌ | ✅ | -| | [Garbage Collection](/maintenance/cleanup) | ✅ | ✅ | -| | [Distributed compaction](/enterprise/distributed-compaction) | ❌ | ✅ | -| | [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) | ❌ | ✅ | -| **Security** | [Authentication](/enterprise/authentication) | ❌ | ✅ | -| | [Authorization](/governance/authorization) | ❌ | ✅ | -| | [Audit Log](/governance/audit-log) | ❌ | ✅ | -| **Deployment** | [Horizontal Scaling](/enterprise/horizontal-scaling) | ❌ | ✅ | -| | [OpenTelemetry](/deployment/opentelemetry) | ✅ | ✅ | -| | [Kubernetes](/enterprise/deployment/kubernetes) | ❌ | ✅ | +See [Embedded vs Enterprise](/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including +architecture, latency, throughput, and day-to-day usage differences. ## Projects using LanceDB {#projects-using-lancedb} From edc49e60e2e14a53ff67ff62d33b68981d8a6c6f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 15:16:28 +0800 Subject: [PATCH 006/203] feat: expose Function failure tracebacks (#4861) Function refresh failures and skipped-row diagnostics lose the traceback when decoded by the SDK. Expose the server-provided optional `traceback` on job failure details and Function error records in Rust, Python, and Node.js, while keeping existing compact error messages. Responses from older servers remain supported when the field is absent. Tracebacks may be truncated by the server. The Rust `Error::JobFailed` variant now stores `Box` so the added diagnostics do not enlarge every `Result` error payload. --- docs/src/js/interfaces/FunctionErrorRecord.md | 10 ++++++++++ docs/src/js/interfaces/JobFailureInfo.md | 10 ++++++++++ nodejs/src/job.rs | 3 +++ nodejs/src/table.rs | 3 +++ python/python/lancedb/_lancedb.pyi | 6 ++++++ python/python/tests/test_remote_db.py | 13 +++++++++++++ python/src/job.rs | 3 +++ python/src/table.rs | 3 +++ rust/lancedb/src/error.rs | 4 +++- rust/lancedb/src/function.rs | 3 +++ rust/lancedb/src/job.rs | 2 +- rust/lancedb/src/remote/job.rs | 13 +++++++++---- rust/lancedb/src/remote/sql.rs | 5 +++-- rust/lancedb/src/remote/table.rs | 14 ++++++++++++-- 14 files changed, 82 insertions(+), 10 deletions(-) diff --git a/docs/src/js/interfaces/FunctionErrorRecord.md b/docs/src/js/interfaces/FunctionErrorRecord.md index 3a26534a0..16198e70e 100644 --- a/docs/src/js/interfaces/FunctionErrorRecord.md +++ b/docs/src/js/interfaces/FunctionErrorRecord.md @@ -90,3 +90,13 @@ detail was capped. ```ts tableVersion: number; ``` + +*** + +### traceback? + +```ts +optional traceback: string; +``` + +User-code traceback, possibly truncated by the server. diff --git a/docs/src/js/interfaces/JobFailureInfo.md b/docs/src/js/interfaces/JobFailureInfo.md index 5683ee5f0..fe9ce04e3 100644 --- a/docs/src/js/interfaces/JobFailureInfo.md +++ b/docs/src/js/interfaces/JobFailureInfo.md @@ -31,3 +31,13 @@ optional phase: string; ```ts optional retryable: boolean; ``` + +*** + +### traceback? + +```ts +optional traceback: string; +``` + +User-code traceback, possibly truncated by the server. diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index b8b2d9e94..485035d33 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -141,6 +141,7 @@ impl Job { self.inner.failure().map(|failure| JobFailureInfo { phase: failure.phase, message: failure.message, + traceback: failure.traceback, retryable: failure.retryable, }) } @@ -218,5 +219,7 @@ impl From for JobInfo { pub struct JobFailureInfo { pub phase: Option, pub message: Option, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub retryable: Option, } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 9c9fd5156..c480ba042 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1530,6 +1530,8 @@ pub struct FunctionErrorRecord { pub table_version: i64, pub error_type: String, pub error_message: String, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub created_at_millis: i64, } @@ -1545,6 +1547,7 @@ impl From for FunctionErrorRecord { table_version: record.table_version as i64, error_type: record.error_type, error_message: record.error_message, + traceback: record.traceback, created_at_millis: record.created_at_millis, } } diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 351933ed5..ed62b6b1d 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -465,6 +465,10 @@ class JobFailureInfo: @property def message(self) -> Optional[str]: ... @property + def traceback(self) -> Optional[str]: + """User-code traceback, possibly truncated by the server.""" + ... + @property def retryable(self) -> Optional[bool]: ... @property def sql_job_id(self) -> Optional[str]: ... @@ -1014,6 +1018,8 @@ class FunctionErrorRecord: table_version: int error_type: str error_message: str + traceback: Optional[str] + """User-code traceback, possibly truncated by the server.""" created_at_millis: int class FunctionErrorFragment: diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8aec4d185..8178aec62 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2055,6 +2055,9 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): "table_version": 11, "error_type": "ValueError", "error_message": "bad input 'x'", + "traceback": ( + "Traceback (most recent call last):\nValueError: bad input 'x'" + ), "created_at_millis": 1700000000000, } ], @@ -2102,6 +2105,9 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): assert errors.records[0].row_id == 42 assert errors.records[0].row_address == 12884901897 assert errors.records[0].function_version == "2" + assert errors.records[0].traceback == ( + "Traceback (most recent call last):\nValueError: bad input 'x'" + ) assert repr(errors.records[0]) == ( 'FunctionErrorRecord(job_id="j-7", fragment_id=3, row_offset=9, ' 'row_address=12884901897, column="embedding", ' @@ -5128,6 +5134,10 @@ def test_remote_connection_jobs_surface(): failure=dict( phase="execute", message="worker died", + traceback=( + "Traceback (most recent call last):\n" + "RuntimeError: worker died" + ), retryable=True, sql_job_id="sql-job-1", ), @@ -5217,6 +5227,9 @@ def test_remote_connection_jobs_surface(): assert progress["waiting_for_job_id"] == "job-maintenance" assert progress["paused_at_millis"] == 1200 assert job.failure.message == "worker died" + assert job.failure.traceback == ( + "Traceback (most recent call last):\nRuntimeError: worker died" + ) assert job.failure.sql_job_id == "sql-job-1" assert repr(job.failure) == ( 'JobFailureInfo(phase="execute", message="worker died", retryable=True, ' diff --git a/python/src/job.rs b/python/src/job.rs index aa4d8890f..79a9cd524 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -232,6 +232,8 @@ impl From for JobInfo { pub struct JobFailureInfo { phase: Option, message: Option, + /// User-code traceback, possibly truncated by the server. + traceback: Option, retryable: Option, sql_job_id: Option, } @@ -342,6 +344,7 @@ impl From for JobDescription { failure: description.failure.map(|failure| JobFailureInfo { phase: failure.phase, message: failure.message, + traceback: failure.traceback, retryable: failure.retryable, sql_job_id: failure.sql_job_id, }), diff --git a/python/src/table.rs b/python/src/table.rs index 4ccc76f89..44c8017c4 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -622,6 +622,8 @@ pub struct FunctionErrorRecord { pub table_version: u64, pub error_type: String, pub error_message: String, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, pub created_at_millis: i64, } @@ -662,6 +664,7 @@ impl From for FunctionErrorRecord { table_version: record.table_version, error_type: record.error_type, error_message: record.error_message, + traceback: record.traceback, created_at_millis: record.created_at_millis, } } diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index c31167148..9c79fcf95 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -159,6 +159,8 @@ pub struct JobFailure { pub phase: Option, /// A human-readable reason, when known. pub message: Option, + /// User-code traceback, possibly truncated by the server. + pub traceback: Option, /// Whether a retry could clear the failure, when known. pub retryable: Option, /// Isolated SQL job that raised this failure, when the server supplies @@ -255,7 +257,7 @@ pub enum Error { #[snafu(display("Job{} failed{failure}", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobFailed { job_id: Option, - failure: JobFailure, + failure: Box, }, #[snafu(display("Job{} was cancelled", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobCancelled { job_id: Option }, diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 96eb4de10..5f322a8f4 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1121,6 +1121,9 @@ pub struct FunctionErrorRecord { pub error_type: String, /// The error's text. pub error_message: String, + /// User-code traceback, possibly truncated by the server. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub traceback: Option, /// When the error was recorded, in milliseconds since the epoch. pub created_at_millis: i64, } diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 823834798..8644c6a48 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -583,7 +583,7 @@ impl Outcome { Self::Failed(source) => { let (job_id, failure) = match source.as_ref() { Error::JobFailed { job_id, failure } => (job_id.clone(), failure.clone()), - _ => (None, JobFailure::from_source(source)), + _ => (None, Box::new(JobFailure::from_source(source))), }; Err(Error::JobFailed { job_id, failure }) } diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index a5baab7b0..0c652a3ae 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -74,6 +74,8 @@ pub(super) struct ReportedFailure { #[serde(default)] message: Option, #[serde(default)] + traceback: Option, + #[serde(default)] retryable: Option, #[serde(default)] sql_job_id: Option, @@ -134,6 +136,7 @@ impl ReportedFailure { JobFailure { phase: self.phase, message: self.message, + traceback: self.traceback, retryable: self.retryable, sql_job_id: self.sql_job_id, source: None, @@ -266,10 +269,12 @@ impl JobHandle for RemoteJob { JobState::Failed => { return Err(Error::JobFailed { job_id: Some(self.job_id.clone()), - failure: description - .failure - .map(ReportedFailure::into_job_failure) - .unwrap_or_default(), + failure: Box::new( + description + .failure + .map(ReportedFailure::into_job_failure) + .unwrap_or_default(), + ), }); } JobState::Cancelled => { diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 94d8bf063..83dedcb6d 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -1666,13 +1666,14 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro if let Some(sql_job_id) = sql_job_id { return Error::JobFailed { job_id: Some(sql_job_id.clone()), - failure: JobFailure { + failure: Box::new(JobFailure { phase: None, message: Some(status.message().into()), + traceback: None, retryable: None, sql_job_id: Some(sql_job_id), source: Some(Arc::new(error)), - }, + }), }; } error diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index b95227db6..af0946600 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -8592,6 +8592,7 @@ mod tests { // The server said only that it failed, so nothing may be invented. assert!(failure.message.is_none(), "{failure:?}"); assert!(failure.phase.is_none(), "{failure:?}"); + assert!(failure.traceback.is_none(), "{failure:?}"); assert!(failure.retryable.is_none(), "{failure:?}"); assert_eq!(err.to_string(), "Job job-err failed"); } @@ -8616,7 +8617,7 @@ mod tests { "/v1/jobs/describe" => http::Response::builder() .status(200) .body( - r#"{"job_id": "job-err", "job_state": "FAILED", "failure": {"phase": "commit", "message": "preempted", "retryable": true}}"# + r#"{"job_id": "job-err", "job_state": "FAILED", "failure": {"phase": "commit", "message": "preempted", "traceback": "Traceback (most recent call last):\nValueError: preempted", "retryable": true}}"# .to_string(), ) .unwrap(), @@ -8634,6 +8635,10 @@ mod tests { panic!("expected JobFailed, got {err:?}"); }; assert_eq!(failure.message.as_deref(), Some("preempted")); + assert_eq!( + failure.traceback.as_deref(), + Some("Traceback (most recent call last):\nValueError: preempted") + ); assert_eq!(failure.phase.as_deref(), Some("commit")); assert_eq!(failure.retryable, Some(true)); assert_eq!(err.to_string(), "Job job-err failed: preempted (in commit)"); @@ -11029,7 +11034,8 @@ mod tests { "row_id": 42, "row_address": 12884901897, "column": "embedding", "function": "embed", "function_version": "2", "table_version": 11, "error_type": "ValueError", - "error_message": "bad input 'x'", "created_at_millis": 1700000000000}], + "error_message": "bad input 'x'", "traceback": "Traceback (most recent call last):\nValueError: bad input 'x'", + "created_at_millis": 1700000000000}], "fragments": [{"job_id": "j-7", "fragment_id": 4, "rows_skipped": 500, "rows_recorded": 100}], "truncated": true}"#, @@ -11060,6 +11066,9 @@ mod tests { table_version: 11, error_type: "ValueError".into(), error_message: "bad input 'x'".into(), + traceback: Some( + "Traceback (most recent call last):\nValueError: bad input 'x'".into() + ), created_at_millis: 1_700_000_000_000, }] ); @@ -11091,6 +11100,7 @@ mod tests { .unwrap(); assert!(legacy.row_id.is_none()); assert!(legacy.row_address.is_none()); + assert!(legacy.traceback.is_none()); // No filter sends no filter, and an empty listing reads as such. let table = Table::new_with_handler("my_table", |request| { From dc6a08a25f4c8065af7c11bc534ea53bbfc5c9d1 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 4 Nov 2026 23:34:31 -0800 Subject: [PATCH 007/203] docs: rename the Semantic Search sidebar group to Search (#4862) The Search group covers full-text and hybrid search as well as vector search, and full-text search is lexical, not semantic. This renames the group to "Search" in the sidebar and in the Embedded vs Enterprise comparison table. `mint validate` and `mint broken-links --check-anchors` pass on the assembled site. --- docs/web/basics/embedded-vs-enterprise.mdx | 2 +- docs/web/docs.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index 6df5e5edb..36589eb36 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -37,7 +37,7 @@ file format, so moving data from one edition to the other does not require a dat | | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ | | | [Import Datasets](/ingestion/import) | ❌ | ✅ | | | [Distributed Write](/enterprise/distributed-write) | ❌ | ✅ | -| **Semantic Search** | [Vector search](/search/vector-search) | ✅ | ✅ | +| **Search** | [Vector search](/search/vector-search) | ✅ | ✅ | | | [Full-text search](/search/full-text-search) | ✅ | ✅ | | | [Hybrid search](/search/hybrid-search) | ✅ | ✅ | | | [Filtering](/search/filtering) | ✅ | ✅ | diff --git a/docs/web/docs.json b/docs/web/docs.json index 038edc4ce..4f5f49d0d 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -419,7 +419,7 @@ ] }, { - "group": "Semantic Search", + "group": "Search", "pages": [ "search/index", "search/vector-search", From e6b04c5da7822c48bddb7f1a7982ffdaf00a53df Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 15:37:16 +0800 Subject: [PATCH 008/203] docs(function): define forward-compatible version projection (#4863) Clarify `FunctionVersion` forward compatibility: unknown top-level fields are accepted during decoding and omitted from canonical JSON, while all defined fields and the open `image.descriptor` content retain their values. Extend the existing Rust and Python canonical round-trip tests to assert the complete projected object, including future discriminator values. This documents and tests the existing behavior; it does not change runtime serialization or promise lossless retention of unknown top-level fields. Related: ENT-2176. --- python/python/lancedb/functions.py | 6 ++++++ .../tests/test_first_class_function_slice1.py | 11 ++++++++--- rust/lancedb/src/function.rs | 6 ++++++ .../tests/first_class_function_slice1.rs | 18 +++++++++++------- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 0257e4d7b..fb606cd36 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -469,6 +469,12 @@ _ObjectVersion = Annotated[ class FunctionVersion(_RemoteValue): """A pinned object revision, independent of its executable image digest. + Unknown top-level fields from newer servers are accepted for forward + decoding, but they are not exposed on this value and are omitted from + ``to_canonical_json()``. Known fields retain their complete values, while + unknown fields inside the open ``image.descriptor`` mapping remain + available. + ``name`` and ``namespace_path`` are the Function's parts, as a [SecretReference][lancedb.functions.SecretReference] carries a Secret's; they are what [get_function][lancedb.db.DBConnection.get_function] takes. diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 980c11993..27a9a9376 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -301,10 +301,15 @@ def test_unknown_fields_and_discriminators_are_forward_decodable(): version = FunctionVersion.from_json(json.dumps(value)) assert version.image.descriptor["future_interface"] == {"kind": "wasm"} - assert json.loads(version.to_canonical_json())["image"]["descriptor"][ - "future_interface" - ] == {"kind": "wasm"} assert version.signature.output.kind == "future_output_shape" + assert not hasattr(version, "future_version_metadata") + + canonical = json.loads(version.to_canonical_json()) + expected = json.loads(fixture("remote_function_version.canonical.json")) + expected["image"]["descriptor"]["future_interface"] = {"kind": "wasm"} + expected["signature"]["output"]["kind"] = "future_output_shape" + assert canonical == expected + assert "future_version_metadata" not in canonical def test_function_application_uses_rename_columns_only(): diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 5f322a8f4..c68f29923 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -570,6 +570,12 @@ impl<'de> Deserialize<'de> for RowTimeoutSeconds { /// /// The Function is named by its parts, `name` and `namespace_path`, the way a /// [`SecretReference`](crate::secrets::SecretReference) names a Secret. +/// +/// Unknown top-level fields from newer servers are accepted for forward +/// decoding, but they are not part of this value and are omitted from +/// canonical JSON. Known fields retain their complete values, while unknown +/// fields inside the open [`FunctionImage::descriptor`] JSON object remain +/// available. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersion { name: String, diff --git a/rust/lancedb/tests/first_class_function_slice1.rs b/rust/lancedb/tests/first_class_function_slice1.rs index 86ccea1cc..878e74bb0 100644 --- a/rust/lancedb/tests/first_class_function_slice1.rs +++ b/rust/lancedb/tests/first_class_function_slice1.rs @@ -182,13 +182,17 @@ fn unknown_fields_and_discriminators_are_forward_decodable() { let version = FunctionVersion::from_json(&result.to_string()).expect("future remote value"); assert_eq!(version.image().descriptor["future_interface"]["version"], 2); assert_eq!(version.signature().output.kind, "future_output_shape"); - assert_eq!( - serde_json::from_str::( - &version.to_canonical_json().expect("canonical future value") - ) - .expect("canonical JSON")["image"]["descriptor"]["future_interface"], - serde_json::json!({"version": 2}) - ); + let canonical: Value = + serde_json::from_str(&version.to_canonical_json().expect("canonical future value")) + .expect("canonical JSON"); + + let mut expected: Value = + serde_json::from_str(fixture("remote_function_version.canonical.json").trim()) + .expect("canonical FunctionVersion fixture"); + expected["image"]["descriptor"]["future_interface"] = serde_json::json!({"version": 2}); + expected["signature"]["output"]["kind"] = Value::String("future_output_shape".to_string()); + assert_eq!(canonical, expected); + assert!(canonical.get("future_version_metadata").is_none()); } #[test] From 071c9c541de6f2662712ae017420b73b82d18dae Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 4 Nov 2026 23:39:10 -0800 Subject: [PATCH 009/203] docs: add Console page, hide CLI from nav, drop Branches from the Management nav (#4859) ## Summary - Hides `tools/cli.mdx` from the sidebar and from sitemap/search via `.mintignore`, unlinking its one reference in `basics/sql.mdx`. No SDK doc-link depends on this page. - Removes `tables/branching.mdx` from the Management nav group, but leaves it reachable (no `.mintignore` entry): the SDK's `diff_branch()`/`cherry_pick()` error messages link to `/tables/branching#diff-a-branch` and `#merge-a-branch`, and `rust/lancedb/src/docs.rs`'s link-resolution test asserts those paths aren't `.mintignore`'d. - Adds a Console row to the comparison table, linking to the companion change's new `enterprise/console` page. ## Companion change lancedb/sophon#9783 adds `enterprise/console.mdx` and inserts it into the "Getting Started" nav group this PR touches. --------- Co-authored-by: Claude Sonnet 5 --- docs/web/.mintignore | 1 + docs/web/basics/embedded-vs-enterprise.mdx | 1 + docs/web/basics/sql.mdx | 2 +- docs/web/docs.json | 2 -- 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/web/.mintignore b/docs/web/.mintignore index e69de29bb..388087951 100644 --- a/docs/web/.mintignore +++ b/docs/web/.mintignore @@ -0,0 +1 @@ +tools/cli.mdx diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index 36589eb36..c11324300 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -84,6 +84,7 @@ file format, so moving data from one edition to the other does not require a dat | | [Secret](/management/secret) | ❌ | ✅ | | | [Function](/management/function) | ❌ | ✅ | | | [Storage integration](/management/storage-integration) | ❌ | ✅ | +| | [Console](/enterprise/console) | ❌ | ✅ | | **Maintenance** | [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance) | ❌ | ✅ | | | [Vector Indexing](/indexing/vector-index) | ✅ | ✅ | | | [FTS Indexing](/indexing/fts-index) | ✅ | ✅ | diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 93b766c44..46f54ce53 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -80,7 +80,7 @@ endpoint, returning results as Arrow record batches: does 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. -3. **The [LanceDB CLI](/tools/cli).** Open an interactive SQL shell, or run a +3. **The LanceDB CLI.** Open an interactive SQL shell, or run a statement or file, directly from the command line with no code at all. The [SQL reference](/sql#connecting) shows a query from Python. See diff --git a/docs/web/docs.json b/docs/web/docs.json index 4f5f49d0d..bdc849f63 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -383,7 +383,6 @@ "quickstart", "basics/sdk", "basics/sql", - "tools/cli", "basics/agentic-skills", "deployment/support" ] @@ -494,7 +493,6 @@ "management/database", "management/namespace", "management/table", - "tables/branching", "management/view", "management/materialized-view", "management/secret", From 1db0d3ca5f57303419a1522e2527a285e6254eb2 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Thu, 5 Nov 2026 00:13:02 -0800 Subject: [PATCH 010/203] docs: label early access features and hide ones not ready to document (#4855) Labels early access features and hides features we aren't documenting yet. **Early access label:** Functions (4 pages, plus the GPU refresh, checkpointing and adaptive execution pages), Secrets (3 pages), Tiered Index Cache, Blob V2, and merge insert, which is labelled for Enterprise only. Two sidebar titles are shorter so the tag fits. **Hidden:** branching, JSON columns and geospatial. - The JSON functions page and the agent branch-experiments tutorial go in `.mintignore`. - `tables/branching` stays reachable but out of the nav, as #4859 left it, because SDK error messages link to it. - Other pages' mentions of these features become draft comments, so they're easy to restore. **Secrets page:** drops references to manual KMS setup, which the control plane handles. It keeps the encryption-at-rest facts, states the Azure value-size limit inline, and points a 501 error to support. --- docs/web/.mintignore | 7 +++++++ docs/web/basics/embedded-vs-enterprise.mdx | 6 +++++- docs/web/basics/naming.mdx | 14 +++++++++++--- docs/web/curation/create-function.mdx | 3 +++ docs/web/curation/gpu-function-execution.mdx | 5 ++++- docs/web/curation/vend-secret.mdx | 3 +++ docs/web/docs.json | 4 +--- docs/web/enterprise/adaptive-execution.mdx | 3 +++ docs/web/enterprise/checkpointing.mdx | 3 +++ docs/web/enterprise/gpu-refresh-execution.mdx | 3 +++ docs/web/enterprise/tiered-index-cache.mdx | 5 ++++- docs/web/index.mdx | 6 +++++- docs/web/ingestion/merge-insert.mdx | 2 ++ docs/web/maintenance/cleanup.mdx | 14 ++++++++++---- docs/web/management/function.mdx | 3 +++ docs/web/management/secret.mdx | 15 ++++++++------- docs/web/management/table.mdx | 18 ++++++++++++------ docs/web/search/realtime-read.mdx | 4 ++-- docs/web/sql/data-types.mdx | 10 +++++++++- docs/web/sql/ddl/function.mdx | 3 +++ docs/web/sql/ddl/secret.mdx | 3 ++- docs/web/sql/dql/functions.mdx | 8 ++++++-- docs/web/sql/dql/scalar-functions.mdx | 10 +++++++++- docs/web/tutorials/index.mdx | 2 +- 24 files changed, 119 insertions(+), 35 deletions(-) diff --git a/docs/web/.mintignore b/docs/web/.mintignore index 388087951..8fea3d17d 100644 --- a/docs/web/.mintignore +++ b/docs/web/.mintignore @@ -1 +1,8 @@ tools/cli.mdx +# Branching is Beta; not documented until early access. tables/branching.mdx +# stays reachable (out of the nav only): SDK error messages link to it. +# To restore: docs.json Tutorials > Feature Engineering, after tutorials/feature-engineering/materialized-views. +agent-branch-experiments.mdx +# JSON columns are Beta; not documented until early access. +# To restore: docs.json Documentation > SQL Reference > DQL, after sql/dql/vector-distance. +sql/dql/json-functions.mdx diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index c11324300..da58acb7d 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -78,7 +78,6 @@ file format, so moving data from one edition to the other does not require a dat | | [Database](/management/database) | ✅ | ✅ | | | [Namespace](/management/namespace) | ✅ | ✅ | | | [Table](/management/table) | ✅ | ✅ | -| | [Branches](/tables/branching) | ✅ | ✅ | | | [View](/management/view) | ❌ | ✅ | | | [Materialized view](/management/materialized-view) | ❌ | ✅ | | | [Secret](/management/secret) | ❌ | ✅ | @@ -104,6 +103,11 @@ file format, so moving data from one edition to the other does not require a dat | | [OpenTelemetry](/deployment/opentelemetry) | ✅ | ✅ | | | [Kubernetes](/enterprise/deployment/kubernetes) | ❌ | ✅ | +{/* +Draft until branching reaches early access; restore to the Management rows. +| | [Branches](/tables/branching) | ✅ | ✅ | +*/} + ## Usage differences between Enterprise and Embedded {#usage-differences-between-enterprise-and-oss} The [quickstart](/quickstart) guide shows both LanceDB Embedded connections and Enterprise `db://...` diff --git a/docs/web/basics/naming.mdx b/docs/web/basics/naming.mdx index 165840218..b00f50bf4 100644 --- a/docs/web/basics/naming.mdx +++ b/docs/web/basics/naming.mdx @@ -10,7 +10,7 @@ keywords: ["names", "naming", "table name", "namespace", "identifier", "limits"] -Databases, namespaces, tables, views and branches all have names. Choose names +Databases, namespaces, tables and views all have names.{/* Draft until branching reaches early access: restore "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. @@ -21,10 +21,14 @@ Use the following rules for names that work across LanceDB Embedded and LanceDB | Table, materialized view, view | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | | Namespace component | ASCII letters and digits, `-`, `_`, `.` | 1 to 64 characters; at most 10 components in a path | | Database | ASCII letters and digits, `-`, `_`, `.`, with `/` between components | 1 to 64 characters for the whole name | -| Branch | Avoid `$` and `:`; use ASCII letters, digits, `-` and `_` for portability | Keep to 1 to 64 characters | | Secret | ASCII letters and digits, `-`, `_`, `.` | 1 to 128 characters | | Function | ASCII letters and digits, `_` | 1 to 128 characters | +{/* +Draft until branching reaches early access; restore after the Database row. +| Branch | Avoid `$` and `:`; use ASCII letters, digits, `-` and `_` for portability | Keep to 1 to 64 characters | +*/} + - Names and individual namespace or database components must not be empty. - Table, view, namespace and database components cannot be `.` or `..`. - Secret names cannot be `.` or `..`. @@ -60,5 +64,9 @@ The empty path `[]` identifies the root namespace. ## Learn more {#next} - [Namespaces](/management/namespace): create namespaces and address tables. -- [Branches](/tables/branching): name and manage separate lines of table history. - [Limits](/basics/limits): check other constraints before designing your schema. + +{/* +Draft until branching reaches early access; restore after Namespaces. +- [Branches](/tables/branching): name and manage separate lines of table history. +*/} diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 232cf79dc..a2751cf8f 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -1,5 +1,6 @@ --- title: "Create a Function" +tag: "Early access" 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 @@ -9,6 +10,8 @@ availability: enterprise: available --- +Early access + 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 diff --git a/docs/web/curation/gpu-function-execution.mdx b/docs/web/curation/gpu-function-execution.mdx index f769faef4..e7f6f0f6a 100644 --- a/docs/web/curation/gpu-function-execution.mdx +++ b/docs/web/curation/gpu-function-execution.mdx @@ -1,6 +1,7 @@ --- title: "GPU Function Execution" -sidebarTitle: "GPU Function Execution" +tag: "Early access" +sidebarTitle: "GPU Functions" description: "How a GPU Function's worker gets scheduled onto a GPU-capable node, and what happens when none is free." icon: microchip keywords: ["gpu", "gpu class", "scheduling", "function", "udf", "kubernetes", "node selector"] @@ -9,6 +10,8 @@ availability: enterprise: available --- +Early access + [Registering a GPU Function](/curation/create-function#gpu) sets `gpu=True` and an optional `gpu_class`; this page covers what happens after that, when a job actually needs a worker. An operator configures one or more named diff --git a/docs/web/curation/vend-secret.mdx b/docs/web/curation/vend-secret.mdx index 6a16fcdf0..801f16436 100644 --- a/docs/web/curation/vend-secret.mdx +++ b/docs/web/curation/vend-secret.mdx @@ -1,5 +1,6 @@ --- title: "Vend a Secret to a Function" +tag: "Early access" sidebarTitle: "Vend Secret" description: "Bind a Secret to a Function by reference, and how its value reaches running code during SQL evaluation and refresh." icon: key @@ -9,6 +10,8 @@ availability: enterprise: available --- +Early access + A Function that calls an external service needs a credential without putting it in the function's source -- see [Create a Function](/curation/create-function#remote) for how to register diff --git a/docs/web/docs.json b/docs/web/docs.json index bdc849f63..58ad78a52 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -590,7 +590,6 @@ "sql/dql/dedupe", "sql/dql/duplicate-pairs", "sql/dql/vector-distance", - "sql/dql/json-functions", "sql/dql/blob-descriptor", "sql/dql/generate-series", "sql/dql/explain" @@ -708,8 +707,7 @@ "group": "Feature Engineering", "pages": [ "tutorials/feature-engineering/feature-engineering-101", - "tutorials/feature-engineering/materialized-views", - "agent-branch-experiments" + "tutorials/feature-engineering/materialized-views" ] }, { diff --git a/docs/web/enterprise/adaptive-execution.mdx b/docs/web/enterprise/adaptive-execution.mdx index 3584cc191..0c8c20b86 100644 --- a/docs/web/enterprise/adaptive-execution.mdx +++ b/docs/web/enterprise/adaptive-execution.mdx @@ -1,5 +1,6 @@ --- title: "Adaptive Execution" +tag: "Early access" sidebarTitle: "Adaptive Execution" description: "How a Function refresh's part size, resource class, worker count and checkpoint frequency adjust themselves to observed behavior." icon: "gauge-high" @@ -8,6 +9,8 @@ availability: enterprise: available --- +Early access + When a [computed column](/feature-engineering/add-computed-column) or [materialized view](/feature-engineering/materialized-views) is filled by a registered [Function](/curation/create-function), LanceDB Enterprise diff --git a/docs/web/enterprise/checkpointing.mdx b/docs/web/enterprise/checkpointing.mdx index 1569071d0..ca6eab814 100644 --- a/docs/web/enterprise/checkpointing.mdx +++ b/docs/web/enterprise/checkpointing.mdx @@ -1,5 +1,6 @@ --- title: "Function Refresh Checkpointing" +tag: "Early access" sidebarTitle: "Checkpointing" description: "How a Function refresh's progress survives a worker failure or restart, part by part." icon: "floppy-disk" @@ -9,6 +10,8 @@ availability: enterprise: available --- +Early access + This page is about checkpointing a [Function refresh](/enterprise/adaptive-execution) specifically -- not [PyTorch training checkpointing](/training/checkpointing), a different, unrelated mechanism covered elsewhere. diff --git a/docs/web/enterprise/gpu-refresh-execution.mdx b/docs/web/enterprise/gpu-refresh-execution.mdx index b9c7e6acc..7fcacf4b5 100644 --- a/docs/web/enterprise/gpu-refresh-execution.mdx +++ b/docs/web/enterprise/gpu-refresh-execution.mdx @@ -1,5 +1,6 @@ --- title: "GPU Refresh Execution" +tag: "Early access" sidebarTitle: "GPU Refresh Execution" description: "A computed column or materialized view filled by a GPU Function schedules its refresh workers the same way GPU Function execution does in Data Curation." icon: microchip @@ -9,6 +10,8 @@ availability: enterprise: available --- +Early access + A [computed column](/feature-engineering/add-computed-column) or [materialized view](/feature-engineering/materialized-views) filled by a registered [Function](/curation/create-function) with `gpu=True` refreshes diff --git a/docs/web/enterprise/tiered-index-cache.mdx b/docs/web/enterprise/tiered-index-cache.mdx index 439c52df2..f807f04ae 100644 --- a/docs/web/enterprise/tiered-index-cache.mdx +++ b/docs/web/enterprise/tiered-index-cache.mdx @@ -1,6 +1,7 @@ --- title: "Tiered Index Cache" -sidebarTitle: "Tiered Index Cache" +tag: "Early access" +sidebarTitle: "Index Cache" description: "How LanceDB Enterprise caches deserialized index structures across memory and local disk." icon: "layer-group" availability: @@ -8,6 +9,8 @@ availability: enterprise: available --- +Early access + The tiered index cache holds deserialized vector, full-text and scalar index structures in memory, backed by a local-disk tier beneath it. When memory fills, the cache serializes evicted entries and spills them to disk diff --git a/docs/web/index.mdx b/docs/web/index.mdx index 8b290b97a..7b6bc6eed 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -23,7 +23,7 @@ time stitching infrastructure together and more time improving datasets, testing ## 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. +Keep your AI data in one table.{/* Draft until branching reaches early access: restore ", and give each agent-driven experiment its own isolated branch" before the period. */} Find the failure, fix the data, and retrain. @@ -31,11 +31,15 @@ Find the failure, fix the data, and retrain. 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. + {/* + Draft until branching reaches early access. + 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). + */} 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 diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index d0ecab8b9..baf241b30 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -30,6 +30,8 @@ import { import { PyWriteWorkflow, TsWriteWorkflowBody, TsWriteWorkflowTail, RsWriteWorkflow } from '/snippets/ingestion_examples.mdx'; +Early access in Enterprise + Use merge insert when incoming records should be compared with existing rows. Combine update and insert policies for an **upsert**. Use [append](/ingestion/insert) when every incoming row should simply be added. diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index c7fc2cabe..21ba079f9 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -37,7 +37,7 @@ retention period comes from its configuration instead. The latest version is never removed, whatever you pass. `timedelta(0)` makes every older version eligible for removal, but cleanup still keeps tagged -versions and the files branches still read, as the warning below describes. +versions{/* Draft until branching reaches early access: restore " and the files branches still read" */}, as the warning below describes. Pruning is what makes [time travel](/management/table#versioning) finite: an @@ -47,12 +47,18 @@ whatever its age, when it is: - the **latest** version; - a **tagged** version. +{/* +Draft until branching reaches early access. + Cleanup also keeps the files a **branch** still reads, and the version the branch was forked from while the branch's remaining versions read the parent's files. That does not keep the fork for good: once the branch has replaced the data it inherited and its own older versions are pruned, cleanup prunes the -fork version like any other. To keep a version recoverable, tag it, subject to -the policy below, or keep the window wide enough to cover it. +fork version like any other. +*/} + +To keep a version recoverable, tag it, subject to the policy below, or keep +the window wide enough to cover it. Under the default policy, a tag can also stop cleanup. When a tagged version is older than the window and is not the latest, cleanup refuses to run: it raises @@ -75,7 +81,7 @@ need before running this, not after. [Managed blobs](/management/table#managed-blobs) store out-of-line payloads under the table's `_blobs/` directory. Cleanup follows the references from -retained snapshots, including protected tags and branches, before selecting +retained snapshots, including protected tags{/* Draft until branching reaches early access: restore " and branches" */}, before selecting objects for deletion. Replacing a blob or deleting a row makes its old payload eligible only after no retained snapshot references it. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 38a346c18..3a4f0736c 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -1,5 +1,6 @@ --- title: "Functions" +tag: "Early access" sidebarTitle: "Function" description: "Register a Python function once and apply it as a column, for work SQL cannot express." icon: code @@ -23,6 +24,8 @@ import { } from '/snippets/function.mdx'; import { PyConnectEnterprisePlaceholders as FunctionConnect } from '/snippets/connection.mdx'; +Early access + Some columns cannot be written as a SQL expression: an embedding, a model call, an image decode. A function is a Python callable registered with the database, versioned, and then applied as a column. The code runs where the data is diff --git a/docs/web/management/secret.mdx b/docs/web/management/secret.mdx index 0359ce6a3..b8a37fb51 100644 --- a/docs/web/management/secret.mdx +++ b/docs/web/management/secret.mdx @@ -1,5 +1,6 @@ --- title: "Secret" +tag: "Early access" sidebarTitle: "Secret" description: "Create, rotate, list, describe and drop a named credential that Functions bind by reference." icon: key @@ -9,6 +10,8 @@ availability: enterprise: available --- +Early access + A **Secret** is a catalog object, like a table or a namespace: a named credential, such as a model provider's API key, stored once and addressed by name. A [Function](/curation/create-function) binds a Secret by reference @@ -109,12 +112,10 @@ Every Secret's value is encrypted directly with your deployment's key in AWS KMS, Google Cloud KMS, or Azure Key Vault -- there is no separate application data key to manage. Storage, backups and replicas hold only ciphertext. Decryption goes through your KMS, which records it in your cloud's audit -log. A deployment without a KMS key does not offer Secrets; see -[KMS integration](/enterprise/deployment/kms). +log. BYOC You are responsible for the network egress -policy for the jobs that run Functions, and for scoping the Function -identity's cloud role to the KMS key so it can decrypt but not encrypt. +policy for the jobs that run Functions. ### Redaction {#redaction} @@ -131,7 +132,7 @@ that holds that credential. | Item | Limit | | --- | --- | | Secret name | 1--128 characters from `A-Z a-z 0-9 _ . -`. `$` is reserved as the namespace delimiter. | -| Value | One nonempty UTF-8 string, at most 4,096 bytes. Azure Key Vault RSA keys allow less -- see [KMS integration](/enterprise/deployment/kms). | +| Value | One nonempty UTF-8 string, at most 4,096 bytes. On Azure, at most 158, 286 or 414 bytes for an RSA-2048, RSA-3072 or RSA-4096 key. | | Bindings per Function | 16 | | Environment variable name | `[A-Za-z_][A-Za-z0-9_]*`, and not [reserved](#reserved) | | Variables per Function | Each bound once. Two variables may bind the same Secret. | @@ -157,8 +158,8 @@ refreshing one: the Secret was never created in that namespace, was dropped, or its name is misspelled in the binding. Create it, or register a new Function version with the right name. -**501 from a Secret API call**: the deployment has no KMS key configured, so -Secrets are disabled. See [KMS integration](/enterprise/deployment/kms). +**501 from a Secret API call**: Secrets aren't enabled for this deployment. +Contact [LanceDB support](/deployment/support). ## Privileges {#privileges} diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 14ff57cf4..c229e13f0 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -143,8 +143,8 @@ import { 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 -searches over its columns. Branches let you make changes separately from the -main table history. +searches over its columns.{/* Draft until branching reaches early access: restore "Branches let you make changes separately from the +main table history." */} This page covers table management, data types, schema changes and version history. For loading records, see [Ingestion](/ingestion). For changes to @@ -161,7 +161,11 @@ In LanceDB Enterprise, tables are also created and dropped in SQL with [`CREATE | **Columns** | including vectors, blobs, and [computed](/feature-engineering/add-computed-column) columns | | **Versions** | every write commits one, so reads can [travel back](/management/table#versioning) | | **Indexes** | vector, full-text and scalar, built over its columns | + +{/* +Draft until branching reaches early access. | **Branches** | isolated lines of change you can [merge or discard](/tables/branching) | +*/} ## Create a table {#create} @@ -326,7 +330,7 @@ as it is to the format. | String and binary | `utf8`, `large_utf8`, `binary`, `large_binary`, `fixed_size_binary(n)` | | Date and time | `date32`, `date64`, `time32`, `time64`, `timestamp`, `duration` | | Nested | `struct`, `list`, `large_list`, `fixed_size_list`, `map` | -| Lance extensions | vectors, [JSON](/sql/data-types#json), [blobs](#multimodal), bfloat16 | +| Lance extensions | vectors, [blobs](#multimodal), bfloat16{/* Draft until JSON columns reach early access: restore "[JSON](/sql/data-types#json), " after "vectors, " */} | A vector column is a `fixed_size_list`, an ordinary Arrow type, which is why it is selectable and joinable but why arithmetic over it is list @@ -345,9 +349,7 @@ file, up to 64 KiB by default, and larger values are stored outside it. ### Blob columns {#multimodal-blob-v2} - -Blob V2 is in early access. - +Early access A `blob` column keeps metadata separate from the payload bytes, so queries can filter rows without loading the blobs. @@ -1490,6 +1492,9 @@ Deleting a tag only removes the label, not the version it points to. After deletion, the underlying table version becomes eligible for cleanup again. +{/* +Draft until branching reaches early access. + ### Branches {#versioning-branches} Beyond linear history, LanceDB also supports **branches**: isolated, writable @@ -1499,6 +1504,7 @@ writable history, making it ideal for experiments, backfills, and migrations that you want to keep separate from production reads on `main`. Branches are covered in their own guide: see [Branches](/tables/branching). +*/} ### Delete Data From the Table {#versioning-delete-data-from-the-table} diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx index cebfd6d77..e586a1eac 100644 --- a/docs/web/search/realtime-read.mdx +++ b/docs/web/search/realtime-read.mdx @@ -70,8 +70,8 @@ returning a result that omits un-compacted rows. ## Limitations {#limitations} -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 +Support for all table operations on RTE tables is coming soon. Time travel,{/* Draft until branching reaches early access: restore " branching," */} +`count_rows`, row IDs (`with_row_id`), and `TABLESAMPLE` are not yet available. diff --git a/docs/web/sql/data-types.mdx b/docs/web/sql/data-types.mdx index 651d04d29..ef5dfcab7 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", "json"] +keywords: ["sql types", "arrow", "cast", "pseudo-columns", "vector"] availability: embedded: unavailable enterprise: available @@ -84,6 +84,9 @@ calculations. SQL vector search depends on the Enterprise server version and que plan; see [SQL](/basics/sql#no-vector-sql). +{/* +Draft until JSON columns reach early access. + ### JSON {#json} Stored as JSONB in `large_binary` with the `lance.json` extension name. It reads @@ -98,6 +101,7 @@ WHERE json_get_int(data, 'status') = 200 `json_get`, its typed variants, and `json_extract` are **index-accelerated** by a JSON scalar index. See [JSON functions](/sql/dql/json-functions). +*/} ### bfloat16 {#bfloat16} @@ -105,6 +109,9 @@ Sixteen-bit floats in the bfloat16 layout, stored as `fixed_size_binary(2)`. Useful as a vector element type when halving the memory matters more than the precision does. +{/* +Draft: geospatial queries and indexes are unsupported in LanceDB Enterprise. + ## Geospatial {#geospatial} @@ -118,6 +125,7 @@ spatial index is gated the same way. Geometry can still be stored (it is binary, and binary columns work), but nothing interprets it. Filter on a bounding box held in ordinary numeric columns if you need spatial predicates today. +*/} ## Pseudo-columns {#pseudo-columns} diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 5dbdb58ae..8cd45f8bc 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -1,5 +1,6 @@ --- title: "Function" +tag: "Early access" sidebarTitle: "Function" description: "Create, describe, alter, list, and drop registered functions with SQL." icon: function @@ -9,6 +10,8 @@ availability: enterprise: available --- +Early access + [SQL runs in LanceDB Enterprise.](/sql) ## CREATE FUNCTION {#create} diff --git a/docs/web/sql/ddl/secret.mdx b/docs/web/sql/ddl/secret.mdx index 33ba009da..6c6e3c4c6 100644 --- a/docs/web/sql/ddl/secret.mdx +++ b/docs/web/sql/ddl/secret.mdx @@ -1,12 +1,13 @@ --- title: "Secret" +tag: "Early access" sidebarTitle: "Secret" description: "CREATE, ALTER, DROP, SHOW and DESCRIBE SECRET, and granting privileges on Secrets." icon: key keywords: ["secret", "create secret", "alter secret", "drop secret", "show secrets", "describe secret", "grant", "sql"] --- -Enterprise [SQL runs in LanceDB Enterprise.](/sql) +Early access Enterprise [SQL runs in LanceDB Enterprise.](/sql) A [Secret](/management/secret) is a named credential that Functions bind by reference. These statements store, rotate, list, describe and drop Secrets. diff --git a/docs/web/sql/dql/functions.mdx b/docs/web/sql/dql/functions.mdx index 945abbe03..0ea53a508 100644 --- a/docs/web/sql/dql/functions.mdx +++ b/docs/web/sql/dql/functions.mdx @@ -15,7 +15,7 @@ plus what Lance adds. | | | | --- | --- | -| [Scalar functions](/sql/dql/scalar-functions) | per row: math, string, regex, date/time, array, struct, JSON | +| [Scalar functions](/sql/dql/scalar-functions) | per row: math, string, regex, date/time, array, struct{/* Draft until JSON columns reach early access: restore ", JSON" */} | | [Aggregate functions](/sql/dql/aggregation#functions) | per group: `count`, `sum`, statistical, approximate | | [Window functions](/sql/dql/window#functions) | per window: ranking, offset, running aggregates | | [Table functions](#table-functions) | produce a relation rather than a value | @@ -45,13 +45,17 @@ see [Data types](/sql/data-types#pseudo-columns). ## What Lance accelerates {#accelerated} -Two function families use an index rather than scanning, which is the difference +`contains_tokens` uses an index rather than scanning, which is the difference between a fast predicate and a slow one: | | Index used | | --- | --- | | [`contains_tokens`](/sql/dql/contains-tokens) | full-text index | + +{/* +Draft until JSON columns reach early access; restore "Two function families" above. | [`json_get`, typed variants, `json_extract`](/sql/dql/json-functions) | JSON scalar index | +*/} Confirm with [`EXPLAIN`](/sql/dql/explain): an accelerated predicate shows an index node rather than a `LanceScan` followed by a filter. diff --git a/docs/web/sql/dql/scalar-functions.mdx b/docs/web/sql/dql/scalar-functions.mdx index b0910c01a..9bd2057b0 100644 --- a/docs/web/sql/dql/scalar-functions.mdx +++ b/docs/web/sql/dql/scalar-functions.mdx @@ -3,7 +3,7 @@ title: "Scalar functions" 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"] +keywords: ["scalar functions", "string functions", "math functions", "regex", "array functions"] availability: embedded: unavailable enterprise: available @@ -133,7 +133,14 @@ reference page: | [`contains_tokens`](/sql/dql/contains-tokens) | index-accelerated keyword predicate, usable in `WHERE` | | [`ivf_partition`](/sql/dql/ivf-partition) | assign each row to its trained IVF index partition | | [`blob_descriptor`](/sql/dql/blob-descriptor) | a BlobV2 column's payload location, without reading it | + +{/* +Draft until JSON columns reach early access. | [JSON accessors](/sql/dql/json-functions) | `json_get` and its typed variants, `json_extract`, and more | +*/} + +{/* +Draft: geospatial queries and indexes are unsupported in LanceDB Enterprise. ### Geospatial {#geo} @@ -143,6 +150,7 @@ Lance defines `st_*` functions on GeoArrow, but they sit behind a build feature feature rather than an unknown-function error, and the spatial index is gated the same way. +*/} ## Additional scalar functions {#escape-hatch} diff --git a/docs/web/tutorials/index.mdx b/docs/web/tutorials/index.mdx index 6ada57c9a..b9aea29a2 100644 --- a/docs/web/tutorials/index.mdx +++ b/docs/web/tutorials/index.mdx @@ -21,7 +21,7 @@ are runnable in Colab; the rest are written up here. Retrieval-augmented generation and agent applications. - Deriving columns, materialized views, experimenting on branches. + Deriving columns and materialized views.{/* Draft until branching reaches early access: restore "Deriving columns, materialized views, experimenting on branches." */} Curating data and training models directly on a table. From 7abc57a4d0daa0188024aad1fb3cbd47d0908d59 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 5 Nov 2026 16:33:23 +0800 Subject: [PATCH 011/203] test: cover refined RQ queries after deferred compaction (#4839) Add SDK coverage for a refined IVF_RQ7 query after deferred compaction with physical row addresses. The test combines deletion and prefiltering, verifies the retained index UUID and actual FRI metadata, requires an ANN plan, and compares IDs/distances before and after compaction plus recall against a flat oracle. This is a test-only change on main with the released Lance beta.10 dependency adopted by #4838. It adds no production behavior or dependency changes. Sophon lazy-executor adoption and integrated performance acceptance remain separate. Validation on macOS ARM64 with pinned Rust 1.97.0: - Five focused SDK regressions passed (0.15 s test runtime), covering deferred FRI compaction/refinement, stable row IDs, ANN approximation mode and large query limits. - `cargo clippy --locked --features remote --tests --examples -- -D warnings` passed. - Formatting and diff checks passed. The native test linker emitted a macOS compact-unwind size warning; all cases completed successfully without linker-setting changes. --- rust/lancedb/src/table/optimize.rs | 139 ++++++++++++++++++++++++++++- 1 file changed, 138 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 446234a6e..a5346afef 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -447,11 +447,16 @@ pub(crate) async fn execute_optimize( #[cfg(test)] mod tests { use super::{oversized_sq_partition, segment_touches_fragments, sq_vector_dimension}; + use arrow::compute::concat_batches; use arrow_array::{ Array, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, + cast::AsArray, + types::{Float32Type, Int32Type}, }; use arrow_schema::{DataType, Field, Schema}; + use lance::index::DatasetIndexExt; use lance_arrow::FixedSizeListArrayExt; + use lance_index::frag_reuse::FRAG_REUSE_INDEX_NAME; use rstest::rstest; use std::{collections::HashSet, sync::Arc}; @@ -462,7 +467,7 @@ mod tests { scalar::BTreeIndexBuilder, vector::{IvfHnswSqIndexBuilder, IvfRqIndexBuilder}, }; - use crate::query::ExecutableQuery; + use crate::query::{ExecutableQuery, QueryBase}; use crate::table::{CompactionOptions, OptimizeAction, OptimizeStats}; use futures::TryStreamExt; @@ -1340,6 +1345,138 @@ mod tests { assert_eq!(all_values, expected); } + #[tokio::test] + async fn test_refined_rq_query_after_deferred_compaction() { + const ROWS: i32 = 128; + const DIMENSION: i32 = 32; + let conn = connect("memory://").execute().await.unwrap(); + let vectors = FixedSizeListArray::try_new_from_values( + Float32Array::from_iter_values((0..ROWS).flat_map(|id| { + (0..DIMENSION).map(move |offset| (id as f32 * 0.1 + offset as f32 * 0.3).sin()) + })), + DIMENSION, + ) + .unwrap(); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vectors.data_type().clone(), false), + ])), + vec![ + Arc::new(Int32Array::from_iter_values(0..ROWS)), + Arc::new(vectors), + ], + ) + .unwrap(); + let table = conn + .create_table("refined_rq_compaction", batch.slice(0, 64)) + .storage_option(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "false") + .execute() + .await + .unwrap(); + table.add(batch.slice(64, 64)).execute().await.unwrap(); + table + .create_index( + &["vector"], + Index::IvfRq( + IvfRqIndexBuilder::default() + .num_partitions(4) + .num_bits(7) + .max_iterations(5), + ), + ) + .name("rq".to_string()) + .execute() + .await + .unwrap(); + table.delete("id % 7 = 0").await.unwrap(); + let dataset = table.dataset().unwrap().get().await.unwrap(); + assert_eq!(dataset.fragments().len(), 2); + let original_index = dataset.load_indices_by_name("rq").await.unwrap()[0].uuid; + + let key = (0..DIMENSION) + .map(|offset| (0.5 + offset as f32 * 0.3).sin()) + .collect::>(); + let query = || { + table + .query() + .only_if("id % 3 != 0") + .nearest_to(key.as_slice()) + .unwrap() + .nprobes(4) + .unwrap() + .limit(8) + }; + let before = query() + .fast_search() + .refine_factor(4) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let before = concat_batches(&before[0].schema(), &before).unwrap(); + + let stats = table + .optimize(OptimizeAction::Compact { + options: CompactionOptions { + target_rows_per_fragment: 256, + defer_index_remap: true, + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + assert_eq!(stats.compaction.unwrap().fragments_removed, 2); + let dataset = table.dataset().unwrap().get().await.unwrap(); + assert_eq!(dataset.fragments().len(), 1); + assert_eq!( + dataset.load_indices_by_name("rq").await.unwrap()[0].uuid, + original_index + ); + assert!( + dataset + .load_indices() + .await + .unwrap() + .iter() + .any(|index| index.name == FRAG_REUSE_INDEX_NAME) + ); + + let refined = query().fast_search().refine_factor(4); + let plan = refined.explain_plan(false).await.unwrap(); + assert!(plan.contains("ANNIvf"), "{plan}"); + let after = refined + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let after = concat_batches(&after[0].schema(), &after).unwrap(); + assert_eq!(after.num_rows(), 8); + assert_eq!(after["id"].as_ref(), before["id"].as_ref()); + assert_eq!(after["_distance"].as_ref(), before["_distance"].as_ref()); + let found = after["id"].as_primitive::().values(); + assert!(found.iter().all(|id| id % 7 != 0 && id % 3 != 0)); + assert!(after["_distance"].as_primitive::().values()[0] < 1e-5); + + let exact = query() + .bypass_vector_index() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let exact = concat_batches(&exact[0].schema(), &exact).unwrap(); + let truth = exact["id"].as_primitive::().values(); + let recall = found.iter().filter(|id| truth.contains(id)).count() as f64 / 8.0; + assert!(recall >= 0.5, "recall={recall}"); + } + #[tokio::test] async fn test_compaction_preserves_schema() { let conn = connect("memory://").execute().await.unwrap(); From b5c5ede39faabb2b5ba216391b942e9bec66ce26 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Thu, 5 Nov 2026 00:36:20 -0800 Subject: [PATCH 012/203] feat(python)!: rename the @udf decorator to @function (#4837) The client registers Functions, but the decorator that packages one was called `udf` and produced a `UdfDefinition`. Rename them to `function` and `FunctionDefinition`, and say "function" instead of "UDF" in the docstrings, error messages and docs around them. `udf` and `UdfDefinition` stay as deprecated aliases that emit a `DeprecationWarning`. The source packager strips either spelling of the decorator, so `@udf` and `@function` produce the same artifact and digest, and the wire contract is unchanged. DataFusion and Lance UDF types, and Geneva's `@udf` in the integration docs, are unrelated and untouched. --- docs/src/python/python.md | 12 +- docs/web-tests/py/test_function.py | 16 +- docs/web/curation/chunking.mdx | 8 +- docs/web/curation/create-function.mdx | 28 +- docs/web/management/function.mdx | 18 +- docs/web/snippets/function.mdx | 4 +- python/python/lancedb/__init__.py | 12 +- python/python/lancedb/db.py | 24 +- python/python/lancedb/functions.py | 136 +++++---- python/python/lancedb/remote/db.py | 4 +- python/python/tests/test_e2e_remote_db.py | 4 +- .../tests/test_first_class_function_slice2.py | 284 +++++++++--------- .../python/tests/test_function_packaging.py | 100 +++--- rust/lancedb/src/function.rs | 2 +- rust/lancedb/src/secrets.rs | 2 +- .../tests/first_class_function_slice2.rs | 2 +- 16 files changed, 367 insertions(+), 289 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index efb57605b..3baa128ae 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -382,7 +382,7 @@ code that used the former LanceDB Enterprise-only argument order. ## Functions and Jobs -A decorated `udf` definition is also a local callable. Call a decorated function +A `@function` definition is also a local callable. Call a decorated function directly with row inputs, or call a decorated class with its initialization fields and then call the returned instance; call `close()` if the class defines it. This path uses the current Python environment and does not create a registered @@ -391,15 +391,15 @@ the remote Arrow adapter. A registered `FunctionVersion` call instead binds `col(...)` inputs and returns a remote `FunctionApplication`. ```python -from lancedb import udf +from lancedb import function -@udf +@function def normalize(text: str) -> str: return text.strip().lower() -@udf +@function class Scale: def __init__(self, factor: float): self.factor = factor @@ -455,9 +455,9 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.PythonEnvironmentSpec -::: lancedb.functions.udf +::: lancedb.functions.function -::: lancedb.functions.UdfDefinition +::: lancedb.functions.FunctionDefinition ::: lancedb.secrets.EnvVarSecret diff --git a/docs/web-tests/py/test_function.py b/docs/web-tests/py/test_function.py index 835f269d3..147520b18 100644 --- a/docs/web-tests/py/test_function.py +++ b/docs/web-tests/py/test_function.py @@ -14,7 +14,7 @@ creates both under names unique to its run, never replaces an existing object, and drops only what it created. The other tests run locally and check the client side of the same code: what -`@udf` sends for registration, how a registered version binds a column, where a +`@function` sends for registration, how a registered version binds a column, where a local connection stops, and when the Enterprise test connects. They do not run a Function remotely. """ @@ -32,10 +32,10 @@ from lancedb import col from lancedb.functions import FunctionApplication, FunctionVersion # --8<-- [start:function_define] -from lancedb import udf +from lancedb import function -@udf +@function def double(value: float) -> float: return value * 2 @@ -52,7 +52,7 @@ def describe(value: float): # --8<-- [start:function_class_define] -@udf(pip=["sentence-transformers"]) +@function(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. @@ -146,7 +146,7 @@ def test_function_output_nullability(): pa.field("half", pa.float64(), nullable=False), pa.field("note", pa.string(), nullable=True), ] - struct = udf(input_schema=inputs, output_schema=pa.schema(fields))(describe) + struct = function(input_schema=inputs, output_schema=pa.schema(fields))(describe) output = struct.registration_request.signature.output assert output.kind == "named_struct" assert [(field.name, field.nullable) for field in output.fields] == [ @@ -160,7 +160,7 @@ def test_function_output_nullability(): pa.field("result", pa.struct(fields), nullable=True), ): with pytest.raises(ValueError, match="non-nullable"): - udf(input_schema=inputs, output_schema=nullable)(describe) + function(input_schema=inputs, output_schema=nullable)(describe) def test_function_registration_is_remote(tmp_path): @@ -242,8 +242,8 @@ def test_function_enterprise(monkeypatch): # this run creates both under names only it uses, and drops only those. run = uuid.uuid4().hex[:12] table_name = f"function_demo_{run}" - double = udf(name=f"double_{run}")(WALKTHROUGH_DOUBLE.__wrapped__) - embed = udf(name=f"embed_{run}", pip=["sentence-transformers"])( + double = function(name=f"double_{run}")(WALKTHROUGH_DOUBLE.__wrapped__) + embed = function(name=f"embed_{run}", pip=["sentence-transformers"])( WALKTHROUGH_EMBED.__wrapped__ ) create_table = db.create_table diff --git a/docs/web/curation/chunking.mdx b/docs/web/curation/chunking.mdx index e5fc51087..3592f6be5 100644 --- a/docs/web/curation/chunking.mdx +++ b/docs/web/curation/chunking.mdx @@ -40,9 +40,9 @@ register it from Python, or the same function from SQL with ```python Python icon="python" import pyarrow as pa -from lancedb.functions import udf +from lancedb.functions import function -@udf( +@function( output_schema=pa.list_( pa.struct([ pa.field("chunk_index", pa.int64(), nullable=False), @@ -113,7 +113,7 @@ A chunker that samples one timestamp per second needs no blob access at all ```python Python icon="python" -@udf( +@function( output_schema=pa.list_( pa.struct([ pa.field("frame_index", pa.int64(), nullable=False), @@ -138,7 +138,7 @@ rather than loading the whole clip -- and returns one JPEG per call: from datetime import timedelta from lancedb import BlobReader -@udf( +@function( name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index a2751cf8f..9f6370347 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -29,9 +29,9 @@ inferred from the annotations: ```python Python icon="python" -from lancedb import udf +from lancedb import function -@udf(pip=["numpy==2.2.0"]) +@function(pip=["numpy==2.2.0"]) def score(value: float) -> float: return value * 2 @@ -55,9 +55,9 @@ 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 +from lancedb import function -@udf( +@function( pip=["numpy==2.2.0"], batch_size=32, row_timeout_seconds=90, @@ -81,15 +81,15 @@ service's default per-call deadline. ## Stateful Functions: load once, call many times {#stateful} -A `@udf`-decorated **class** is the same callable with state. Each remote +A `@function`-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 +from lancedb import function -@udf +@function class scale: def __init__(self, factor: float, offset: float = 0.0): self.factor = factor @@ -119,13 +119,13 @@ in the Function version. `gpu=True` remains required: ```python Python icon="python" import pyarrow as pa -from lancedb import udf +from lancedb import function gpu_class = next( gpu.name for gpu in db.list_gpu_classes() if gpu.gpu_model == "NVIDIA A10G" ) -@udf( +@function( gpu=True, gpu_class=gpu_class, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], @@ -215,9 +215,9 @@ how the `video: BlobReader` parameter does that: from datetime import timedelta from lancedb import BlobReader, col -from lancedb.functions import udf +from lancedb.functions import function -@udf( +@function( name="extract_frame", gpu=True, pip=["av==13.1.0", "pillow==11.0.0"], @@ -264,7 +264,7 @@ A second Function can bind a blob another Function produced. Register ```python Python icon="python" -@udf(gpu=True, pip=["transformers==4.47.0"]) +@function(gpu=True, pip=["transformers==4.47.0"]) def caption(jpeg: bytes) -> str: ... # run a vision-language model over the JPEG, return one sentence @@ -342,10 +342,10 @@ box type without loading the rest of the video: ```python Python icon="python" -from lancedb import BlobReader, udf +from lancedb import BlobReader, function -@udf +@function def first_box_type(video: BlobReader) -> bytes: video.seek(4) return video.read(4) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 3a4f0736c..b9abbe743 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -49,7 +49,7 @@ The steps below take a column of numbers to a filled column of their doubles. ## Define a function {#define} -`@udf` packages a scalar Python callable. Input and output types are inferred +`@function` packages a scalar Python callable. Input and output types are inferred from annotations, so `double` takes one non-nullable `float64` parameter, `value`, and returns a non-nullable `float64`: @@ -204,7 +204,7 @@ the table a second one first: ```python Python icon="python" table.add_columns({"count": "value + 1"}) -@udf +@function def ratio(numerator: float, denominator: float) -> float: return numerator / denominator @@ -222,7 +222,7 @@ mapping, so both columns come from one atomic binding: ```python Python icon="python" import pyarrow as pa -@udf( +@function( input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), output_schema=pa.schema([ pa.field("half", pa.float64(), nullable=False), @@ -280,7 +280,7 @@ and `__call__` handles each row or batch. {FunctionClassDefine} -Registering the class does not construct it. `@udf` reads the signature of +Registering the class does not construct it. `@function` 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 @@ -347,7 +347,7 @@ dependencies are part of its definition: ```python Python icon="python" -@udf(gpu=True) +@function(gpu=True) def extract_frame(video: BlobReader, ts: float) -> bytes: ... # runs only on a GPU-capable worker ``` @@ -389,7 +389,7 @@ 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`. No API returns a Secret's value, +`create_function_async`, not to `@function`. No API returns a Secret's value, and it never appears in the function's registration: the function reads the environment variable the way it always did, and the binding is what puts a value there. A mistyped Secret name is caught at registration; a mistyped @@ -402,7 +402,7 @@ full worked example. ## Failure handling {#failures} A function that raises fails the job. There is no per-row retry or skip policy -in the function definition: `@udf` takes no error-handling parameter, so a +in the function definition: `@function` takes no error-handling parameter, so a function that calls a flaky external service should handle that itself, inside the function body. @@ -437,7 +437,7 @@ 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]) +@function(gpu=True, code=[caption_worker]) def caption(jpeg: bytes) -> str: return caption_worker.run(jpeg) ``` @@ -446,7 +446,7 @@ def caption(jpeg: bytes) -> str: Each module in `code` is captured and shipped the same way the function itself is: as source, snapshotted at registration. Only `.py` source files are included; package data such as JSON, YAML, prompt, or tokenizer files is not -copied. `@udf` warns before registration when it skips such files from a +copied. `@function` warns before registration when it skips such files from a package in `code`, naming the affected paths. To use a package that includes the required resources, install it with `pip=` or `conda=` and remove that package from `code`; otherwise the Python-only copied package shadows the diff --git a/docs/web/snippets/function.mdx b/docs/web/snippets/function.mdx index c760714c2..ec1ad2820 100644 --- a/docs/web/snippets/function.mdx +++ b/docs/web/snippets/function.mdx @@ -4,7 +4,7 @@ export const PyFunctionApply = "from lancedb import col\n\ntable.add_columns({\" 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 PyFunctionClassDefine = "@function(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 PyFunctionClassRegister = "embedder = db.create_function_async(embed).wait()\n"; @@ -12,7 +12,7 @@ export const PyFunctionConnect = "import os\n\nimport lancedb\n\ndb = lancedb.co 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"; -export const PyFunctionDefine = "from lancedb import udf\n\n\n@udf\ndef double(value: float) -> float:\n return value * 2\n"; +export const PyFunctionDefine = "from lancedb import function\n\n\n@function\ndef double(value: float) -> float:\n return value * 2\n"; export const PyFunctionInspect = "rows = table.search().select([\"value\", \"doubled\"]).to_list()\nprint(sorted((row[\"value\"], row[\"doubled\"]) for row in rows))\n# [(1.0, 2.0), (2.0, 4.0), (3.0, 6.0)]\n"; diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 6ff0dd1ff..f1ddfda52 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -3,6 +3,7 @@ import os +import warnings from concurrent.futures import ThreadPoolExecutor from datetime import timedelta from typing import Dict, Optional, Union, Any, List, Iterable, Literal, TYPE_CHECKING @@ -39,12 +40,13 @@ from .functions import ( FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, FunctionBinding as FunctionBinding, + FunctionDefinition as FunctionDefinition, FunctionRegistrationRequest as FunctionRegistrationRequest, FunctionVersion as FunctionVersion, HuggingFaceModel as HuggingFaceModel, PythonRuntimeSpec as PythonRuntimeSpec, RefreshColumnResult as RefreshColumnResult, - UdfDefinition as UdfDefinition, + function as function, udf as udf, ) from .secrets import EnvVarSecret as EnvVarSecret @@ -77,6 +79,7 @@ from .catalog import ( if TYPE_CHECKING: from lance.blob import BlobType as BlobType + from .functions import UdfDefinition as UdfDefinition def __getattr__(name: str): @@ -85,6 +88,13 @@ def __getattr__(name: str): globals()["BlobType"] = BlobType return BlobType + if name == "UdfDefinition": + from . import functions + + warnings.warn( + functions.UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2 + ) + return functions.FunctionDefinition raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 2cf438e72..9df75a794 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -58,7 +58,7 @@ from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore -from .functions import FunctionVersion, UdfDefinition +from .functions import FunctionVersion, FunctionDefinition from .graph import ( AsyncPropertyGraph, EdgeTable, @@ -958,12 +958,12 @@ class DBConnection(EnforceOverrides): def create_function( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: - """Build and register a scalar Python UDF, then return its version. + """Build and register a scalar Python function, then return its version. The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. @@ -971,8 +971,8 @@ class DBConnection(EnforceOverrides): Parameters ---------- - definition : UdfDefinition - A callable decorated with [udf][lancedb.udf]. + definition : FunctionDefinition + A callable decorated with [function][lancedb.function]. secrets : sequence of EnvVarSecret, optional One [EnvVarSecret][lancedb.secrets.EnvVarSecret] per credential the Function needs, each naming a Secret and the environment variable @@ -1002,12 +1002,12 @@ class DBConnection(EnforceOverrides): def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: - """Submit a scalar Python UDF for building and registration. + """Submit a scalar Python function for building and registration. The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as @@ -2284,7 +2284,7 @@ class LanceDBConnection(DBConnection): @override def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, @@ -3573,12 +3573,12 @@ class AsyncConnection(object): async def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[FunctionVersion]: - """Submit a scalar Python UDF for building and registration. + """Submit a scalar Python function for building and registration. The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as @@ -3589,8 +3589,8 @@ class AsyncConnection(object): the namespace the Function is registered in; None or an empty list is the root. LanceDB Embedded connections raise ``NotImplementedError``. """ - if not isinstance(definition, UdfDefinition): - raise TypeError("create_function_async requires a @udf definition") + if not isinstance(definition, FunctionDefinition): + raise TypeError("create_function_async requires a @function definition") request = definition.bind_secrets(secrets) inner = await self._inner.create_function_async( request.to_canonical_json(), namespace_path diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index fb606cd36..4fa3340d5 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -35,6 +35,7 @@ from typing import ( Callable, Literal, Optional, + TYPE_CHECKING, Union, get_args, get_origin, @@ -333,7 +334,7 @@ class HuggingFaceModel(_RemoteValue): snapshot before initialization, so the model can load without a revision argument or a Hugging Face Hub request:: - @udf( + @function( pip=["sentence-transformers==3.3.1"], models=[HuggingFaceModel( repo="sentence-transformers/all-MiniLM-L6-v2", @@ -482,8 +483,8 @@ class FunctionVersion(_RemoteValue): ``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. + ``definition.registration_request.artifact.digest`` to check whether a local + [FunctionDefinition][lancedb.functions.FunctionDefinition] has the same source. It is ``None`` when the server does not provide a source digest. ``gpu_class`` is the operator-defined GPU pool fixed into this Function @@ -639,7 +640,7 @@ def _initialization_value(name: str, value: Any) -> Any: class FunctionRegistrationRequest(_RemoteValue): - """Stable remote registration envelope produced by :func:`udf`. + """Stable remote registration envelope produced by :func:`function`. Credential values deliberately have no field here. The only secret-shaped thing a client sends is ``secret_bindings``: the name of a Secret the @@ -1375,11 +1376,15 @@ def _infer_signature( return FunctionSignature(inputs=tuple(inputs), output=output) -def _is_udf_decorator(node: ast.expr) -> bool: +# Both spellings strip from packaged source; `udf` is the deprecated alias. +_DECORATOR_NAMES = frozenset({"function", "udf"}) + + +def _is_function_decorator(node: ast.expr) -> bool: if isinstance(node, ast.Call): node = node.func - return (isinstance(node, ast.Name) and node.id == "udf") or ( - isinstance(node, ast.Attribute) and node.attr == "udf" + return (isinstance(node, ast.Name) and node.id in _DECORATOR_NAMES) or ( + isinstance(node, ast.Attribute) and node.attr in _DECORATOR_NAMES ) @@ -1444,7 +1449,7 @@ def _module_references(module_source: str) -> set[str]: visit(child, found) found: set[str] = set() - module = symtable.symtable(module_source, "", "exec") + module = symtable.symtable(module_source, "", "exec") for symbol in module.get_symbols(): if ( symbol.is_referenced() @@ -1517,7 +1522,7 @@ def _definition_node( ) except (OSError, TypeError) as error: raise ValueError( - f"@udf requires inspectable Python source for {target.__qualname__!r}" + f"@function requires inspectable Python source for {target.__qualname__!r}" ) from error module = ast.parse(source) is_class = inspect.isclass(target) @@ -1532,15 +1537,16 @@ def _definition_node( ] if len(definitions) != 1 or isinstance(definitions[0], ast.AsyncFunctionDef): raise ValueError( - "@udf source must contain exactly one " + "@function source must contain exactly one " + ("class" if is_class else "synchronous function") ) definition = definitions[0] if entry: if any( - not _is_udf_decorator(decorator) for decorator in definition.decorator_list + not _is_function_decorator(decorator) + for decorator in definition.decorator_list ): - raise ValueError("@udf cannot package additional Python decorators") + raise ValueError("@function cannot package additional Python decorators") definition.decorator_list = [] return definition @@ -1551,7 +1557,7 @@ def _definition_namespace(target: Any) -> Mapping[str, Any]: module = sys.modules.get(target.__module__) if module is None: raise ValueError( - f"@udf cannot resolve the module of {target.__qualname__!r}" + f"@function cannot resolve the module of {target.__qualname__!r}" ) namespace = vars(module) environment = namespace.get("__builtins__", builtins) @@ -1566,7 +1572,7 @@ def _definition_namespace(target: Any) -> Mapping[str, Any]: # The artifact runs under the standard builtins; only the exact mapping is # provably equivalent (a subclass or copy can change lookups and hooks). if environment is not vars(builtins): - raise ValueError("@udf cannot package a non-standard builtins environment") + raise ValueError("@function cannot package a non-standard builtins environment") return namespace @@ -1580,7 +1586,7 @@ def _is_self_reference(target: Any, namespace: Mapping[str, Any], name: str) -> return True # The decorator's own result is the one wrapper known to behave like # `target`; any other binding may differ from the packaged definition. - return type(bound) is UdfDefinition and bound._function is target + return type(bound) is FunctionDefinition and bound._function is target def _packaged_by_source(value: Any) -> bool: @@ -1593,7 +1599,7 @@ def _packaged_by_source(value: Any) -> bool: qualname = value.__qualname__ if "<" in qualname or "." in qualname: raise ValueError( - f"@udf cannot package {qualname!r}: only module-level functions and " + f"@function cannot package {qualname!r}: only module-level functions and " "classes travel with a Function, not lambdas, closures, or nested " "definitions" ) @@ -1689,7 +1695,7 @@ class _SourcePackager: 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" + "@function cannot package functions that capture closure values" ) namespace = _definition_namespace(target) reader_name = ( @@ -1702,7 +1708,7 @@ class _SourcePackager: dynamic = _namespace_acquisition(definition, references) if dynamic: raise ValueError( - f"@udf cannot package dynamic namespace access: {dynamic!r}" + f"@function cannot package dynamic namespace access: {dynamic!r}" ) self._warn_unshipped_direct_imports(definition) self._packaged.add(id(target)) @@ -1714,9 +1720,9 @@ class _SourcePackager: if name == target.__name__: if not _is_self_reference(target, namespace, name): raise ValueError( - f"@udf cannot package {name!r}: the module binds that name " - "to another value, which the artifact's own definition " - "would shadow" + f"@function cannot package {name!r}: the module binds that " + "name to another value, which the artifact's own " + "definition would shadow" ) continue if name in namespace: @@ -1725,7 +1731,7 @@ class _SourcePackager: unresolved.append(name) if unresolved: raise ValueError( - f"@udf source contains unresolved global names: {unresolved!r}" + f"@function source contains unresolved global names: {unresolved!r}" ) return source @@ -1771,7 +1777,7 @@ class _SourcePackager: claimed = self._names.setdefault(name, meaning) if claimed != meaning: raise ValueError( - f"@udf cannot package {name!r}: packaged definitions bind that " + f"@function cannot package {name!r}: packaged definitions bind that " "name to different values" ) @@ -1779,8 +1785,8 @@ class _SourcePackager: if _packaged_by_source(value): if value.__name__ != name: raise ValueError( - f"@udf packages {value.__qualname__!r} by source, so it must be " - f"referenced by its own name, not {name!r}" + f"@function packages {value.__qualname__!r} by source, so it " + f"must be referenced by its own name, not {name!r}" ) if id(value) not in self._packaged: self._definitions.append(self._definition(value, entry=False)) @@ -1799,7 +1805,8 @@ class _SourcePackager: if isinstance(value, types.ModuleType): if value.__name__.split(".")[0] in _NAMESPACE_MODULES: raise ValueError( - f"@udf cannot package dynamic namespace access: {value.__name__!r}" + "@function cannot package dynamic namespace access: " + f"{value.__name__!r}" ) try: imported = importlib.import_module(value.__name__) @@ -1854,7 +1861,7 @@ class _SourcePackager: return self._warned_imports.add(top) warnings.warn( - f"@udf source imports {module_name!r} from {locations[0]}, a local " + f"@function source imports {module_name!r} from {locations[0]}, a local " "module the Function's environment may not be able to import; ship " f"it with code=[{top}] or declare the package that provides it in " "pip/conda", @@ -2070,10 +2077,10 @@ def _class_call(cls: type) -> Callable[..., Any]: return call -class UdfDefinition: +class FunctionDefinition: """A Python callable prepared for remote Function registration. - Instances are created with :func:`udf`. Calling an instance is ordinary + Instances are created with :func:`function`. Calling an instance is ordinary local Python: a decorated function is called directly, while a decorated class is constructed using its initialization fields and the returned instance is called with each input. Reuse the instance and call its @@ -2114,7 +2121,9 @@ class UdfDefinition: if not is_class and ( not inspect.isfunction(function) or inspect.iscoroutinefunction(function) ): - raise TypeError("@udf requires a synchronous Python function or a class") + raise TypeError( + "@function requires a synchronous Python function or a class" + ) function_name = name or function.__name__ if not _FUNCTION_NAME.fullmatch(function_name): raise ValueError(f"invalid Function name: {function_name!r}") @@ -2181,7 +2190,7 @@ class UdfDefinition: if is_class: if "<" in function.__qualname__ or "." in function.__qualname__: raise ValueError( - "@udf classes must be defined at module level; nested classes " + "@function classes must be defined at module level; nested classes " "would capture their enclosing scope" ) signature = _infer_signature( @@ -2327,12 +2336,12 @@ class UdfDefinition: @overload -def udf(function: Callable[..., Any]) -> UdfDefinition: ... +def function(target: Callable[..., Any]) -> FunctionDefinition: ... @overload -def udf( - function: None = None, +def function( + target: None = None, *, name: Optional[str] = None, input_schema: Optional[pa.Schema] = None, @@ -2350,11 +2359,11 @@ def udf( image: Optional[str] = None, code: Sequence[types.ModuleType] = (), models: Sequence[HuggingFaceModel] = (), -) -> Callable[[Callable[..., Any]], UdfDefinition]: ... +) -> Callable[[Callable[..., Any]], FunctionDefinition]: ... -def udf( - function: Optional[Callable[..., Any]] = None, +def function( + target: Optional[Callable[..., Any]] = None, *, name: Optional[str] = None, input_schema: Optional[pa.Schema] = None, @@ -2511,7 +2520,7 @@ def udf( files are not copied. To use a package that includes required data resources, install it with ``pip=`` or ``conda=`` and remove that package from ``code=`` so the copied Python package cannot shadow the - installed distribution. ``@udf`` warns when it skips files from a + installed distribution. ``@function`` warns when it skips files from a package in ``code=``. models : sequence of HuggingFaceModel, optional Immutable Hugging Face repository snapshots prepared in the worker @@ -2523,7 +2532,7 @@ def udf( Returns ------- - UdfDefinition + FunctionDefinition A callable definition accepted by :meth:`lancedb.db.DBConnection.create_function`, :meth:`lancedb.db.AsyncConnection.create_function_async` and @@ -2531,14 +2540,14 @@ def udf( Examples -------- - >>> from lancedb import udf - >>> @udf(pip=["numpy==2.2.0"]) + >>> from lancedb import function + >>> @function(pip=["numpy==2.2.0"]) ... def score(value: float) -> float: ... return value * 2 >>> score(1.5) 3.0 >>> import pyarrow as pa - >>> @udf( + >>> @function( ... input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), ... output_schema=pa.int64(), ... ) @@ -2546,14 +2555,14 @@ def udf( ... return value >>> batch_identity(pa.array([1, 2, 3])).to_pylist() [1, 2, 3] - >>> @udf(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") + >>> @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") ... def gpu_score(value: int) -> int: ... return value * 2 >>> gpu_score.registration_request.runtime.gpu True >>> gpu_score.registration_request.runtime.gpu_class 'a10g' - >>> @udf + >>> @function ... class scale: ... def __init__(self, factor: float, offset: float = 0.0): ... self.factor, self.offset = factor, offset @@ -2570,7 +2579,7 @@ def udf( >>> [field.name for field in scale.registration_request.signature.initialization] ['factor', 'offset'] >>> import lancedb - >>> @udf( + >>> @function( ... input_schema=pa.schema([lancedb.blob("image", nullable=False)]), ... output_schema=lancedb.blob("copy", nullable=False), ... ) @@ -2611,8 +2620,8 @@ def udf( ``blob_mode="bytes"`` cannot fetch payloads inside lists. """ - def decorate(target: Any) -> UdfDefinition: - return UdfDefinition( + def decorate(target: Any) -> FunctionDefinition: + return FunctionDefinition( target, name=name, input_schema=input_schema, @@ -2632,9 +2641,9 @@ def udf( models=tuple(models), ) - if function is None: + if target is None: return decorate - return decorate(function) + return decorate(target) __all__ = [ @@ -2660,6 +2669,31 @@ __all__ = [ "PythonAdapterSpec", "PythonRuntimeSpec", "RefreshColumnResult", - "UdfDefinition", - "udf", + "FunctionDefinition", ] + + +def udf(*args: Any, **kwargs: Any) -> Any: + """Deprecated alias of :func:`function`.""" + warnings.warn( + "lancedb.udf is deprecated; use lancedb.function", + DeprecationWarning, + stacklevel=2, + ) + return function(*args, **kwargs) + + +UDF_DEFINITION_DEPRECATION = ( + "lancedb.UdfDefinition is deprecated; use lancedb.FunctionDefinition" +) + + +def __getattr__(name: str) -> Any: + if name == "UdfDefinition": + warnings.warn(UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2) + return FunctionDefinition + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +if TYPE_CHECKING: + UdfDefinition = FunctionDefinition diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 8453de125..655391b1f 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -38,7 +38,7 @@ import pyarrow as pa from ..common import DATA from lancedb.listing import Listing, NamespaceListing, TableListing from ..db import DBConnection, LOOP -from ..functions import FunctionVersion, UdfDefinition +from ..functions import FunctionVersion, FunctionDefinition from ..graph import EdgeTable, NodeTable, PropertyGraph from ..job import AsyncJob, Job from ..sql import Query as SqlQuery @@ -968,7 +968,7 @@ class RemoteDBConnection(DBConnection): @override def create_function_async( self, - definition: UdfDefinition, + definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, namespace_path: Optional[List[str]] = None, diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index 5a2f1e290..8b06943da 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -10,7 +10,7 @@ import lancedb import numpy as np import pyarrow as pa import pytest -from lancedb import LanceDBConnection, udf +from lancedb import LanceDBConnection, function from lancedb.index import FTS # TODO: setup integ test mark and script @@ -98,7 +98,7 @@ def test_function_execution_controls_through_sql_and_materialized_view(): view_name = f"batch_probe_view_{suffix}" registered_version = None - @udf( + @function( name=function_name, input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.int64(), diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 6df017cff..238d787d1 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -32,11 +32,11 @@ from lancedb.functions import ( PythonRuntimeSpec, SecretBinding, SecretReference, - UdfDefinition, + FunctionDefinition, _canonical_arrow_type, _exact_arrow_type, _GRAMMAR_PRIMITIVES, - udf, + function, ) from lancedb.secrets import EnvVarSecret from lancedb.remote.db import RemoteDBConnection @@ -62,7 +62,7 @@ FUNCTION_VERSION = json.loads( )["version"] -@udf( +@function( pip=["numpy>=2"], env={"MODE": "test"}, python_version="3.12", @@ -71,7 +71,7 @@ def normalize_score(value: float) -> float: return value / 100.0 -@udf( +@function( pip=["openai==3.7.0"], env={"MODE": "test"}, python_version="3.12", @@ -80,8 +80,8 @@ def analyze_caption(caption: str) -> str: return caption.strip() -def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): - assert isinstance(normalize_score, UdfDefinition) +def test_scalar_function_matches_shared_registration_golden_and_remains_callable(): + assert isinstance(normalize_score, FunctionDefinition) assert normalize_score(25.0) == 0.25 assert ( normalize_score.registration_request.to_canonical_json() @@ -96,13 +96,13 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): } -def test_udf_declares_pinned_hugging_face_models(): +def test_function_declares_pinned_hugging_face_models(): model = HuggingFaceModel( repo="sentence-transformers/all-MiniLM-L6-v2", revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41", ) - @udf(pip=["sentence-transformers==3.3.1"], models=[model]) + @function(pip=["sentence-transformers==3.3.1"], models=[model]) def embed_text(value: str) -> list[float]: return [1.0] @@ -117,19 +117,19 @@ def test_udf_declares_pinned_hugging_face_models(): assert "models" not in undeclared with pytest.raises(ValueError, match="once"): - udf(name="duplicate_model", models=[model, model])(lambda value: value) + function(name="duplicate_model", models=[model, model])(lambda value: value) with pytest.raises(ValueError, match="40-character"): HuggingFaceModel(repo="owner/model", revision="main") with pytest.raises(ValueError, match="reserve"): - udf( + function( name="reserved_model_env", models=[model], env={"HF_HOME": "/tmp/model"}, )(lambda value: value) -def test_udf_execution_controls_match_shared_registration_golden(): - controlled = udf( +def test_function_execution_controls_match_shared_registration_golden(): + controlled = function( pip=["numpy>=2"], env={"MODE": "test"}, python_version="3.12", @@ -144,8 +144,8 @@ def test_udf_execution_controls_match_shared_registration_golden(): ) -def test_udf_execution_controls_apply_to_vectorized_functions(): - @udf( +def test_function_execution_controls_apply_to_vectorized_functions(): + @function( input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.int64(), batch_size=3, @@ -171,28 +171,28 @@ def test_udf_execution_controls_apply_to_vectorized_functions(): ({"row_timeout_seconds": True}, "row_timeout_seconds"), ], ) -def test_udf_execution_controls_require_their_positive_ranges(options, field): +def test_function_execution_controls_require_their_positive_ranges(options, field): def identity(value: int) -> int: return value with pytest.raises(ValueError, match=field): - udf(**options)(identity) + function(**options)(identity) @pytest.mark.parametrize( "name", ["examples.image_info", "image-info", "image_info.", "image_info-"] ) -def test_udf_rejects_function_names_with_periods_or_hyphens(name): +def test_function_rejects_function_names_with_periods_or_hyphens(name): with pytest.raises(ValueError, match="invalid Function name"): - @udf(name=name) + @function(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 test_function_accepts_function_names_with_letters_digits_and_underscores(name): + @function(name=name) def image_info(value: int) -> int: return value @@ -200,7 +200,7 @@ def test_udf_accepts_function_names_with_letters_digits_and_underscores(name): assert image_info(1) == 1 -def test_secret_bound_udf_matches_its_shared_registration_golden(): +def test_secret_bound_function_matches_its_shared_registration_golden(): assert analyze_caption(" hello ") == "hello" bound = analyze_caption.bind_secrets( [EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")] @@ -446,15 +446,15 @@ def test_a_secret_name_admits_what_a_namespace_name_does(): ) -def _main_udf_source( +def _main_function_source( *, threshold: int = 20, input_annotation: str = "int", comparison: str = ">=" ) -> str: return ( "from __future__ import annotations\n" - "from lancedb.functions import udf\n" + "from lancedb.functions import function\n" f"THRESHOLD = {threshold}\n" "\n" - "@udf\n" + "@function\n" f"def label(value: {input_annotation}) -> str:\n" f" return 'big' if value {comparison} THRESHOLD else 'small'\n" "\n" @@ -463,7 +463,7 @@ def _main_udf_source( ) -def _run_main_udf(path: Path, source: str) -> dict: +def _run_main_function(path: Path, source: str) -> dict: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(source) result = subprocess.run( @@ -475,15 +475,15 @@ def _run_main_udf(path: Path, source: str) -> dict: return json.loads(result.stdout) -def test_main_udf_registration_identity_is_stable_across_processes_and_paths( +def test_main_function_registration_identity_is_stable_across_processes_and_paths( tmp_path, ): - source = _main_udf_source() + source = _main_function_source() original_path = tmp_path / "original" / "job.py" moved_path = tmp_path / "moved" / "renamed_job.py" - original_runs = [_run_main_udf(original_path, source) for _ in range(2)] - moved_run = _run_main_udf(moved_path, source) + original_runs = [_run_main_function(original_path, source) for _ in range(2)] + moved_run = _run_main_function(moved_path, source) assert len({run["artifact"]["digest"] for run in [*original_runs, moved_run]}) == 1 assert all( @@ -492,15 +492,15 @@ def test_main_udf_registration_identity_is_stable_across_processes_and_paths( ) assert original_runs[0] == original_runs[1] == moved_run - body_change = _run_main_udf( - tmp_path / "changes" / "body.py", _main_udf_source(comparison=">") + body_change = _run_main_function( + tmp_path / "changes" / "body.py", _main_function_source(comparison=">") ) - global_change = _run_main_udf( - tmp_path / "changes" / "global.py", _main_udf_source(threshold=21) + global_change = _run_main_function( + tmp_path / "changes" / "global.py", _main_function_source(threshold=21) ) - annotation_change = _run_main_udf( + annotation_change = _run_main_function( tmp_path / "changes" / "annotation.py", - _main_udf_source(input_annotation="float"), + _main_function_source(input_annotation="float"), ) baseline = original_runs[0] @@ -524,11 +524,13 @@ def _run_packaged(definition, *args): """Execute the shipped artifact in a fresh namespace, as a worker would.""" source = base64.b64decode(definition.registration_request.artifact.content.data) namespace: dict = {} - exec(compile(source, "", "exec"), namespace) + exec(compile(source, "", "exec"), namespace) return namespace[definition.registration_request.artifact.entrypoint](*args) -def _execute_registered_array_udf_v1(request: dict, batch: pa.RecordBatch) -> pa.Array: +def _execute_registered_array_function_v1( + request: dict, batch: pa.RecordBatch +) -> pa.Array: """Exercise adapter-v1 annotation dispatch over a registered artifact.""" assert request["artifact"]["adapter"] == { "kind": "scalar_to_arrow_batch", @@ -542,7 +544,7 @@ def _execute_registered_array_udf_v1(request: dict, batch: pa.RecordBatch) -> pa "RecordBatch": pa.RecordBatch, "typing": typing, } - exec(compile(source, "", "exec"), namespace) + exec(compile(source, "", "exec"), namespace) function = namespace[request["artifact"]["entrypoint"]] parameters = tuple(inspect.signature(function).parameters.values()) annotations = typing.get_type_hints(function) @@ -555,8 +557,8 @@ def _execute_registered_array_udf_v1(request: dict, batch: pa.RecordBatch) -> pa return result -def test_udf_conda_environment(): - @udf(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"]) +def test_function_conda_environment(): + @function(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"]) def halve(value: float) -> float: return value / 2 @@ -570,13 +572,13 @@ def test_udf_conda_environment(): assert "channels" not in pip_request["runtime"]["environment"] with pytest.raises(ValueError, match="not both"): - udf(name="both", pip=["numpy"], conda=["numpy"])(lambda value: value) + function(name="both", pip=["numpy"], conda=["numpy"])(lambda value: value) with pytest.raises(ValueError, match="requires conda"): - udf(name="channels", conda_channels=["conda-forge"])(lambda value: value) + function(name="channels", conda_channels=["conda-forge"])(lambda value: value) -def test_udf_apt_system_packages(): - @udf(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"]) +def test_function_apt_system_packages(): + @function(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"]) def decode(value: float) -> float: return value @@ -587,7 +589,7 @@ def test_udf_apt_system_packages(): "system_packages": ["libavcodec60", "libavutil58"], } - @udf(conda=["numpy"], apt=["libsndfile1"]) + @function(conda=["numpy"], apt=["libsndfile1"]) def conda_decode(value: float) -> float: return value @@ -596,14 +598,14 @@ def test_udf_apt_system_packages(): 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) + function(name="padded", apt=[" libsndfile1"])(lambda value: value) @pytest.mark.parametrize("packages", [{"pip": ["numpy"]}, {"conda": ["numpy"]}]) -def test_udf_image(packages): +def test_function_image(packages): image = "ghcr.io/acme/embedder@sha256:" + "a" * 64 - @udf(image=image, **packages) + @function(image=image, **packages) def embed(value: float) -> float: return value @@ -616,13 +618,13 @@ def test_udf_image(packages): @pytest.mark.parametrize( "image", ["ghcr.io/acme/embedder:latest", "embedder@sha256:" + "a" * 64, ""] ) -def test_udf_image_requires_digest_reference(image): +def test_function_image_requires_digest_reference(image): with pytest.raises(ValueError, match="sha256"): - udf(name="pinned", image=image)(lambda value: value) + function(name="pinned", image=image)(lambda value: value) -def test_udf_gpu_marker_uses_gpu_runtime(): - @udf(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") +def test_function_gpu_marker_uses_gpu_runtime(): + @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") def double_on_gpu(value: int) -> int: return value * 2 @@ -631,7 +633,7 @@ def test_udf_gpu_marker_uses_gpu_runtime(): assert request["runtime"]["gpu"] is True assert request["runtime"]["gpu_class"] == "a10g" - @udf(pip=["pyarrow"]) + @function(pip=["pyarrow"]) def cpu_function(value: int) -> int: return value @@ -647,12 +649,12 @@ def test_udf_gpu_marker_uses_gpu_runtime(): for invalid in [None, 0, 1, -1, 1.5, "", "true", "1", "H100"]: with pytest.raises(ValueError, match="gpu must be a boolean"): - udf(name="invalid_gpu", gpu=invalid)(identity) + function(name="invalid_gpu", gpu=invalid)(identity) for invalid in ["H100", "a_b", "-a10g", "a10g-", "a" * 64]: with pytest.raises(ValueError, match="gpu_class"): - udf(name="invalid_gpu_class", gpu=True, gpu_class=invalid)(identity) + function(name="invalid_gpu_class", gpu=True, gpu_class=invalid)(identity) with pytest.raises(ValueError, match="requires gpu=True"): - udf(name="gpu_class_without_gpu", gpu_class="a10g")(identity) + function(name="gpu_class_without_gpu", gpu_class="a10g")(identity) base_runtime = { "kind": "python_v2", @@ -692,8 +694,8 @@ def test_unknown_runtime_discards_payload_before_known_field_validation(): assert runtime.to_canonical_json() == '{"kind":"python_v3"}' -def test_udf_packages_attribute_access_and_body_imports(): - @udf +def test_function_packages_attribute_access_and_body_imports(): + @function def word_norm(body: str) -> float: import numpy as np @@ -706,14 +708,14 @@ def test_udf_packages_attribute_access_and_body_imports(): assert _run_packaged(word_norm, "aa bb") == pytest.approx(8**0.5) -def test_udf_packages_module_globals_and_global_caches(): - @udf +def test_function_packages_module_globals_and_global_caches(): + @function def label(value: int) -> str: return "big" if value >= THRESHOLD else "small" assert _run_packaged(label, 21) == "big" - @udf + @function def cached(value: int) -> int: global _CACHE if _CACHE is None: @@ -723,16 +725,16 @@ def test_udf_packages_module_globals_and_global_caches(): assert _run_packaged(cached, 2) == 42 -def test_udf_annotations_are_not_runtime_names(): - @udf +def test_function_annotations_are_not_runtime_names(): + @function def identity(value: date) -> date: return value assert _run_packaged(identity, date(2026, 8, 25)) == date(2026, 8, 25) -def test_udf_nested_scopes_resolve_lexically(): - @udf +def test_function_nested_scopes_resolve_lexically(): + @function def score(value: int) -> int: offset = 2 @@ -744,7 +746,7 @@ def test_udf_nested_scopes_resolve_lexically(): assert _run_packaged(score, 3) == 5 -def test_udf_resolves_module_globals_before_builtins(tmp_path): +def test_function_resolves_module_globals_before_builtins(tmp_path): module_path = tmp_path / "shadowing_udfs.py" module_path.write_text( "max = 7\n" @@ -765,10 +767,10 @@ def test_udf_resolves_module_globals_before_builtins(tmp_path): spec.loader.exec_module(module) # The module's `max = 7` is what the interpreter would use, so it ships. - assert _run_packaged(udf(module.uses_literal_shadow), 1) == 8 + assert _run_packaged(function(module.uses_literal_shadow), 1) == 8 # A callable global cannot ship; it must not be silently swapped for the builtin. with pytest.raises(TypeError, match="unsupported global value of type function"): - udf(module.uses_callable_shadow) + function(module.uses_callable_shadow) def test_canonical_arrow_type_prefers_the_compact_grammar(): @@ -801,8 +803,8 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): _canonical_arrow_type(outside) -def test_udf_nested_annotations_are_postponed_in_the_artifact(): - @udf +def test_function_nested_annotations_are_postponed_in_the_artifact(): + @function def score(value: int) -> int: def identity(item: date) -> date: return item @@ -813,8 +815,8 @@ def test_udf_nested_annotations_are_postponed_in_the_artifact(): assert _run_packaged(score, 3) == 3 -def test_udf_ships_globals_the_body_deletes(): - @udf +def test_function_ships_globals_the_body_deletes(): + @function def clear(value: int) -> int: global _CACHE del _CACHE @@ -823,7 +825,7 @@ def test_udf_ships_globals_the_body_deletes(): assert _run_packaged(clear, 3) == 3 -def test_udf_rejects_a_module_global_that_does_not_import_as_itself(tmp_path): +def test_function_rejects_a_module_global_that_does_not_import_as_itself(tmp_path): module_path = tmp_path / "fake_module_udfs.py" module_path.write_text( "import types\n" @@ -837,10 +839,10 @@ def test_udf_rejects_a_module_global_that_does_not_import_as_itself(tmp_path): module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) with pytest.raises(TypeError, match="does not import as 'numpy'"): - udf(module.score) + function(module.score) -def test_udf_rejects_a_module_level_namespace_alias(tmp_path): +def test_function_rejects_a_module_level_namespace_alias(tmp_path): module_path = tmp_path / "aliasing_udfs.py" module_path.write_text( "import builtins as b\n" @@ -853,7 +855,7 @@ def test_udf_rejects_a_module_level_namespace_alias(tmp_path): module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) with pytest.raises(ValueError, match="dynamic namespace access"): - udf(module.score) + function(module.score) @pytest.mark.parametrize( @@ -866,7 +868,7 @@ def test_udf_rejects_a_module_level_namespace_alias(tmp_path): "sys.modules[__name__].THRESHOLD", ], ) -def test_udf_rejects_dynamic_namespace_access(access): +def test_function_rejects_dynamic_namespace_access(access): namespace: dict = {} exec( f"def score(value: int) -> int:\n return value + {access}\n", @@ -886,9 +888,11 @@ def _package_from_text(source: str, module_globals: dict | None = None): import tempfile directory = tempfile.mkdtemp() - path = Path(directory) / "generated_udf_module.py" + path = Path(directory) / "generated_function_module.py" path.write_text(source) - spec = importlib.util.spec_from_file_location(f"generated_udf_{id(source)}", path) + spec = importlib.util.spec_from_file_location( + f"generated_function_{id(source)}", path + ) module = importlib.util.module_from_spec(spec) if module_globals: module.__dict__.update(module_globals) @@ -898,10 +902,10 @@ def _package_from_text(source: str, module_globals: dict | None = None): for value in vars(module).values() if callable(value) and getattr(value, "__module__", None) == module.__name__ ] - return udf(functions[0]) + return function(functions[0]) -def test_udf_rejects_a_non_standard_builtins_environment(): +def test_function_rejects_a_non_standard_builtins_environment(): def score(value: int) -> int: return len([1]) + value @@ -916,7 +920,7 @@ def test_udf_rejects_a_non_standard_builtins_environment(): patched.__annotations__ = score.__annotations__ assert patched(3) == 102 with pytest.raises(ValueError, match="non-standard builtins environment"): - udf(patched) + function(patched) class ReportingDict(dict): # reports standard entries, resolves differently def __missing__(self, key): @@ -928,7 +932,7 @@ def test_udf_rejects_a_non_standard_builtins_environment(): disguised.__annotations__ = score.__annotations__ assert disguised(3) == 102 with pytest.raises(ValueError, match="non-standard builtins environment"): - udf(disguised) + function(disguised) hooked = types.FunctionType( score.__code__, @@ -937,10 +941,10 @@ def test_udf_rejects_a_non_standard_builtins_environment(): ) hooked.__annotations__ = score.__annotations__ with pytest.raises(ValueError, match="non-standard builtins environment"): - udf(hooked) + function(hooked) -def test_udf_recursion_versus_a_rebound_module_name(tmp_path): +def test_function_recursion_versus_a_rebound_module_name(tmp_path): module_path = tmp_path / "rebound_udfs.py" module_path.write_text( "def fact(value: int) -> int:\n" @@ -952,20 +956,20 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path): spec = importlib.util.spec_from_file_location("rebound_udfs", module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) - assert _run_packaged(udf(module.fact), 5) == 120 + assert _run_packaged(function(module.fact), 5) == 120 raw = module.score module.score = 10 with pytest.raises(ValueError, match="binds that name to another value"): - udf(raw) + function(raw) # A wrapper that merely exposes __wrapped__ is not the function. module.score = functools.wraps(raw)(lambda value: 41) with pytest.raises(ValueError, match="binds that name to another value"): - udf(raw) + function(raw) # The decorator's own result is; a subclass of it is not. - module.fact = udf(module.fact) + module.fact = function(module.fact) assert _run_packaged(module.fact, 4) == 24 - class Twisted(UdfDefinition): + class Twisted(FunctionDefinition): def __call__(self, *args, **kwargs): return 41 @@ -980,7 +984,7 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path): python_version=None, ) with pytest.raises(ValueError, match="binds that name to another value"): - udf(raw_fact) + function(raw_fact) def test_canonical_arrow_type_uses_exact_json_for_list_child_properties(): @@ -1051,12 +1055,12 @@ def _shadows_missing_in_a_lambda(value: int) -> int: @pytest.mark.parametrize( - "function", + "target", [_calls_missing, _shadows_missing_in_a_comprehension, _shadows_missing_in_a_lambda], ) -def test_udf_rejects_a_truly_unresolved_global(function): +def test_function_rejects_a_truly_unresolved_global(target): with pytest.raises(ValueError, match=r"unresolved global names: \['missing'\]"): - udf(function) + function(target) def _arrow_type_from_golden(spec: dict) -> pa.DataType: @@ -1111,7 +1115,7 @@ def test_explicit_arrow_schema_is_deterministic(): nullable=False, ) - @udf(input_schema=input_schema, output_schema=output_schema) + @function(input_schema=input_schema, output_schema=output_schema) def explicit(value): return [value, value, value] @@ -1123,7 +1127,7 @@ def test_explicit_arrow_schema_is_deterministic(): def test_blob_fields_use_the_scalar_function_semantic_type(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), output_schema=lancedb.blob("result", nullable=False), ) @@ -1137,12 +1141,12 @@ def test_blob_fields_use_the_scalar_function_semantic_type(): def test_blob_input_access_is_inferred_from_annotations(): - @udf + @function def read_blob(video: BlobReader, timestamp_s: float) -> bytes: video.seek(int(timestamp_s)) return video.read(4) - @udf + @function def read_bytes(video: bytes) -> int: return len(video) @@ -1159,11 +1163,11 @@ def test_blob_input_access_is_inferred_from_annotations(): def test_nullable_blob_reader_and_explicit_blob_bytes(): - @udf + @function def nullable(video: Optional[BlobReader]) -> int: return 0 if video is None else video.size() - @udf( + @function( input_schema=pa.schema([lancedb.blob("video", nullable=False)]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1183,7 +1187,7 @@ def test_blob_reader_rejects_an_incompatible_explicit_schema(): return video.size() with pytest.raises(TypeError, match="requires a Blob V2 field"): - udf( + function( read, input_schema=pa.schema([pa.field("video", pa.int64(), nullable=False)]), output_schema=pa.field("size", pa.int64(), nullable=False), @@ -1191,7 +1195,7 @@ def test_blob_reader_rejects_an_incompatible_explicit_schema(): def test_whole_named_struct_function_can_include_a_blob_result_field(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), output_schema=pa.field( "payload", @@ -1245,7 +1249,7 @@ def test_struct_blob_signature_fields_preserve_exact_metadata_and_nullability(): nullable=False, ) - @udf(input_schema=pa.schema([nested_input]), output_schema=nested_output) + @function(input_schema=pa.schema([nested_input]), output_schema=nested_output) def copy_payload(payload): return payload @@ -1289,7 +1293,7 @@ def test_struct_blob_signature_supports_multiple_struct_levels(): nullable=False, ) - @udf( + @function( input_schema=pa.schema([recursive]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1310,7 +1314,7 @@ def test_struct_blob_signature_supports_multiple_struct_levels(): ], ) def test_blob_output_accepts_list_ancestors(data_type): - @udf( + @function( input_schema=pa.schema([lancedb.blob("video", nullable=False)]), output_schema=pa.field("frames", data_type, nullable=False), ) @@ -1335,7 +1339,7 @@ def test_blob_output_accepts_list_ancestors(data_type): def test_blob_output_rejects_map_and_fixed_size_list_ancestors(data_type): with pytest.raises(TypeError, match="nested under collection types"): - @udf( + @function( input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]), output_schema=pa.field("frames", data_type, nullable=False), ) @@ -1346,7 +1350,7 @@ def test_blob_output_rejects_map_and_fixed_size_list_ancestors(data_type): def test_blob_output_named_struct_accepts_list_ancestor(): frames_type = pa.list_(lancedb.blob("item", nullable=False)) - @udf( + @function( input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]), output_schema=pa.schema( [ @@ -1384,7 +1388,7 @@ def test_blob_signature_rejects_collection_ancestors(data_type): match="Blob v2 fields nested under collection types are not supported", ): - @udf( + @function( input_schema=pa.schema([pa.field("value", data_type, nullable=False)]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1411,7 +1415,7 @@ def test_blob_signature_rejects_collection_below_a_struct(): match="Blob v2 fields nested under collection types are not supported", ): - @udf( + @function( input_schema=pa.schema([nested]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1420,7 +1424,7 @@ def test_blob_signature_rejects_collection_below_a_struct(): def test_blob_fields_support_vectorized_pyarrow_arrays(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=True)]), output_schema=lancedb.blob("result", nullable=False), ) @@ -1433,7 +1437,7 @@ def test_blob_fields_support_vectorized_pyarrow_arrays(): values = pa.array([b"large blob", b"", None], type=pa.large_binary()) request = json.loads(copy_blobs.registration_request.to_canonical_json()) batch = pa.RecordBatch.from_arrays([values], names=["image"]) - result = _execute_registered_array_udf_v1(request, batch) + result = _execute_registered_array_function_v1(request, batch) assert isinstance(result, pa.LargeBinaryArray) assert result.to_pylist() == [b"large blob", b"", b""] @@ -1454,7 +1458,7 @@ def test_blob_fields_support_vectorized_pyarrow_arrays(): def test_documented_blob_array_identity_executes_packaged_artifact(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), output_schema=lancedb.blob("copy", nullable=False), ) @@ -1463,7 +1467,7 @@ def test_documented_blob_array_identity_executes_packaged_artifact(): values = pa.array([b"large blob", b""], type=pa.large_binary()) request = json.loads(copy_blobs.registration_request.to_canonical_json()) - result = _execute_registered_array_udf_v1( + result = _execute_registered_array_function_v1( request, pa.RecordBatch.from_arrays([values], names=["image"]), ) @@ -1471,7 +1475,7 @@ def test_documented_blob_array_identity_executes_packaged_artifact(): def test_named_struct_function_can_include_a_blob_result_field(): - @udf( + @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), output_schema=pa.schema( [ @@ -1492,7 +1496,7 @@ def test_named_struct_function_can_include_a_blob_result_field(): def test_named_struct_function_preserves_nullable_result_fields(): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.schema( [ @@ -1510,7 +1514,7 @@ def test_named_struct_function_preserves_nullable_result_fields(): ("failure_code", False), ] - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.schema( [ @@ -1540,7 +1544,7 @@ def test_metadata_marked_blob_field_uses_the_semantic_type(): metadata={"ARROW:extension:name": "lance.blob.v2"}, ) - @udf( + @function( input_schema=pa.schema([metadata_blob]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1560,7 +1564,7 @@ def test_blob_marker_rejects_invalid_storage_layout(): with pytest.raises(TypeError, match="requires a supported Blob storage layout"): - @udf( + @function( input_schema=pa.schema([malformed]), output_schema=pa.field("size", pa.int64(), nullable=False), ) @@ -1587,7 +1591,7 @@ def test_nested_non_blob_extension_is_not_silently_unwrapped(): ) with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([nested]), output_schema=pa.field("result", pa.int64(), nullable=False), ) @@ -1599,7 +1603,7 @@ def test_explicit_large_utf8_schemas_use_the_canonical_function_name(): input_schema = pa.schema([pa.field("text", pa.large_string(), nullable=True)]) output_schema = pa.field("result", pa.large_string(), nullable=False) - @udf(input_schema=input_schema, output_schema=output_schema) + @function(input_schema=input_schema, output_schema=output_schema) def preserve(text): return text @@ -1625,7 +1629,7 @@ def test_explicit_large_utf8_schemas_use_the_canonical_function_name(): def test_large_binary_schemas_use_the_canonical_function_name(): payload = pa.field("data", pa.large_binary(), nullable=True) - @udf( + @function( input_schema=pa.schema([payload]), output_schema=pa.field("result", pa.large_binary(), nullable=False), ) @@ -1696,7 +1700,7 @@ def test_nested_struct_output_uses_canonical_exact_json(): ] ) - @udf( + @function( input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]), output_schema=pa.field("analysis", analysis, nullable=False), ) @@ -1746,31 +1750,31 @@ def test_nested_struct_output_uses_canonical_exact_json(): def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(TypeError, match="missing Function annotations"): - @udf + @function def missing(value): return value with pytest.raises(TypeError, match="unsupported Function annotation"): - @udf + @function def unsupported(value: set[str]) -> str: return "" with pytest.raises(ValueError, match="output must be non-nullable"): - @udf + @function def nullable_output(value: int) -> Optional[int]: return value with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"): - @udf(input_schema=pa.schema([pa.field("value", pa.int64())])) + @function(input_schema=pa.schema([pa.field("value", pa.int64())])) def partial_schema(value): return value with pytest.raises(ValueError, match="exactly match callable parameters"): - @udf( + @function( input_schema=pa.schema([pa.field("other", pa.int64())]), output_schema=pa.int64(), ) @@ -1779,7 +1783,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(ValueError, match="output must be non-nullable"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.field("result", pa.int64(), nullable=True), ) @@ -1792,7 +1796,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): ]: with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.schema([invalid_field]), ) @@ -1801,7 +1805,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema( [pa.field("value", pa.int64(), metadata={"k": "v"})] ), @@ -1812,7 +1816,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.field( "result", pa.int64(), nullable=False, metadata={"k": "v"} @@ -1824,7 +1828,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): struct_type = pa.struct([pa.field("value", pa.int64(), nullable=False)]) with pytest.raises(TypeError, match="unsupported Arrow type"): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64())]), output_schema=pa.field( "result", struct_type, nullable=False, metadata={"k": "v"} @@ -1848,7 +1852,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): ]: with pytest.raises(TypeError, match="schema metadata"): - @udf(input_schema=input_schema, output_schema=output_schema) + @function(input_schema=input_schema, output_schema=output_schema) def schema_metadata(value): return value @@ -2093,8 +2097,8 @@ def test_building_a_binding_contacts_no_server(): assert state["requests"] == [] -def test_vectorized_blob_udf_executes_packaged_artifact_and_publishes(tmp_path): - @udf( +def test_vectorized_blob_function_executes_packaged_artifact_and_publishes(tmp_path): + @function( input_schema=pa.schema([lancedb.blob("image", nullable=True)]), output_schema=lancedb.blob("copy", nullable=False), ) @@ -2135,7 +2139,7 @@ def test_vectorized_blob_udf_executes_packaged_artifact_and_publishes(tmp_path): ) hydrated = source.fetch_blobs("image", input_hits) assert isinstance(hydrated, pa.LargeBinaryArray) - result = _execute_registered_array_udf_v1( + result = _execute_registered_array_function_v1( registration, pa.RecordBatch.from_arrays([hydrated], names=["image"]), ) @@ -2181,7 +2185,7 @@ def test_blob_list_output_fresh_artifact_survives_local_reopen( input_type = physical_list(pa.int64()) item = lancedb.blob("item", nullable=True) - @udf( + @function( input_schema=pa.schema([pa.field("frames", input_type, nullable=False)]), output_schema=pa.field("frames", declared_list(item), nullable=False), ) @@ -2199,7 +2203,7 @@ def test_blob_list_output_fresh_artifact_survives_local_reopen( item_field = declared["fields"][0] assert item_field["metadata"]["ARROW:extension:name"] == "lance.blob.v2" - result = _execute_registered_array_udf_v1( + result = _execute_registered_array_function_v1( request, pa.RecordBatch.from_arrays( [pa.array([[0], [1]], type=input_type)], @@ -2264,11 +2268,11 @@ def test_a_function_namespace_path_must_be_a_list_of_segments(): def test_one_explicit_schema_infers_the_other_from_annotations(): - @udf(input_schema=pa.schema([pa.field("value", pa.int64())])) + @function(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)) + @function(output_schema=pa.field("result", pa.float32(), nullable=False)) def explicit_output(value: Optional[int]): return float(value or 0) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index f97be9d89..f61d306f7 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,7 +20,7 @@ import pyarrow as pa import pytest from lancedb import col -from lancedb.functions import FunctionVersion, udf +from lancedb.functions import FunctionDefinition, FunctionVersion, function FIXTURES = ( Path(__file__).parents[3] @@ -63,7 +63,7 @@ def helper_package(tmp_path, monkeypatch): return write -@udf +@function class scale: def __init__( self, @@ -114,11 +114,11 @@ def test_class_function_declares_inputs_output_and_initialization(): assert scale.registration_request.artifact.entrypoint == "scale" source = artifact(scale).decode() assert source.startswith("from __future__ import annotations\n") - assert "class scale:" in source and "@udf" not in source + assert "class scale:" in source and "@function" not in source def test_function_without_initialization_keeps_its_wire_form(): - @udf + @function def double(value: int) -> int: return value * 2 @@ -147,11 +147,11 @@ def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_pac """ module = helper_package("fx_batch_annotations", {"__init__.py": source}) with pytest.raises(TypeError, match="input_schema and output_schema"): - udf(module.identity) + function(module.identity) def test_array_batch_annotations_accept_explicit_schemas(): - @udf( + @function( input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), output_schema=pa.int64(), ) @@ -168,7 +168,7 @@ def test_array_batch_annotations_accept_explicit_schemas(): assert identity(values).equals(values) -@pytest.mark.parametrize("class_udf", [False, True]) +@pytest.mark.parametrize("class_function", [False, True]) @pytest.mark.parametrize("postponed", [False, True]) @pytest.mark.parametrize( ("annotation", "nullable"), @@ -185,13 +185,13 @@ def test_array_batch_annotations_accept_explicit_schemas(): ], ) def test_blob_reader_annotations_resolve_in_the_artifact( - helper_package, monkeypatch, class_udf, postponed, annotation, nullable + helper_package, monkeypatch, class_function, postponed, annotation, nullable ): definition = ( f"class read_blob:\n" f" def __call__(self, video: {annotation}) -> int:\n" f" return 0\n" - if class_udf + if class_function else f"def read_blob(video: {annotation}) -> int:\n return 0\n" ) module = helper_package( @@ -202,9 +202,9 @@ def test_blob_reader_annotations_resolve_in_the_artifact( + "import lancedb\n" "from typing import Optional\n" "from lancedb import BlobReader, BlobReader as Reader\n" - "from lancedb.functions import udf\n" + "from lancedb.functions import function\n" "MaybeReader = Optional[Reader]\n\n" - f"@udf\n{definition}" + f"@function\n{definition}" ) }, ) @@ -221,7 +221,7 @@ def test_blob_reader_annotations_resolve_in_the_artifact( namespace = {} exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace) packaged = namespace["read_blob"] - if class_udf: + if class_function: packaged = packaged.__call__ assert get_type_hints(packaged) == { "video": Optional[worker.BlobReader] if nullable else worker.BlobReader, @@ -237,11 +237,11 @@ def test_blob_reader_annotation_does_not_shadow_body_globals( { "__init__.py": """ from lancedb import BlobReader - from lancedb.functions import udf + from lancedb.functions import function _lance_blob_reader = 7 - @udf + @function def read_blob(video: BlobReader) -> int: return _lance_blob_reader """ @@ -280,14 +280,14 @@ def test_class_function_rejects_unsupported_initialization(init, message): namespace, ) with pytest.raises((TypeError, ValueError), match=message): - udf(namespace["bad"]) + function(namespace["bad"]) def test_class_function_requires_call_and_a_plain_close(): with pytest.raises(TypeError, match="synchronous __call__"): - udf(NoCall) + function(NoCall) with pytest.raises(TypeError, match="close must be a method taking no"): - udf(BadClose) + function(BadClose) def test_nested_class_and_closure_are_rejected_with_the_reason(): @@ -299,13 +299,13 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): return nested with pytest.raises(ValueError, match="defined at module level"): - udf(build()) + function(build()) factor = 3 with pytest.raises(ValueError, match="capture closure values"): - @udf + @function def closes_over(value: int) -> int: return value * factor @@ -372,10 +372,10 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( """ import fx_helpers from fx_helpers.rate import TokenBucket - from lancedb import udf + from lancedb import function - @udf(code=[fx_helpers]) + @function(code=[fx_helpers]) class limited: def __init__(self, tpm: int): self.limiter = TokenBucket(tpm) @@ -445,7 +445,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package): with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") - @udf(code=[cache]) + @function(code=[cache]) def cache_only(value: int) -> int: return value @@ -468,7 +468,7 @@ def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_packag with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") - @udf(code=[resources]) + @function(code=[resources]) def resource_boundary(value: int) -> int: return value @@ -495,7 +495,7 @@ def test_code_rejects_submodules_duplicates_and_non_modules(helper_package): ]: with pytest.raises((TypeError, ValueError), match=message): - @udf(code=code) + @function(code=code) def f(value: int) -> int: return value @@ -514,10 +514,10 @@ def test_local_module_outside_code_warns_at_registration(tmp_path, helper_packag textwrap.dedent( f""" from fx_local import normalize - from lancedb import udf + from lancedb import function - @udf({options}) + @function({options}) def {name}(value: int) -> int: return normalize(value) """ @@ -551,10 +551,10 @@ def test_local_module_imported_in_function_body_warns_at_registration( (tmp_path / f"{name}.py").write_text( textwrap.dedent( f""" - from lancedb import udf + from lancedb import function - @udf({options}) + @function({options}) def {name}(value: int) -> int: import fx_body_local @@ -610,20 +610,20 @@ import pyarrow as pa import fx_mmlb from fx_mmlb.embedding import OpenAIEmbedder -from lancedb import udf +from lancedb import function TEXT = pa.schema([pa.field("text", pa.string())]) EMBEDDING = pa.list_(pa.field("item", pa.float64(), nullable=False)) -@udf(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING) +@function(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING) class openai_embedding_batch(OpenAIEmbedder): def __call__(self, text: pa.Array) -> pa.Array: item = pa.field("item", pa.float64(), nullable=False) return pa.array(self.embed(text.to_pylist()), pa.list_(item)) -@udf(code=[fx_mmlb]) +@function(code=[fx_mmlb]) class openai_embedding(OpenAIEmbedder): def __call__(self, text: str) -> list[float]: return self.embed([text])[0] @@ -695,7 +695,7 @@ def test_main_definitions_travel_by_source(tmp_path): import math from dataclasses import dataclass - from lancedb import udf + from lancedb import function SCALE = 2 @@ -714,7 +714,7 @@ def test_main_definitions_travel_by_source(tmp_path): return helper(value) * self.settings.factor - @udf + @function class scaled(Base): def __init__(self, factor: int): self.settings = Settings(factor) @@ -750,11 +750,11 @@ def test_main_lambdas_are_rejected(tmp_path): script.write_text( textwrap.dedent( """ - from lancedb import udf + from lancedb import function double = lambda value: value * 2 - @udf + @function def uses_lambda(value: int) -> int: return double(value) """ @@ -765,3 +765,33 @@ def test_main_lambdas_are_rejected(tmp_path): ) assert result.returncode != 0 assert "not lambdas, closures, or nested definitions" in result.stderr + + +def test_udf_alias_warns_and_packages_like_function(helper_package): + def source(decorator: str) -> str: + return f""" + import lancedb + from lancedb import function, udf + + @{decorator} + def double(value: int) -> int: + return value * 2 + """ + + current = helper_package("fx_alias_current", {"__init__.py": source("function")}) + expected = current.double.registration_request.artifact.digest + for name, decorator in (("fx_alias_bare", "udf"), ("fx_alias_attr", "lancedb.udf")): + with pytest.warns(DeprecationWarning, match="lancedb.udf is deprecated"): + module = helper_package(name, {"__init__.py": source(decorator)}) + assert isinstance(module.double, FunctionDefinition) + assert "udf" not in artifact(module.double).decode() + assert module.double.registration_request.artifact.digest == expected + + +def test_udf_definition_alias_warns(): + with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"): + from lancedb import UdfDefinition + assert UdfDefinition is FunctionDefinition + with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"): + from lancedb.functions import UdfDefinition as module_alias + assert module_alias is FunctionDefinition diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index c68f29923..6063c34f3 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -720,7 +720,7 @@ pub struct FunctionArtifactContent { /// Internal execution adapter selected for a Python callable artifact. /// -/// This is part of the executor request envelope, not the user-facing UDF +/// This is part of the executor request envelope, not the user-facing Function /// authoring mode. For version 1, the executor selects vectorized execution /// when every callable parameter is annotated as `pyarrow.Array`; it passes one /// Arrow array per declared input and requires an Arrow array matching the diff --git a/rust/lancedb/src/secrets.rs b/rust/lancedb/src/secrets.rs index c15c7ead9..29a07ba95 100644 --- a/rust/lancedb/src/secrets.rs +++ b/rust/lancedb/src/secrets.rs @@ -82,7 +82,7 @@ impl SecretReference { #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[non_exhaustive] pub enum SecretBinding { - /// Delivered as an environment variable, which the UDF's library already + /// Delivered as an environment variable, which the function's library already /// reads. The variable is the delivery target; the Secret is what fills it. Env { variable: String, diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 815ddcf08..fe8fc27c5 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -109,7 +109,7 @@ fn execution_controls_are_validated_before_canonical_serialization() { assert!(error.to_string().contains("batch_size"), "{error}"); } -/// The same shared golden as the Python suite builds from `@udf(secrets=...)` +/// The same shared golden as the Python suite builds from `@function(secrets=...)` /// plus `bind_secrets`, so both clients agree byte for byte on a bound request. #[test] fn secret_bound_registration_request_matches_shared_canonical_golden() { From 69ac2158a1b590855c46b2d13c92074383e0ce39 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 5 Nov 2026 16:54:23 +0800 Subject: [PATCH 013/203] fix: preserve take_row_ids request order (#4826) `take_row_ids` used an `IN` filter, so the backend could reorder rows and collapse duplicate IDs. That can silently misalign training rows with labels or sample weights. Restore the requested order and duplicate occurrences in the shared Rust take path for native and remote tables, and retain that information through Python query serialization. Missing or deleted IDs are omitted. Explicit Rust `order_by` overrides request order, and pagination applies after restoring occurrences. Empty projections and `_rowid` projection aliases retain their output schema. RTE tables reject unsupported takes with the existing base-table guidance before checking the internal row-ID projection used for ordering. An explicit `use_rte(False)` reads the base table with the same requested order and occurrences. A pre-existing fixture defect also blocked CI: `test_table_add_in_threadpool` responded without reading uploads, allowing a connection reset during response decoding. This PR includes a fix confined to that test's handler: consume each request body before responding and verify one create row plus ten inserted rows. This was not a regression in the take implementation. Production write retries, concurrency and HTTP client code are unchanged. The selective sampling guide scopes the row-ID guarantees to SDK releases containing this fix, preserves the distinct offset-take semantics, and explains that ordered takes collect and combine matching rows before output batching. It recommends smaller ID requests and narrow projections because `max_batch_length` does not cap working memory. This uses the existing REST query protocol and requires a new SDK release; no deployed service was changed. Validation: - Docs follow-up: the changed page compiles with the Mint 4.2.888 MDX compiler; Typos 1.26.0 passes and Vale 3.24.0 has no findings on changed lines. Full-site Mint validation reports four existing snippet-import warnings on the reranking/vector-search pages, identical with the original page restored in a baseline comparison. - The applied threadpool test passed locally after the fixture change. The identical candidate previously passed 10 trials with the ordinary reader and 10 with an unbuffered reader; each trial verifies all uploaded rows. Those checks used macOS arm64/Python 3.14/default features, not the full failing CI environment. The normal new-head macOS Python 3.13/experimental-functions job remains the required platform check. - Python package Ruff format/check passed. Repository-root Ruff still reports 59 existing errors and six formatting differences in unchanged `docs/web-tests` files; none are in changed files. - At `a569d3f0`, the RTE diagnostic regression was reproduced and fixed; 5 targeted cases and strict workspace Clippy passed. The fixture-only follow-up changes no production Rust/Python code, so that evidence is reused. - Earlier validation at `6bcc0878`: 439 Rust query/remote-table tests and 24 Python take/getitems tests passed; the focused 49-test suite also covered offset dataloaders. A local 9,216-row, four-fragment reproduction returned 200 seeded random batches of 64 rows with zero ordering or label-alignment mismatches. The ordering and projection implementation is unchanged by the follow-ups. - No live Enterprise run was performed. Fixes [ENT-3469](https://linear.app/lancedb/issue/ENT-3469). --- docs/web/curation/selective-sampling.mdx | 41 +- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/query.py | 5 + python/python/lancedb/table.py | 31 +- python/python/tests/test_merge_insert_lsm.py | 25 +- python/python/tests/test_query.py | 47 +- python/python/tests/test_remote_db.py | 59 +- python/src/query.rs | 3 + rust/lancedb/src/query.rs | 604 +++++++++++++++---- rust/lancedb/src/remote/table.rs | 131 +++- rust/lancedb/src/table.rs | 17 +- rust/lancedb/src/table/query.rs | 7 +- rust/lancedb/src/table/query/lsm.rs | 26 +- 13 files changed, 795 insertions(+), 202 deletions(-) diff --git a/docs/web/curation/selective-sampling.mdx b/docs/web/curation/selective-sampling.mdx index 7e6d941b4..f284abd22 100644 --- a/docs/web/curation/selective-sampling.mdx +++ b/docs/web/curation/selective-sampling.mdx @@ -57,16 +57,37 @@ let rows_by_offset = tbl.take_offsets(vec![0, 1, 2]).execute().await?; Both methods return a query builder; call `.to_arrow()`, `.to_list()` or -similar to execute it. Repeated *offsets* produce repeated rows, so -`take_offsets` also supports sampling with replacement -- `take_row_ids` -does not: a row ID repeated in the input list still returns that row only -once, since the lookup is a set membership test. Neither method guarantees -result order matches the order of the input list; for `take_row_ids`, pass -`with_row_id=True` to add `_rowid` to the output and align the results -yourself if you need to. `take_offsets` tracks `_rowoffset` internally to -restore repeated rows, but drops that column from the output again -afterward unless you explicitly `select` it -- add `_rowoffset` to your -selection when you need it to align a `take_offsets` result yourself. +similar to execute it. + + +The guarantees for row IDs below apply to SDK releases containing +[the ordering fix in #4826](https://github.com/lancedb/lancedb/pull/4826). +Earlier releases may collapse repeated IDs and return rows in a different +order. + + +`take_row_ids` returns matching rows in the order of the input IDs and +preserves repeated IDs in both LanceDB Embedded and LanceDB Enterprise. For example, +`take_row_ids([1005, 1001, 1005])` returns row 1005, row 1001, then row 1005 +again if both IDs exist. Missing or deleted IDs are omitted. This supports +sampling with replacement. In Rust, an explicit nonempty +`QueryBase::order_by` list overrides the requested order; limits and offsets +apply after restoring repeated rows. + +`take_offsets` also preserves repeated offsets, but does not guarantee +input order. It tracks `_rowoffset` internally to restore repeated rows +and drops that column from the output unless you explicitly `select` it. +Add `_rowoffset` to your selection when you need to align a `take_offsets` +result with the input offsets. + + +Ordered takes by row ID collect all matching batches, combine them into one +batch and reorder the rows before returning output batches. Even +`to_batches(max_batch_length=1)` only limits the returned batch size; it +does not bound working memory. For large requests or rows with large +column values, split the input IDs into smaller requests and use +`.select(...)` to fetch only the columns you need. + Offsets are mostly useful for sampling: the valid range is always `[0, len(table))`, so you can draw a random sample of offsets without diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index ed62b6b1d..f17856f3c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -897,6 +897,7 @@ class PyQueryRequest: limit: Optional[int] offset: Optional[int] take_offsets: Optional[List[int]] + take_row_ids: Optional[List[int]] filter: Optional[Union[str, bytes]] full_text_search: Optional[FullTextQuery] select: Optional[Union[str, List[str]]] diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 5185bf2a8..ce313c610 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -236,6 +236,7 @@ def _query_is_plain_scan(query: Query) -> bool: query.vector is None and query.full_text_query is None and query.take_offsets is None + and query.take_row_ids is None and not query.postfilter and not query.order_by ) @@ -1009,6 +1010,9 @@ class Query(pydantic.BaseModel): # This is populated when a take query is converted to this serializable form. take_offsets: Optional[List[int]] = None + # Row IDs whose requested order and duplicate occurrences must be restored. + take_row_ids: Optional[List[int]] = None + # if true, will only search the indexed data fast_search: Optional[bool] = None @@ -1034,6 +1038,7 @@ class Query(pydantic.BaseModel): query.limit = req.limit query.offset = req.offset query.take_offsets = req.take_offsets + query.take_row_ids = req.take_row_ids query.filter = req.filter query.full_text_query = req.full_text_search query.columns = req.select diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 4724776a1..59876a8c3 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -132,6 +132,7 @@ def _requires_local_namespace_execution(query: Query) -> bool: # The namespace QueryTable request does not support these query options. return ( query.take_offsets is not None + or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None ) @@ -2556,9 +2557,8 @@ class Table(ABC): Row ids are not stable and are relative to the current version of the table. They can change due to compaction and updates. - No guarantees are made regarding the order in which results are returned. If - you desire an output order that matches the order of the given ids, you will - need to add the row id column to the output and align it yourself. + Results follow the requested row-id order. Repeated IDs produce repeated + rows; missing or deleted IDs are omitted. This also applies to remote tables. Unlike offsets, row ids are not 0-indexed and no assumptions should be made about the possible range of row ids. In order to use this method you must @@ -7256,10 +7256,24 @@ class AsyncTable: | AsyncQuery | AsyncTakeQuery ): - if query.take_offsets is not None: - take_query = self.take_offsets(query.take_offsets) - if query.columns: - take_query = take_query.select(query.columns) + if query.take_offsets is not None or query.take_row_ids is not None: + if query.take_offsets is not None and query.take_row_ids is not None: + raise ValueError("Only one of take_offsets and take_row_ids may be set") + take_query = ( + self.take_row_ids(query.take_row_ids) + if query.take_row_ids is not None + else self.take_offsets(query.take_offsets) + ) + if query.columns is not None: + columns = query.columns + # Native requests serialize dynamic projections as (name, SQL) pairs. + if ( + isinstance(columns, list) + and columns + and isinstance(columns[0], tuple) + ): + columns = dict(columns) + take_query = take_query.select(columns) if query.use_rte is not None: take_query = take_query.use_rte(query.use_rte) if query.with_row_id: @@ -8119,6 +8133,9 @@ class AsyncTable: """ Take a list of row ids from the table. + Results follow the requested row-id order. Repeated IDs produce repeated + rows; missing or deleted IDs are omitted. This also applies to remote tables. + Row ids are not stable and are relative to the current version of the table. They can change due to compaction and updates. diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py index c7d69d779..f5280383c 100644 --- a/python/python/tests/test_merge_insert_lsm.py +++ b/python/python/tests/test_merge_insert_lsm.py @@ -278,7 +278,7 @@ def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path): # with_row_id is unsupported by the LSM scanner; on an RTE table the default # (auto-routed) read hard-errors instead of silently reading a stale base. - with pytest.raises(Exception): + with pytest.raises(Exception, match=r"with_row_id.*use_rte\(false\)"): table.search().with_row_id(True).to_arrow() # use_rte(False) is the escape hatch: it reads the base table only. @@ -563,19 +563,28 @@ def test_lsm_read_time_travel_errors(tmp_path): assert sorted(base["id"].to_pylist()) == [1, 2, 3] -def test_lsm_read_take_row_ids_errors(tmp_path): +@pytest.mark.parametrize("with_row_id", [False, True]) +@pytest.mark.parametrize("use_rte", [None, True]) +def test_lsm_read_take_row_ids_errors(tmp_path, with_row_id, use_rte): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0)) table = db.create_table("t", _reader([1, 2, 3])) table.set_unenforced_primary_key("id") table.enable_rte(RTEWriteSpec.unsharded()) _lsm_upsert(table, [4]) - # take-by-row-id auto-routes through the LSM scanner, which has no stable _rowid, - # so it hard-errors instead of failing with an opaque column-not-found error. - with pytest.raises(Exception, match="row id"): - table.take_row_ids([0, 1]).to_arrow() + # Automatic and explicit RTE routing must explain the unsupported take, + # including when row IDs are only requested internally for ordering. + take = table.take_row_ids([1, 0, 1, 2**64 - 1], with_row_id=with_row_id) + if use_rte is not None: + take = take.use_rte(use_rte) + with pytest.raises(Exception, match=r"take by row id.*use_rte\(false\)"): + take.to_arrow() # use_rte(False) is the escape hatch: it reads the base table. - base = table.take_row_ids([0, 1]).use_rte(False).to_arrow() - assert base.num_rows == 2 + base = take.use_rte(False).to_arrow() + assert base["id"].to_pylist() == [2, 1, 2] + assert base["value"].to_pylist() == [1, 0, 1] + assert ("_rowid" in base.column_names) == with_row_id + if with_row_id: + assert base["_rowid"].to_pylist() == [1, 0, 1] def test_lsm_read_fts_postfilter_errors(tmp_path): diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index a4ac3851d..d39f01a39 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -2417,13 +2417,36 @@ def test_take_queries(tmp_path): assert sorted(converted["idx"].to_pylist()) == [2, 5, 5, 17] # Take by row id - assert list( - sorted(table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list()) - ) == [ - 2, - 5, - 17, - ] + assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17] + + +@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}]) +@pytest.mark.parametrize("empty", [False, True]) +def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty): + table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": [0, 1]})) + table.add(pa.table({"idx": [2, 3]})) + rows = table.search().with_row_id(True).to_arrow().to_pylist() + row_ids = {row["idx"]: row["_rowid"] for row in rows} + table.delete("idx = 1") + requested = ( + [] if empty else [row_ids[3], row_ids[1], row_ids[3], 2**64 - 1, row_ids[0]] + ) + take = table.take_row_ids(requested) + if selection is not None: + take = take.select(selection) + actual = take.to_arrow() + assert actual.num_rows == (0 if empty else 3) + if selection == {"_rowid": "100 - idx"}: + assert actual.column_names == ["_rowid"] + assert actual["_rowid"].to_pylist() == ([] if empty else [97, 97, 100]) + elif selection == []: + assert actual.num_columns == 0 + else: + assert actual.column_names == ["idx"] + assert actual["idx"].to_pylist() == ([] if empty else [3, 3, 0]) + query = take.to_query_object() + assert query.take_row_ids == requested + assert table._execute_query(query).read_all() == actual def test_take_queries_with_row_id(tmp_path): @@ -2432,6 +2455,7 @@ def test_take_queries_with_row_id(tmp_path): by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow() assert "_rowid" in by_row_id.column_names + assert by_row_id["_rowid"].to_pylist() == [5, 2, 17] by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() assert "_rowid" in by_offset.column_names @@ -2446,6 +2470,7 @@ async def test_take_queries_with_row_id_async(tmp_path): 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 + assert by_row_id["_rowid"].to_pylist() == [5, 2, 17] by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow() assert "_rowid" in by_offset.column_names @@ -2472,16 +2497,12 @@ def test_take_queries_to_batches(tmp_path): rs = list(table.take_row_ids([5, 2, 17]).to_batches()) assert all(isinstance(b, pa.RecordBatch) for b in rs) assert sum(b.num_rows for b in rs) == 3 - assert sorted(v for b in rs for v in b.column("idx").to_pylist()) == [2, 5, 17] + assert [v for b in rs for v in b.column("idx").to_pylist()] == [5, 2, 17] # Take with select projection → to_batches preserves the projection rs = list(table.take_row_ids([5, 2, 17]).select(["label"]).to_batches()) assert all(b.schema.names == ["label"] for b in rs) - assert sorted(v for b in rs for v in b.column("label").to_pylist()) == [ - "17", - "2", - "5", - ] + assert [v for b in rs for v in b.column("label").to_pylist()] == ["5", "2", "17"] def test_getitems(tmp_path): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8178aec62..cd2261f04 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1422,7 +1422,26 @@ def test_table_to_pandas_not_supported(): def test_table_add_in_threadpool(): + received = [] + def handler(request): + # Consume uploads before responding: closing with unread bytes can reset + # the connection while the client is still reading the response. + if request.headers.get("Transfer-Encoding") == "chunked": + body = bytearray() + while size := int(request.rfile.readline().split(b";")[0], 16): + body.extend(request.rfile.read(size)) + assert request.rfile.read(2) == b"\r\n" + assert request.rfile.read(2) == b"\r\n" + else: + body = request.rfile.read(int(request.headers.get("Content-Length", 0))) + if request.path in ( + "/v1/table/test/create/?mode=create", + "/v1/table/test/insert/", + ): + received.append( + (request.path, pa.ipc.open_stream(body).read_all().to_pylist()) + ) if request.path == "/v1/table/test/insert/": request.send_response(200) request.end_headers() @@ -1461,6 +1480,9 @@ def test_table_add_in_threadpool(): for future in futures: future.result() + assert [rows for path, rows in received if "/create/" in path] == [[{"id": 1}]] + assert [rows for path, rows in received if "/insert/" in path] == [[{"id": 1}]] * 10 + def test_table_create_indices(): # Track received index creation requests to validate name parameter @@ -3232,8 +3254,41 @@ def test_remote_take_row_ids_with_row_id(): 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] + result = table.take_row_ids([0, 1]).to_arrow() + assert result.column_names == ["id"] + assert bodies[-1]["with_row_id"] is True + + +@pytest.mark.parametrize("with_row_id", [False, True]) +@pytest.mark.parametrize("selection", [None, [], ["id"], ["_rowid", "id"]]) +def test_remote_take_row_ids_order_and_roundtrip(with_row_id, selection): + def handler(body): + assert body["with_row_id"] is True + assert "_rowid IN" in body["filter"] + assert "take_row_ids" not in body + assert "_rowid" not in body.get("columns", []) + data = pa.table( + { + "id": pa.chunked_array([[1, 5], [17]]), + "_rowid": pa.chunked_array([[1, 5], [17]], type=pa.uint64()), + } + ) + return data.select(body.get("columns", ["id"]) + ["_rowid"]) + + with query_test_table(handler) as table: + take = table.take_row_ids([17, 5, 2**64 - 1, 17, 1], with_row_id=with_row_id) + if selection is not None: + take = take.select(selection) + result = take.to_batches(max_batch_length=1).read_all() + assert result.num_rows == 4 + expected_columns = ["id"] if selection is None else list(selection) + if with_row_id: + expected_columns = [name for name in expected_columns if name != "_rowid"] + expected_columns.append("_rowid") + assert result.column_names == expected_columns + for column in expected_columns: + assert result[column].to_pylist() == [17, 5, 17, 1] + assert table._execute_query(take.to_query_object()).read_all() == result def test_query_sync_minimal(): diff --git a/python/src/query.rs b/python/src/query.rs index bda4b7783..2097dac69 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -355,6 +355,7 @@ pub struct PyQueryRequest { pub limit: Option, pub offset: Option, pub take_offsets: Option>, + pub take_row_ids: Option>, pub filter: Option, pub full_text_search: Option>, pub select: PySelect, @@ -387,6 +388,7 @@ impl From for PyQueryRequest { limit: query_request.limit, offset: query_request.offset, take_offsets: query_request.take_offsets, + take_row_ids: query_request.take_row_ids, filter: query_request.filter.map(PyQueryFilter), full_text_search: query_request .full_text_search @@ -419,6 +421,7 @@ impl From for PyQueryRequest { limit: vector_query.base.limit, offset: vector_query.base.offset, take_offsets: vector_query.base.take_offsets, + take_row_ids: vector_query.base.take_row_ids, filter: vector_query.base.filter.map(PyQueryFilter), full_text_search: None, select_source_columns: PySelect::source_columns(&vector_query.base.select), diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 10914f5f2..866bfbc0d 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -17,12 +17,15 @@ use arrow_schema::{DataType, SchemaRef}; use datafusion_common::{DataFusionError, Result as DataFusionResult}; use datafusion_execution::TaskContext; use datafusion_expr::{Expr, col, lit}; -use datafusion_physical_expr::{EquivalenceProperties, Partitioning}; +use datafusion_physical_expr::{ + EquivalenceProperties, Partitioning, expressions::col as physical_col, +}; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, coalesce_partitions::CoalescePartitionsExec, execution_plan::{Boundedness, EmissionType}, limit::GlobalLimitExec, + projection::ProjectionExec, stream::RecordBatchStreamAdapter, }; use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt, stream, try_join}; @@ -850,6 +853,11 @@ pub struct QueryRequest { #[doc(hidden)] pub take_offsets: Option>, + /// Row IDs whose requested order and multiplicity are restored after lookup. + /// This is client-side metadata, not part of the remote query protocol. + #[doc(hidden)] + pub take_row_ids: Option>, + /// Apply filter to the returned rows. pub filter: Option, @@ -919,6 +927,7 @@ impl Default for QueryRequest { limit: None, offset: None, take_offsets: None, + take_row_ids: None, filter: None, filter_error: None, full_text_search: None, @@ -936,6 +945,10 @@ impl Default for QueryRequest { } impl QueryRequest { + pub(crate) fn has_take(&self) -> bool { + self.take_offsets.is_some() || self.take_row_ids.is_some() + } + /// Add a filter, combining it with any existing filter using a logical AND. /// /// If the new filter cannot be combined with the existing one (because they @@ -1676,42 +1689,42 @@ impl HasQuery for VectorQuery { } } -fn take_occurrences(offsets: &[u64]) -> HashMap { - let mut occurrences = HashMap::with_capacity(offsets.len()); - for offset in offsets { - *occurrences.entry(*offset).or_insert(0) += 1; +fn take_occurrences(indices: &[u64]) -> HashMap { + let mut occurrences = HashMap::with_capacity(indices.len()); + for index in indices { + *occurrences.entry(*index).or_insert(0) += 1; } occurrences } fn restore_take_batch_with_occurrences( batch: RecordBatch, - offsets: &[u64], + indices: &[u64], occurrences: &HashMap, ordering_column: &str, drop_ordering_column: bool, preserve_order: bool, ) -> Result { - let actual_offsets = batch + let actual_indices = batch .column_by_name(ordering_column) .ok_or_else(|| Error::Schema { message: format!( "take query result did not include ordering column '{ordering_column}'" ), })?; - let actual_offsets = match actual_offsets.data_type() { - DataType::UInt64 => actual_offsets + let actual_indices = match actual_indices.data_type() { + DataType::UInt64 => actual_indices .as_primitive::() .values() .to_vec(), - DataType::Int64 => actual_offsets + DataType::Int64 => actual_indices .as_primitive::() .values() .iter() - .map(|offset| { - u64::try_from(*offset).map_err(|_| Error::Schema { + .map(|index| { + u64::try_from(*index).map_err(|_| Error::Schema { message: format!( - "take query ordering column '{ordering_column}' contained a negative offset" + "take query ordering column '{ordering_column}' contained a negative index" ), }) }) @@ -1725,26 +1738,26 @@ fn restore_take_batch_with_occurrences( } }; - let mut desired_order = Vec::with_capacity(offsets.len()); + let mut desired_order = Vec::with_capacity(indices.len()); if preserve_order { - let ordering = actual_offsets + let ordering = actual_indices .iter() .copied() .enumerate() - .map(|(index, offset)| (offset, index as u64)) + .map(|(position, index)| (index, position as u64)) .collect::>(); - // Missing offsets retain the filter-based behavior of returning no row. + // Missing indices retain the filter-based behavior of returning no row. desired_order.extend( - offsets + indices .iter() - .filter_map(|offset| ordering.get(offset).copied()), + .filter_map(|index| ordering.get(index).copied()), ); } else { - // Public take queries do not guarantee output order. Preserve the lookup's - // existing order and only restore the multiplicity of each matching row. - for (index, offset) in actual_offsets.iter().enumerate() { - if let Some(count) = occurrences.get(offset) { - desired_order.extend(std::iter::repeat_n(index as u64, *count)); + // Unordered offset takes and explicitly sorted queries retain the lookup's + // order while restoring the multiplicity of each matching row. + for (position, index) in actual_indices.iter().enumerate() { + if let Some(count) = occurrences.get(index) { + desired_order.extend(std::iter::repeat_n(position as u64, *count)); } } } @@ -1761,7 +1774,15 @@ fn restore_take_batch_with_occurrences( }; if drop_ordering_column { - ordered_batch = ordered_batch.drop_column(ordering_column)?; + // Project preserves the row count even when no user columns were selected. + let columns = ordered_batch + .schema() + .fields() + .iter() + .enumerate() + .filter_map(|(i, field)| (field.name() != ordering_column).then_some(i)) + .collect::>(); + ordered_batch = ordered_batch.project(&columns)?; } Ok(ordered_batch) @@ -1770,32 +1791,32 @@ fn restore_take_batch_with_occurrences( #[cfg(test)] fn restore_take_batch( batch: RecordBatch, - offsets: &[u64], + indices: &[u64], ordering_column: &str, drop_ordering_column: bool, preserve_order: bool, ) -> Result { restore_take_batch_with_occurrences( batch, - offsets, - &take_occurrences(offsets), + indices, + &take_occurrences(indices), ordering_column, drop_ordering_column, preserve_order, ) } -/// Restores the logical offset occurrence sequence above the physical lookup plan. +/// Restores the logical index occurrence sequence above the physical lookup plan. /// /// The lookup plan returns each matching row at most once. For ordinary unordered /// takes this operator expands each input batch incrementally and preserves the -/// lookup's partitioning. The explicitly ordered reader path collects one coalesced +/// lookup's partitioning. Ordered takes collect one coalesced /// input before restoring requested order. Pagination must remain above this operator /// so it applies to occurrences. #[derive(Debug)] struct TakeRestoreExec { input: Arc, - offsets: Vec, + indices: Vec, occurrences: Arc>, ordering_column: String, drop_ordering_column: bool, @@ -1807,15 +1828,20 @@ struct TakeRestoreExec { impl TakeRestoreExec { fn try_new( input: Arc, - offsets: Vec, + indices: Vec, ordering_column: String, drop_ordering_column: bool, preserve_order: bool, ) -> Result { let schema = if drop_ordering_column { - RecordBatch::new_empty(input.schema()) - .drop_column(&ordering_column)? - .schema() + let schema = input.schema(); + let columns = schema + .fields() + .iter() + .enumerate() + .filter_map(|(i, field)| (field.name() != &ordering_column).then_some(i)) + .collect::>(); + Arc::new(schema.project(&columns)?) } else { input.schema() }; @@ -1838,8 +1864,8 @@ impl TakeRestoreExec { Ok(Self { input, - occurrences: Arc::new(take_occurrences(&offsets)), - offsets, + occurrences: Arc::new(take_occurrences(&indices)), + indices, ordering_column, drop_ordering_column, preserve_order, @@ -1858,7 +1884,7 @@ impl DisplayAs for TakeRestoreExec { write!( formatter, "TakeRestoreExec: occurrences={}", - self.offsets.len() + self.indices.len() ) } } @@ -1907,7 +1933,7 @@ impl ExecutionPlan for TakeRestoreExec { let child = children.into_iter().next().unwrap(); let plan = Self::try_new( child, - self.offsets.clone(), + self.indices.clone(), self.ordering_column.clone(), self.drop_ordering_column, self.preserve_order, @@ -1930,7 +1956,7 @@ impl ExecutionPlan for TakeRestoreExec { let input = self.input.execute(partition, context)?; let output_schema = self.schema.clone(); - let offsets = self.offsets.clone(); + let indices = self.indices.clone(); let occurrences = self.occurrences.clone(); let ordering_column = self.ordering_column.clone(); let drop_ordering_column = self.drop_ordering_column; @@ -1947,7 +1973,7 @@ impl ExecutionPlan for TakeRestoreExec { }; restore_take_batch_with_occurrences( batch, - &offsets, + &indices, &occurrences, &ordering_column, drop_ordering_column, @@ -1960,7 +1986,7 @@ impl ExecutionPlan for TakeRestoreExec { batch.and_then(|batch| { restore_take_batch_with_occurrences( batch, - &offsets, + &indices, &occurrences, &ordering_column, drop_ordering_column, @@ -1998,10 +2024,20 @@ impl ExecutionPlan for TakeRestoreExec { pub struct TakeQuery { parent: Arc, request: QueryRequest, - offsets: Option>, preserve_order: bool, } +struct TakeLookup { + request: QueryRequest, + indices: Vec, + ordering_column: String, + drop_ordering_column: bool, + output_offset: usize, + output_limit: Option, + preserve_order: bool, + output_projection: Option>, +} + impl TakeQuery { /// Create a new `TakeQuery` that will return rows at the given offsets. /// @@ -2020,10 +2056,9 @@ impl TakeQuery { filter: Some(QueryFilter::Datafusion( col("_rowoffset").in_list(in_list, false), )), - take_offsets: Some(offsets.clone()), + take_offsets: Some(offsets), ..Default::default() }, - offsets: Some(offsets), preserve_order: false, } } @@ -2032,14 +2067,20 @@ impl TakeQuery { /// /// See [`crate::Table::take_row_ids`] for more details. pub fn from_row_ids(parent: Arc, row_ids: Vec) -> Self { - let in_list: Vec = row_ids.iter().map(|id| lit(*id)).collect(); + let mut seen = HashSet::with_capacity(row_ids.len()); + let in_list = row_ids + .iter() + .copied() + .filter(|id| seen.insert(*id)) + .map(lit) + .collect(); Self { parent, request: QueryRequest { filter: Some(QueryFilter::Datafusion(col(ROW_ID).in_list(in_list, false))), + take_row_ids: Some(row_ids), ..Default::default() }, - offsets: None, preserve_order: false, } } @@ -2048,7 +2089,7 @@ impl TakeQuery { /// /// This is reserved for readers whose API explicitly guarantees ordering. pub(crate) fn preserve_order(mut self) -> Self { - debug_assert!(self.offsets.is_some()); + debug_assert!(self.request.take_offsets.is_some()); self.preserve_order = true; self } @@ -2106,29 +2147,124 @@ impl TakeQuery { Ok((request, ordering_column, drop_ordering_column)) } - async fn prepare_offsets_lookup( + async fn prepare_take_lookup( parent: &dyn BaseTable, request: &QueryRequest, - ) -> Result<(QueryRequest, String, bool, usize, Option)> { - let (mut request, ordering_column, drop_ordering_column) = - Self::request_with_row_offset(parent, request).await?; + preserve_order: bool, + ) -> Result { + let (indices, by_row_id) = match (&request.take_offsets, &request.take_row_ids) { + (Some(indices), None) => (indices.clone(), false), + (None, Some(indices)) => (indices.clone(), true), + _ => { + return Err(Error::InvalidInput { + message: "take lookup requires exactly one of take_offsets or take_row_ids" + .to_string(), + }); + } + }; + let preserve_order = + preserve_order || (by_row_id && request.order_by.as_ref().is_none_or(Vec::is_empty)); + let (mut request, ordering_column, drop_ordering_column, output_projection) = if by_row_id { + let mut request = request.clone(); + let with_row_id = request.with_row_id; + let mut names = match &request.select { + Select::All => None, + Select::Columns(names) => Some(names.clone()), + Select::Dynamic(pairs) => { + Some(pairs.iter().map(|(name, _)| name.clone()).collect()) + } + Select::Expr(pairs) => Some(pairs.iter().map(|(name, _)| name.clone()).collect()), + }; + let selected_row_id = names + .as_ref() + .is_some_and(|names| names.iter().any(|name| name == ROW_ID)); + // with_row_id appends the metadata column, but Lance leaves an + // existing projection alias named _rowid untouched. Rename that + // alias during lookup so it cannot be mistaken for the real ID. + let alias = if selected_row_id + && matches!(request.select, Select::Dynamic(_) | Select::Expr(_)) + { + let mut alias = "__lancedb_take_row_id".to_string(); + while names.as_ref().is_some_and(|names| names.contains(&alias)) { + alias.push('_'); + } + Some(alias) + } else { + None + }; + match &mut request.select { + // Remote tables expose metadata through with_row_id, not + // through the ordinary selected-column list. + Select::Columns(columns) => columns.retain(|name| name != ROW_ID), + Select::Dynamic(pairs) => { + if let Some(alias) = &alias { + for (name, _) in pairs.iter_mut().filter(|(name, _)| name == ROW_ID) { + *name = alias.clone(); + } + } + } + Select::Expr(pairs) => { + if let Some(alias) = &alias { + for (name, _) in pairs.iter_mut().filter(|(name, _)| name == ROW_ID) { + *name = alias.clone(); + } + } + } + Select::All => {} + } + if with_row_id && let Some(names) = &mut names { + if let Some(position) = names.iter().position(|name| name == ROW_ID) { + names.remove(position); + } + names.push(ROW_ID.to_string()); + } + let output_projection = if selected_row_id { + names.map(|names| { + names + .into_iter() + .map(|name| { + let input_name = if name == ROW_ID { + alias.as_ref().unwrap_or(&name).clone() + } else { + name.clone() + }; + (input_name, name) + }) + .collect() + }) + } else { + None + }; + let drop_row_id = alias.is_some() || (!with_row_id && !selected_row_id); + request.with_row_id = true; + (request, ROW_ID.to_string(), drop_row_id, output_projection) + } else { + let (request, column, drop_column) = + Self::request_with_row_offset(parent, request).await?; + (request, column, drop_column, None) + }; + request.take_offsets = None; + request.take_row_ids = None; // The lookup operates on distinct physical rows. Pagination is a logical // operation over occurrences and must be applied only after restoration. let output_offset = request.offset.take().unwrap_or_default(); let output_limit = request.limit.take(); - Ok(( + Ok(TakeLookup { request, + indices, ordering_column, drop_ordering_column, output_offset, output_limit, - )) + preserve_order, + output_projection, + }) } - fn wrap_offsets_plan( + fn wrap_take_plan( lookup: Arc, - offsets: &[u64], + indices: &[u64], ordering_column: String, drop_ordering_column: bool, output_offset: usize, @@ -2142,7 +2278,7 @@ impl TakeQuery { }; let restored: Arc = Arc::new(TakeRestoreExec::try_new( lookup, - offsets.to_vec(), + indices.to_vec(), ordering_column, drop_ordering_column, preserve_order, @@ -2159,7 +2295,7 @@ impl TakeQuery { } } - fn wrap_offsets_explanation( + fn wrap_take_explanation( lookup: &str, occurrence_count: usize, output_offset: usize, @@ -2199,21 +2335,6 @@ impl TakeQuery { } } - async fn create_offsets_plan( - &self, - offsets: &[u64], - options: QueryExecutionOptions, - ) -> Result> { - create_take_offsets_plan( - self.parent.as_ref(), - &self.request, - offsets, - options, - self.preserve_order, - ) - .await - } - /// Convert the `TakeQuery` into a `QueryRequest`. pub fn into_request(self) -> QueryRequest { self.request @@ -2258,15 +2379,22 @@ impl TakeQuery { } } -pub(crate) async fn create_take_offsets_plan( +pub(crate) async fn create_take_plan( parent: &dyn BaseTable, request: &QueryRequest, - offsets: &[u64], options: QueryExecutionOptions, preserve_order: bool, ) -> Result> { - let (request, ordering_column, drop_ordering_column, output_offset, output_limit) = - TakeQuery::prepare_offsets_lookup(parent, request).await?; + let TakeLookup { + request, + indices, + ordering_column, + drop_ordering_column, + output_offset, + output_limit, + preserve_order, + output_projection, + } = TakeQuery::prepare_take_lookup(parent, request, preserve_order).await?; let lookup_options = if preserve_order { options.without_output_batch_length_limit() } else { @@ -2276,43 +2404,73 @@ pub(crate) async fn create_take_offsets_plan( .create_plan(&AnyQuery::Query(request), lookup_options) .await?; - TakeQuery::wrap_offsets_plan( + let plan = TakeQuery::wrap_take_plan( lookup, - offsets, + &indices, ordering_column, drop_ordering_column, output_offset, output_limit, preserve_order, - ) + )?; + if let Some(projection) = output_projection { + let schema = plan.schema(); + let expressions = projection + .into_iter() + .map(|(input, output)| Ok((physical_col(&input, &schema)?, output))) + .collect::>>()?; + Ok(Arc::new(ProjectionExec::try_new(expressions, plan)?)) + } else { + Ok(plan) + } } -pub(crate) async fn explain_take_offsets_plan( +pub(crate) async fn explain_take_plan( parent: &dyn BaseTable, request: &QueryRequest, - offsets: &[u64], verbose: bool, + preserve_order: bool, ) -> Result { - let (request, _, _, output_offset, output_limit) = - TakeQuery::prepare_offsets_lookup(parent, request).await?; + let TakeLookup { + request, + indices, + output_offset, + output_limit, + preserve_order, + output_projection, + .. + } = TakeQuery::prepare_take_lookup(parent, request, preserve_order).await?; let lookup = parent .explain_plan(&AnyQuery::Query(request), verbose) .await?; - Ok(TakeQuery::wrap_offsets_explanation( + let explanation = TakeQuery::wrap_take_explanation( &lookup, - offsets.len(), + indices.len(), output_offset, output_limit, - false, - )) + preserve_order, + ); + if output_projection.is_some() { + Ok(format!( + "ProjectionExec\n{}", + explanation + .lines() + .map(|line| format!(" {line}")) + .collect::>() + .join("\n") + )) + } else { + Ok(explanation) + } } -pub(crate) async fn prepare_take_offsets_request( +pub(crate) async fn prepare_take_request( parent: &dyn BaseTable, request: &QueryRequest, ) -> Result { - let (request, _, _, _, _) = TakeQuery::prepare_offsets_lookup(parent, request).await?; - Ok(request) + Ok(TakeQuery::prepare_take_lookup(parent, request, false) + .await? + .request) } impl HasQuery for TakeQuery { @@ -2323,8 +2481,14 @@ impl HasQuery for TakeQuery { impl ExecutableQuery for TakeQuery { async fn create_plan(&self, options: QueryExecutionOptions) -> Result> { - if let Some(offsets) = &self.offsets { - return self.create_offsets_plan(offsets, options).await; + if self.request.has_take() { + return create_take_plan( + self.parent.as_ref(), + &self.request, + options, + self.preserve_order, + ) + .await; } let req = AnyQuery::Query(self.request.clone()); @@ -2335,7 +2499,7 @@ impl ExecutableQuery for TakeQuery { &self, options: QueryExecutionOptions, ) -> Result { - if self.offsets.is_some() { + if self.request.has_take() { let plan = self.create_plan(options.clone()).await?; let inner = execute_plan(plan, Default::default())?; let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize); @@ -2354,23 +2518,14 @@ impl ExecutableQuery for TakeQuery { } async fn explain_plan(&self, verbose: bool) -> Result { - if let Some(offsets) = &self.offsets { - let (request, _, _, output_offset, output_limit) = - Self::prepare_offsets_lookup(self.parent.as_ref(), &self.request).await?; - // Ask the backend to explain only the distinct-row lookup. This keeps - // remote explanation non-executing while still showing the client-side - // operators that create_plan and execution place above that lookup. - let lookup = self - .parent - .explain_plan(&AnyQuery::Query(request), verbose) - .await?; - return Ok(Self::wrap_offsets_explanation( - &lookup, - offsets.len(), - output_offset, - output_limit, + if self.request.has_take() { + return explain_take_plan( + self.parent.as_ref(), + &self.request, + verbose, self.preserve_order, - )); + ) + .await; } let query = AnyQuery::Query(self.request.clone()); @@ -2378,10 +2533,9 @@ impl ExecutableQuery for TakeQuery { } async fn analyze_plan_with_options(&self, options: QueryExecutionOptions) -> Result { - if self.offsets.is_some() { + if self.request.has_take() { if self.parent.analyze_plan_is_remote() { - let (request, _, _, _, _) = - Self::prepare_offsets_lookup(self.parent.as_ref(), &self.request).await?; + let request = prepare_take_request(self.parent.as_ref(), &self.request).await?; // Remote analysis is owned by the service. The current wire // request represents only the distinct-row lookup, so return // the service report unchanged instead of fabricating metrics @@ -4200,13 +4354,17 @@ mod tests { assert!(!analyzed.contains("CoalescePartitionsExec")); } + #[rstest::rstest] + #[case::unsorted(vec![5, 1, 17], vec![5, 1, 17])] + #[case::duplicate_and_missing(vec![17, 5, 17, u64::MAX, 1], vec![17, 5, 17, 1])] + #[case::empty(vec![], vec![])] #[tokio::test] - async fn test_take_row_ids() { + async fn test_take_row_ids(#[case] requested: Vec, #[case] expected: Vec) { let tmp_dir = tempdir().unwrap(); let table = make_test_table(&tmp_dir).await; let results = table - .take_row_ids(vec![5, 1, 17]) + .take_row_ids(requested) .execute() .await .unwrap() @@ -4215,18 +4373,226 @@ mod tests { .unwrap(); assert_eq!(results.len(), 1); - assert_eq!(results[0].num_rows(), 3); + assert_eq!(results[0].num_rows(), expected.len()); assert_eq!(results[0].num_columns(), 2); - let mut ids = results[0] + let ids = results[0] .column_by_name("id") .unwrap() .as_primitive::() .values() .to_vec(); - ids.sort(); + assert_eq!(ids, expected); + } - assert_eq!(ids, vec![1, 5, 17]); + #[rstest::rstest] + #[case::stable(true)] + #[case::physical(false)] + #[tokio::test] + async fn test_take_row_ids_deleted_and_pagination(#[case] stable: bool) { + let tmp_dir = tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = arrow_array::record_batch!( + ("id", Int32, [0, 1, 2, 3]), + ("label", Utf8, ["a", "b", "c", "d"]) + ) + .unwrap(); + let table = conn + .create_table("rows", vec![batch]) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + max_rows_per_file: 2, + max_rows_per_group: 2, + enable_stable_row_ids: stable, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let batches = table + .query() + .select(Select::columns(&["id"])) + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batch = concat_batches(&batches[0].schema(), &batches).unwrap(); + let row_ids: HashMap<_, _> = batch["id"] + .as_primitive::() + .values() + .iter() + .copied() + .zip( + batch[ROW_ID] + .as_primitive::() + .values() + .iter() + .copied(), + ) + .collect(); + table.delete("id = 1").await.unwrap(); + let take = table + .take_row_ids(vec![ + row_ids[&3], + row_ids[&1], + row_ids[&3], + u64::MAX, + row_ids[&0], + ]) + .select(Select::columns(&["label"])) + .with_row_id() + .offset(1) + .limit(2); + let batches = take + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["label"] + .as_string::() + .iter() + .collect::>(), + vec![Some("d"), Some("a")] + ); + assert_eq!( + actual[ROW_ID] + .as_primitive::() + .values() + .as_ref(), + &[row_ids[&3], row_ids[&0]] + ); + let request = take.clone().into_request(); + let direct = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + concat_batches(&direct[0].schema(), &direct).unwrap(), + actual + ); + let plan = take + .create_plan(QueryExecutionOptions::default()) + .await + .unwrap(); + let planned = execute_plan(plan, Default::default()) + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + concat_batches(&planned[0].schema(), &planned).unwrap(), + actual + ); + } + + #[rstest::rstest] + #[case::empty(Select::Columns(vec![]), vec![], vec![])] + #[case::explicit_row_id(Select::columns(&[ROW_ID, "id"]), vec![ROW_ID, "id"], vec![5, 1, 17])] + #[case::dynamic_alias(Select::dynamic(&[(ROW_ID, "20 - id"), ("__lancedb_take_row_id", "id")]), vec![ROW_ID, "__lancedb_take_row_id"], vec![15, 19, 3])] + #[case::expr_alias(Select::expr_projection(&[(ROW_ID, lit(20) - col("id"))]), vec![ROW_ID], vec![15, 19, 3])] + #[tokio::test] + async fn test_take_row_ids_projection( + #[case] selection: Select, + #[case] names: Vec<&str>, + #[case] values: Vec, + #[values(false, true)] with_row_id: bool, + #[values(false, true)] order_by: bool, + ) { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let mut take = table.take_row_ids(vec![5, 1, 17]).select(selection); + if with_row_id { + take = take.with_row_id(); + } + if order_by { + take = take.order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])); + } + let batches = take + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!(actual.num_rows(), 3); + let mut expected_names = names.clone(); + if with_row_id { + expected_names.retain(|name| *name != ROW_ID); + expected_names.push(ROW_ID); + } + assert_eq!( + actual + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + expected_names + ); + if !values.is_empty() { + let row_ids = actual.column_by_name(ROW_ID).unwrap(); + if row_ids.data_type() == &DataType::UInt64 { + assert_eq!( + row_ids.as_primitive::().values().as_ref(), + if order_by { &[1, 5, 17] } else { &[5, 1, 17] } + ); + } else { + let mut expected = values; + if order_by { + expected.swap(0, 1); + } + assert_eq!( + row_ids.as_primitive::().values().as_ref(), + expected.as_slice() + ); + } + } + } + + #[tokio::test] + async fn test_take_row_ids_explicit_order_by() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let batches = table + .take_row_ids(vec![17, 5, 1, 5]) + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])) + .offset(1) + .limit(2) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"].as_primitive::().values().as_ref(), + &[5, 5] + ); } } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index af0946600..6534f5519 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3013,10 +3013,9 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result> { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::create_take_offsets_plan(self, request, offsets, options, false) - .await; + return crate::query::create_take_plan(self, request, options, false).await; } let streams = self.execute_query(query, &options).await?; @@ -3038,16 +3037,10 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - let plan = crate::query::create_take_offsets_plan( - self, - request, - offsets, - options.clone(), - false, - ) - .await?; + let plan = + crate::query::create_take_plan(self, request, options.clone(), false).await?; let inner = execute_plan(plan, Default::default())?; let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize); let inner = if let Some(timeout) = options.timeout { @@ -3108,9 +3101,9 @@ impl BaseTable for RemoteTable { async fn explain_plan(&self, query: &AnyQuery, verbose: bool) -> Result { if let AnyQuery::Query(request) = query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::explain_take_offsets_plan(self, request, offsets, verbose).await; + return crate::query::explain_take_plan(self, request, verbose, false).await; } let base_request = self @@ -3166,10 +3159,10 @@ impl BaseTable for RemoteTable { options: QueryExecutionOptions, ) -> Result { let prepared_query = if let AnyQuery::Query(request) = query - && request.take_offsets.is_some() + && request.has_take() { Some(AnyQuery::Query( - crate::query::prepare_take_offsets_request(self, request).await?, + crate::query::prepare_take_request(self, request).await?, )) } else { None @@ -7741,8 +7734,11 @@ mod tests { assert_eq!(result, "analyzed plan"); } + #[rstest::rstest] + #[case::offsets(false)] + #[case::row_ids(true)] #[tokio::test] - async fn test_take_offsets_explain_plan_does_not_execute_query() { + async fn test_take_explain_plan_does_not_execute_query(#[case] by_row_id: bool) { let table = Table::new_with_handler("my_table", |request| { assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/explain_plan/"); @@ -7753,8 +7749,12 @@ mod tests { .unwrap() }); - let explained = table - .take_offsets(vec![0, 1, 0, 2]) + let take = if by_row_id { + table.take_row_ids(vec![0, 1, 0, 2]) + } else { + table.take_offsets(vec![0, 1, 0, 2]) + }; + let explained = take .select(crate::query::Select::columns(&["id"])) .limit(3) .explain_plan(false) @@ -7763,7 +7763,7 @@ mod tests { assert!(explained.contains("GlobalLimitExec")); assert!(explained.contains("TakeRestoreExec")); - assert!(!explained.contains("CoalescePartitionsExec")); + assert_eq!(explained.contains("CoalescePartitionsExec"), by_row_id); assert!(explained.contains("RemoteLookupExec")); } @@ -7816,8 +7816,11 @@ mod tests { ); } + #[rstest::rstest] + #[case::offsets(false)] + #[case::row_ids(true)] #[tokio::test] - async fn test_take_offsets_analyze_plan_delegates_to_remote() { + async fn test_take_analyze_plan_delegates_to_remote(#[case] by_row_id: bool) { let table = Table::new_with_handler("my_table", |request| { assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/analyze_plan/"); @@ -7835,8 +7838,12 @@ mod tests { .unwrap() }); - let analyzed = table - .take_offsets(vec![0, 1, 0, 2]) + let take = if by_row_id { + table.take_row_ids(vec![0, 1, 0, 2]) + } else { + table.take_offsets(vec![0, 1, 0, 2]) + }; + let analyzed = take .select(crate::query::Select::columns(&["id"])) .limit(3) .analyze_plan_with_options(QueryExecutionOptions { @@ -7849,6 +7856,84 @@ mod tests { assert_eq!(analyzed, "Remote analyzed plan: worker metrics"); } + #[rstest::rstest] + #[tokio::test] + async fn test_take_row_ids_restores_remote_order( + #[values(false, true)] with_row_id: bool, + #[values(false, true)] converted: bool, + ) { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/query/"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["columns"], json!(["id"])); + assert_eq!(body["with_row_id"], true); + assert_eq!(body["k"], json!(isize::MAX as usize)); + assert!(body.get("offset").is_none()); + assert!(body["filter"].as_str().unwrap().contains("_rowid IN")); + assert!(body.get("take_row_ids").is_none()); + + // The server can return the physical rows in any order and batches. + let data = arrow_array::record_batch!( + ("id", Int32, [1, 5, 17]), + ("_rowid", UInt64, [1, 5, 17]) + ) + .unwrap(); + let mut response = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut response, &data.schema()).unwrap(); + writer.write(&data.slice(0, 2)).unwrap(); + writer.write(&data.slice(2, 1)).unwrap(); + writer.finish().unwrap(); + } + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(response) + .unwrap() + }); + let mut take = table + .take_row_ids(vec![17, 5, u64::MAX, 17, 1]) + .select(crate::query::Select::columns(&["id"])) + .offset(1) + .limit(3); + if with_row_id { + take = take.with_row_id(); + } + let options = QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }; + let batches = if converted { + table + .base_table() + .query(&AnyQuery::Query(take.into_request()), options) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + } else { + take.execute_with_options(options) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + }; + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + let actual = arrow::compute::concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"] + .as_primitive::() + .values() + .as_ref(), + &[5, 17, 1] + ); + assert_eq!(actual.column_by_name("_rowid").is_some(), with_row_id); + } + #[tokio::test] async fn test_query_structured_fts() { let table = diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 1bd3a711a..34846d33e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1864,9 +1864,20 @@ impl Table { /// There is an ongoing effort to make row ids stable which is tracked at /// https://github.com/lancedb/lancedb/issues/1120 /// - /// No guarantees are made regarding the order in which results are returned. If you - /// desire an output order that matches the order of the given ids, you will need - /// to add the row id column to the output and align it yourself. + /// Results follow the requested row-id order, including repeated IDs. Missing or + /// deleted IDs are omitted. An explicit nonempty [`QueryBase::order_by`] overrides + /// the requested order. Limits and offsets apply after restoring occurrences. + /// These guarantees also apply to remote tables. + /// + /// ```rust + /// use lancedb::query::ExecutableQuery; + /// # async fn example(table: &lancedb::Table, first: u64, second: u64) -> lancedb::Result<()> { + /// // If both IDs exist, return second, first, then second again. + /// let rows = table.take_row_ids(vec![second, first, second]).execute().await?; + /// # Ok(()) + /// # } + /// ``` + /// /// Parameters /// ---------- /// row_ids: list[int] diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 8a72872e8..e9bcd380d 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -121,7 +121,7 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // The namespace QueryTable request cannot represent approx_mode, search_effort or use_rte. // For use_rte that is worse than a tuning miss: RTE read routing lives only // in `create_plan`, so a pushed-down query would return stale base-only data. - if query.base().use_rte.is_some() || query.base().take_offsets.is_some() { + if query.base().use_rte.is_some() || query.base().has_take() { return true; } matches!( @@ -164,10 +164,9 @@ pub async fn create_plan( ) -> Result> { let query = query.canonicalized()?; if let AnyQuery::Query(request) = &query - && let Some(offsets) = &request.take_offsets + && request.has_take() { - return crate::query::create_take_offsets_plan(table, request, offsets, options, false) - .await; + return crate::query::create_take_plan(table, request, options, false).await; } let query = match query { diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index d348a6668..400df6c82 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -161,6 +161,19 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if !query.query_vector.is_empty() && query.base.full_text_search.is_some() { return unsupported("hybrid (vector + full-text) search"); } + // Take lookups add with_row_id internally to restore requested order. Report + // the unsupported take before that implementation detail. Neither _rowid nor + // _rowoffset is exposed by the LSM scanner, which only exposes _rowaddr. + if let Some(QueryFilter::Datafusion(expr)) = &query.base.filter + && expr + .column_refs() + .iter() + .any(|c| c.name == "_rowid" || c.name == "_rowoffset") + { + return unsupported( + "take by row id or row offset (the LSM scanner has no stable _rowid / _rowoffset)", + ); + } if query.base.with_row_id { return unsupported("with_row_id (the LSM scanner exposes _rowaddr, not a stable _rowid)"); } @@ -204,19 +217,6 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if let Some(QueryFilter::Substrait(_)) = &query.base.filter { return unsupported("Substrait filters"); } - // Take-by-row-id / row-offset queries carry a `_rowid` / `_rowoffset` filter, - // columns the LSM scanner never exposes (only `_rowaddr`); reject with guidance - // rather than failing deep in datafusion with a column-not-found error. - if let Some(QueryFilter::Datafusion(expr)) = &query.base.filter - && expr - .column_refs() - .iter() - .any(|c| c.name == "_rowid" || c.name == "_rowoffset") - { - return unsupported( - "take by row id or row offset (the LSM scanner has no stable _rowid / _rowoffset)", - ); - } Ok(()) } From 5e38120bdc1b3aa9afe2c0f3b3ba3a81e4fcdbf9 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 5 Nov 2026 01:40:54 -0800 Subject: [PATCH 014/203] docs: add storage integration SDK examples, abstract RTE write, simplify cache pages (#4865) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - **Define Storage Integration**: un-gates the Python (and Rust, for S3) `create_storage_integration` examples, drafted against #4618 and held back until it shipped -- it's now in v0.42.0-beta.0+, and the signature matches the drafts exactly. - **Naming rules**: drops the `Branch` row and its "Learn more" link, consistent with de-emphasizing branches elsewhere in this nav. - **Distributed RTE Write**: removes the REST path, the `__lance_mem_wal` index name, and "WAL node" terminology in favor of an abstract framing -- a query node routes writes to RTE nodes, each of which can host shards from many different tables. Both diagram variants are updated to match. - **Data Page Cache / Tiered Index Cache / Cache Prewarm**: drop Helm-specific and exact-percentage detail (disk-budget math, `startup_prewarm_block_query_ready`/`healthPort`/failure-policy table) in favor of a short feature → architecture → why-it-matters shape, each closing with a contact-sales pointer. Data Page Cache's on-demand prewarm section is removed outright. ## Note I wasn't able to get a clean visual render of the updated Distributed RTE Write diagram in local preview -- Mermaid isn't rendering in headless Chrome in this environment for *any* page right now, confirmed against an unmodified reference page showing the identical symptom. The diagram source follows the exact pattern already shipped and working in the 21 diagrams from the earlier brand-theming pass, and `mint validate`/`mint broken-links` both pass clean. --------- Co-authored-by: Claude Sonnet 5 --- docs/web/basics/embedded-vs-enterprise.mdx | 12 +- docs/web/basics/jobs.mdx | 50 ++----- .../curation/blob-late-materialization.mdx | 2 +- docs/web/curation/chunking.mdx | 35 +++-- docs/web/curation/dedupe.mdx | 2 +- docs/web/curation/distributed-shuffle.mdx | 4 +- docs/web/curation/gpu-function-execution.mdx | 79 ----------- docs/web/curation/slurm-scheduling.mdx | 70 ---------- docs/web/curation/windowing.mdx | 4 +- docs/web/deployment/multicloud.mdx | 111 +++++++++++++++ docs/web/deployment/slurm.mdx | 131 ++++++++++++++++++ docs/web/docs.json | 24 ++-- docs/web/enterprise/adaptive-execution.mdx | 3 - .../advanced-conflict-resolution.mdx | 4 +- docs/web/enterprise/cache-prewarm.mdx | 96 ++++++++----- docs/web/enterprise/data-page-cache.mdx | 37 ++--- .../web/enterprise/distributed-compaction.mdx | 28 ++-- docs/web/enterprise/distributed-indexing.mdx | 70 ++++++---- .../enterprise/distributed-real-time-read.mdx | 80 +++++++++-- .../distributed-real-time-write.mdx | 99 ++++++------- docs/web/enterprise/distributed-search.mdx | 4 +- docs/web/enterprise/distributed-write.mdx | 4 +- docs/web/enterprise/gpu-refresh-execution.mdx | 93 ------------- docs/web/enterprise/horizontal-scaling.mdx | 2 +- .../intelligent-auto-maintenance.mdx | 6 +- .../enterprise/realtime-engine-compaction.mdx | 6 +- .../enterprise/slurm-refresh-scheduling.mdx | 39 ------ docs/web/enterprise/tiered-index-cache.mdx | 28 ++-- docs/web/indexing/gpu-indexing.mdx | 4 +- .../ingestion/define-storage-integration.mdx | 37 ----- docs/web/ingestion/import.mdx | 4 +- docs/web/ingestion/realtime-write.mdx | 14 +- docs/web/quickstart.mdx | 7 - docs/web/search/realtime-read.mdx | 14 +- docs/web/tables/realtime-engine.mdx | 16 +-- 35 files changed, 597 insertions(+), 622 deletions(-) delete mode 100644 docs/web/curation/gpu-function-execution.mdx delete mode 100644 docs/web/curation/slurm-scheduling.mdx create mode 100644 docs/web/deployment/multicloud.mdx create mode 100644 docs/web/deployment/slurm.mdx delete mode 100644 docs/web/enterprise/gpu-refresh-execution.mdx delete mode 100644 docs/web/enterprise/slurm-refresh-scheduling.mdx diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index da58acb7d..0dae6d6e3 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -42,7 +42,7 @@ file format, so moving data from one edition to the other does not require a dat | | [Hybrid search](/search/hybrid-search) | ✅ | ✅ | | | [Filtering](/search/filtering) | ✅ | ✅ | | | [Reranking](/reranking) | ✅ | ✅ | -| | [Distributed search](/enterprise/distributed-search) | ❌ | ✅ | +| | [Distributed Search](/enterprise/distributed-search) | ❌ | ✅ | | | [RTE Read](/search/realtime-read) | ✅ | ✅ | | | [Distributed RTE Read](/enterprise/distributed-real-time-read) | ❌ | ✅ | | | [Cache Prewarm](/enterprise/cache-prewarm) | ❌ | ✅ | @@ -52,19 +52,15 @@ file format, so moving data from one edition to the other does not require a dat | | [Aggregation and profiling](/curation/aggregate) | ❌ | ✅ | | | [Joins](/curation/join) | ❌ | ✅ | | | [Blob Late Materialization](/curation/blob-late-materialization) | ❌ | ✅ | -| | [Ranking and deduplication](/curation/windowing) | ❌ | ✅ | +| | [Ranking](/curation/windowing) | ❌ | ✅ | | | [Near-duplicate detection](/curation/dedupe) | ❌ | ✅ | | | [Chunking](/curation/chunking) | ❌ | ✅ | | | [Changes since a version](/curation/changes) | ❌ | ✅ | -| | [GPU Function Execution](/curation/gpu-function-execution) | ❌ | ✅ | -| | [Slurm Scheduling](/curation/slurm-scheduling) | ❌ | ✅ | | **Feature Engineering** | [Computed columns](/feature-engineering/add-computed-column) | ❌ | ✅ | | | [Incremental Refresh](/enterprise/incremental-refresh) | ❌ | ✅ | | | [Auto Refresh](/enterprise/auto-refresh) | ❌ | ✅ | | | [Checkpointing](/enterprise/checkpointing) | ❌ | ✅ | | | [Adaptive Execution](/enterprise/adaptive-execution) | ❌ | ✅ | -| | [GPU Refresh Execution](/enterprise/gpu-refresh-execution) | ❌ | ✅ | -| | [Slurm Scheduling](/enterprise/slurm-refresh-scheduling) | ❌ | ✅ | | | [Refresh Materialized View](/feature-engineering/refresh-materialized-view) | ❌ | ✅ | | | [Embedding registry](/embedding) | ✅ | ✅ | | **Training** | [PyTorch data loader](/training/data-loading) | ✅ | ✅ | @@ -94,7 +90,7 @@ file format, so moving data from one edition to the other does not require a dat | | [Compaction](/maintenance/compaction) | ✅ | ✅ | | | [RTE Compaction](/enterprise/realtime-engine-compaction) | ❌ | ✅ | | | [Garbage Collection](/maintenance/cleanup) | ✅ | ✅ | -| | [Distributed compaction](/enterprise/distributed-compaction) | ❌ | ✅ | +| | [Distributed Compaction](/enterprise/distributed-compaction) | ❌ | ✅ | | | [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) | ❌ | ✅ | | **Security** | [Authentication](/enterprise/authentication) | ❌ | ✅ | | | [Authorization](/governance/authorization) | ❌ | ✅ | @@ -102,6 +98,8 @@ file format, so moving data from one edition to the other does not require a dat | **Deployment** | [Horizontal Scaling](/enterprise/horizontal-scaling) | ❌ | ✅ | | | [OpenTelemetry](/deployment/opentelemetry) | ✅ | ✅ | | | [Kubernetes](/enterprise/deployment/kubernetes) | ❌ | ✅ | +| | [Multicloud](/deployment/multicloud) | ❌ | ✅ | +| | [Slurm](/deployment/slurm) | ❌ | ✅ | {/* Draft until branching reaches early access; restore to the Management rows. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index ee6dfa638..c10e24978 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -227,45 +227,21 @@ described below. ### SQL-backed job handles -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 -execution before returning. A completed DROP means the catalog binding has been -removed; physical cleanup continues in the background. +On Enterprise, several catalog operations return a job handle backed by the +SQL query engine rather than the job registry: -Remote function registration also returns a SQL query job. The SQL operation -submits the durable image build and waits for catalog publication before returning -the immutable FunctionVersion. `drop_function_async()` returns the catalog-removal -boolean together with a query job; waiting on that handle confirms removal while -physical cleanup continues separately. +| Operation | SDK methods | Behavior | +| --- | --- | --- | +| Materialized views | `create_materialized_view_async()`, `refresh_async()`, `drop_materialized_view_async()` | Synchronous variants wait on the same SQL execution. Drop removes the catalog binding immediately; physical cleanup continues in the background. | +| Functions | Registration, `drop_function_async()` | Registration waits for catalog publication before returning the immutable FunctionVersion. Drop confirms catalog removal while cleanup continues separately. | +| Secrets | Create, alter, list, describe, drop | Credential values are bound as SQL parameters, never embedded in SQL text or returned in results. `DESCRIBE SECRET` additionally exposes rotation history. | +| Views | Create, describe, list, drop | Create returns the stored definition and schema. Drop confirms catalog removal while cleanup continues separately. | -Remote Secret create, alter, list, describe, and drop use the SQL query backend. -The synchronous APIs wait on query completion internally. Create and alter bind -the credential as a parameter to -`CREATE SECRET name TYPE = GENERIC_STRING SECRET_STRING = $1` or -`ALTER SECRET name SET SECRET_STRING = $1`, keeping it out of SQL text. Results contain only -completion status or Secret names and timestamps; they never return credential -values. SQL `DESCRIBE SECRET` additionally exposes rotation history. - -Remote view creation, description, listing, and drop also use SQL. Creation -returns the stored definition and schema from the same SQL execution. -`drop_view_async()` returns a query job: waiting confirms catalog removal while -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. -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. +All of these report `job.job_type` as `"query"`, with `job.id` holding the +connection-scoped SQL query UUID -- use `describe_query(job.id)` to inspect +one. Unlike registry handles, they don't expose event history, can't be +reopened through `open_job()` or reattached after a client restart, and +cancellation depends on the SQL server's support for it. ### Object teardown {#teardown} diff --git a/docs/web/curation/blob-late-materialization.mdx b/docs/web/curation/blob-late-materialization.mdx index af6b335eb..81398a112 100644 --- a/docs/web/curation/blob-late-materialization.mdx +++ b/docs/web/curation/blob-late-materialization.mdx @@ -91,7 +91,7 @@ qualifies. It applies to a plain inner equi-join (a single `ON left_col `LIMIT` fused into it) where one side -- and only one side -- bottoms out at a single, otherwise-unfiltered table scan: no existing row filter, scan range, fragment subset, deleted-row handling, or -[real-time write](/ingestion/realtime-write) tier. If both sides would +[RTE write](/ingestion/realtime-write) tier. If both sides would otherwise qualify, the side with a BlobV2 column is preferred over the other; if neither or both sides have one, the rewrite declines rather than guessing which to narrow. diff --git a/docs/web/curation/chunking.mdx b/docs/web/curation/chunking.mdx index 3592f6be5..cff8f4b49 100644 --- a/docs/web/curation/chunking.mdx +++ b/docs/web/curation/chunking.mdx @@ -77,15 +77,19 @@ def split_into_passages(text): ## 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: +Wrap the function call in `UNNEST` in the `SELECT` list, with an alias: it +yields one row per element of the list the function returns, with every +other selected column repeated. Reference the exploded struct's fields +through that alias in a query over this one: ```sql SQL icon="database" +WITH exploded AS ( + SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p + FROM documents +) SELECT doc_id, title, p.chunk_index, p.chunk_text -FROM documents, split_into_passages(text) AS p +FROM exploded ``` @@ -160,8 +164,12 @@ timestamp, then call `extract_frame` on each row to produce its image: ```sql SQL icon="database" +WITH sampled AS ( + SELECT video_id, video, UNNEST(sample_frame_timestamps(duration_seconds)) AS f + FROM videos +) SELECT video_id, f.frame_index, f.ts, extract_frame(video, f.ts) AS jpeg -FROM videos, sample_frame_timestamps(duration_seconds) AS f +FROM sampled ``` @@ -179,8 +187,12 @@ recomputing the explosion on every query: ```sql SQL icon="database" CREATE MATERIALIZED VIEW chunks AS +WITH exploded AS ( + SELECT doc_id, title, UNNEST(split_into_passages(text)) AS p + FROM documents +) SELECT doc_id, title, p.chunk_index, p.chunk_text -FROM documents, split_into_passages(text) AS p +FROM exploded ``` @@ -194,10 +206,11 @@ FROM documents, split_into_passages(text) AS p 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. +[refresh](/feature-engineering/refresh-column). A single `UNNEST(...)` -- +whether unnesting a Function's list output directly, as above, or an +existing list column -- is the only lateral expansion a materialized view +can carry, and it can't be combined with `GROUP BY`, so keep aggregation or +further curation in a second step over the chunked table. ## Chunk, then curate {#next} diff --git a/docs/web/curation/dedupe.mdx b/docs/web/curation/dedupe.mdx index f02ac8471..470e170c2 100644 --- a/docs/web/curation/dedupe.mdx +++ b/docs/web/curation/dedupe.mdx @@ -9,7 +9,7 @@ availability: enterprise: available --- -[Ranking and deduplication](/curation/windowing#dedup) removes records by an +[Ranking](/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 diff --git a/docs/web/curation/distributed-shuffle.mdx b/docs/web/curation/distributed-shuffle.mdx index e834a463a..6b73cb778 100644 --- a/docs/web/curation/distributed-shuffle.mdx +++ b/docs/web/curation/distributed-shuffle.mdx @@ -11,7 +11,7 @@ availability: A distributed SQL query plans as a sequence of **stages**, each with its own set of partitions, connected by an **exchange**: a streaming gRPC service that carries one stage's output to the next stage's plan -executors. [Distributed search](/enterprise/distributed-search) covers +executors. [Distributed Search](/enterprise/distributed-search) covers how a query gets placed on the fleet in the first place; this page covers what happens between placement and the final result, for a query whose plan needs data repartitioned across machines -- a hash join or a grouped @@ -102,7 +102,7 @@ connection. ## What to read next {#next} - + How a query gets placed on the query-serving fleet in the first place. diff --git a/docs/web/curation/gpu-function-execution.mdx b/docs/web/curation/gpu-function-execution.mdx deleted file mode 100644 index e7f6f0f6a..000000000 --- a/docs/web/curation/gpu-function-execution.mdx +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: "GPU Function Execution" -tag: "Early access" -sidebarTitle: "GPU Functions" -description: "How a GPU Function's worker gets scheduled onto a GPU-capable node, and what happens when none is free." -icon: microchip -keywords: ["gpu", "gpu class", "scheduling", "function", "udf", "kubernetes", "node selector"] -availability: - embedded: unavailable - enterprise: available ---- - -Early access - -[Registering a GPU Function](/curation/create-function#gpu) sets `gpu=True` -and an optional `gpu_class`; this page covers what happens after that, when -a job actually needs a worker. An operator configures one or more named -**GPU classes** for the deployment -- each one a Kubernetes node selector, -toleration set, and resource name (such as `nvidia.com/gpu`) pointing at a -specific pool of GPU nodes, plus a hardware description (GPU model, GPU -memory, how many GPUs one worker may request). A Function with no -`gpu_class` uses the deployment's `default` class. - -## Placement {#placement} - -When a job needs to run a GPU Function, the agent resolves its `gpu_class` -(or `default`) to that class's node selector, tolerations, and resource -name, and requests a worker pod shaped accordingly -- this is a separate -placement path from the ordinary CPU worker ladder used by non-GPU -Functions and other background jobs (see -the [Job Framework](/basics/jobs) for that general job -machinery). The resulting pod can only schedule onto a node matching the -class's selector and tolerations, so a class is really naming a pool of -nodes, not just a resource count. - -## Waiting for capacity {#capacity} - -A GPU class describes the deployment's hardware, not live availability -- -listing classes never tells you whether a GPU is free right now. If no -node in the class has room, the worker pod stays pending rather than -failing the job outright or falling back to a CPU worker: the job reports -that it is waiting on that GPU class's capacity, and starts running as soon -as a matching node has room. A job stuck waiting indefinitely usually means -the class's node pool needs more capacity, not that anything is -misconfigured. - -{/* -Draft for the list_gpu_classes release. Keep this section unpublished -until that API ships -- v0.41.0 (the latest release) does not have it, -and there is no SQL equivalent; discovery is a REST call -(`GET /v1/gpu/classes`), not a SQL statement. - -## Inspecting GPU classes {#inspecting} - - -```python Python icon="python" -for gpu in db.list_gpu_classes(): - print(gpu.name, gpu.gpu_model, gpu.gpu_memory_bytes, gpu.max_gpu_count_per_worker) -``` - - -Returns the operator-configured classes: name, resource name, GPU model -and memory, and the largest per-worker GPU count the class permits. -Listing requires the System Usage privilege. -*/} - -## What to read next {#next} - - - - Register a GPU Function and pin it to a specific class. - - - The job types a deployment runs on its own schedule. - - - The same placement path, for a computed column or MV refresh instead of a direct call. - - diff --git a/docs/web/curation/slurm-scheduling.mdx b/docs/web/curation/slurm-scheduling.mdx deleted file mode 100644 index fbd13bb31..000000000 --- a/docs/web/curation/slurm-scheduling.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: "Slurm Scheduling" -sidebarTitle: "Slurm Scheduling" -description: "Run LanceDB Enterprise worker pods on a Slurm-on-Kubernetes cluster, accounted by Slurm." -icon: "server" -availability: - embedded: unavailable - enterprise: available ---- - -[Slurm](https://slurm.schedmd.com/) is the workload manager most GPU -clusters run to schedule and account for jobs -- queueing work across -shared nodes, enforcing fair-share and priority policies between teams, -and tracking GPU-hour usage per job. That makes it the de facto standard -in AI training infrastructure, where expensive GPU nodes are shared -across many training and data jobs instead of dedicated to one team. -CoreWeave, a major GPU cloud provider, runs Slurm this way through SUNK -(Slurm on Kubernetes) -- Slurm's scheduling and accounting layered onto -an otherwise ordinary Kubernetes cluster. - -LanceDB Enterprise's job workers -- indexing, compaction, cache prewarm, -registration, and most other background work -- all launch as ordinary -Kubernetes pods through one shared scheduling configuration. Today, that -configuration integrates with CoreWeave's SUNK specifically; the rest of -this page describes its effect. On a Neocloud running SUNK, pointing -that configuration at SUNK's pod scheduler puts every one of those -worker pods under Slurm's scheduling and accounting, instead of plain -Kubernetes bin-packing. See [Architecture](/index#architecture). - -## What SUNK changes {#what-changes} - -Most agent-launched worker pods -- a one-pod job worker or a multi-worker -distributed indexer Job -- share one scheduling configuration: node -selector, tolerations, scheduler name, and termination grace period. -Pointing the scheduler name at the cluster's SUNK pod scheduler routes -pod placement through SUNK instead of the default Kubernetes scheduler, -so Slurm sees and accounts for the workload. SUNK also expects a short -termination grace period, kept below Slurm's own kill-wait threshold -- -deployments commonly use 5 to 20 seconds. - - -Function refresh's own child workers -- including GPU Function execution --- get the scheduler name but not this shared termination-grace setting; -they currently launch with Kubernetes' 30-second default, above most -SUNK deployments' kill-wait bound. Confirm with your deployment operator -before running Function refresh on a SUNK-scheduled cluster. See -[GPU Function execution](/curation/gpu-function-execution) for the -placement mechanism this affects. - - -## Configuring a SUNK-backed deployment {#config} - -This scheduling configuration is set by a deployment operator, not by a -SQL statement, table property, or SDK call -- there is no per-query or -per-table knob for it. [Contact support](https://www.lancedb.com/contact) -to configure or size a SUNK-backed deployment. - -## What to read next {#next} - - - - How a GPU-bound Function gets scheduled onto GPU-equipped workers. - - - The query, executor, cache and jobs fleets SUNK schedules onto. - - - What does and doesn't carry over for a computed column or MV refresh. - - diff --git a/docs/web/curation/windowing.mdx b/docs/web/curation/windowing.mdx index 10fccf1e4..f467937da 100644 --- a/docs/web/curation/windowing.mdx +++ b/docs/web/curation/windowing.mdx @@ -1,6 +1,6 @@ --- -title: "Ranking and deduplication" -sidebarTitle: "Rank and Deduplicate" +title: "Ranking" +sidebarTitle: "Ranking" description: "Choose records with explicit ranking rules and deterministic tie handling." icon: chart-simple keywords: ["window", "deduplication", "row_number", "rank", "train test split", "per class"] diff --git a/docs/web/deployment/multicloud.mdx b/docs/web/deployment/multicloud.mdx new file mode 100644 index 000000000..5ce4e309e --- /dev/null +++ b/docs/web/deployment/multicloud.mdx @@ -0,0 +1,111 @@ +--- +title: "Multicloud" +sidebarTitle: "Multicloud" +description: "Keep deployment orchestration in your cloud while dispatching compute-heavy work, like GPU UDF execution, to run in a different cloud." +icon: "cloud" +keywords: ["multicloud", "cross-cloud", "gpu", "deployment"] +availability: + embedded: unavailable + enterprise: available +--- + +A LanceDB Enterprise deployment doesn't have to keep all of its compute in +one cloud. Orchestration -- query nodes, job coordination, the catalog -- +stays with your deployment in its own cloud account and region. Specific, +compute-heavy work, such as a GPU-bound Function's execution during a +refresh, can instead dispatch to run in a **different** cloud account, +region, or provider entirely, and send its results back to complete the job. + +## How it fits together {#architecture} + +Your deployment's job orchestration plans the work and tracks it to +completion the same way it would locally. The part that actually needs the +remote capacity -- a GPU UDF call, for example -- runs across a network +boundary instead of on a worker in your own cloud, and reports its result +back the same way a local worker would. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + QN["Query node"] + Job["Job orchestration"] + end + + subgraph R["Remote cloud"] + direction TB + Exec["Compute execution
(e.g. GPU UDFs)"] + end + + QN --> Job + Job -- "dispatches work" --> Exec + Exec -- "results" --> Job + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Exec accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + QN["Query node"] + Job["Job orchestration"] + end + + subgraph R["Remote cloud"] + direction TB + Exec["Compute execution
(e.g. GPU UDFs)"] + end + + QN --> Job + Job -- "dispatches work" --> Exec + Exec -- "results" --> Job + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Exec accent +``` + +
+ +## Why it matters {#why-it-matters} + +The cloud that's right for your primary deployment -- where your data and +other infrastructure already live -- isn't always the cloud with the best +GPU availability or pricing. Splitting orchestration from execution means +you don't have to choose: keep your deployment where it already makes +sense, and reach compute capacity elsewhere only for the work that +actually needs it, without migrating the deployment or operating that +remote capacity yourself. + +[Contact us](https://www.lancedb.com/contact) to learn more about setting +up cross-cloud execution for your deployment. + +## What to read next {#next} + + + + A common way the remote cloud's compute gets scheduled: as Slurm jobs. + + + How a refresh's resource class, part size and worker count adjust themselves. + + diff --git a/docs/web/deployment/slurm.mdx b/docs/web/deployment/slurm.mdx new file mode 100644 index 000000000..87204d9b2 --- /dev/null +++ b/docs/web/deployment/slurm.mdx @@ -0,0 +1,131 @@ +--- +title: "Slurm" +sidebarTitle: "Slurm" +description: "Run LanceDB Enterprise's own pods as Slurm-scheduled jobs, and reach a Neocloud's GPU capacity through Slurm in the multicloud case." +icon: "server" +keywords: ["slurm", "scheduling", "gpu", "neocloud", "preemption", "multicloud"] +availability: + embedded: unavailable + enterprise: available +--- + +[Slurm](https://slurm.schedmd.com/) is the workload manager most GPU +clusters run to schedule and account for jobs -- queueing work across +shared nodes, enforcing fair-share and priority policies between teams, +and tracking GPU-hour usage per job. That makes it the de facto standard +in AI training infrastructure, where expensive GPU nodes are shared +across many training and data jobs instead of dedicated to one team. +GPU-focused cloud providers ("Neoclouds") such as CoreWeave and Nebius run +Slurm-based scheduling across their Kubernetes clusters for exactly this +reason. + +Slurm shows up for LanceDB Enterprise in two related ways. Its own pods -- +query nodes, plan executors, and background job workers alike -- can run +as Slurm-scheduled jobs rather than plain Kubernetes pods, under the same +scheduling and accounting as everything else on the cluster. And in the +[multicloud](/deployment/multicloud) case, when the remote cloud is a +Neocloud, Slurm is commonly how the dispatched GPU work actually gets +scheduled there. + +## How it fits together {#architecture} + +Scheduling LanceDB's pods through Slurm puts them under the same +scheduler as GPU training jobs, so the cluster's capacity is accounted +for consistently regardless of which one is using it -- Slurm's +fair-share and priority policies apply to LanceDB the same way they +apply to a training job, including preemption when training needs the +capacity back. + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "clusterBkg": "#211d1a", "clusterBorder": "#4c443f", "edgeLabelBackground": "#171513", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + Job["Job orchestration"] + end + + subgraph N["Neocloud (e.g. CoreWeave, Nebius)"] + direction TB + Slurm["Slurm scheduler"] + Train["GPU training jobs"] + LDB["LanceDB Enterprise pods"] + Slurm --> Train + Slurm --> LDB + Train -.->|"can preempt"| LDB + end + + Job -- "dispatches GPU work" --> Slurm + LDB -- "results" --> Job + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Slurm accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "clusterBkg": "#f4ebe8", "clusterBorder": "#ad9e95", "edgeLabelBackground": "#ffffff", + "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + subgraph P["Your cloud"] + direction TB + Job["Job orchestration"] + end + + subgraph N["Neocloud (e.g. CoreWeave, Nebius)"] + direction TB + Slurm["Slurm scheduler"] + Train["GPU training jobs"] + LDB["LanceDB Enterprise pods"] + Slurm --> Train + Slurm --> LDB + Train -.->|"can preempt"| LDB + end + + Job -- "dispatches GPU work" --> Slurm + LDB -- "results" --> Job + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Slurm accent +``` + +
+ +## Why it matters {#why-it-matters} + +Most GPU infrastructure already runs Slurm for training. Deploying LanceDB +Enterprise into that same infrastructure, under the same scheduler, means +it can share capacity with training workloads safely -- queued, accounted, +and preemptible like everything else -- instead of requiring a separate, +dedicated pool of nodes carved out just for LanceDB. Combined with +[multicloud](/deployment/multicloud) dispatch, that makes it practical to +keep your primary deployment wherever it already lives and still reach +GPU capacity on a Neocloud built around Slurm, only for the work that +needs it. + +[Contact us](https://www.lancedb.com/contact) to learn more about running +LanceDB Enterprise on a Slurm-scheduled cluster. + +## What to read next {#next} + + + + The cross-cloud dispatch model this page's Neocloud case builds on. + + + The query, executor, cache and jobs fleets this scheduling applies to. + + diff --git a/docs/web/docs.json b/docs/web/docs.json index 58ad78a52..33a3bbf46 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -121,11 +121,11 @@ }, { "source": "/curation/sunk-integration", - "destination": "/curation/slurm-scheduling" + "destination": "/deployment/slurm" }, { "source": "/curation/slurm-integration", - "destination": "/curation/slurm-scheduling" + "destination": "/deployment/slurm" }, { "source": "/curation/sampling", @@ -362,6 +362,14 @@ { "source": "/enterprise/distributed-column-refresh", "destination": "/enterprise/adaptive-execution" + }, + { + "source": "/curation/slurm-scheduling", + "destination": "/deployment/slurm" + }, + { + "source": "/enterprise/slurm-refresh-scheduling", + "destination": "/deployment/slurm" } ], "navigation": { @@ -452,9 +460,7 @@ "curation/clustering", "curation/dedupe", "feature-engineering/view", - "curation/vend-secret", - "curation/gpu-function-execution", - "curation/slurm-scheduling" + "curation/vend-secret" ] }, { @@ -468,9 +474,7 @@ "enterprise/incremental-refresh", "enterprise/auto-refresh", "enterprise/checkpointing", - "enterprise/adaptive-execution", - "enterprise/gpu-refresh-execution", - "enterprise/slurm-refresh-scheduling" + "enterprise/adaptive-execution" ] }, { @@ -534,7 +538,9 @@ "pages": [ "enterprise/horizontal-scaling", "deployment/opentelemetry", - "enterprise/deployment/kubernetes" + "enterprise/deployment/kubernetes", + "deployment/multicloud", + "deployment/slurm" ] }, { diff --git a/docs/web/enterprise/adaptive-execution.mdx b/docs/web/enterprise/adaptive-execution.mdx index 0c8c20b86..97ab71e67 100644 --- a/docs/web/enterprise/adaptive-execution.mdx +++ b/docs/web/enterprise/adaptive-execution.mdx @@ -136,7 +136,4 @@ part sizing described above still decides how many rows each part covers. How a part's progress survives a failure or restart. - - How a GPU-bound Function's worker gets placed, for a refresh specifically. -
diff --git a/docs/web/enterprise/advanced-conflict-resolution.mdx b/docs/web/enterprise/advanced-conflict-resolution.mdx index 6fcdbeed3..aafbabc37 100644 --- a/docs/web/enterprise/advanced-conflict-resolution.mdx +++ b/docs/web/enterprise/advanced-conflict-resolution.mdx @@ -190,10 +190,10 @@ flowchart TD The `index_remap` job type, and keeping an index current as the table changes. - + How compaction itself scales across the jobs fleet. - + How an index build scales across the jobs fleet. diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index d721eb027..3ce773d73 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -3,61 +3,83 @@ title: "Cache Prewarm" sidebarTitle: "Cache Prewarm" description: "Populate the tiered index cache ahead of a request, instead of filling it lazily on first read." icon: "fire" -keywords: ["prewarm", "cache", "page cache", "index cache", "startup"] +keywords: ["prewarm", "cache", "index cache", "startup"] availability: embedded: unavailable enterprise: available --- -This page is about `startup_prewarm_idx`, which warms the distributed -[tiered index cache](/enterprise/tiered-index-cache) a plan executor keeps -as part of Enterprise's serving layer -- LanceDB Embedded has no such -cache, so there is nothing for it to warm on Embedded. Embedded does have -its own, separate `prewarm_index()` on a table, an idempotent hint that -loads a built index into memory ahead of a query; it has no equivalent for -raw column data, where only Enterprise supports prewarming. On Enterprise, -the index cache fills lazily on first read by default; `startup_prewarm_idx` -loads it ahead of that first request instead. The -[data page cache](/enterprise/data-page-cache) is a separate cache with its -own, on-demand prewarm -- `startup_prewarm_idx` does not touch it. +Cache Prewarm loads the [tiered index cache](/enterprise/tiered-index-cache) +a plan executor keeps as part of Enterprise's serving layer, instead of +leaving it to fill lazily on first read. You configure which tables to +prewarm; on startup, each plan executor loads those tables' indexes into +cache before it joins the fleet. The executor does not accept queries until +prewarming finishes, so it never serves a request against a cold cache. -## At plan executor startup {#startup} +LanceDB Embedded has no such cache, so there is nothing for it to warm +there. Embedded does have its own, separate `prewarm_index()` on a table -- +an idempotent hint that loads a built index into memory ahead of a query. -`startup_prewarm_idx` runs as part of a plan executor's own boot sequence, -before it joins the fleet, rather than on a schedule. A deployment configures -it with `startup_prewarm_enabled`, an index selection (which columns' indexes -to warm, up to 1024 entries), and a concurrency limit for how many it loads -at once. +
-Whether this delays the executor from serving queries is a separate setting, -`startup_prewarm_block_query_ready`, off by default in the binary itself but -**on by default in the Helm chart** -- most deployments block on it unless -the chart value is set otherwise: +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + List[("Configured list
of tables to prewarm")] + Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + List -.-> Warm + Warm --> Ready["Ready — joins the fleet,
starts serving queries"] + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class Warm,List accent +``` -- **Unset:** the executor becomes query-ready immediately and - prewarm runs concurrently in the background. Early queries may still miss - the cache; later ones benefit once prewarm catches up. -- **Set (the Helm chart's default):** query readiness waits for prewarm to - finish, up to `startup_prewarm_timeout_secs`. Blocking query readiness - this way requires `healthPort` to be set (9096 in the chart's default - values), so process health stays reachable while readiness is gated. +
-If prewarm fails or times out, `startup_prewarm_failure_policy` decides what -happens next: +
-| Policy | Behavior | -| --- | --- | -| `mark_ready_cold` (default) | The executor becomes query-ready anyway, just without a warm cache. | -| `stay_not_ready` | Combined with blocking query readiness, the executor never becomes ready -- a failed prewarm keeps it out of the fleet rather than serving cold. | +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + List[("Configured list
of tables to prewarm")] + Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + List -.-> Warm + Warm --> Ready["Ready — joins the fleet,
starts serving queries"] + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class Warm,List accent +``` + +
+ +## Why it matters {#why-it-matters} + +Without prewarming, a fresh or restarted executor would fill its indexes +lazily, so the first queries it serves pay the cost of loading and +deserializing them from object storage. Holding the executor out of the +fleet until its configured tables are warm means every query it ever +serves gets a warm cache, so performance stays consistent through restarts +and rollouts instead of dipping right after each one. + +[Contact us](https://www.lancedb.com/contact) to learn more about how +prewarming is configured for your deployment. ## What to read next {#next} - The raw-data-page cache -- warmed on demand, not by startup prewarm. + The raw-data-page cache -- a separate cache from the one prewarm fills. - The deserialized-index cache startup prewarm fills. + The deserialized-index cache prewarm fills. Where plan executors and query nodes sit in the serving fleet. diff --git a/docs/web/enterprise/data-page-cache.mdx b/docs/web/enterprise/data-page-cache.mdx index 55d40aef7..11eee89d2 100644 --- a/docs/web/enterprise/data-page-cache.mdx +++ b/docs/web/enterprise/data-page-cache.mdx @@ -56,36 +56,21 @@ flowchart LR -A table's local disk cache shares one budget with the +A table's local disk cache shares one configurable budget with the [tiered index cache](/enterprise/tiered-index-cache#disk-budget)'s disk -tier where both are enabled on the same executor -- raising one's share of -that budget lowers the other's. +tier where both are enabled on the same executor. -## Prewarming on demand {#prewarm} +## Why it matters {#why-it-matters} -[Cache Prewarm](/enterprise/cache-prewarm)'s `startup_prewarm_idx` only -warms the [tiered index cache](/enterprise/tiered-index-cache), not this -one. The data page cache has its own, separate on-demand prewarm, run by a -deployment operator rather than called from application code, optionally -scoped to specific columns: +Object storage is durable and cheap, but every round trip to it adds +latency and egress cost. For workloads that read the same ranges +repeatedly -- a hot subset of embeddings, a frequently-filtered column -- +the data page cache turns most of those reads into local memory or disk +hits instead, so performance stays predictable as traffic grows and you +pay object storage once per page, not once per read. - -```bash CLI icon="terminal" -lancedb admin cache prewarm data --table embedding_table --column embedding -``` - - -The command returns once the request is accepted, not once prewarming -finishes; it is idempotent and safe to run concurrently from multiple -clients. Prewarming has a large upfront cost, so it pays off for workloads -that repeatedly query the same columns -- large columns such as embeddings -or binary data may not be practical to prewarm this way. - - -The OSS SDK's `table.prewarm_data()` targets LanceDB Cloud, a different -product; calling it against an Enterprise deployment 404s. Use the admin -command above instead. - +[Contact us](https://www.lancedb.com/contact) to learn more about how +caching is sized and tuned for your workload. ## Cache interfaces {#interfaces} diff --git a/docs/web/enterprise/distributed-compaction.mdx b/docs/web/enterprise/distributed-compaction.mdx index 2219647d9..8d1fb4191 100644 --- a/docs/web/enterprise/distributed-compaction.mdx +++ b/docs/web/enterprise/distributed-compaction.mdx @@ -1,6 +1,6 @@ --- -title: "Distributed compaction" -sidebarTitle: "Distributed compaction" +title: "Distributed Compaction" +sidebarTitle: "Distributed Compaction" description: "How LanceDB Enterprise distributes compaction across a fleet of job workers." icon: "compress" availability: @@ -12,8 +12,8 @@ Distributed compaction splits a table's fragments into independent, fragment-disjoint tasks and fans them out across job workers in LanceDB Enterprise. Unlike an index build, a compaction plan needs no bin-packing: Lance's own planner already produces disjoint tasks, so workers claim and -execute them directly through the job registry, with no coordination -needed to decide who does what. See [Architecture](/index#architecture). +execute them directly, with no coordination needed to decide who does +what. See [Architecture](/index#architecture).
@@ -24,16 +24,16 @@ needed to decide who does what. See [Architecture](/index#architecture). "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR - L["Lance's planner
splits fragments into
disjoint tasks"] --> R[("Job registry")] - R --> W1["Worker
claims fragments 1-2"] - R --> W2["Worker
claims fragments 3-4"] - R --> W3["Worker
claims fragments 5-6"] + L["Lance's planner
splits fragments into
disjoint tasks"] + L --> W1["Worker
claims fragments 1-2"] + L --> W2["Worker
claims fragments 3-4"] + L --> W3["Worker
claims fragments 5-6"] W1 --> C["Fleet-wide eligibility gate:
one worker claims the commit"] W2 --> C W3 --> C classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 - class R,C accent + class C accent ```
@@ -47,16 +47,16 @@ flowchart LR "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR - L["Lance's planner
splits fragments into
disjoint tasks"] --> R[("Job registry")] - R --> W1["Worker
claims fragments 1-2"] - R --> W2["Worker
claims fragments 3-4"] - R --> W3["Worker
claims fragments 5-6"] + L["Lance's planner
splits fragments into
disjoint tasks"] + L --> W1["Worker
claims fragments 1-2"] + L --> W2["Worker
claims fragments 3-4"] + L --> W3["Worker
claims fragments 5-6"] W1 --> C["Fleet-wide eligibility gate:
one worker claims the commit"] W2 --> C W3 --> C classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 - class R,C accent + class C accent ``` diff --git a/docs/web/enterprise/distributed-indexing.mdx b/docs/web/enterprise/distributed-indexing.mdx index 10ba43055..afbfe30c3 100644 --- a/docs/web/enterprise/distributed-indexing.mdx +++ b/docs/web/enterprise/distributed-indexing.mdx @@ -1,19 +1,33 @@ --- -title: "Distributed indexing" -sidebarTitle: "Distributed indexing" -description: "How LanceDB Enterprise distributes an index build across a fleet of job workers." +title: "Distributed Indexing" +sidebarTitle: "Distributed Indexing" +description: "How LanceDB Enterprise distributes a vector index build across a fleet of workers, stage by stage." icon: "layer-group" availability: embedded: unavailable enterprise: available --- -Distributed indexing bin-packs a vector, full-text, or scalar index build into -a plan of claimable tasks, then fans the plan out across job workers in -LanceDB Enterprise. Workers claim tasks independently through the job -registry and commit the finished index together. A vector index build first -trains a shared IVF/PQ model from sampled data, then workers build storage -from that model in parallel. See [Architecture](/index#architecture). +A vector index build splits into stages, and the data in scope narrows at +each one: training works from a small sample, shuffling touches every row +once, and merging works entirely within one partition at a time. Full-text +and scalar index builds skip training and shuffling -- they bin-pack +directly into independent tasks workers claim and build in parallel, +closer to how [distributed compaction](/enterprise/distributed-compaction) +splits work. See [Architecture](/index#architecture). + +## Stages of a vector index build {#stages} + +1. **Train.** A sample of the table's vectors -- not the full dataset -- + trains the shared model every worker will use: IVF partition centroids, + and for IVF-PQ, a PQ codebook on top of them. +2. **Shuffle.** Every row in the table gets assigned to its nearest + trained partition and regrouped so that all of one partition's rows end + up together, wherever in the table they originally lived. +3. **Merge.** Each partition is now self-contained, so workers build and + merge partitions in parallel with no cross-partition coordination -- + one worker's output never depends on another's. +4. **Commit.** The finished index is committed to the table.
@@ -24,18 +38,17 @@ from that model in parallel. See [Architecture](/index#architecture). "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR - S["Sample data"] --> T["Train shared IVF/PQ model
(vector index only)"] - T --> P["Bin-pack build plan
into claimable tasks"] - P --> R[("Job registry")] - R --> W1["Worker
claims a task"] - R --> W2["Worker
claims a task"] - R --> W3["Worker
claims a task"] - W1 --> C["Commit the
finished index"] - W2 --> C - W3 --> C + S["Sample"] --> T["Train IVF centroids
+ PQ codebook"] + T --> Sh["Shuffle: assign every row
to its nearest partition"] + Sh --> M1["Merge
partition A"] + Sh --> M2["Merge
partition B"] + Sh --> M3["Merge
partition C"] + M1 --> C["Commit the
finished index"] + M2 --> C + M3 --> C classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 - class R accent + class Sh accent ```
@@ -49,18 +62,17 @@ flowchart LR "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR - S["Sample data"] --> T["Train shared IVF/PQ model
(vector index only)"] - T --> P["Bin-pack build plan
into claimable tasks"] - P --> R[("Job registry")] - R --> W1["Worker
claims a task"] - R --> W2["Worker
claims a task"] - R --> W3["Worker
claims a task"] - W1 --> C["Commit the
finished index"] - W2 --> C - W3 --> C + S["Sample"] --> T["Train IVF centroids
+ PQ codebook"] + T --> Sh["Shuffle: assign every row
to its nearest partition"] + Sh --> M1["Merge
partition A"] + Sh --> M2["Merge
partition B"] + Sh --> M3["Merge
partition C"] + M1 --> C["Commit the
finished index"] + M2 --> C + M3 --> C classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 - class R accent + class Sh accent ``` diff --git a/docs/web/enterprise/distributed-real-time-read.mdx b/docs/web/enterprise/distributed-real-time-read.mdx index c5175c5bd..1b6a582c4 100644 --- a/docs/web/enterprise/distributed-real-time-read.mdx +++ b/docs/web/enterprise/distributed-real-time-read.mdx @@ -1,5 +1,5 @@ --- -title: "Distributed Real Time Read" +title: "Distributed RTE Read" sidebarTitle: "Distributed RTE Read" description: "How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine." icon: "network-wired" @@ -8,13 +8,13 @@ availability: enterprise: available --- -[Real Time Read](/search/realtime-read) covers what a query against an +[RTE Read](/search/realtime-read) covers what a query against an RTE-enabled table returns: base-table rows merged with the fresh tier, fresh rows superseding base rows with the same primary key. On a single Embedded process that merge is one function call against one Lance dataset. In LanceDB Enterprise, the base table and the fresh tier are usually served by different machines -- plan executors for the base table, -a [WAL node](/tables/realtime-engine#wal-nodes) for the table's shards -- +an [RTE node](/tables/realtime-engine#wal-nodes) for the table's shards -- so a query has to combine their results across the network instead.
@@ -34,7 +34,7 @@ flowchart LR B1["Base-table arm
index-covered scan or ANN search"] end - subgraph WN["WAL node (owns this table's shards)"] + subgraph WN["RTE node (owns this table's shards)"] direction TB W1["SSTable arm
index-covered"] W2["Active memtable arm
vector: in-memory HNSW*
FTS/scalar: indexed"] @@ -73,7 +73,7 @@ flowchart LR B1["Base-table arm
index-covered scan or ANN search"] end - subgraph WN["WAL node (owns this table's shards)"] + subgraph WN["RTE node (owns this table's shards)"] direction TB W1["SSTable arm
index-covered"] W2["Active memtable arm
vector: in-memory HNSW*
FTS/scalar: indexed"] @@ -99,24 +99,76 @@ flowchart LR The distributed plan for an RTE-enabled table is an ordinary plan executor query plan with one additional node spliced in: a union exec that queries -the owning WAL node's shard and merges its rows into the base arm's stream +the owning RTE node's shard and merges its rows into the base arm's stream by primary key, keeping the newest generation on a collision and cutting back to the requested top-K once both sides have contributed. An optimizer -pass inserts this node only when the query actually touches a WAL-enabled +pass inserts this node only when the query actually touches an RTE-enabled table; a query that touches none produces a plan identical to one with no RTE tables involved at all, so RTE adds no overhead to queries that never use it. Because the base arm already read through the plan-executor fleet's ordinary caches and index structures, the only new network hop this adds is the one -to the WAL node that owns the table's shards -- the same WAL node [Real Time +to the RTE node that owns the table's shards -- the same RTE node [Real Time writes](/ingestion/realtime-write) land on, found by the query node through the same consistent hash of database and table name. -## Semantic search stays index-covered {#index-coverage} +## Search stays index-covered {#index-coverage} + +Every tier the union exec reads from -- the base table, the RTE node's +SSTables, and its currently-active memtable -- is covered by a maintained +index, for vector, full-text, and scalar search alike: + +| Layer | Vector search | Full-text / scalar search | +| --- | --- | --- | +| Base table | ANN index | Maintained index | +| SSTables | ANN index | Maintained index | +| Active memtable | In-memory HNSW graph\* | Maintained index | + +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", + "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", + "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + B["Base table"] --> I1["Vector, full-text, and
scalar index coverage"] + S["SSTables"] --> I1 + M["Active memtable"] --> I2["Full-text and scalar index
coverage; vector via
in-memory HNSW*"] + I1 --> R["No unindexed data
left to scan in full"] + I2 --> R + classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 + classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 + class R accent +``` + +
+ +
+ +```mermaid +%%{init: {"theme": "base", "themeVariables": { + "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", + "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", + "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" +}}}%% +flowchart LR + B["Base table"] --> I1["Vector, full-text, and
scalar index coverage"] + S["SSTables"] --> I1 + M["Active memtable"] --> I2["Full-text and scalar index
coverage; vector via
in-memory HNSW*"] + I1 --> R["No unindexed data
left to scan in full"] + I2 --> R + classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 + classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 + class R accent +``` + +
For full-text and scalar search, a maintained index covers every tier the -union exec reads from -- the base table, the WAL node's SSTables, and its +union exec reads from -- the base table, the RTE node's SSTables, and its currently-active memtable -- so a row written a moment ago is just as index-searchable as one written yesterday. If a resident memtable predates an index being added to the maintained set, the query is rejected outright @@ -147,13 +199,13 @@ table alone. ## What to read next {#next} - + What a query returns, and how Embedded does this same merge in-process. - - How writes reach the WAL node this page's queries read from. + + How writes reach the RTE node this page's queries read from. - + The ordinary plan-executor path this layers on top of. diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx index 1f54f0cdb..96188dae4 100644 --- a/docs/web/enterprise/distributed-real-time-write.mdx +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -1,30 +1,32 @@ --- -title: "Distributed Real Time Write" +title: "Distributed RTE Write" sidebarTitle: "Distributed RTE Write" -description: "How Enterprise scales real time writes horizontally across a dedicated WAL-node tier, and the throughput limits that come with it." +description: "How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it." icon: "bolt" -keywords: ["rte", "real time engine", "wal node", "shard", "sharding", "horizontal scaling", "write throughput", "memwal"] +keywords: ["rte", "real time engine", "shard", "sharding", "horizontal scaling", "write throughput"] availability: embedded: unavailable enterprise: available --- -[Real Time writes](/ingestion/realtime-write) describes `table.enable_rte(spec)` +[RTE writes](/ingestion/realtime-write) describes `table.enable_rte(spec)` as one call that works the same way on either connection. On Enterprise, that call does not run locally -- it posts to the server, which installs the write path on a dedicated, horizontally scalable serving tier instead of running it in your process. This page covers that tier: how it shards a table's writes, the one real limit sharding does not remove, and the throughput you can expect. -## The WAL-node tier {#wal-nodes} +## How writes are routed {#routing} -Enabling RTE on a remote table sends the spec to the server -(`POST /v1/table//enable_rte/`), which installs Lance's `__lance_mem_wal` -index on the dataset. From then on, every request for that table -- reads and -writes alike -- is consistent-hashed on the database and table name to a -single owning **WAL node**, a stateful pod separate from the query nodes and -plan executors that serve ordinary queries. WAL node pods share nothing but -the underlying object storage; no pod talks to another one directly. +Enabling RTE on a remote table sends the spec to the server, which installs +the write path on the dataset instead of running it in your process. From +then on, the query node routes every request for that table -- reads and +writes alike -- to a single owning **RTE node**, a stateful component +separate from the query nodes and plan executors that serve ordinary +queries. A query node routes different tables to different RTE nodes, and +a single RTE node can host shards from many different tables at once. RTE +nodes share nothing but the underlying object storage; no node talks to +another one directly.
@@ -36,22 +38,22 @@ the underlying object storage; no pod talks to another one directly. "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR - Q["Query node
hashes (db, table) to one WAL node"] + Q["Query node
routes each table's shards to an RTE node"] - subgraph W0["WAL node A — owns table 'frames'"] + subgraph W0["RTE node A"] direction TB - S0["Shard 0
ShardWriter"] - S1["Shard 1
ShardWriter"] - S2["Shard 2
ShardWriter"] + S0["Shard 0 — table 'frames'"] + S1["Shard 0 — table 'events'"] end - subgraph W1["WAL node B — owns table 'events'"] + subgraph W1["RTE node B"] direction TB - S3["Shard 0
ShardWriter"] + S2["Shard 0 — table 'metrics'"] end - Q -- "writes + reads for 'frames'" --> W0 - Q -- "writes + reads for 'events'" --> W1 + Q -- "'frames'" --> W0 + Q -- "'events'" --> W0 + Q -- "'metrics'" --> W1 classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 ``` @@ -67,22 +69,22 @@ flowchart LR "fontFamily": "Inter, sans-serif", "fontSize": "18px" }}}%% flowchart LR - Q["Query node
hashes (db, table) to one WAL node"] + Q["Query node
routes each table's shards to an RTE node"] - subgraph W0["WAL node A — owns table 'frames'"] + subgraph W0["RTE node A"] direction TB - S0["Shard 0
ShardWriter"] - S1["Shard 1
ShardWriter"] - S2["Shard 2
ShardWriter"] + S0["Shard 0 — table 'frames'"] + S1["Shard 0 — table 'events'"] end - subgraph W1["WAL node B — owns table 'events'"] + subgraph W1["RTE node B"] direction TB - S3["Shard 0
ShardWriter"] + S2["Shard 0 — table 'metrics'"] end - Q -- "writes + reads for 'frames'" --> W0 - Q -- "writes + reads for 'events'" --> W1 + Q -- "'frames'" --> W0 + Q -- "'events'" --> W0 + Q -- "'metrics'" --> W1 classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 ``` @@ -91,25 +93,16 @@ flowchart LR ## Shards scale one table, replicas scale the cluster {#shards-vs-replicas} `RTEWriteSpec::bucket(column, num_buckets)` splits a table into `num_buckets` -**table shards**, each a separate, independently-appending `ShardWriter`. A -shard's identity is derived from the table's own URI -(`uuid_v5(WAL_SHARD_NS, "{table_uri}#{i}")`), not assigned by an operator, so -a shard survives the table being claimed by a different pod later. +**table shards**, each a separate, independently-appending stream, giving the +table that many parallel write paths instead of one. A shard's identity is +derived from the table itself, not assigned by an operator, so a shard +survives the table being claimed by a different RTE node later. -This is where the horizontal scaling actually happens, and where its limit -is: **one WAL node owns every shard of a given table.** Splitting `frames` -into 8 shards gives it 8 independent append streams, all still served by the -one pod that owns `frames` -- it raises that table's own ceiling, not the -number of pods working on it. Adding WAL node replicas instead spreads -*other* tables' ownership across more pods, raising how many tables the -cluster can serve, not how fast any single one of them can write. - - -A single table's write throughput is capped by one pod's capacity, however -many shards you give it. A workload that needs to exceed one pod's ceiling on -one table is not solved by adding shards -- there is no path to spreading one -table's shards across multiple WAL nodes today. - +This is where the horizontal scaling actually happens: splitting `frames` +into 8 shards gives it 8 independent append streams instead of 1, raising +that table's own write ceiling. Adding RTE node replicas spreads shard +ownership across more nodes, so the cluster can host more tables -- and more +shards -- without any one node becoming a bottleneck for everything it serves. `RTEWriteSpec::identity(column)` and `RTEWriteSpec::unsharded()` both resolve to a single table shard -- `bucket` is the sharding mode that actually @@ -121,22 +114,22 @@ scaling. A table shard is the unit of capacity: measured runs show it sustaining roughly 85-90 MB/s of durable append before acknowledgement, and throughput scaling nearly linearly with shard count up to at least 8 shards on one -pod -- the bottleneck is the durable write itself, not CPU or memory. This +node -- the bottleneck is the durable write itself, not CPU or memory. This is observed capacity, not an enforced quota; nothing in the deployment caps a shard's or a table's throughput below it. [Contact -support](https://www.lancedb.com/contact) if your workload needs more than -one pod's worth of capacity for a single table. +support](https://www.lancedb.com/contact) if your workload needs more write +throughput than this provides. ## What to read next {#next} - + Enable RTE and write to a table; the same call on Embedded or Enterprise. MemWAL, shards, memtables and SSTables -- the shared architecture. - + How reads combine the WAL tier's fresh rows with the base table across the fleet. diff --git a/docs/web/enterprise/distributed-search.mdx b/docs/web/enterprise/distributed-search.mdx index d9ea2b3a3..617c24508 100644 --- a/docs/web/enterprise/distributed-search.mdx +++ b/docs/web/enterprise/distributed-search.mdx @@ -1,6 +1,6 @@ --- -title: "Distributed search" -sidebarTitle: "Distributed search" +title: "Distributed Search" +sidebarTitle: "Distributed Search" description: "How LanceDB Enterprise distributes index execution and table-data reads." icon: "network-wired" availability: diff --git a/docs/web/enterprise/distributed-write.mdx b/docs/web/enterprise/distributed-write.mdx index 46624d04b..73df91cf1 100644 --- a/docs/web/enterprise/distributed-write.mdx +++ b/docs/web/enterprise/distributed-write.mdx @@ -1,6 +1,6 @@ --- -title: "Distributed write" -sidebarTitle: "Distributed write" +title: "Distributed Write" +sidebarTitle: "Distributed Write" description: "How LanceDB Enterprise distributes a CTAS import's writes across plan executors." icon: upload availability: diff --git a/docs/web/enterprise/gpu-refresh-execution.mdx b/docs/web/enterprise/gpu-refresh-execution.mdx deleted file mode 100644 index 7fcacf4b5..000000000 --- a/docs/web/enterprise/gpu-refresh-execution.mdx +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: "GPU Refresh Execution" -tag: "Early access" -sidebarTitle: "GPU Refresh Execution" -description: "A computed column or materialized view filled by a GPU Function schedules its refresh workers the same way GPU Function execution does in Data Curation." -icon: microchip -keywords: ["gpu", "gpu class", "scheduling", "refresh", "computed column", "function"] -availability: - embedded: unavailable - enterprise: available ---- - -Early access - -A [computed column](/feature-engineering/add-computed-column) or -[materialized view](/feature-engineering/materialized-views) filled by a -registered [Function](/curation/create-function) with `gpu=True` refreshes -through the exact same placement path as -[GPU Function execution](/curation/gpu-function-execution) in Data -Curation -- refreshing a column is not a separate scheduling code path -from calling the Function directly, just a different caller. - -
- -```mermaid -%%{init: {"theme": "base", "themeVariables": { - "background": "#171513", "primaryColor": "#1e1b19", "primaryTextColor": "#f4ebe8", - "primaryBorderColor": "#4c443f", "lineColor": "#847770", "textColor": "#f4ebe8", - "edgeLabelBackground": "#171513", "fontFamily": "Inter, sans-serif", "fontSize": "18px" -}}}%% -flowchart LR - F["Function registered with
gpu=True, gpu_class"] --> A{"Who requests
a worker?"} - A -->|"You, directly"| D["Data Curation:
GPU Function execution"] - A -->|"A refresh job"| R["Feature Engineering:
computed column / MV refresh"] - D --> P["Same GPU-class placement,
same capacity-wait behavior"] - R --> P - classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 - classDef accent fill:#2a1810,stroke:#e8582d,stroke-width:1.5px,color:#f4ebe8 - class P accent -``` - -
- -
- -```mermaid -%%{init: {"theme": "base", "themeVariables": { - "background": "#ffffff", "primaryColor": "#ffffff", "primaryTextColor": "#221d19", - "primaryBorderColor": "#ad9e95", "lineColor": "#6b625c", "textColor": "#221d19", - "edgeLabelBackground": "#ffffff", "fontFamily": "Inter, sans-serif", "fontSize": "18px" -}}}%% -flowchart LR - F["Function registered with
gpu=True, gpu_class"] --> A{"Who requests
a worker?"} - A -->|"You, directly"| D["Data Curation:
GPU Function execution"] - A -->|"A refresh job"| R["Feature Engineering:
computed column / MV refresh"] - D --> P["Same GPU-class placement,
same capacity-wait behavior"] - R --> P - classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 - classDef accent fill:#fff1ec,stroke:#e8582d,stroke-width:1.5px,color:#221d19 - class P accent -``` - -
- -The Function's `gpu_class` (or the deployment's `default`) resolves to the -same node selector, tolerations and resource name either way, and a -refresh that needs more GPU capacity than is currently free waits the -same way a direct call would -- see -[Waiting for capacity](/curation/gpu-function-execution#capacity) for that -behavior in full. [Adaptive Execution](/enterprise/adaptive-execution)'s -resource-consumption-based sizing applies here too: a refresh's GPU -utilization is measured and fed back into sizing the *next* part the same -way CPU and memory are. - -A single refresh can also override the Function's registered placement for -that run -- see -[Configure workers and resources](/feature-engineering/refresh-column#resources) -for the `gpu_class`/`gpu_count` options on `refresh_column_async` and the -equivalent SQL `WITH (...)` clause. - -## What to read next {#next} - - - - The full placement and capacity-wait mechanism this page reuses. - - - How a refresh's resource class, part size and worker count adjust themselves. - - - Override GPU class and count for one refresh call. - - diff --git a/docs/web/enterprise/horizontal-scaling.mdx b/docs/web/enterprise/horizontal-scaling.mdx index 7ecb4c5a0..8b8f5c6fa 100644 --- a/docs/web/enterprise/horizontal-scaling.mdx +++ b/docs/web/enterprise/horizontal-scaling.mdx @@ -211,7 +211,7 @@ placement. ## Scaling interfaces {#scaling-interfaces} -- [Distributed search](/enterprise/distributed-search) for how a query +- [Distributed Search](/enterprise/distributed-search) for how a query divides across query nodes and plan executors generally. - [Architecture](/index#architecture) for the components a replica group is made of. diff --git a/docs/web/enterprise/intelligent-auto-maintenance.mdx b/docs/web/enterprise/intelligent-auto-maintenance.mdx index 4b52cc267..38cbdd2a5 100644 --- a/docs/web/enterprise/intelligent-auto-maintenance.mdx +++ b/docs/web/enterprise/intelligent-auto-maintenance.mdx @@ -11,7 +11,7 @@ availability: Keeping a table in good condition takes several different kinds of work -- compacting files, catching indexes up, cleaning old versions, folding a -real-time write tier into the base table -- each with its own trigger. In +RTE write tier into the base table -- each with its own trigger. In LanceDB Enterprise, a fleet of agent processes decides when each of these needs to run, continuously, per table, in the background across your cluster -- nothing to schedule, trigger, or monitor by hand unless you want @@ -92,7 +92,7 @@ whichever ones are due: 1. **WAL index catch-up.** Checked first and gated by nothing else, because it is correctness-driven rather than discretionary: while an index lags - behind the compacted generation, the real-time write tier cannot trim its + behind the compacted generation, the RTE write tier cannot trim its log. See [RTE Compaction](/enterprise/realtime-engine-compaction). 2. **Index operations.** Reindexing a column, unless a compaction that cannot defer its remap is about to run this same tick -- deferred-remap @@ -100,7 +100,7 @@ whichever ones are due: [Incremental Indexing](/indexing/incremental-indexing). 3. **Compaction.** Whether enough small fragments or deleted rows have accumulated to merge. See [Compaction](/maintenance/compaction) and - [Distributed compaction](/enterprise/distributed-compaction). + [Distributed Compaction](/enterprise/distributed-compaction). 4. **Cleanup.** Independent of the other four -- it can always run in parallel with them. [See below](#cleanup) for exactly when it's due. 5. **Deferred-remap catch-up.** The batched, amortized follow-up for index diff --git a/docs/web/enterprise/realtime-engine-compaction.mdx b/docs/web/enterprise/realtime-engine-compaction.mdx index 5451111ad..e04429ab8 100644 --- a/docs/web/enterprise/realtime-engine-compaction.mdx +++ b/docs/web/enterprise/realtime-engine-compaction.mdx @@ -8,7 +8,7 @@ availability: enterprise: available --- -[Distributed compaction](/enterprise/distributed-compaction) merges small +[Distributed Compaction](/enterprise/distributed-compaction) merges small base-table fragments and reclaims deleted rows -- the same operation [Compaction](/maintenance/compaction) describes for LanceDB Embedded. A table with the [real time engine](/tables/realtime-engine) enabled has a @@ -191,7 +191,7 @@ Either way, the bound also assumes a free compaction slot when the shard becomes eligible; an eligible shard can wait in queue behind `WAL_COMPACT_CONCURRENCY` other passes already running, so the actual delay can run longer than the trigger alone suggests. See -[Real Time reads](/search/realtime-read) +[RTE reads](/search/realtime-read) for what a live RTE read sees instead. ## What to read next {#next} @@ -200,7 +200,7 @@ for what a live RTE read sees instead. The MemWAL format, shards, and WAL nodes this page assumes. - + The unrelated, ordinary compaction every table -- WAL-enabled or not -- gets. diff --git a/docs/web/enterprise/slurm-refresh-scheduling.mdx b/docs/web/enterprise/slurm-refresh-scheduling.mdx deleted file mode 100644 index 48fb85985..000000000 --- a/docs/web/enterprise/slurm-refresh-scheduling.mdx +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: "Slurm Scheduling" -sidebarTitle: "Slurm Scheduling" -description: "A computed column or materialized view refresh launches worker pods through the same SUNK-backed scheduling configuration as any other job worker." -icon: "server" -keywords: ["slurm", "sunk", "scheduling", "refresh", "computed column"] -availability: - embedded: unavailable - enterprise: available ---- - -This page is about [Slurm scheduling](/curation/slurm-scheduling) as it -applies to a computed column or materialized view refresh specifically -- -the mechanism itself is covered in depth on that Data Curation page. A -refresh's top-level job -- the one that shows up in `SHOW JOBS` -- is an -agent-launched job worker like any other, and shares the full scheduling -configuration: node selector, tolerations, scheduler name and -termination grace period alike. - - -That job's own *child* workers -- the ones that actually plan, finalize -and run a Function during the refresh -- are different: they inherit the -scheduler name, but not the termination grace period, so they launch -with Kubernetes' 30-second default regardless of the shared -configuration. See [What SUNK changes](/curation/slurm-scheduling#what-changes) -for why that matters on most SUNK deployments, and confirm with your -deployment operator before running a Function-backed refresh there. - - -## What to read next {#next} - - - - The full scheduling configuration this page reuses. - - - GPU-specific placement for a refresh's Function workers. - - diff --git a/docs/web/enterprise/tiered-index-cache.mdx b/docs/web/enterprise/tiered-index-cache.mdx index f807f04ae..0e54a2575 100644 --- a/docs/web/enterprise/tiered-index-cache.mdx +++ b/docs/web/enterprise/tiered-index-cache.mdx @@ -67,21 +67,25 @@ flowchart LR Where enabled, the index disk tier and the [data page cache](/enterprise/data-page-cache)'s disk tier draw from one -combined disk allocation per executor: a configurable percentage of the -provisioned volume (90% by default, leaving headroom for filesystem -metadata and kubelet usage), out of which the index disk tier reserves its -own configurable share of the *full* provisioned volume. On a 200 GiB -volume, the 90% default leaves 180 GiB combined; reserving 25% of the full -200 GiB (50 GiB) for the index disk tier leaves the remaining 130 GiB for -data pages. An exact byte split overrides the percentage split when you -need one tier sized precisely rather than proportionally. Setting the -index disk tier's share to zero disables it while leaving the in-memory -index cache and the data page cache's disk tier untouched. +combined, configurable disk allocation per executor, split between the two +tiers so neither one needs its own dedicated volume. + +## Why it matters {#why-it-matters} + +Vector, full-text, and scalar indexes can easily outgrow available memory +on large tables. Without this cache, an eviction means re-reading and +re-deserializing that index from object storage on the next request -- +slow, and repeated on every eviction. Spilling to local disk instead keeps +index lookups fast even when the working set is larger than memory, without +giving every executor enough memory to hold every index at once. + +[Contact us](https://www.lancedb.com/contact) to learn more about how +caching is sized and tuned for your workload. ## Index cache interfaces {#interfaces} -- [Cache Prewarm](/enterprise/cache-prewarm) for how `startup_prewarm_idx` - warms this cache ahead of the first request. +- [Cache Prewarm](/enterprise/cache-prewarm) for warming this cache ahead + of the first request. - [Data Page Cache](/enterprise/data-page-cache) for the related cache that holds raw table data pages instead of deserialized index structures. - [Vector indexes](/indexing/vector-index), [full-text indexes](/indexing/fts-index), diff --git a/docs/web/indexing/gpu-indexing.mdx b/docs/web/indexing/gpu-indexing.mdx index 35169d93b..8370bfba1 100644 --- a/docs/web/indexing/gpu-indexing.mdx +++ b/docs/web/indexing/gpu-indexing.mdx @@ -82,7 +82,7 @@ you need to [install PyTorch with CUDA support](https://pytorch.org/get-started/ Keeping an index up-to-date as new data arrives. - - How a GPU-bound Function's worker gets scheduled -- the same GPU-placement story for Functions instead of index builds. + + Running these GPU workers alongside training on shared Slurm-scheduled infrastructure. diff --git a/docs/web/ingestion/define-storage-integration.mdx b/docs/web/ingestion/define-storage-integration.mdx index 8da9eda33..446d47d22 100644 --- a/docs/web/ingestion/define-storage-integration.mdx +++ b/docs/web/ingestion/define-storage-integration.mdx @@ -48,14 +48,6 @@ CREATE STORAGE INTEGRATION raw STORAGE_AWS_ACCESS_KEY_ID_SECRET = aws_key_id STORAGE_AWS_SECRET_ACCESS_KEY_SECRET = aws_key_secret ``` - - -{/* -Draft for the storage-integration SDK release (#4618). Keep this section -unpublished until create_storage_integration ships in a release; it is not -in v0.41.0. - - ```python Python icon="python" db.create_storage_integration( "raw", "s3://customer-data/raw/", @@ -70,7 +62,6 @@ db.create_storage_integration( aws_secret_access_key_secret="aws_key_secret", ) ``` - ```rust use lancedb::storage_integration::CreateStorageIntegrationRequest; @@ -84,7 +75,6 @@ let info = db.create_storage_integration( ).await?; ``` -*/} ### Google Cloud Storage {#gcp} @@ -95,14 +85,6 @@ CREATE STORAGE INTEGRATION gcs STORAGE_PREFIX = 'gs://customer-data/raw/' GCP_CREDENTIALS_JSON_SECRET = gcp_service_account ``` - - -{/* -Draft for the storage-integration SDK release (#4618). Keep this section -unpublished until create_storage_integration ships in a release; it is not -in v0.41.0. - - ```python Python icon="python" db.create_storage_integration( "gcs", "gs://customer-data/raw/", @@ -111,7 +93,6 @@ db.create_storage_integration( ) ``` -*/} The Secret holds the full service-account JSON key. GCP has no role-based alternative. @@ -128,14 +109,6 @@ CREATE STORAGE INTEGRATION blobs STORAGE_AZURE_CLIENT_ID_SECRET = azure_client STORAGE_AZURE_CLIENT_SECRET_SECRET = azure_credential ``` - - -{/* -Draft for the storage-integration SDK release (#4618). Keep this section -unpublished until create_storage_integration ships in a release; it is not -in v0.41.0. - - ```python Python icon="python" db.create_storage_integration( "blobs", "az://customer-data/raw/", @@ -147,7 +120,6 @@ db.create_storage_integration( ) ``` -*/} All four options are required together; there is no role-based alternative for Azure. @@ -161,14 +133,6 @@ CREATE STORAGE INTEGRATION hub STORAGE_PREFIX = 'hf://datasets/owner/private/data/' HUGGINGFACE_TOKEN_SECRET = hf_token ``` - - -{/* -Draft for the storage-integration SDK release (#4618, #4775). Keep this -section unpublished until create_storage_integration ships in a release; -it is not in v0.41.0. - - ```python Python icon="python" db.create_storage_integration( "hub", "hf://datasets/owner/private/data/", @@ -177,7 +141,6 @@ db.create_storage_integration( ) ``` -*/} `HUGGINGFACE_TOKEN_SECRET` is required to create this integration; omitting it is rejected, not treated as anonymous. For anonymous access at diff --git a/docs/web/ingestion/import.mdx b/docs/web/ingestion/import.mdx index 0dbe02139..0affeb4cf 100644 --- a/docs/web/ingestion/import.mdx +++ b/docs/web/ingestion/import.mdx @@ -45,7 +45,7 @@ Azure examples. ## How the import runs {#distributed} -See [Distributed write](/enterprise/distributed-write) for how an import's +See [Distributed Write](/enterprise/distributed-write) for how an import's writes divide across plan executors, and when a small import instead runs as one local task. @@ -65,7 +65,7 @@ omits the destination's unflushed data. Query and import HuggingFace or object-storage datasets in full. - + How an import's writes divide across plan executors. diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx index c2d389c33..ead2362f3 100644 --- a/docs/web/ingestion/realtime-write.mdx +++ b/docs/web/ingestion/realtime-write.mdx @@ -1,5 +1,5 @@ --- -title: "Real Time writes" +title: "RTE writes" sidebarTitle: "RTE Write" description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." icon: "bolt" @@ -12,7 +12,7 @@ availability: 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). +[RTE reads](/search/realtime-read). `table.enable_rte(spec)` is the same call on both connections, but what it does underneath differs: @@ -22,7 +22,7 @@ does underneath differs: there is no separate serving layer to scale or configure. - **Enterprise** forwards the call to the server, which runs it on a dedicated, horizontally scalable WAL-node tier instead of your table's - query-serving fleet. See [Distributed Real Time Write](/enterprise/distributed-real-time-write) + query-serving fleet. See [Distributed RTE Write](/enterprise/distributed-real-time-write) for how that tier shards a table's writes and the throughput limits that come with it. ## Getting started {#getting-started} @@ -162,7 +162,7 @@ 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 +immediately — see [RTE reads](/search/realtime-read) for querying them back: @@ -232,13 +232,13 @@ your own machine's resources. An Enterprise table can be split into shards that write independently, with each shard's durable-append throughput bounded by its WAL node's own capacity -- measured, not an enforced cap. See -[Distributed Real Time Write](/enterprise/distributed-real-time-write#throughput) +[Distributed RTE Write](/enterprise/distributed-real-time-write#throughput) for the numbers. ## Next steps {#next-steps} -- [Real Time reads](/search/realtime-read) — query an RTE table -- [Distributed Real Time Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this +- [RTE reads](/search/realtime-read) — query an RTE table +- [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this - [How the real time engine works](/tables/realtime-engine#memwal-format) - [Merge insert](/ingestion/merge-insert) - [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 11d0ed4ac..5bd9a3efe 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -10,13 +10,6 @@ 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, except -steps 5 and 6, which need Enterprise either way. - - ## 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. diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx index e586a1eac..19c5bc2ab 100644 --- a/docs/web/search/realtime-read.mdx +++ b/docs/web/search/realtime-read.mdx @@ -1,5 +1,5 @@ --- -title: "Real Time reads" +title: "RTE reads" sidebarTitle: "RTE 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" @@ -12,9 +12,9 @@ availability: 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; for enabling RTE and writing to -a table, see [Real Time writes](/ingestion/realtime-write). For how Enterprise +a table, see [RTE writes](/ingestion/realtime-write). For how Enterprise combines these results across machines, see -[Distributed Real Time Read](/enterprise/distributed-real-time-read). +[Distributed RTE Read](/enterprise/distributed-real-time-read). ## Query a real time table {#query} @@ -25,7 +25,7 @@ moment ago is already reflected: ```python Python icon="python" -# continuing the `frames` table connected and written to in Real Time writes +# continuing the `frames` table connected and written to in RTE writes import numpy as np query_vector = np.random.rand(frames.schema.field("embedding").type.list_size).astype("float32") @@ -57,7 +57,7 @@ maintained-index rules for vector, full-text, and scalar search, just with no network hop to a separate serving tier. There is no WAL node to route to and nothing to combine across machines: a query against an RTE-enabled Embedded table already reads the fresh tier together with the base table in one call. -See [Distributed Real Time Read](/enterprise/distributed-real-time-read) for +See [Distributed RTE Read](/enterprise/distributed-real-time-read) for what Enterprise adds on top when that fresh tier is served by a separate machine from the one answering the rest of the query. @@ -77,8 +77,8 @@ available. ## Next steps {#next-steps} -- [Real Time writes](/ingestion/realtime-write) — enable RTE and write to a table -- [Distributed Real Time Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise +- [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table +- [Distributed RTE Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise - [How the real time engine works](/tables/realtime-engine#memwal-format) - [Hybrid search](/search/hybrid-search) - [Vector search](/search/vector-search) diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index f058cc836..5c6983cc5 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -25,7 +25,7 @@ table, and nothing about how you query that table changes. RTE is built on **MemWAL**, a log-structured-merge (LSM) format that Lance itself defines -- the structure Enterprise serves is part of the open Lance format, not a layer bolted on beside it. A table with RTE enabled is divided -into one or more **shards** (see [Real Time writes](/ingestion/realtime-write#primary-key) +into one or more **shards** (see [RTE writes](/ingestion/realtime-write#primary-key) for enabling and sizing them), and each shard holds: - A **memtable**: the active, in-memory table for that shard's newest rows, @@ -49,8 +49,8 @@ later folds SSTables into the base table, catching its indexes up as it goes. This section describes LanceDB Enterprise's serving layer. LanceDB Embedded runs the same MemWAL mechanics directly against the local dataset, in one process -- there is no separate node to route to or scale; see -[Real Time writes](/ingestion/realtime-write#getting-started) and -[Real Time reads](/search/realtime-read#embedded) for what that looks like. +[RTE writes](/ingestion/realtime-write#getting-started) and +[RTE reads](/search/realtime-read#embedded) for what that looks like. RTE's Enterprise serving layer is a dedicated component, separate from the [query nodes and plan executors](/enterprise/distributed-search) @@ -81,13 +81,13 @@ pods are never both appending to the same shard's WAL at once. Every query runs against the base table and the fresh tier -- every shard's memtable and not-yet-compacted SSTables -- in parallel. Fresh rows supersede base rows with the same primary key, and the two are merged into one result. -See [Real Time reads](/search/realtime-read) for what this means for query +See [RTE reads](/search/realtime-read) for what this means for query results. ## Next steps {#next-steps} -- [Real Time writes](/ingestion/realtime-write) — enable RTE and write to a table -- [Real Time reads](/search/realtime-read) — query an RTE table -- [Distributed Real Time Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales writes -- [Distributed Real Time Read](/enterprise/distributed-real-time-read) — how Enterprise combines reads across machines +- [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table +- [RTE reads](/search/realtime-read) — query an RTE table +- [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales writes +- [Distributed RTE Read](/enterprise/distributed-real-time-read) — how Enterprise combines reads across machines - [RTE Compaction](/enterprise/realtime-engine-compaction) — how Enterprise folds shards into the base table From fa4b14a9d62f2456133ae8b624c9dc30e14d456a Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 5 Nov 2026 18:35:14 +0800 Subject: [PATCH 015/203] docs(functions): clarify filtered refresh and error policies (#4868) The refresh guide and SQL reference do not warn that a `WHERE` refresh recomputes filled rows, and the guide describes resources as per-worker allocations. Clarify the aggregate Function budget and expression-only `num_workers`, show the output-null predicate with its stale-value and successful-null limitations in both references, and document refresh-level `error_policy='skip'`. Link both guides to the current SQL options route. Validation: Vale 3.24.0 found no issues on changed lines; `git diff --check` and the new link targets passed. Mint 4.2.888 reports the same four existing `RsExampleBody`/`RsExampleTail` import warnings in `reranking/index.mdx` and `search/vector-search.mdx` on both pristine base `5e38120b` and this branch. No additional warnings. Behavior was checked against the owning Sophon implementation; no runtime code changed or runtime tests were run. Companion to https://github.com/lancedb/sophon/pull/9806 for ENT-3279. Page visibility and saved documentation editions are unchanged. DOC-90 retains publication and matching-shipped-release verification. --- .../feature-engineering/refresh-column.mdx | 38 ++++++++++++--- docs/web/management/function.mdx | 25 +++++++--- docs/web/sql/dml/refresh-column.mdx | 47 +++++++++++++------ 3 files changed, 82 insertions(+), 28 deletions(-) diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index fa4abae6f..ea8b49b9b 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -51,9 +51,10 @@ The SQL form is [`REFRESH COLUMN`](/sql/dml/refresh-column), with the same resou ## What a refresh recomputes {#idempotent} -A refresh fills rows that have no value and recomputes rows whose inputs -changed since they were computed. Every other row is left alone, so a second -refresh with nothing changed does nothing. This supports two common workflows. +Without a `WHERE` predicate, a refresh fills unassigned rows and recomputes +values whose inputs changed since they were computed. Every other row is left +alone, so a second refresh with nothing changed does nothing. This supports +two common workflows. **Appending is cheap.** Rows added since the last refresh are filled by the next one; filled rows whose inputs are unchanged are skipped. Backfilling a @@ -86,6 +87,21 @@ REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' ``` +A filtered refresh recomputes **every matching live row**, including rows +whose outputs are already current. Repeating the same predicate repeats those +Function calls and their cost. To select only null outputs within a slice: + + +```sql SQL icon="database" +REFRESH COLUMN embedding ON documents + WHERE created_at > '2026-01-01' AND embedding IS NULL +``` + + +This skips non-null outputs even when their inputs changed, and can recompute +outputs that were successfully computed as `NULL`. Use an unfiltered refresh +to let LanceDB track which outputs need updating. + **Enterprise job type:** `computed_refresh` for a SQL-expression column, `function_refresh` for one filled by a registered [function](/management/function). @@ -130,10 +146,18 @@ REFRESH COLUMN embedding ON documents ``` -`num_workers` sets the count instead of a per-worker budget; the two are -alternatives rather than a pair. `batch_size` controls how many rows a worker -takes at a time, and `error_policy = 'skip'` continues past rows that fail -rather than failing the job. +The resource values cap the Function workers together: this example allows +up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not +per-worker allocations or a guaranteed worker count. `num_workers` is only +accepted for SQL-expression columns; registered Function columns reject it. +When setting CPU or memory, supply all three budget fields, using +`gpu_count = 0` for a CPU-only Function. + +`batch_size` caps rows in one Function call; LanceDB adapts actual call and +work sizes. For Function columns, the refresh defaults to +`error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for +failing rows and record them in the error store, subject to failure limits. +See the [SQL refresh options](/sql/dml/refresh-column#options). For a column filled by a registered Function, the Python and Rust job APIs can override the Function's GPU placement for this refresh: diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index b9abbe743..63a3f6446 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -401,15 +401,28 @@ full worked example. ## Failure handling {#failures} -A function that raises fails the job. There is no per-row retry or skip policy -in the function definition: `@function` takes no error-handling parameter, so a -function that calls a flaky external service should handle that itself, inside -the function body. +By default, a Function that raises fails the refresh job. The Function +definition has no error-handling parameter; choose the row-error policy on +the refresh instead: + + +```sql SQL icon="database" +REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip') +``` + + +`skip` writes null outputs for failing rows and records their errors. Inspect +them with `SHOW ERRORS` or `table.function_errors()`. Failure limits still +apply, and initialization or infrastructure failures can still fail the job. +See the [SQL refresh options](/sql/dml/refresh-column#options). A Function +that calls a transiently failing external service can handle bounded retries +inside its body. Letting the job fail is the other option: fix the cause and refresh again. The -next refresh [skips rows that are filled and current](/feature-engineering/refresh-column#idempotent), +next unfiltered refresh [skips rows that are filled and current](/feature-engineering/refresh-column#idempotent), but how much of the failed job's work was kept is not guaranteed, so do not -count on the retry costing only the rows that did not complete. +count on the retry costing only the rows that did not complete. A refresh with +`WHERE` recomputes every matching live row, including already-filled outputs. ## What gets packaged {#packaging} diff --git a/docs/web/sql/dml/refresh-column.mdx b/docs/web/sql/dml/refresh-column.mdx index c00298214..98a360366 100644 --- a/docs/web/sql/dml/refresh-column.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -1,7 +1,7 @@ --- title: "REFRESH COLUMN" sidebarTitle: "REFRESH COLUMN" -description: "Filling a computed column: idempotent, scoped, and resumable." +description: "Fill computed outputs and select rows to recompute." icon: arrows-rotate keywords: ["refresh column", "backfill", "computed column"] availability: @@ -28,27 +28,38 @@ REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' ``` -A refresh gives values to rows that lack them, recomputes rows whose inputs -changed, and **leaves other filled rows alone**. That makes it idempotent, cheap -to repeat as data arrives, and safe to re-run after a failure, though a re-run -can recompute values the failed run had already written. +Without `WHERE`, a refresh fills unassigned rows and recomputes values whose +inputs changed, leaving other current values alone. A retry after a failure +can still repeat work that was not committed. -`WHERE` scopes the refresh, which is how you fill a slice and check it before -committing to the whole table. +With `WHERE`, a refresh **recomputes every matching live row**, including rows +that already have current values. Repeating a predicate can repeat the Function +calls and their cost. To select only null outputs within a slice: + + +```sql SQL icon="database" +REFRESH COLUMN embedding ON documents + WHERE created_at > '2026-01-01' AND embedding IS NULL +``` + + +This skips non-null outputs even if their inputs changed. It also selects +outputs that were successfully computed as `NULL`. Use an unfiltered refresh +to let LanceDB track which outputs need updating. ## Options {#options} | Option | Meaning | | --- | --- | -| `num_workers` | how many workers to use | -| `cpu_millis` | aggregate CPU ceiling across the refresh's workers, not a per-worker size | -| `memory_bytes` | aggregate memory ceiling across the refresh's workers | +| `num_workers` | fixed worker count for SQL-expression columns; rejected for registered Function columns | +| `cpu_millis` | aggregate CPU ceiling across the refresh's Function workers, in thousandths of a CPU | +| `memory_bytes` | aggregate memory ceiling across the refresh's Function workers, in bytes | | `gpu_count` | aggregate GPU budget across the refresh's workers. Function columns only | | `gpu_class` | GPU class name for the refresh's workers. Function columns only | -| `batch_size` | rows passed to each Function call. Function columns only | +| `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only | | `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only | | `row_timeout_seconds` | deadline for one Function call. Function columns only | -| `error_policy` | `'skip'` continues past failing rows instead of failing the job. Function columns only | +| `error_policy` | `'fail'` (default) stops on a row error; `'skip'` writes null outputs and records row errors, subject to failure limits. Function columns only | | `max_failed_fraction` | fail the job once more than this share of rows has failed. Function columns only | | `max_failed_rows` | fail the job once more than this many rows has failed. Function columns only | @@ -59,9 +70,15 @@ REFRESH COLUMN embedding ON documents ``` -`num_workers` sets a count; the budget options size the refresh's workers in -aggregate, not each one individually. They are alternatives rather than a -pair. +The example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the +Function workers together. It does not reserve those resources per worker or +guarantee a worker count. When setting CPU or memory, provide all three budget +fields. A complete CPU-only budget uses `gpu_count = 0`. + +Set `error_policy` on the refresh, not on the Function definition. With `skip`, +inspect failures with `SHOW ERRORS` or `table.function_errors()` and retry the +affected rows after fixing the cause. Initialization, infrastructure, and +publication failures can still fail the job. `num_workers` is refused for a column filled by a registered From e2a859f6a3f6b4db5f5cf4e4666b8a1fb6524e30 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 18:52:40 +0800 Subject: [PATCH 016/203] test: allow hidden pages in SDK documentation links (#4869) The SDK documentation-link test fails on `DocLink::BranchDiff` after the branching page is hidden from navigation. [Mintlify serves hidden MDX pages by their URL](https://www.mintlify.com/docs/guides/hidden-pages), so navigation membership is not a route-validity requirement. Remove that assertion while retaining the file, `.mintignore`, redirect-target, and anchor checks. Validated on the development EC2 with `cargo test --profile ci --features remote --locked --lib docs::tests::test_all_doc_links_resolve_in_repo_docs -- --exact --nocapture`: the unchanged base fails on `tables/branching`; this fix passes. The identical patch also passes against the exact #4867 head, checking all 14 `DocLink::ALL` entries. Formatting passes. This repairs the shared docs-test blocker for #4867; its separate `cargo deny` dependency finding is unchanged. --- rust/lancedb/src/docs.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/rust/lancedb/src/docs.rs b/rust/lancedb/src/docs.rs index ccfd1c28c..a52b1a000 100644 --- a/rust/lancedb/src/docs.rs +++ b/rust/lancedb/src/docs.rs @@ -519,6 +519,8 @@ mod tests { "DocLink::{link:?} points to a .mintignore'd page: {rel_page}" ); + // Mintlify serves MDX pages even when they are intentionally omitted + // from navigation, so docs.json membership is not required. let mdx_path = if docs_web.join(&direct_mdx).is_file() { docs_web.join(&direct_mdx) } else if docs_web.join(&index_mdx).is_file() { @@ -527,12 +529,6 @@ mod tests { panic!("DocLink::{link:?} target page does not exist under docs/web: {rel_page}"); }; - assert!( - docs_json.contains(&format!("\"{rel_page}\"")) - || docs_json.contains(&format!("\"{rel_page}/index\"")), - "DocLink::{link:?} target page is not routed in docs/web/docs.json: {rel_page}" - ); - if let Some(anchor) = link.anchor() { let raw_mdx = std::fs::read_to_string(&mdx_path) .unwrap_or_else(|e| panic!("failed to read {}: {e}", mdx_path.display())); From 3dc779d0ee4db432217d4c8e70a4ef37c57fd498 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 5 Nov 2026 03:01:51 -0800 Subject: [PATCH 017/203] fix: nav, redirect and badge cleanup across several pages (#4870) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Removes the stale `/enterprise` redirect that hijacked the real LanceDB Enterprise page, sending it to the Embedded vs Enterprise comparison page instead. - Removes the Merge page from the Data Ingestion nav (confusing parity story between Embedded and Enterprise); moves RTE Write up to right below Delete and renames it **RTE Write (Upsert)** to take over that slot. - Removes the Early access badge from Tiered Index Cache and restores its full sidebar title (was shortened to "Index Cache" to fit the badge). - Moves Changes below Dedupe in Data Curation. - Matches Advanced Conflict Resolution's sidebar title to its page title (previously just "Conflict Resolution" in the sidebar). - Marks Job Framework as Enterprise-only. - Distributed RTE Write diagram now shows the `metrics` table split across multiple shards, illustrating the per-table sharding described in the page's own text. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_018PXMCbRH6i5w47TsjeEUMT --------- Co-authored-by: Claude Sonnet 5 --- docs/web/basics/embedded-vs-enterprise.mdx | 3 +-- docs/web/basics/jobs.mdx | 2 +- docs/web/docs.json | 9 ++------- docs/web/enterprise/advanced-conflict-resolution.mdx | 2 +- docs/web/enterprise/distributed-real-time-write.mdx | 4 +++- docs/web/enterprise/tiered-index-cache.mdx | 5 +---- docs/web/ingestion/realtime-write.mdx | 4 ++-- rust/lancedb/src/docs.rs | 2 +- 8 files changed, 12 insertions(+), 19 deletions(-) diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index 0dae6d6e3..a4e00040b 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -31,8 +31,7 @@ file format, so moving data from one edition to the other does not require a dat | Area | Feature | Embedded | Enterprise | | --- | --- | :-: | :-: | | **Data Ingestion** | [Insert data](/ingestion/insert) | ✅ | ✅ | -| | [Merge](/ingestion/merge-insert) | ✅ | ✅ | -| | [RTE Write](/ingestion/realtime-write) | ✅ | ✅ | +| | [RTE Write (Upsert)](/ingestion/realtime-write) | ✅ | ✅ | | | [Distributed RTE Write](/enterprise/distributed-real-time-write) | ❌ | ✅ | | | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ | | | [Import Datasets](/ingestion/import) | ❌ | ✅ | diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index c10e24978..5336d1dfd 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -5,7 +5,7 @@ description: "Track background work from submission to completion." icon: hourglass-half keywords: ["job", "background", "progress", "events", "cancel"] availability: - embedded: available + embedded: unavailable enterprise: available --- diff --git a/docs/web/docs.json b/docs/web/docs.json index 33a3bbf46..c20341793 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -39,10 +39,6 @@ "source": "/deployment/monitoring", "destination": "/deployment/opentelemetry" }, - { - "source": "/enterprise", - "destination": "/basics/embedded-vs-enterprise" - }, { "source": "/enterprise/intelligent-scheduling", "destination": "/enterprise/intelligent-auto-maintenance" @@ -414,14 +410,13 @@ "ingestion/index", "ingestion/create-table", "ingestion/insert", - "ingestion/merge-insert", "ingestion/update", "ingestion/delete", + "ingestion/realtime-write", "ingestion/define-storage-integration", "ingestion/migrate-from-embedded", "ingestion/import", "enterprise/distributed-write", - "ingestion/realtime-write", "enterprise/distributed-real-time-write" ] }, @@ -449,7 +444,6 @@ "curation/inspect-datasets", "curation/create-function", "curation/chunking", - "curation/changes", "curation/statistical-sampling", "curation/selective-sampling", "curation/aggregate", @@ -459,6 +453,7 @@ "curation/windowing", "curation/clustering", "curation/dedupe", + "curation/changes", "feature-engineering/view", "curation/vend-secret" ] diff --git a/docs/web/enterprise/advanced-conflict-resolution.mdx b/docs/web/enterprise/advanced-conflict-resolution.mdx index aafbabc37..3826de8a5 100644 --- a/docs/web/enterprise/advanced-conflict-resolution.mdx +++ b/docs/web/enterprise/advanced-conflict-resolution.mdx @@ -1,6 +1,6 @@ --- title: "Advanced Conflict Resolution" -sidebarTitle: "Conflict Resolution" +sidebarTitle: "Advanced Conflict Resolution" description: "How compaction and indexing stay safe to run concurrently, using Lance's fragment reuse index." icon: shuffle keywords: ["fragment reuse index", "FRI", "compaction", "indexing", "remap", "conflict resolution"] diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx index 96188dae4..ac91e2d0d 100644 --- a/docs/web/enterprise/distributed-real-time-write.mdx +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -49,6 +49,7 @@ flowchart LR subgraph W1["RTE node B"] direction TB S2["Shard 0 — table 'metrics'"] + S3["Shard 1 — table 'metrics'"] end Q -- "'frames'" --> W0 @@ -80,6 +81,7 @@ flowchart LR subgraph W1["RTE node B"] direction TB S2["Shard 0 — table 'metrics'"] + S3["Shard 1 — table 'metrics'"] end Q -- "'frames'" --> W0 @@ -123,7 +125,7 @@ throughput than this provides. ## What to read next {#next} - + Enable RTE and write to a table; the same call on Embedded or Enterprise. diff --git a/docs/web/enterprise/tiered-index-cache.mdx b/docs/web/enterprise/tiered-index-cache.mdx index 0e54a2575..692477498 100644 --- a/docs/web/enterprise/tiered-index-cache.mdx +++ b/docs/web/enterprise/tiered-index-cache.mdx @@ -1,7 +1,6 @@ --- title: "Tiered Index Cache" -tag: "Early access" -sidebarTitle: "Index Cache" +sidebarTitle: "Tiered Index Cache" description: "How LanceDB Enterprise caches deserialized index structures across memory and local disk." icon: "layer-group" availability: @@ -9,8 +8,6 @@ availability: enterprise: available --- -Early access - The tiered index cache holds deserialized vector, full-text and scalar index structures in memory, backed by a local-disk tier beneath it. When memory fills, the cache serializes evicted entries and spills them to disk diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx index ead2362f3..5b61e67bc 100644 --- a/docs/web/ingestion/realtime-write.mdx +++ b/docs/web/ingestion/realtime-write.mdx @@ -1,6 +1,6 @@ --- -title: "RTE writes" -sidebarTitle: "RTE Write" +title: "RTE Write (Upsert)" +sidebarTitle: "RTE Write (Upsert)" 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"] diff --git a/rust/lancedb/src/docs.rs b/rust/lancedb/src/docs.rs index a52b1a000..d69a1612c 100644 --- a/rust/lancedb/src/docs.rs +++ b/rust/lancedb/src/docs.rs @@ -169,7 +169,7 @@ impl DocLink { | Self::Views | Self::MaterializedViews | Self::PrewarmData - | Self::Authorization => "/enterprise", + | Self::Authorization => "/basics/embedded-vs-enterprise", } } From 3c4aaa8e628d93593cd74b49e4a6bdb119084dce Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 19:11:41 +0800 Subject: [PATCH 018/203] fix: preserve typed catalog errors through Flight and Python (#4867) Catalog lookup failures lose their structured resource identity at the Rust/Python SDK boundaries, leaving callers with generic errors or empty correlation fields. Decode the existing Flight SQL error metadata and preserve resource kind/name, namespace, error code, and request/job IDs in the existing error types. Direct `get_function` calls unwrap named Function or namespace failures. Generic SQL job failures remain `JobFailedError` with the typed resource error as their cause; native deferred commands correctly leave durable job IDs null. Existing unstructured SQL classifications, including `FailedPrecondition`, remain supported. Validation: focused Rust/Python regressions and a native-extension run against a real Sophon process passed all five Function/Secret resource-error cases. The final one-commit candidate passes `cargo check -p lancedb-python` and formatting; earlier runtime evidence applies after removal of an unused tuple member. Independent deployed acceptance remains pending for ENT-3373. Server companion: https://github.com/lancedb/sophon/pull/9804. Integration validation: all 14 DocLinks pass on the merge candidate with #4869. The subsequent main documentation routing change was inspected; it does not alter the typed-error paths. The inherited pin-utils cargo-deny finding is tracked in a separate dependency repair. --- python/src/error.rs | 223 ++++++++++++++++++++++++++++ rust/lancedb/src/error.rs | 58 ++++++++ rust/lancedb/src/remote/db.rs | 86 ++++++++++- rust/lancedb/src/remote/sql.rs | 3 + rust/lancedb/src/remote/sql_test.rs | 28 ++++ 5 files changed, 397 insertions(+), 1 deletion(-) diff --git a/python/src/error.rs b/python/src/error.rs index a86051e5d..3fd27f7be 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -310,6 +310,9 @@ fn new_py_sql_error<'py>( grpc_code: i32, metadata: &RemoteErrorMetadata, ) -> PyResult> { + if sql_has_resource_error(metadata, grpc_code) { + return new_py_sql_resource_error(py, message, request_id, grpc_code, metadata); + } py.import("lancedb.remote.errors")? .getattr("SqlError")? .call1(( @@ -322,6 +325,51 @@ fn new_py_sql_error<'py>( )) } +fn new_py_sql_resource_error<'py>( + py: Python<'py>, + message: &str, + request_id: &str, + grpc_code: i32, + metadata: &RemoteErrorMetadata, +) -> PyResult> { + let resource = metadata.resource.as_ref().unwrap(); + py.import("lancedb.remote.errors")? + .getattr("HttpError")? + .call1(( + message, + request_id, + grpc_code_to_http_status(grpc_code), + metadata.error_code.as_deref(), + resource.kind.as_str(), + resource.name.as_str(), + resource.namespace_path.clone(), + false, + metadata.job_id.as_deref(), + metadata.job_request_id.as_deref(), + )) +} + +fn sql_has_resource_error(metadata: &RemoteErrorMetadata, grpc_code: i32) -> bool { + metadata.resource.is_some() + && matches!( + (metadata.error_code.as_deref(), grpc_code), + // These are gRPC status codes, not HTTP status codes. + (Some("not_found"), 5) | (Some("already_exists"), 6) + ) +} + +fn grpc_code_to_http_status(grpc_code: i32) -> Option { + match grpc_code { + 3 => Some(400), + 5 => Some(404), + 6 => Some(409), + 7 => Some(403), + 9 => Some(400), + 12 => Some(501), + _ => None, + } +} + // Preserve the typed transport classification across the Python boundary. // A missing status code alone also covers malformed job responses, which // waiting longer cannot repair. @@ -335,3 +383,178 @@ fn is_transport_error(err: &(dyn std::error::Error + 'static)) -> bool { } err.source().is_some_and(is_transport_error) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use lancedb::error::{JobFailure, RemoteResourceIdentity}; + use pyo3::types::PyAnyMethods; + + use super::*; + + #[test] + fn generic_job_failure_retains_the_named_resource_as_its_cause() { + Python::initialize(); + let source = LanceError::Sql { + message: "Function 'missing' was not found".into(), + request_id: "current-request".into(), + grpc_code: 5, + metadata: Box::new({ + let mut metadata = RemoteErrorMetadata::default(); + metadata.error_code = Some("not_found".into()); + metadata.job_id = Some("outer-job".into()); + metadata.job_request_id = Some("worker-request".into()); + metadata.resource = Some(RemoteResourceIdentity::new( + "function", + "missing", + vec!["ns".into()], + )); + metadata + }), + }; + let error = LanceError::JobFailed { + job_id: Some("outer-job".into()), + failure: Box::new(JobFailure { + message: Some("Function 'missing' was not found".into()), + traceback: None, + sql_job_id: Some("outer-job".into()), + source: Some(Arc::new(source)), + ..Default::default() + }), + }; + + let py_err = Python::attach(|_| { + let result: std::result::Result<(), LanceError> = Err(error); + result.infer_error().unwrap_err() + }); + Python::attach(|py| { + let value = py_err.value(py); + let job_failed = py + .import("lancedb.exceptions") + .unwrap() + .getattr("JobFailedError") + .unwrap(); + assert!(value.is_instance(&job_failed).unwrap(), "{py_err:?}"); + let cause = value.getattr("__cause__").unwrap(); + let function_not_found = py + .import("lancedb.remote.errors") + .unwrap() + .getattr("FunctionNotFoundError") + .unwrap(); + assert!( + cause.is_instance(&function_not_found).unwrap(), + "{py_err:?}" + ); + assert_eq!( + cause + .getattr("error_code") + .unwrap() + .extract::() + .unwrap(), + "not_found" + ); + assert_eq!( + cause + .getattr("resource_kind") + .unwrap() + .extract::() + .unwrap(), + "function" + ); + assert_eq!( + cause + .getattr("resource_name") + .unwrap() + .extract::() + .unwrap(), + "missing" + ); + assert_eq!( + cause + .getattr("namespace_path") + .unwrap() + .extract::>() + .unwrap(), + ["ns"] + ); + assert_eq!( + cause + .getattr("status_code") + .unwrap() + .extract::() + .unwrap(), + 404 + ); + assert_eq!( + cause + .getattr("request_id") + .unwrap() + .extract::() + .unwrap(), + "current-request" + ); + assert_eq!( + cause + .getattr("job_id") + .unwrap() + .extract::() + .unwrap(), + "outer-job" + ); + assert_eq!( + cause + .getattr("job_request_id") + .unwrap() + .extract::() + .unwrap(), + "worker-request" + ); + }); + } + + #[test] + fn direct_catalog_lookup_is_raised_as_the_named_resource_error() { + Python::initialize(); + for (kind, name, namespace_path, exception) in [ + ( + "function", + "missing", + vec!["ns".into()], + "FunctionNotFoundError", + ), + ("namespace", "ns", Vec::new(), "NamespaceNotFoundError"), + ] { + let mut metadata = RemoteErrorMetadata::default(); + metadata.error_code = Some("not_found".into()); + metadata.resource = Some(RemoteResourceIdentity::new(kind, name, namespace_path)); + let error = LanceError::Sql { + message: format!("{kind} '{name}' was not found"), + request_id: "current-request".into(), + grpc_code: 5, + metadata: Box::new(metadata), + }; + let py_err = Python::attach(|_| { + let result: std::result::Result<(), LanceError> = Err(error); + result.infer_error().unwrap_err() + }); + Python::attach(|py| { + let value = py_err.value(py); + let class = py + .import("lancedb.remote.errors") + .unwrap() + .getattr(exception) + .unwrap(); + assert!(value.is_instance(&class).unwrap(), "{py_err:?}"); + assert_eq!( + value + .getattr("resource_name") + .unwrap() + .extract::() + .unwrap(), + name + ); + }); + } + } +} diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 9c79fcf95..cc5bd1f4e 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -27,6 +27,35 @@ pub struct HttpErrorDetails { pub namespace_path: Vec, } +/// Stable resource identity reported with a remote Flight SQL failure. +#[cfg(feature = "remote")] +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct RemoteResourceIdentity { + /// The kind of resource named by the error. + pub kind: String, + /// The leaf name of the resource. + pub name: String, + /// The parent namespace path of the resource. + pub namespace_path: Vec, +} + +#[cfg(feature = "remote")] +impl RemoteResourceIdentity { + /// Construct a resource identity as reported by a remote service. + pub fn new( + kind: impl Into, + name: impl Into, + namespace_path: Vec, + ) -> Self { + Self { + kind: kind.into(), + name: name.into(), + namespace_path, + } + } +} + /// Correlation and classification metadata reported by a remote server. /// /// Fields are absent when the server did not supply them. Diagnostic text is @@ -41,6 +70,8 @@ pub struct RemoteErrorMetadata { pub job_id: Option, /// Request executed by the isolated SQL worker. pub job_request_id: Option, + /// Structured resource identity supplied by the server, when available. + pub resource: Option, } #[cfg(feature = "remote")] @@ -56,10 +87,37 @@ impl RemoteErrorMetadata { error_code: header("x-lancedb-error-code"), job_id: header("x-lancedb-sql-job-id"), job_request_id: header("x-job-request-id"), + resource: header("x-lancedb-resource") + .as_deref() + .and_then(parse_flight_resource_identity), } } } +#[cfg(feature = "remote")] +#[derive(Deserialize)] +struct FlightResourceIdentity { + kind: String, + name: String, + namespace_path: Vec, +} + +/// Decode the ASCII-safe structured resource metadata used by Flight SQL. +#[cfg(feature = "remote")] +pub(crate) fn parse_flight_resource_identity(value: &str) -> Option { + use base64::Engine as _; + + let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(value) + .ok()?; + let identity = serde_json::from_slice::(&bytes).ok()?; + Some(RemoteResourceIdentity { + kind: identity.kind, + name: identity.name, + namespace_path: identity.namespace_path, + }) +} + #[cfg(feature = "remote")] #[derive(Debug)] pub(crate) struct HttpErrorSource { diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index b9a3f8ae1..9af99dced 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -52,6 +52,34 @@ use super::util::parse_server_version; use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; use futures::TryStreamExt; +#[cfg(feature = "remote")] +fn direct_catalog_resource_error(error: Error) -> Error { + let Error::JobFailed { failure, .. } = &error else { + return error; + }; + let Some(Error::Sql { + message, + request_id, + grpc_code, + metadata, + }) = failure.source.as_deref() + else { + return error; + }; + let named_catalog_resource = metadata.resource.as_ref().is_some_and(|resource| { + matches!(resource.kind.as_str(), "function" | "namespace" | "secret") + }); + if !named_catalog_resource { + return error; + } + Error::Sql { + message: message.clone(), + request_id: request_id.clone(), + grpc_code: *grpc_code, + metadata: metadata.clone(), + } +} + // Request structure for the remote clone table API #[derive(serde::Serialize)] struct RemoteCloneTableRequest { @@ -861,6 +889,7 @@ impl Database for RemoteDatabase { self.sql_client()? .describe_function(name, version, namespace_path) .await + .map_err(direct_catalog_resource_error) } async fn list_functions( @@ -991,6 +1020,7 @@ impl Database for RemoteDatabase { self.sql_client()? .write_secret(name, value, namespace_path, true) .await + .map_err(direct_catalog_resource_error) } async fn alter_secret(&self, name: &str, value: &str, namespace_path: &[String]) -> Result<()> { crate::utils::validate_secret_name(name)?; @@ -998,6 +1028,7 @@ impl Database for RemoteDatabase { self.sql_client()? .write_secret(name, value, namespace_path, false) .await + .map_err(direct_catalog_resource_error) } async fn list_secrets( &self, @@ -1008,11 +1039,15 @@ impl Database for RemoteDatabase { self.sql_client()? .list_secrets(namespace_path, options) .await + .map_err(direct_catalog_resource_error) } async fn drop_secret(&self, name: &str, namespace_path: &[String]) -> Result<()> { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; - self.sql_client()?.drop_secret(name, namespace_path).await + self.sql_client()? + .drop_secret(name, namespace_path) + .await + .map_err(direct_catalog_resource_error) } async fn describe_secret(&self, name: &str, namespace_path: &[String]) -> Result { crate::utils::validate_secret_name(name)?; @@ -1020,6 +1055,7 @@ impl Database for RemoteDatabase { self.sql_client()? .describe_secret(name, namespace_path) .await + .map_err(direct_catalog_resource_error) } async fn create_view( @@ -1910,6 +1946,7 @@ mod tests { use crate::connection::ConnectBuilder; use crate::database::Database; + use crate::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity}; use crate::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::{ @@ -1919,6 +1956,53 @@ mod tests { remote::{ARROW_STREAM_CONTENT_TYPE, ClientConfig, HeaderProvider, JSON_CONTENT_TYPE}, }; + #[test] + fn catalog_helpers_unwrap_only_a_named_resource_job_failure() { + let job_failed = |source: Error| Error::JobFailed { + job_id: Some("job-1".into()), + failure: Box::new(JobFailure { + sql_job_id: Some("job-1".into()), + source: Some(Arc::new(source)), + ..Default::default() + }), + }; + + for (kind, name) in [ + ("function", "missing"), + ("namespace", "missing_ns"), + ("secret", "missing_secret"), + ] { + let resource = RemoteResourceIdentity::new(kind, name, vec!["ns".into()]); + let sql = Error::Sql { + message: format!("{kind} '{name}' was not found"), + request_id: "worker-request".into(), + grpc_code: 5, + metadata: Box::new(RemoteErrorMetadata { + error_code: Some("not_found".into()), + job_id: Some("job-1".into()), + resource: Some(resource.clone()), + ..Default::default() + }), + }; + let Error::Sql { metadata, .. } = super::direct_catalog_resource_error(job_failed(sql)) + else { + panic!("catalog helper must surface the {kind} resource failure"); + }; + assert_eq!(metadata.resource, Some(resource)); + } + + let generic = Error::Sql { + message: "query failed".into(), + request_id: "worker-request".into(), + grpc_code: 3, + metadata: Box::new(RemoteErrorMetadata::default()), + }; + assert!(matches!( + super::direct_catalog_resource_error(job_failed(generic)), + Error::JobFailed { .. } + )); + } + #[tokio::test] async fn test_catalog_namespace_identifier_validates_all_namespace_components() { let mut db = super::RemoteDatabase::new_mock(|_| -> http::Response { diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 83dedcb6d..724c813b3 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -1655,6 +1655,9 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro error_code: header("x-lancedb-error-code"), job_id: header(SQL_JOB_ID_METADATA_KEY), job_request_id: header("x-job-request-id"), + resource: header("x-lancedb-resource") + .as_deref() + .and_then(crate::error::parse_flight_resource_identity), }; let sql_job_id = metadata.job_id.clone(); let error = Error::Sql { diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index cbca4e9f6..37125c1fd 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3545,3 +3545,31 @@ fn sql_status_keeps_input_category_and_request_ids() { let error = super::sql_status_error("request", &tonic::Status::not_found("column_not_found")); assert!(error.remote_error_metadata().unwrap().error_code.is_none()); } + +#[test] +fn sql_status_reports_structured_resource_identity() { + let mut status = tonic::Status::not_found("Function 'missing' was not found"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "not_found".parse().unwrap()); + status.metadata_mut().insert( + "x-lancedb-resource", + "eyJraW5kIjoiZnVuY3Rpb24iLCJuYW1lIjoibWlzc2luZyIsIm5hbWVzcGFjZV9wYXRoIjpbIm5zIl19" + .parse() + .unwrap(), + ); + status + .metadata_mut() + .insert("x-lancedb-sql-job-id", "sql-job-1".parse().unwrap()); + + let error = super::sql_status_error("current-request", &status); + let resource = error + .remote_error_metadata() + .unwrap() + .resource + .as_ref() + .unwrap(); + assert_eq!(resource.kind, "function"); + assert_eq!(resource.name, "missing"); + assert_eq!(resource.namespace_path, ["ns"]); +} From 181ac2b5671ff7040392d713906630b63027355e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 19:43:12 +0800 Subject: [PATCH 019/203] test: match SDK documentation fallback URL (#4875) Update the SDK documentation-link CI assertion to match the production fallback URL introduced by #4870. #4870 changed `rust/lancedb/src/docs.rs` from `/enterprise` to `/basics/embedded-vs-enterprise`. The extractor already reads that source, but its regression test still expected the old value. Keep the assertion and update only the expected URL. Verification: `python -m unittest discover -s ci/tests -v` passes 35/35 on Python 3.12. The same command on main `3c4aaa8e` fails only `test_extracts_all_links_from_repo_docs_rs`. --- ci/tests/test_extract_sdk_doc_links.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/tests/test_extract_sdk_doc_links.py b/ci/tests/test_extract_sdk_doc_links.py index 504d28168..0e4c5fe97 100644 --- a/ci/tests/test_extract_sdk_doc_links.py +++ b/ci/tests/test_extract_sdk_doc_links.py @@ -27,7 +27,7 @@ class TestExtractSdkDocLinks(unittest.TestCase): urls, ) self.assertIn( - "https://docs.lancedb.com/enterprise", + "https://docs.lancedb.com/basics/embedded-vs-enterprise", urls, ) From 9ba1920e0e2c3ec2f49f2cf69f01d08ccf836aa9 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 5 Nov 2026 19:50:50 +0800 Subject: [PATCH 020/203] fix(node): normalize record batches before IPC serialization (#4871) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Passing a record batch created by an ESM `apache-arrow` import to `RRFReranker.rerankHybrid` throws an IPC footer parse error. The SDK's CommonJS Arrow writer receives data types from another module instance. Normalize single-record-batch input with the existing table sanitizer before writing IPC. Extend the Arrow 15–21 round-trip test with caller-created batches and nulls, and add a native ESM reranker regression covering 64-bit row IDs, scores, and an empty FTS side. Validation: - Reproduced with published `0.42.0-beta.3`; CommonJS and explicitly normalized ESM controls pass. - Same native module and inputs: all 8 targeted cases fail with the parent serializer and pass with this change. - Local native build, TypeScript build, lint, and formatting pass. - Current-head CI passes on Linux Node 22/24/26, macOS, and Arrow 19/20. The macOS run passes 1,643 tests; Linux Node 24 also passes docs and example checks. --- nodejs/__test__/arrow.test.ts | 10 ++++++++-- nodejs/__test__/rerankers.test.ts | 31 ++++++++++++++++++++++++++++++- nodejs/lancedb/arrow.ts | 4 +++- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index 376533961..27dd14954 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -1567,11 +1567,17 @@ describe.each(arrowVersions)("Arrow %#", (arrow: ApacheArrow) => { const records = [ { text: "dog", vector: [0.1, 0.2] }, { text: "cat", vector: [0.3, 0.4] }, + { text: null, vector: null }, ]; - const table = await convertToTable(records); + const table = arrow.tableFromArrays({ + text: records.map((row) => row.text), + vector: records.map((row) => row.vector), + }); const batch = table.batches[0]; - const buffer = await fromRecordBatchToBuffer(batch); + const buffer = await fromRecordBatchToBuffer( + batch as Parameters[0], + ); const result = await fromBufferToRecordBatch(buffer); expect(JSON.stringify(batch.toArray())).toEqual( diff --git a/nodejs/__test__/rerankers.test.ts b/nodejs/__test__/rerankers.test.ts index 256ef686c..8e3a36f98 100644 --- a/nodejs/__test__/rerankers.test.ts +++ b/nodejs/__test__/rerankers.test.ts @@ -1,13 +1,42 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -import { spawn } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import * as path from "node:path"; import { RecordBatch } from "apache-arrow"; import * as tmp from "tmp"; import { Connection, Index, Table, connect, makeArrowTable } from "../lancedb"; import { RRFReranker } from "../lancedb/rerankers"; +it("reranks record batches created by an ESM Arrow import", () => { + const script = ` +import assert from "node:assert/strict"; +import { tableFromArrays } from "apache-arrow"; +import { rerankers } from "./dist/index.js"; + +const ids = [1n, 9007199254740993n]; +const batch = tableFromArrays({ _rowid: new BigUint64Array(ids) }).batches[0]; +const reranker = await rerankers.RRFReranker.create(); +const result = await reranker.rerankHybrid("", batch, batch); + +assert.equal(result.numRows, 2); +assert.deepEqual(Array.from(result.getChild("_rowid").toArray()), ids); +const scores = result.getChild("_relevance_score").toArray(); +assert.ok(Math.abs(scores[0] - 2 / 61) < 1e-8); +assert.ok(Math.abs(scores[1] - 2 / 62) < 1e-8); + +const oneSide = await reranker.rerankHybrid("", batch, batch.slice(0, 0)); +assert.deepEqual(Array.from(oneSide.getChild("_rowid").toArray()), ids); +const oneSideScores = oneSide.getChild("_relevance_score").toArray(); +assert.ok(Math.abs(oneSideScores[0] - 1 / 61) < 1e-8); +assert.ok(Math.abs(oneSideScores[1] - 1 / 62) < 1e-8); +`; + execFileSync(process.execPath, ["--input-type=module", "-e", script], { + cwd: path.resolve(__dirname, ".."), + timeout: 10_000, + }); +}); + describe("rerankers", function () { let tmpDir: tmp.DirResult; let conn: Connection; diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 56c8e1897..f920eecb8 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -1386,7 +1386,9 @@ export async function fromBufferToRecordBatch( export async function fromRecordBatchToBuffer( batch: RecordBatch, ): Promise { - const writer = new RecordBatchFileWriter().writeAll([batch]); + // Arrow writers require data types from their own library instance. + const table = sanitizeTable({ schema: batch.schema, batches: [batch] }); + const writer = new RecordBatchFileWriter().writeAll(table); return Buffer.from(await writer.toUint8Array()); } From 1e40ef681e542fbe2877cd51ed52fd86fc2f336c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 20:03:34 +0800 Subject: [PATCH 021/203] fix: remove unmaintained pin-utils from AWS dependencies (#4874) `cargo deny` rejects `pin-utils 0.1.0` as unmaintained under RUSTSEC-2026-0441; there is no patched release. The dependency comes from the AWS Smithy graph. Refresh that graph to include [smithy-rs #4882](https://github.com/smithy-lang/smithy-rs/pull/4882), replacing the obsolete `aws-smithy-types = ">=1.3.6, <1.7"` constraint with `1.9.1`. The lockfile audit attributes every changed package identity and resolved dependency edge to the AWS graph. Existing git dependency pins are preserved. The selected AWS crates declare Rust 1.94.1, within the workspace's unchanged 1.95.0 requirement. Validation at the exact candidate on the development EC2 host, both exit 0: - `mbx +1.97.1 deny check advisories bans licenses sources` - `mbx +1.97.1 check --quiet --locked -p lancedb --tests --features remote,aws,dynamodb,bedrock` The second command compiles the selected test targets; it is not a runtime integration test. Full all-features compilation remains unverified: an earlier attempt stopped in lance-linalg because the host Clang 15 does not support the required `_Float16` target. --- Cargo.lock | 597 +++++++++++++++++++++++++++++------------------------ Cargo.toml | 3 +- 2 files changed, 327 insertions(+), 273 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 65bcd8c5b..7213e382b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,9 +626,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-config" -version = "1.8.16" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f156acdd2cf55f5aa53ee416c4ac851cf1222694506c0b1f78c85695e9ca9d" +checksum = "939e256cfe0ed68e96d32f194339d88210d5c10685cff0787400158f852c6819" dependencies = [ "aws-credential-types", "aws-runtime", @@ -640,12 +640,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", + "http", "sha1 0.10.6", "time", "tokio", @@ -656,9 +657,9 @@ dependencies = [ [[package]] name = "aws-credential-types" -version = "1.2.14" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f20799b373a1be121fe3005fba0c2090af9411573878f224df44b42727fcaf7" +checksum = "576e8da35751dc85409ec1cd15999f692c277a1fbe9336780fe6f15e49dd637d" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", @@ -692,9 +693,9 @@ dependencies = [ [[package]] name = "aws-runtime" -version = "1.7.3" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dcd93c82209ac7413532388067dce79be5a8780c1786e5fae3df22e4dee2864" +checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -708,10 +709,8 @@ dependencies = [ "bytes", "bytes-utils", "fastrand", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "percent-encoding", "pin-project-lite", "tracing", @@ -720,10 +719,11 @@ dependencies = [ [[package]] name = "aws-sdk-bedrockruntime" -version = "1.130.0" +version = "1.153.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2f7bca252e3c5c8f0ed12c5501bf8b0fbadb937cd9fdd71a0ebd9d7526540f" +checksum = "89b8aeb4b1b6d5f9d377264cff21b4e4d773e66ee3c5582b4099a8fbc702bdb3" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -734,12 +734,12 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "http-body-util", "regex-lite", "tracing", @@ -747,10 +747,11 @@ dependencies = [ [[package]] name = "aws-sdk-dynamodb" -version = "1.111.0" +version = "1.137.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc418346e3cb248c7d59e642acbcb06488b7c7cd2ba6ebc79e8003f618c60099" +checksum = "41515f51bd2b5608268336bda372065e8fd5d1ca2f684b63e5c25ae4abb62c53" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -759,22 +760,24 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", + "url", ] [[package]] name = "aws-sdk-kms" -version = "1.106.0" +version = "1.129.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2336350f96efcf9c2552b7fdb4dd07a0c1fef11f22b28fb020a9e33e7925cf9d" +checksum = "5c5cdb29ad25d71c9ee54c408a672c98d90a24a0ea6eb063025483e0e894b411" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -783,22 +786,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-s3" -version = "1.132.0" +version = "1.157.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5575840a3a6b11f6011463ebe359320dfe5b67babb5e9b06fed6ddf809a9ab40" +checksum = "6ea9794c741520d8baec9462bcd0ad12164d4f5f78d008a8da9d6a0b7222caa8" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-sigv4", @@ -810,6 +814,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", @@ -817,10 +822,9 @@ dependencies = [ "fastrand", "hex", "hmac 0.13.0", - "http 0.2.12", - "http 1.5.0", - "http-body 1.1.0", - "lru", + "http", + "http-body", + "lru 0.18.5", "percent-encoding", "regex-lite", "sha2 0.11.0", @@ -830,10 +834,11 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "1.98.0" +version = "1.119.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69c77aafa20460c68b6b3213c84f6423b6e76dbf89accd3e1789a686ffd9489" +checksum = "3c414f25ec4aa9dc18f5cc8f55e18848bb509fcda4ce7c77bee6072e95806bc9" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -842,22 +847,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-ssooidc" -version = "1.100.0" +version = "1.121.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c7e7b09346d5ca22a2a08267555843a6a0127fb20d8964cb6ecfb8fdb190225" +checksum = "bc638bb4355e6514334dcc3228cd4622f5ee54d704bd6a9010a5a91d7856d9d9" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -866,22 +872,23 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sdk-sts" -version = "1.103.0" +version = "1.124.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2249b81a2e73a8027c41c378463a81ec39b8510f184f2caab87de912af0f49b" +checksum = "3f8a0dd8fbde04ba58ad722113c7addb11bf94cf549b1ea0eb9ea427fb87198a" dependencies = [ + "arc-swap", "aws-credential-types", "aws-runtime", "aws-smithy-async", @@ -891,21 +898,21 @@ dependencies = [ "aws-smithy-query", "aws-smithy-runtime", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "aws-smithy-xml", "aws-types", "fastrand", - "http 0.2.12", - "http 1.5.0", + "http", "regex-lite", "tracing", ] [[package]] name = "aws-sigv4" -version = "1.4.3" +version = "1.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68dc0b907359b120170613b5c09ccc61304eac3998ff6274b97d93ee6490115a" +checksum = "f385da9b7757ed4c8214797ad663ff534fb622006143530aa80e21f8e06ff85c" dependencies = [ "aws-credential-types", "aws-smithy-eventstream", @@ -913,15 +920,14 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "bytes", - "crypto-bigint 0.5.5", + "crypto-bigint", + "ecdsa", "form_urlencoded", "hex", "hmac 0.13.0", - "http 0.2.12", - "http 1.5.0", + "http", "p256", "percent-encoding", - "ring", "sha2 0.11.0", "subtle", "time", @@ -931,9 +937,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", @@ -942,17 +948,17 @@ 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", "bytes", "crc-fast", "hex", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "md-5", "pin-project-lite", @@ -963,9 +969,9 @@ dependencies = [ [[package]] name = "aws-smithy-eventstream" -version = "0.60.20" +version = "0.61.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf09d74e5e32f76b8762da505a3cd59303e367a664ca67295387baa8c1d7548" +checksum = "14c8a643d0e114cae39e45415e3225793a6396698b7779a0c9e3ede731d8fc71" dependencies = [ "aws-smithy-types", "bytes", @@ -974,9 +980,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.63.6" +version = "0.64.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231" +checksum = "19af609dd5edf8b056cd0bb001c706c8b3b1458055328b334ec13d7f46f6aaa8" dependencies = [ "aws-smithy-eventstream", "aws-smithy-runtime-api", @@ -985,26 +991,25 @@ dependencies = [ "bytes-utils", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "percent-encoding", "pin-project-lite", - "pin-utils", "tracing", ] [[package]] name = "aws-smithy-http-client" -version = "1.1.13" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3ef8931ad1c98aa6a55b4256f847f3116090819844e0dd41ea682cac5dd2d3" +checksum = "859a81364f8185349c584fb41cd8765a400cf982f447adada590cf008a9f3b85" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", "aws-smithy-types", "h2", - "http 1.5.0", + "http", "hyper", "hyper-rustls", "hyper-util", @@ -1020,9 +1025,9 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.62.7" +version = "0.65.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "701a947f4797e52a911e114a898667c746c39feea467bbd1abd7b3721f702ffa" +checksum = "b45f9fc77ffe92c92c341165a01a565bd30c39ecf5aa8c0719b41719009604f9" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-schema", @@ -1031,28 +1036,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.64.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd" +checksum = "165f6265342a313ad6f7a1ac17a0cdba30c522039d3f41d8d6871ce8a2b34ecd" 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.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e6f5caf6fea86f8c2206541ab5857cfcda9013426cdbe8fa0098b9e2d32182" +checksum = "4cb80fb19c084da5fca9d797845735e184445e5b958599440d67529bf6ef1b64" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -1063,29 +1071,25 @@ dependencies = [ "aws-smithy-types", "bytes", "fastrand", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", - "pin-utils", "tokio", "tracing", ] [[package]] name = "aws-smithy-runtime-api" -version = "1.12.3" +version = "1.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9db177daa6ba8afb9ee1aefcf548c907abcf52065e394ee11a92780057fe0e8c" +checksum = "8c4e85cffe9944b10d576b075432bd8f98dbc081e8681cb37d5b2d87dc27bc84" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", "aws-smithy-types", "bytes", - "http 0.2.12", - "http 1.5.0", + "http", "pin-project-lite", "tokio", "tracing", @@ -1094,9 +1098,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api-macros" -version = "1.0.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d7396fd9500589e62e460e987ecb671bad374934e55ec3b5f498cc7a8a8a7b7" +checksum = "ce237f890a2283c9b328955c3b0918d2d5bf66a1cb6ceccd36a0047246fbc6e6" dependencies = [ "proc-macro2", "quote", @@ -1105,34 +1109,31 @@ dependencies = [ [[package]] name = "aws-smithy-schema" -version = "0.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7442cb268338f0eb8278140a107c046756aa01093d8ef5e99628d34ae09c94f5" +checksum = "9543fc722ed4865ab29fb66bd7ed0bef7b029d265ba8c587144511e30006d431" dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", - "http 1.5.0", + "http", ] [[package]] name = "aws-smithy-types" -version = "1.6.4" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b791f3ac597193fe1d08b82366986eb1f5bc31f2ac6c194c0855276116c76cd" +checksum = "cf183d70774ea2cfcc101ca74a8884e4c76be8b9df65cd303f6a1175c88e8f80" dependencies = [ "base64-simd", "bytes", "bytes-utils", "futures-core", - "http 0.2.12", - "http 1.5.0", - "http-body 0.4.6", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "itoa", "num-integer", "pin-project-lite", - "pin-utils", "ryu", "serde", "time", @@ -1142,22 +1143,26 @@ dependencies = [ [[package]] name = "aws-smithy-xml" -version = "0.60.15" +version = "0.64.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3" +checksum = "590fdc1a70546b2f7f2061c42eaf173fb6f26d935330d069edc04dbd8f01d924" dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", "xmlparser", ] [[package]] name = "aws-types" -version = "1.3.15" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4bbcaa9304ea40902d3d5f42a0428d1bd895a2b0f6999436fb279ffddc58ac" +checksum = "6ba0d970d3947bb064d2ae1d823efa186c1dbde88f88afa8f6549946e5d8deee" dependencies = [ "aws-credential-types", "aws-smithy-async", "aws-smithy-runtime-api", + "aws-smithy-schema", "aws-smithy-types", "rustc_version", "tracing", @@ -1173,8 +1178,8 @@ dependencies = [ "axum-core 0.4.5", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-util", @@ -1207,8 +1212,8 @@ dependencies = [ "bytes", "form_urlencoded", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-util", @@ -1239,8 +1244,8 @@ dependencies = [ "async-trait", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -1259,8 +1264,8 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -1312,9 +1317,9 @@ dependencies = [ [[package]] name = "base16ct" -version = "0.1.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" [[package]] name = "base64" @@ -2061,6 +2066,12 @@ dependencies = [ "cfg-if 1.0.4", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -2235,26 +2246,20 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-bigint" -version = "0.4.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ - "generic-array", - "rand_core 0.6.4", + "cpubits", + "ctutils", + "getrandom 0.4.2", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", "subtle", "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" @@ -2271,7 +2276,9 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ + "getrandom 0.4.2", "hybrid-array", + "rand_core 0.10.1", ] [[package]] @@ -2307,11 +2314,12 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.4" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12218662ccac37d9714f2191252553d67585b97df8c839cbe49e0bde278dc865" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", + "subtle", ] [[package]] @@ -3084,16 +3092,6 @@ 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", -] - [[package]] name = "der" version = "0.7.10" @@ -3101,7 +3099,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "pem-rfc7468", + "pem-rfc7468 0.7.0", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -3290,14 +3299,17 @@ dependencies = [ [[package]] name = "ecdsa" -version = "0.14.8" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" dependencies = [ - "der 0.6.1", + "der 0.8.3", + "digest 0.11.3", "elliptic-curve", "rfc6979", - "signature 1.6.4", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", ] [[package]] @@ -3308,19 +3320,20 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "elliptic-curve" -version = "0.12.3" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" dependencies = [ "base16ct", - "crypto-bigint 0.4.9", - "der 0.6.1", - "digest 0.10.7", + "crypto-bigint", + "crypto-common 0.2.1", + "digest 0.11.3", "ff", - "generic-array", "group", - "pkcs8 0.9.0", - "rand_core 0.6.4", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", "sec1", "subtle", "zeroize", @@ -3551,11 +3564,11 @@ dependencies = [ [[package]] name = "ff" -version = "0.12.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" dependencies = [ - "rand_core 0.6.4", + "rand_core 0.10.1", "subtle", ] @@ -4251,7 +4264,7 @@ dependencies = [ "io-uring", "itoa", "libc", - "lru", + "lru 0.16.4", "prost", "rand 0.9.5", "serde", @@ -4267,12 +4280,12 @@ dependencies = [ [[package]] name = "group" -version = "0.12.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" dependencies = [ "ff", - "rand_core 0.6.4", + "rand_core 0.10.1", "subtle", ] @@ -4287,7 +4300,7 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.5.0", + "http", "indexmap 2.14.0", "slab", "tokio", @@ -4417,7 +4430,7 @@ checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ "dirs", "futures", - "http 1.5.0", + "http", "indicatif", "libc", "log", @@ -4441,7 +4454,7 @@ dependencies = [ "anyhow", "async-trait", "bytes", - "http 1.5.0", + "http", "more-asserts", "serde", "serde_json", @@ -4495,17 +4508,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.5.0" @@ -4516,17 +4518,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.1.0" @@ -4534,7 +4525,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http", ] [[package]] @@ -4545,8 +4536,8 @@ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", ] @@ -4570,11 +4561,13 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[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 = [ + "subtle", "typenum", + "zeroize", ] [[package]] @@ -4588,8 +4581,8 @@ dependencies = [ "futures-channel", "futures-core", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", "httpdate", "itoa", @@ -4605,7 +4598,7 @@ version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ - "http 1.5.0", + "http", "hyper", "hyper-util", "rustls", @@ -4655,8 +4648,8 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "hyper", "ipnet", "libc", @@ -5700,7 +5693,7 @@ dependencies = [ "chrono", "futures", "goosefs-sdk", - "http 1.5.0", + "http", "io-uring", "lance-core", "lance-namespace", @@ -5963,8 +5956,8 @@ dependencies = [ "futures", "half", "hf-hub", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "lance", "lance-arrow", "lance-core", @@ -6049,7 +6042,7 @@ dependencies = [ "directories", "futures", "half", - "http 1.5.0", + "http", "lancedb", "prost", "rcgen", @@ -6369,6 +6362,15 @@ 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.2" @@ -7061,7 +7063,7 @@ dependencies = [ "base64 0.22.1", "chrono", "getrandom 0.2.17", - "http 1.5.0", + "http", "rand 0.8.6", "serde", "serde_json", @@ -7159,7 +7161,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", + "http", "humantime", "itertools 0.14.0", "parking_lot", @@ -7188,7 +7190,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "http 1.5.0", + "http", "http-body-util", "httparse", "humantime", @@ -7311,7 +7313,7 @@ dependencies = [ "base64 0.23.1", "bytes", "futures", - "http 1.5.0", + "http", "jiff", "log", "md-5", @@ -7334,8 +7336,8 @@ checksum = "f772ce6c137ab43647726116d505a649a88d41928fcd813438eb30b02312bcbb" dependencies = [ "bytes", "futures", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "opendal-core", "reqwest 0.13.5", ] @@ -7348,7 +7350,7 @@ checksum = "3734c648617e5ad724d49175dde8323550624f9614f50e9e81b7aafae30b1734" dependencies = [ "asyncband", "futures", - "http 1.5.0", + "http", "opendal-core", ] @@ -7391,7 +7393,7 @@ checksum = "c6cf31b02e7b44191d97c07254eea109b5da9c17210a29e478c8d0dc26dffb1f" dependencies = [ "base64 0.23.1", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "opendal-service-azure-common", @@ -7413,7 +7415,7 @@ dependencies = [ "asyncband", "base64 0.23.1", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "opendal-service-azure-common", @@ -7431,7 +7433,7 @@ version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8107324c3f3cb9970fe20526c2c341b7c5769acbd4699bab73bd525f5fd63d62" dependencies = [ - "http 1.5.0", + "http", "opendal-core", ] @@ -7442,7 +7444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "feb737e6609b4fd42e4773b7b2d8d05031b63cd0df46c7ba68ddd64bae1dd3f3" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "quick-xml 0.41.0", @@ -7460,7 +7462,7 @@ checksum = "3d80eca6f9227bdf65d43e5b8d5fe75dca8cfab1da07571442a0420400847bea" dependencies = [ "async-trait", "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "percent-encoding", @@ -7497,7 +7499,7 @@ dependencies = [ "asyncband", "bytes", "hf-xet", - "http 1.5.0", + "http", "log", "opendal-core", "percent-encoding", @@ -7512,7 +7514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0ebfa355b1d4edb0e5b2a5b86d8de9f811fae1d7baca6d65246b230b2afc0bd" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "opendal-core", "quick-xml 0.41.0", @@ -7531,7 +7533,7 @@ dependencies = [ "base64 0.23.1", "bytes", "crc-fast", - "http 1.5.0", + "http", "log", "md-5", "opendal-core", @@ -7637,13 +7639,15 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" [[package]] name = "p256" -version = "0.11.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ "ecdsa", "elliptic-curve", - "sha2 0.10.9", + "primefield", + "primeorder", + "sha2 0.11.0", ] [[package]] @@ -7747,6 +7751,15 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -7892,12 +7905,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - [[package]] name = "pkcs1" version = "0.7.5" @@ -7924,16 +7931,6 @@ dependencies = [ "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]] name = "pkcs8" version = "0.10.2" @@ -7946,6 +7943,16 @@ dependencies = [ "spki 0.7.3", ] +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", +] + [[package]] name = "pkg-config" version = "0.3.33" @@ -8433,6 +8440,33 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.1", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -9135,7 +9169,7 @@ checksum = "a5e6d659fcdbca6fe2d7ef109c2e28499b7be80501f1bb86c10caf5ec8ac1219" dependencies = [ "anyhow", "form_urlencoded", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-core", @@ -9153,7 +9187,7 @@ dependencies = [ "bytes", "form_urlencoded", "hex", - "http 1.5.0", + "http", "log", "percent-encoding", "quick-xml 0.41.0", @@ -9172,7 +9206,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff250f0fd0b913fbd565e405acc553da0f13bde30bfb5403178c9d0313cdc15f" dependencies = [ "bytes", - "http 1.5.0", + "http", "log", "quick-xml 0.41.0", "reqsign-aws-core", @@ -9190,7 +9224,7 @@ dependencies = [ "base64 0.23.1", "bytes", "form_urlencoded", - "http 1.5.0", + "http", "log", "pem", "percent-encoding", @@ -9213,7 +9247,7 @@ dependencies = [ "futures", "hex", "hmac 0.13.0", - "http 1.5.0", + "http", "jiff", "log", "mea", @@ -9245,7 +9279,7 @@ checksum = "272a5813571885c1455ffe106f0c768577e6ce69313446d4476e8d41dcf6ac5a" dependencies = [ "bytes", "form_urlencoded", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-aws-v4", @@ -9263,7 +9297,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "764629c90f7c3566a6d4e4641ebab9acd604ce02e16eda4d37c7d7e79e16ed90" dependencies = [ "anyhow", - "http 1.5.0", + "http", "log", "percent-encoding", "reqsign-core", @@ -9283,8 +9317,8 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-rustls", @@ -9332,8 +9366,8 @@ dependencies = [ "futures-core", "futures-util", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-rustls", @@ -9388,7 +9422,7 @@ checksum = "199dda04a536b532d0cc04d7979e39b1c763ea749bf91507017069c00b96056f" dependencies = [ "anyhow", "async-trait", - "http 1.5.0", + "http", "reqwest 0.13.5", "thiserror 2.0.18", "tower-service", @@ -9396,13 +9430,12 @@ dependencies = [ [[package]] name = "rfc6979" -version = "0.3.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ - "crypto-bigint 0.4.9", - "hmac 0.12.1", - "zeroize", + "crypto-bigint", + "hmac 0.13.0", ] [[package]] @@ -9809,14 +9842,14 @@ dependencies = [ [[package]] name = "sec1" -version = "0.3.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" dependencies = [ "base16ct", - "der 0.6.1", - "generic-array", - "pkcs8 0.9.0", + "ctutils", + "der 0.8.3", + "hybrid-array", "subtle", "zeroize", ] @@ -10019,6 +10052,16 @@ dependencies = [ "unsafe-libyaml", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "serial_test" version = "3.5.0" @@ -10138,9 +10181,9 @@ dependencies = [ [[package]] name = "signature" -version = "1.6.4" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest 0.10.7", "rand_core 0.6.4", @@ -10148,12 +10191,12 @@ dependencies = [ [[package]] name = "signature" -version = "2.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" dependencies = [ - "digest 0.10.7", - "rand_core 0.6.4", + "digest 0.11.3", + "rand_core 0.10.1", ] [[package]] @@ -10316,16 +10359,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" @@ -10336,6 +10369,16 @@ dependencies = [ "der 0.7.10", ] +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", +] + [[package]] name = "spm_precompiled" version = "0.1.4" @@ -11120,8 +11163,8 @@ dependencies = [ "base64 0.22.1", "bytes", "h2", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "hyper", "hyper-timeout", @@ -11178,8 +11221,8 @@ checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "bitflags 2.11.1", "bytes", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", "tower-layer", @@ -11198,8 +11241,8 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", "pin-project-lite", "tokio", @@ -12348,6 +12391,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.3" @@ -12375,7 +12430,7 @@ dependencies = [ "bytes", "crc32fast", "futures", - "http 1.5.0", + "http", "hyper", "more-asserts", "rand 0.10.1", @@ -12443,7 +12498,7 @@ dependencies = [ "bytes", "chrono", "gearhash", - "http 1.5.0", + "http", "itertools 0.14.0", "more-asserts", "rand 0.10.1", diff --git a/Cargo.toml b/Cargo.toml index 4ba74870e..8cd8d7292 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,8 +49,7 @@ 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" +aws-smithy-types = "1.9.1" base64 = "0.22" bytes = "1" datafusion = { version = "55.0.0", default-features = false } From 5def26112fee5a5721fc55101b61cd4a33c6d81b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 20:32:41 +0800 Subject: [PATCH 022/203] fix(deps): ignore RUSTSEC-2026-0441 pin-utils unmaintained (#4872) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo deny` fails on main because RUSTSEC-2026-0441 marks `pin-utils` as unmaintained. Add an exception reviewed on 2026-11-05, with the advisory and upstream discussion links and a reminder to revisit it when updating AWS dependencies. `pin-utils` is transitive through `aws-smithy-http`, `aws-smithy-runtime`, and `aws-smithy-types`, including the `aws-config` → `lance-io` path. RustSec lists no safe upgrade; clearing the advisory requires upstream migration to supported pinning primitives. Validation on commit dede2c783fda73500cee2b05feffe1b70d56624c: - Before the change, `cargo deny check advisories` failed on RUSTSEC-2026-0441. - `cargo deny check advisories` passes after the change. - `cargo deny check advisories bans licenses sources` passes all four checks, matching the Rust CI deny job. - `git diff HEAD^ HEAD --check` passes. --- deny.toml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/deny.toml b/deny.toml index 602cc2820..458559936 100644 --- a/deny.toml +++ b/deny.toml @@ -131,6 +131,14 @@ ignore = [ { 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" }, + + # pin-utils: unmaintained; reviewed 2026-11-05. Transitive via + # aws-smithy-http/runtime/types, including aws-config -> lance-io. + # No safe upgrade exists; clearing requires AWS Smithy to migrate to + # core::pin::pin!, pin-project, or pin-project-lite. Revisit on AWS updates. + # https://rustsec.org/advisories/RUSTSEC-2026-0441 + # https://github.com/rustsec/advisory-db/issues/3314 + { id = "RUSTSEC-2026-0441", reason = "pin-utils unmaintained via AWS Smithy; no safe upgrade, awaiting upstream migration" }, ] From 57cd31e1aa9960a4073993dd326305058ca1a53d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 5 Nov 2026 21:34:58 +0800 Subject: [PATCH 023/203] test(python): load checked-in error classes for Rust tests (#4876) Bare Rust test runners do not install the `lancedb` Python package, so the typed-error tests fail with `ModuleNotFoundError`. Load the checked-in exception modules once for the embedded interpreter, preserving exception-class identity across parallel tests and the existing type/cause assertions. Rust CI now watches the binding sources and the Python exception modules embedded by these tests, so those changes exercise the macOS Rust test jobs. --- .github/workflows/rust.yml | 3 ++ python/src/error.rs | 73 +++++++++++++++++++++++++++++++++++--- 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index dbdcc3b54..687b8a54c 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -14,6 +14,9 @@ on: - docs/web-tests/blob-v2/rs/** - nodejs/Cargo.toml - python/Cargo.toml + - python/src/** + - python/python/lancedb/exceptions.py + - python/python/lancedb/remote/errors.py - ci/build_no_lock.py - ci/tests/test_build_no_lock.py - .github/actions/setup-protoc/** diff --git a/python/src/error.rs b/python/src/error.rs index 3fd27f7be..c4f20e884 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -386,16 +386,81 @@ fn is_transport_error(err: &(dyn std::error::Error + 'static)) -> bool { #[cfg(test)] mod tests { - use std::sync::Arc; + use std::ffi::CString; + use std::sync::{Arc, Once}; use lancedb::error::{JobFailure, RemoteResourceIdentity}; - use pyo3::types::PyAnyMethods; + use pyo3::types::{PyAnyMethods, PyModule}; use super::*; + static INSTALL_PYTHON_ERROR_MODULES: Once = Once::new(); + + fn install_python_error_modules(py: Python<'_>) -> PyResult<()> { + // Load the checked-in error classes without requiring an installed wheel. + // The namespace exception is only a base for an unrelated remote class. + PyModule::from_code( + py, + c"import sys\n\nimport types\n\n\ + lancedb = types.ModuleType('lancedb')\n\ + lancedb.__path__ = []\n\ + lancedb_remote = types.ModuleType('lancedb.remote')\n\ + lancedb_remote.__path__ = []\n\ + lancedb.remote = lancedb_remote\n\ + namespace = types.ModuleType('lance_namespace')\n\ + namespace_errors = types.ModuleType('lance_namespace.errors')\n\ + namespace_errors.TableNotFoundError = RuntimeError\n\ + namespace.errors = namespace_errors\n\ + sys.modules['lancedb'] = lancedb\n\ + sys.modules['lancedb.remote'] = lancedb_remote\n\ + sys.modules['lance_namespace'] = namespace\n\ + sys.modules['lance_namespace.errors'] = namespace_errors", + c"error_test_bootstrap.py", + c"lancedb_error_test_bootstrap", + )?; + + let exceptions_code = + CString::new(include_str!("../../python/python/lancedb/exceptions.py")).unwrap(); + let exceptions = PyModule::from_code( + py, + &exceptions_code, + c"exceptions.py", + c"lancedb.exceptions", + )?; + let lancedb = py.import("lancedb")?; + lancedb.setattr("exceptions", &exceptions)?; + py.import("sys")? + .getattr("modules")? + .set_item("lancedb.exceptions", &exceptions)?; + + let remote_errors_code = + CString::new(include_str!("../../python/python/lancedb/remote/errors.py")).unwrap(); + let remote_errors = PyModule::from_code( + py, + &remote_errors_code, + c"remote/errors.py", + c"lancedb.remote.errors", + )?; + lancedb + .getattr("remote")? + .setattr("errors", &remote_errors)?; + py.import("sys")? + .getattr("modules")? + .set_item("lancedb.remote.errors", &remote_errors)?; + Ok(()) + } + + fn ensure_python_error_modules() { + Python::initialize(); + // Once waits without holding the GIL; only its one-time closure attaches. + INSTALL_PYTHON_ERROR_MODULES.call_once(|| { + Python::attach(install_python_error_modules).unwrap(); + }); + } + #[test] fn generic_job_failure_retains_the_named_resource_as_its_cause() { - Python::initialize(); + ensure_python_error_modules(); let source = LanceError::Sql { message: "Function 'missing' was not found".into(), request_id: "current-request".into(), @@ -515,7 +580,7 @@ mod tests { #[test] fn direct_catalog_lookup_is_raised_as_the_named_resource_error() { - Python::initialize(); + ensure_python_error_modules(); for (kind, name, namespace_path, exception) in [ ( "function", From 3d790e751d46b63bf69f7863eac8e5d25ef48f8d Mon Sep 17 00:00:00 2001 From: Lance Release Date: Thu, 5 Nov 2026 14:59:02 +0000 Subject: [PATCH 024/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.4=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index bfeaaf02f..9a83cbcb8 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.4" +current_version = "0.42.0-beta.5" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 7213e382b..9735eebb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5914,7 +5914,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" dependencies = [ "ahash", "anyhow", @@ -6025,7 +6025,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" dependencies = [ "anyhow", "arrow-array", @@ -6068,7 +6068,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" dependencies = [ "arrow-array", "arrow-buffer", @@ -6093,7 +6093,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index a0844a469..edf7c1dd4 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.42.0-beta.4 + 0.42.0-beta.5 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 6006329f9..a253fe1b6 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.4 + 0.42.0-beta.5 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 95568874b..2d5df36c9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.4 + 0.42.0-beta.5 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 33a71fff3..52615cfec 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" 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 0152622cf..084d1ce9d 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.42.0-beta.4", + "version": "0.42.0-beta.5", "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 a96e450c4..a7804bbae 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.42.0-beta.4", + "version": "0.42.0-beta.5", "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 606c8c23d..59cbef7df 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.42.0-beta.4", + "version": "0.42.0-beta.5", "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 a84d8f649..4d407e557 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.42.0-beta.4", + "version": "0.42.0-beta.5", "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 fd1223f69..dac2d1cb7 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.42.0-beta.4", + "version": "0.42.0-beta.5", "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 a1ec2e4b8..a01e6ba19 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.42.0-beta.4", + "version": "0.42.0-beta.5", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 3a1be4350..187da18c9 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.42.0-beta.4", + "version": "0.42.0-beta.5", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 3005c769f..57ca0f03b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.4", + "version": "0.42.0-beta.5", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index e816ca6d7..3c60244c2 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 2d246bf39..26ae4f1d7 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 49499fe22..681604aad 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.4" +version = "0.42.0-beta.5" edition = "2021" license.workspace = true repository.workspace = true From 6687db979d4aa6af02c1233ca4a458f81cf9f4f7 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Fri, 6 Nov 2026 02:30:49 +0800 Subject: [PATCH 025/203] feat(functions): expose retry policies in Python and Rust (#4873) Expose `FunctionRetryPolicy` on Function declarations and refresh overrides, together with `error_policy` and recorded attempt counts. Python uses the Rust validation rules before sending a request; local refreshes reject these Enterprise options. The policy bounds calls and backoff, supports class/message/provider-code matching, and can disable retries with `max_attempts=1`. Batch retry and skip operate on the whole failed call. Requires Enterprise server support for the new policy. Validation: rebuilt the Python extension; 47 targeted Python tests and 10 Rust tests passed. Python `make check`, Rust formatting, and `cargo clippy --features remote --tests --examples -- -D warnings` passed. The additional repository-root Ruff sweep reports existing errors under `docs/web-tests`; the Python workspace checks pass. Draft user guidance covers the supporting server requirement, safe repetition of partial work and whole-batch exhaustion. The guide sections stay hidden until release. Vale 3.24.0 passed for the added draft prose; no paired deployed SDK/server retry acceptance was run. Companion server: https://github.com/lancedb/sophon/pull/9812. BREAKING CHANGE: Rust callers constructing `FunctionRegistrationRequest` or `FunctionErrorRecord` with struct literals must supply the new `retry_policy` or `attempts` field, respectively. --- docs/src/python/python.md | 2 + .../feature-engineering/refresh-column.mdx | 28 +++ docs/web/management/function.mdx | 42 ++++- python/python/lancedb/__init__.py | 1 + python/python/lancedb/_lancedb.pyi | 7 + python/python/lancedb/functions.py | 51 ++++++ python/python/lancedb/remote/table.py | 14 +- python/python/lancedb/table.py | 53 ++++++ .../tests/test_first_class_function_slice2.py | 28 +++ python/python/tests/test_remote_db.py | 20 ++- python/python/tests/test_table.py | 8 + python/src/lib.rs | 1 + python/src/table.rs | 30 +++- python/src/util.rs | 11 ++ rust/lancedb/src/function.rs | 12 ++ rust/lancedb/src/function/retry.rs | 160 ++++++++++++++++++ rust/lancedb/src/remote/table.rs | 41 ++++- rust/lancedb/src/table.rs | 12 ++ rust/lancedb/src/table/refresh.rs | 18 ++ 19 files changed, 528 insertions(+), 11 deletions(-) create mode 100644 rust/lancedb/src/function/retry.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 3baa128ae..eb2c8d1db 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -465,6 +465,8 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.FunctionRegistrationRequest +::: lancedb.functions.FunctionRetryPolicy + ::: lancedb.functions.FunctionArtifactRequest ::: lancedb.functions.FunctionArtifactContent diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ea8b49b9b..24d050362 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -159,6 +159,34 @@ work sizes. For Function columns, the refresh defaults to failing rows and record them in the error store, subject to failure limits. See the [SQL refresh options](/sql/dml/refresh-column#options). +{/* +Draft for the Function retry policy release. + +For registered Function columns, pass `retry_policy` to +`refresh_column_async` to replace the Function's registered retry policy +for this refresh. For example, +`retry_policy=FunctionRetryPolicy(transient=True, max_attempts=3)` allows +three attempts, including the first call. Import `FunctionRetryPolicy` +from `lancedb.functions`. Use `FunctionRetryPolicy(max_attempts=1)` to +disable user-error retries. Omitting the override preserves the registered +policy. + +This requires a supporting LanceDB Enterprise server as well as an SDK +that exposes these options. An older Function image may need +re-registration before it accepts a refresh override. Only enable retries +when repeating a failed call's partial work is safe, including any external +requests made before the error. + +The attempt budget belongs to one failed Function call. With an explicit +retry policy and `error_policy="skip"`, exhaustion in a batch Function +writes nulls for the whole failed call and records its errors, subject to +failure limits. It does not split the batch to restart the retry budget. +Row Functions isolate failures per row. Infrastructure recovery, framework +deadlines and cancellation remain separate from this user-error policy. +See [Function failure handling](/management/function#failures) for the +retry and replay boundaries. +*/} + For a column filled by a registered Function, the Python and Rust job APIs can override the Function's GPU placement for this refresh: diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 63a3f6446..4709264c7 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -401,9 +401,8 @@ full worked example. ## Failure handling {#failures} -By default, a Function that raises fails the refresh job. The Function -definition has no error-handling parameter; choose the row-error policy on -the refresh instead: +By default, a Function that raises fails the refresh job. Choose how the +refresh handles row errors with its error policy: ```sql SQL icon="database" @@ -424,6 +423,43 @@ but how much of the failed job's work was kept is not guaranteed, so do not count on the retry costing only the rows that did not complete. A refresh with `WHERE` recomputes every matching live row, including already-filled outputs. +{/* +Draft for the Function retry policy release. + +### Retry transient errors + +Native retries require an SDK that exposes `FunctionRetryPolicy` and a +LanceDB Enterprise server that supports Function retry policies. Upgrading +the SDK alone does not enable retries on an older server. If a refresh +override reports that the Function image does not support retry policies, +re-register the Function on a supporting server. + +Import `FunctionRetryPolicy` from `lancedb.functions` and pass a policy to +`@function` through `retry_policy`. For example, +`FunctionRetryPolicy(transient=True, max_attempts=3)` allows up to three +calls for matching transient failures. `max_attempts` includes the first +call; setting it to `1` disables user-error retries. A +[refresh override](/feature-engineering/refresh-column#resources) replaces +the registered policy for that refresh. + +Enable retries only when repeating a failed call's partial work is safe. +An external request may have succeeded before the Function raised, so this +policy does not guarantee exactly-once external effects. Functions declared +with external side effects reject retry policies. Calls that return +successfully are not repeated by this policy; infrastructure recovery and +later refreshes have separate replay behavior. + +Each failed callable invocation has one attempt budget. After exhaustion, +the refresh's `error_policy` applies. With an explicit retry policy, `skip` +on a batch Function writes nulls for every row in the failed call and records +their errors. It does not split that call into smaller retries with new +budgets. A row Function handles each row separately. Error records expose +`attempts` when the server records it; older records may omit the count. + +Worker recovery uses a separate retry budget. Framework deadlines and +cancellation stop execution without consuming further user-error retries. +*/} + ## What gets packaged {#packaging} diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index f1ddfda52..2208fd612 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -42,6 +42,7 @@ from .functions import ( FunctionBinding as FunctionBinding, FunctionDefinition as FunctionDefinition, FunctionRegistrationRequest as FunctionRegistrationRequest, + FunctionRetryPolicy as FunctionRetryPolicy, FunctionVersion as FunctionVersion, HuggingFaceModel as HuggingFaceModel, PythonRuntimeSpec as PythonRuntimeSpec, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index f17856f3c..d1cee5091 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -617,6 +617,8 @@ class Table: batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[str] = None, + error_policy: Optional[str] = None, ) -> RefreshColumnResult: ... async def refresh_column_async( self, @@ -625,6 +627,8 @@ class Table: batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[str] = None, + error_policy: Optional[str] = None, ) -> Job: ... async def function_errors( self, @@ -1008,6 +1012,7 @@ class RefreshColumnResult: version: int class FunctionErrorRecord: + attempts: Optional[int] job_id: str fragment_id: int row_offset: Optional[int] @@ -1206,3 +1211,5 @@ class AuthzObject: ) -> AuthzObject: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... + +def validate_function_retry_policy(json: str) -> None: ... diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 4fa3340d5..4dad618ba 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -213,6 +213,45 @@ class _OpenRemoteValue(_RemoteValue): return set((self.__pydantic_extra__ or {}).keys()) +class FunctionRetryPolicy(_RemoteValue): + """Bound retries of selected errors inside one Enterprise Function call. + + ``max_attempts`` includes the first call. Matchers are alternatives; + ``transient=True`` selects connection/timeouts, HTTP 429/503 and the + provider codes ``SlowDown`` and ``ServiceUnavailable``. Exception names + may be qualified, and subclasses and wrapped causes also match. + + Backoff doubles with full jitter, bounded by ``max_backoff_seconds``. + Retry-After above that bound ends retries. A failed batch is retried as + one call: under ``skip``, exhaustion nulls every row in that call. + Completed calls are never repeated. Only opt in when repeating partial + work is safe; this does not make external side effects exactly once. + + >>> policy = FunctionRetryPolicy(transient=True, max_attempts=3) + >>> policy.max_attempts + 3 + >>> disabled = FunctionRetryPolicy(max_attempts=1) + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + max_attempts: Annotated[int, Field(strict=True)] = 3 + initial_backoff_seconds: Annotated[float, Field(strict=True)] = 0.2 + max_backoff_seconds: Annotated[float, Field(strict=True)] = 30.0 + exception_types: tuple[str, ...] = () + message_pattern: Optional[str] = None + error_codes: tuple[str, ...] = () + transient: Annotated[bool, Field(strict=True)] = False + honor_retry_after: Annotated[bool, Field(strict=True)] = True + + @model_validator(mode="after") + def _validate_policy(self): + from ._lancedb import validate_function_retry_policy + + validate_function_retry_policy(self.model_dump_json()) + return self + + class FunctionArtifact(_RemoteValue): """Content-addressed Python artifact identity.""" @@ -653,6 +692,7 @@ class FunctionRegistrationRequest(_RemoteValue): runtime: PythonRuntimeSpec batch_size: Optional[int] = None row_timeout_seconds: Optional[float] = None + retry_policy: Optional[FunctionRetryPolicy] = None secret_bindings: tuple[SecretBinding, ...] = () models: tuple[HuggingFaceModel, ...] = () @@ -2108,6 +2148,7 @@ class FunctionDefinition: python_version: Optional[str], batch_size: Optional[int] = None, row_timeout_seconds: Optional[float] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, gpu_class: Optional[str] = None, conda: tuple[str, ...] = (), @@ -2254,6 +2295,7 @@ class FunctionDefinition: runtime=runtime, batch_size=batch_size, row_timeout_seconds=row_timeout_seconds, + retry_policy=retry_policy, models=models, ) # A class's own __dict__ holds its methods; copying it would shadow @@ -2351,6 +2393,7 @@ def function( python_version: Optional[str] = None, batch_size: Optional[int] = None, row_timeout_seconds: Optional[float] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, gpu_class: Optional[str] = None, conda: tuple[str, ...] | list[str] = (), @@ -2373,6 +2416,7 @@ def function( python_version: Optional[str] = None, batch_size: Optional[int] = None, row_timeout_seconds: Optional[float] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, gpu_class: Optional[str] = None, conda: tuple[str, ...] | list[str] = (), @@ -2504,6 +2548,11 @@ def function( scalar Functions and one batch for vectorized Functions. This does not govern class initialization. When omitted, the service applies its default per-call budget. + retry_policy : FunctionRetryPolicy, optional + Retry selected failed calls inside the Function, with bounded attempts + and backoff. A refresh may override this default. Retrying a partial + call must be safe; completed calls are not repeated. For batch Functions, + skip after exhaustion applies to the whole failed call. gpu : bool, default False Whether every remote execution requires a GPU. The execution platform selects one compatible GPU for each worker. The requirement is part of @@ -2631,6 +2680,7 @@ def function( python_version=python_version, batch_size=batch_size, row_timeout_seconds=row_timeout_seconds, + retry_policy=retry_policy, gpu=gpu, gpu_class=gpu_class, conda=tuple(conda), @@ -2657,6 +2707,7 @@ __all__ = [ "FunctionOutput", "FunctionParameter", "FunctionRegistrationRequest", + "FunctionRetryPolicy", "FunctionResultField", "FunctionSignature", "FunctionImage", diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index db74c5375..c916fcb92 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -48,7 +48,11 @@ from lancedb.index import ( LabelList, ) from lancedb.job import Job -from lancedb.functions import FunctionApplication, RefreshColumnResult +from lancedb.functions import ( + FunctionApplication, + FunctionRetryPolicy, + RefreshColumnResult, +) from lancedb.remote.db import LOOP from lancedb.table import IndexConfigType, _maybe_add_fts_error_note import pyarrow as pa @@ -1137,6 +1141,8 @@ class RemoteTable(Table): batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ): return LOOP.run( self._table.refresh_column( @@ -1144,6 +1150,8 @@ class RemoteTable(Table): batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, ) ) @@ -1154,6 +1162,8 @@ class RemoteTable(Table): batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ) -> Job[RefreshColumnResult]: return Job( LOOP.run( @@ -1162,6 +1172,8 @@ class RemoteTable(Table): batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, ) ) ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 59876a8c3..559552cee 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -82,6 +82,7 @@ from .index import ( ) from .expr import Expr from .functions import ( + FunctionRetryPolicy, FunctionApplication, RefreshColumnResult as RefreshColumnJobResult, ) @@ -3166,6 +3167,8 @@ class Table(ABC): batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ) -> "RefreshColumnResult": """ Fill the rows of a computed column that hold no value yet. @@ -3199,6 +3202,13 @@ class Table(ABC): Positive aggregate GPU budget for Function workers. None leaves the server's configured budget unchanged. LanceDB Enterprise only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. Returns ------- @@ -3215,6 +3225,8 @@ class Table(ABC): batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ) -> Job[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -3247,6 +3259,13 @@ class Table(ABC): Positive aggregate GPU budget for Function workers. None leaves the server's configured budget unchanged. LanceDB Enterprise only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. Returns ------- @@ -5358,6 +5377,8 @@ class LanceTable(Table): batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose inputs changed. See @@ -5368,6 +5389,8 @@ class LanceTable(Table): batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, ) ) @@ -5378,6 +5401,8 @@ class LanceTable(Table): batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ) -> Job[RefreshColumnJobResult]: """Fill a computed column's unfilled rows and recompute those whose inputs changed, returning a handle to the refresh job. See @@ -5390,6 +5415,8 @@ class LanceTable(Table): batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, + retry_policy=retry_policy, + error_policy=error_policy, ) ) ) @@ -7745,6 +7772,8 @@ class AsyncTable: batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ) -> RefreshColumnResult: """ Fill the rows of a computed column that hold no value yet. @@ -7778,6 +7807,13 @@ class AsyncTable: Positive aggregate GPU budget for Function workers. None leaves the server's configured budget unchanged. LanceDB Enterprise only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. Returns ------- @@ -7789,6 +7825,10 @@ class AsyncTable: batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, + retry_policy=None + if retry_policy is None + else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), + error_policy=error_policy, ) async def function_errors( @@ -7887,6 +7927,8 @@ class AsyncTable: batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, + retry_policy: Optional[FunctionRetryPolicy] = None, + error_policy: Optional[Literal["fail", "skip"]] = None, ) -> AsyncJob[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -7919,6 +7961,13 @@ class AsyncTable: Positive aggregate GPU budget for Function workers. None leaves the server's configured budget unchanged. LanceDB Enterprise only. + retry_policy: FunctionRetryPolicy, optional + Override retries of failed user-code calls. Only use when repeating + partial work is safe. Set max_attempts=1 to disable retries. + Enterprise Functions only; local refreshes reject this option. + error_policy: {"fail", "skip"}, optional + Action after failure or retry exhaustion. Skip records the error + and attempt count, subject to the server's failure limits. Returns ------- @@ -7947,6 +7996,10 @@ class AsyncTable: batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, + retry_policy=None + if retry_policy is None + else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), + error_policy=error_policy, ), RefreshColumnJobResult.from_json, ) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 238d787d1..9b435b256 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -159,6 +159,34 @@ def test_function_execution_controls_apply_to_vectorized_functions(): assert request["row_timeout_seconds"] == 1.25 +def test_function_retry_policy_is_part_of_registration(): + policy = lancedb.FunctionRetryPolicy(transient=True, max_attempts=4) + definition = function(retry_policy=policy)(normalize_score.__wrapped__) + request = json.loads(definition.registration_request.to_canonical_json()) + assert request["retry_policy"] == {"max_attempts": 4, "transient": True} + assert lancedb.FunctionRetryPolicy(max_attempts=1).max_attempts == 1 + + +@pytest.mark.parametrize( + "options", + [ + {"max_attempts": 0, "transient": True}, + {"max_attempts": 101, "transient": True}, + {"max_attempts": True}, + {"max_attempts": 3}, + {"transient": True, "initial_backoff_seconds": -1}, + {"transient": True, "max_backoff_seconds": float("inf")}, + {"transient": True, "max_backoff_seconds": 0}, + {"message_pattern": "["}, + {"exception_types": [""]}, + {"transient": True, "typo": 1}, + ], +) +def test_function_retry_policy_rejects_invalid_options(options): + with pytest.raises(ValueError): + lancedb.FunctionRetryPolicy(**options) + + @pytest.mark.parametrize( ("options", "field"), [ diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index cd2261f04..994655ef9 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1825,6 +1825,11 @@ def test_remote_create_index_async_returns_job(): {"batch_size": 1}, {"batch_size": 8}, {"gpu_class": "a10g", "gpu_count": 2}, + { + "retry_policy": {"transient": True, "max_attempts": 3}, + "error_policy": "skip", + }, + {"retry_policy": {"max_attempts": 1}, "error_policy": "fail"}, ], ) async def test_remote_refresh_async_returns_typed_terminal_result( @@ -1849,6 +1854,12 @@ async def test_remote_refresh_async_returns_typed_terminal_result( expected["gpu_class"] = refresh_kwargs["gpu_class"] if refresh_kwargs.get("gpu_count") is not None: expected["gpu_count"] = refresh_kwargs["gpu_count"] + if refresh_kwargs.get("retry_policy") is not None: + expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate( + refresh_kwargs["retry_policy"] + ).model_dump(mode="json") + if refresh_kwargs.get("error_policy") is not None: + expected["error_policy"] = refresh_kwargs["error_policy"] assert json.loads(body) == expected request.send_response(202) request.send_header("Content-Type", "application/json") @@ -2010,10 +2021,12 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"gpu_class": "a_b"}, "gpu_class"), ({"gpu_count": 0}, "gpu_count"), ({"gpu_count": -1}, "gpu_count"), + ({"retry_policy": {"transient": True, "max_attempts": 0}}, "retry_policy"), + ({"error_policy": "retry"}, "error_policy"), ], ) @pytest.mark.asyncio -async def test_remote_refresh_rejects_invalid_gpu_options_before_request( +async def test_remote_refresh_rejects_invalid_options_before_request( refresh_kwargs, message ): backfill_requests = [] @@ -2062,7 +2075,8 @@ async def test_remote_refresh_rejects_invalid_gpu_options_before_request( assert backfill_requests == [] -def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): +@pytest.mark.parametrize("attempts", [None, 3]) +def test_remote_function_errors_lists_the_rows_a_refresh_skipped(attempts): listing = { "records": [ { @@ -2077,6 +2091,7 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): "table_version": 11, "error_type": "ValueError", "error_message": "bad input 'x'", + "attempts": attempts, "traceback": ( "Traceback (most recent call last):\nValueError: bad input 'x'" ), @@ -2127,6 +2142,7 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(): assert errors.records[0].row_id == 42 assert errors.records[0].row_address == 12884901897 assert errors.records[0].function_version == "2" + assert errors.records[0].attempts == attempts assert errors.records[0].traceback == ( "Traceback (most recent call last):\nValueError: bad input 'x'" ) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 88635c020..45ce9276e 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5984,6 +5984,14 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) getattr(table, method)("x", batch_size=batch_size) +@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"]) +def test_local_refresh_rejects_function_retry_policy(tmp_path, method): + table = lancedb.connect(tmp_path).create_table("rows", [{"x": 1}]) + policy = lancedb.FunctionRetryPolicy(transient=True) + with pytest.raises(NotImplementedError, match="Enterprise Function refresh"): + getattr(table, method)("x", retry_policy=policy) + + @pytest.mark.asyncio @pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"]) @pytest.mark.parametrize("batch_size", [0, -1]) diff --git a/python/src/lib.rs b/python/src/lib.rs index 0690d9622..27ff4cb01 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -145,6 +145,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(table::tokenize, m)?)?; m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?; m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?; m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?; m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?; m.add_function(wrap_pyfunction!(expr_col, m)?)?; diff --git a/python/src/table.rs b/python/src/table.rs index 44c8017c4..4c5a919d2 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -46,8 +46,22 @@ fn refresh_column_options( batch_size: Option, gpu_class: Option, gpu_count: Option, + retry_policy: Option, + error_policy: Option, ) -> PyResult { let mut options = RefreshColumnOptions::default(); + options.retry_policy = retry_policy + .map(|json| { + serde_json::from_str(&json) + .map_err(|error| PyValueError::new_err(format!("invalid retry_policy: {error}"))) + }) + .transpose()?; + options.error_policy = error_policy + .map(|value| { + serde_json::from_value(serde_json::Value::String(value)) + .map_err(|error| PyValueError::new_err(format!("invalid error_policy: {error}"))) + }) + .transpose()?; options.batch_size = batch_size .map(usize::try_from) .transpose() @@ -611,6 +625,7 @@ impl From for RefreshColumnResult { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrorRecord { + pub attempts: Option, pub job_id: String, pub fragment_id: u64, pub row_offset: Option, @@ -653,6 +668,7 @@ impl FunctionErrorRecord { impl From for FunctionErrorRecord { fn from(record: lancedb::function::FunctionErrorRecord) -> Self { Self { + attempts: record.attempts, job_id: record.job_id, fragment_id: record.fragment_id, row_offset: record.row_offset, @@ -2126,15 +2142,18 @@ impl Table { }) } - #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None))] + #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None))] pub fn refresh_column( self_: PyRef<'_, Self>, column: String, batch_size: Option, gpu_class: Option, gpu_count: Option, + retry_policy: Option, + error_policy: Option, ) -> PyResult> { - let options = refresh_column_options(batch_size, gpu_class, gpu_count)?; + let options = + refresh_column_options(batch_size, gpu_class, gpu_count, retry_policy, error_policy)?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let result = inner @@ -2145,15 +2164,18 @@ impl Table { }) } - #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None))] + #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None))] pub fn refresh_column_async( self_: PyRef<'_, Self>, column: String, batch_size: Option, gpu_class: Option, gpu_count: Option, + retry_policy: Option, + error_policy: Option, ) -> PyResult> { - let options = refresh_column_options(batch_size, gpu_class, gpu_count)?; + let options = + refresh_column_options(batch_size, gpu_class, gpu_count, retry_policy, error_policy)?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let job = inner diff --git a/python/src/util.rs b/python/src/util.rs index 2145c0f14..a956066f1 100644 --- a/python/src/util.rs +++ b/python/src/util.rs @@ -70,3 +70,14 @@ pub fn parse_field_path(path: &str) -> PyResult> { /// A wrapper around a LanceDB type to allow it to be used in Python #[derive(Debug, Clone)] pub struct PyLanceDB(pub T); +/// Validate the Function retry wire contract using the same rules as Rust APIs. +#[pyo3::pyfunction] +pub fn validate_function_retry_policy(json: &str) -> pyo3::PyResult<()> { + let policy: lancedb::function::FunctionRetryPolicy = + serde_json::from_str(json).map_err(|error| { + pyo3::exceptions::PyValueError::new_err(format!("invalid retry_policy: {error}")) + })?; + policy + .validate() + .map_err(|error| pyo3::exceptions::PyValueError::new_err(error.to_string())) +} diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 6063c34f3..41a683c54 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -16,6 +16,9 @@ use serde_json::Value; use crate::secrets::SecretBinding; use crate::{Error, Result}; +mod retry; +pub use retry::{FunctionErrorPolicy, FunctionRetryPolicy}; + /// Semantic Function type for a Blob v2 value. pub const FUNCTION_BLOB_V2_TYPE: &str = "blob_v2"; @@ -787,6 +790,9 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s /// database already holds, which Sophon resolves inside the remote runtime. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { + /// Default retries of failed user-code calls. Enterprise only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retry_policy: Option, pub name: String, pub artifact: FunctionArtifactRequest, pub signature: FunctionSignature, @@ -836,6 +842,9 @@ impl FunctionRegistrationRequest { }; validate_batch_size_value(self.batch_size).map_err(invalid_input)?; validate_row_timeout_value(self.row_timeout_seconds).map_err(invalid_input)?; + if let Some(policy) = &self.retry_policy { + policy.validate()?; + } Ok(()) } } @@ -1094,6 +1103,9 @@ impl FunctionErrorsRequest { /// read access to the table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrorRecord { + /// Number of user-code calls for this failed invocation, when recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub attempts: Option, /// The refresh job that recorded the error. pub job_id: String, /// The fragment holding the row. diff --git a/rust/lancedb/src/function/retry.rs b/rust/lancedb/src/function/retry.rs new file mode 100644 index 000000000..b52d59d2b --- /dev/null +++ b/rust/lancedb/src/function/retry.rs @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Client configuration for retries inside an Enterprise Function invocation. + +use serde::{Deserialize, Serialize}; + +use crate::{Error, Result}; + +/// Retry selected user-code errors without consuming a worker retry attempt. +/// +/// A retry repeats the entire failed call, so opt in only when repeating its +/// partial work is safe. Matchers are alternatives. With a batch Function and +/// `skip`, an exhausted call skips the whole batch rather than bisecting it. +/// +/// ``` +/// use lancedb::function::FunctionRetryPolicy; +/// let policy = FunctionRetryPolicy::transient(); +/// policy.validate().unwrap(); +/// ``` +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(default, deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRetryPolicy { + /// Total calls, including the first; 1 disables retries, maximum 100. + pub max_attempts: u32, + /// Initial exponential-backoff ceiling, with full jitter; default 0.2 seconds. + pub initial_backoff_seconds: f64, + /// Maximum backoff, including Retry-After; default 30 seconds, maximum 3600. + pub max_backoff_seconds: f64, + /// Exception class names, preferably qualified; subclasses also match. + pub exception_types: Vec, + /// Regular expression matched against the exception class and message. + pub message_pattern: Option, + /// Structured provider error codes or HTTP status codes, represented as strings. + pub error_codes: Vec, + /// Match connection/timeouts, HTTP 429/503, SlowDown and ServiceUnavailable. + pub transient: bool, + /// Honor Retry-After within the configured maximum; default true. + pub honor_retry_after: bool, +} + +impl Default for FunctionRetryPolicy { + fn default() -> Self { + Self { + max_attempts: 3, + initial_backoff_seconds: 0.2, + max_backoff_seconds: 30.0, + exception_types: Vec::new(), + message_pattern: None, + error_codes: Vec::new(), + transient: false, + honor_retry_after: true, + } + } +} + +impl FunctionRetryPolicy { + /// Retry known transient errors up to three calls with bounded backoff. + pub fn transient() -> Self { + Self { + transient: true, + ..Self::default() + } + } + + /// Validate before registration or refresh submission. + pub fn validate(&self) -> Result<()> { + let invalid = |message: String| Error::InvalidInput { message }; + if !(1..=100).contains(&self.max_attempts) { + return Err(invalid(format!( + "retry_policy.max_attempts must be between 1 and 100, got {}", + self.max_attempts + ))); + } + for (name, value) in [ + ("initial_backoff_seconds", self.initial_backoff_seconds), + ("max_backoff_seconds", self.max_backoff_seconds), + ] { + if !value.is_finite() || !(0.0..=3600.0).contains(&value) { + return Err(invalid(format!( + "retry_policy.{name} must be finite and between 0 and 3600, got {value}" + ))); + } + } + if self.initial_backoff_seconds > self.max_backoff_seconds { + return Err(invalid( + "retry_policy.initial_backoff_seconds exceeds max_backoff_seconds".into(), + )); + } + if self + .exception_types + .iter() + .chain(&self.error_codes) + .any(String::is_empty) + { + return Err(invalid( + "retry_policy exception_types and error_codes must contain non-empty strings" + .into(), + )); + } + if let Some(pattern) = &self.message_pattern { + regex::Regex::new(pattern).map_err(|error| { + invalid(format!("invalid retry_policy.message_pattern: {error}")) + })?; + } + if self.max_attempts > 1 + && !self.transient + && self.message_pattern.is_none() + && self.exception_types.is_empty() + && self.error_codes.is_empty() + { + return Err(invalid( + "retry_policy requires at least one error matcher".into(), + )); + } + Ok(()) + } +} + +/// What a Function refresh does after a call fails or exhausts retries. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionErrorPolicy { + /// Fail the refresh job. + Fail, + /// Write null and record the error, subject to the server's failure limits. + Skip, +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + use serde_json::json; + + #[rstest] + #[case(json!({"max_attempts": 0, "transient": true}))] + #[case(json!({"max_attempts": 101, "transient": true}))] + #[case(json!({"max_attempts": 3}))] + #[case(json!({"initial_backoff_seconds": -1, "transient": true}))] + #[case(json!({"max_backoff_seconds": 0, "transient": true}))] + #[case(json!({"exception_types": [""]}))] + #[case(json!({"message_pattern": "["}))] + fn reject_invalid_policy(#[case] value: serde_json::Value) { + let policy: FunctionRetryPolicy = serde_json::from_value(value).unwrap(); + assert!(policy.validate().is_err()); + } + + #[test] + fn policy_defaults_and_disabled_policy() { + assert!(FunctionRetryPolicy::transient().validate().is_ok()); + let policy: FunctionRetryPolicy = + serde_json::from_value(json!({"max_attempts":1})).unwrap(); + assert!(policy.validate().is_ok()); + let mut invalid = policy; + invalid.initial_backoff_seconds = f64::NAN; + assert!(invalid.validate().is_err()); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 6534f5519..5dee8eb1d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3977,6 +3977,12 @@ impl BaseTable for RemoteTable { if let Some(gpu_count) = options.gpu_count { body["gpu_count"] = serde_json::json!(gpu_count); } + if let Some(policy) = options.retry_policy { + body["retry_policy"] = serde_json::json!(policy); + } + if let Some(policy) = options.error_policy { + body["error_policy"] = serde_json::json!(policy); + } self.apply_branch_body(&mut body); let request = self .client @@ -10980,6 +10986,38 @@ mod tests { assert_eq!(job.id(), Some("j-gpu")); } + #[tokio::test] + async fn test_refresh_column_async_retry_policy() { + use crate::function::{FunctionErrorPolicy, FunctionRetryPolicy}; + use crate::table::RefreshColumnOptions; + let policy = FunctionRetryPolicy::transient(); + let expected_policy = serde_json::to_value(&policy).unwrap(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column":"quality", "retry_policy": expected_policy, "error_policy":"skip", + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-retry"}"#.to_string()) + .unwrap() + }); + let options = RefreshColumnOptions::default() + .retry_policy(policy) + .error_policy(FunctionErrorPolicy::Skip); + assert_eq!( + table + .refresh_column_async_with_options("quality", options) + .await + .unwrap() + .id(), + Some("j-retry") + ); + } + #[tokio::test] async fn test_refresh_column_rejects_invalid_gpu_options_before_request() { use crate::table::RefreshColumnOptions; @@ -11120,7 +11158,7 @@ mod tests { "column": "embedding", "function": "embed", "function_version": "2", "table_version": 11, "error_type": "ValueError", "error_message": "bad input 'x'", "traceback": "Traceback (most recent call last):\nValueError: bad input 'x'", - "created_at_millis": 1700000000000}], + "created_at_millis": 1700000000000, "attempts": 3}], "fragments": [{"job_id": "j-7", "fragment_id": 4, "rows_skipped": 500, "rows_recorded": 100}], "truncated": true}"#, @@ -11140,6 +11178,7 @@ mod tests { assert_eq!( errors.records, [FunctionErrorRecord { + attempts: Some(3), job_id: "j-7".into(), fragment_id: 3, row_offset: Some(9), diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 34846d33e..94a934c43 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -891,6 +891,12 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { options: RefreshColumnOptions, ) -> Result { options.validate()?; + if options.retry_policy.is_some() || options.error_policy.is_some() { + return Err(Error::NotSupported { + message: "Function retry and error policies require an Enterprise Function refresh" + .into(), + }); + } self.refresh_column(column).await } /// Fill a computed column's unfilled rows and recompute those whose @@ -910,6 +916,12 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { options: RefreshColumnOptions, ) -> Result> { options.validate()?; + if options.retry_policy.is_some() || options.error_policy.is_some() { + return Err(Error::NotSupported { + message: "Function retry and error policies require an Enterprise Function refresh" + .into(), + }); + } self.refresh_column_async(column).await } /// The per-row errors Function refreshes recorded on this table; see diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 330cdfb6d..a9e69452d 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -59,6 +59,10 @@ use crate::{Error, Result}; #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct RefreshColumnOptions { + /// Override the Function's default user-code retry policy. Enterprise only. + pub retry_policy: Option, + /// Action after user-code failure or retry exhaustion. Enterprise only. + pub error_policy: Option, /// Maximum rows per Function call in LanceDB Enterprise. /// /// Must be greater than zero. `None` uses the server default. This has no @@ -77,6 +81,17 @@ pub struct RefreshColumnOptions { } impl RefreshColumnOptions { + /// Override retries of failed Function calls for this refresh. + pub fn retry_policy(mut self, policy: crate::function::FunctionRetryPolicy) -> Self { + self.retry_policy = Some(policy); + self + } + + /// Select fail or skip after the retry policy is exhausted. + pub fn error_policy(mut self, policy: crate::function::FunctionErrorPolicy) -> Self { + self.error_policy = Some(policy); + self + } /// Limit each Function call to at most `batch_size` rows. pub fn batch_size(mut self, batch_size: usize) -> Self { self.batch_size = Some(batch_size); @@ -97,6 +112,9 @@ impl RefreshColumnOptions { /// Validate client-side constraints before any request is sent. pub fn validate(&self) -> Result<()> { + if let Some(policy) = &self.retry_policy { + policy.validate()?; + } if self.batch_size == Some(0) { return Err(Error::InvalidInput { message: "batch_size must be greater than zero".into(), From a2abfbced7d1d78cec6966d20bd881b1749cc7c2 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 6 Nov 2026 02:45:54 +0800 Subject: [PATCH 026/203] fix(python): warn when Function dependencies cannot be verified (#4879) Functions that import a module unavailable on the client currently package silently even when they declare no pip/conda dependencies. Emit an advisory warning for these unresolved imports so callers can declare the required package or confirm that the base image supplies it. Any pip/conda declaration suppresses this new advisory because distribution names need not match import names. The warning does not claim that the module is absent remotely and follows normal Python warning filters, including warnings-as-errors. Validation includes the original `import scipy.ndimage` with `pip=()` through the public decorator/packager path, plus declared-package and existing local-source controls. This does not establish remote image availability or deployment acceptance. Refs ENT-3448. --- python/python/lancedb/functions.py | 38 +++++--- .../python/tests/test_function_packaging.py | 88 +++++++++++++++++++ 2 files changed, 115 insertions(+), 11 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 4dad618ba..fe5a1a45a 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1878,9 +1878,12 @@ class _SourcePackager: return f"{name} = {_literal_source(value)}" def _require_importable(self, module_name: str) -> None: - """Warn about an import the Function's environment likely cannot - satisfy: a module that lives in a local source tree, is not shipped - with ``code=``, and names no declared package. + """Warn about an import the Function's environment may not be able to + satisfy. + + An unresolved module warns only when the Function declares no package + dependencies. A local source module warns unless ``code=`` ships it or + a declared requirement matches its top-level name. A warning rather than an error: a distribution name need not match the module it installs, so a declared package can still provide the @@ -1896,8 +1899,19 @@ class _SourcePackager: ): return locations = _module_locations_for_name(top) + if not locations: + if not self._requirements: + self._warned_imports.add(top) + warnings.warn( + f"@function source imports {top!r}, which is unavailable in the " + "client environment and has no declared pip/conda dependencies. " + "Remote availability cannot be verified; declare the required " + "package or confirm that the base image provides it.", + UserWarning, + ) + return roots = _installed_roots() - if not locations or any(location.startswith(roots) for location in locations): + if any(location.startswith(roots) for location in locations): return self._warned_imports.add(top) warnings.warn( @@ -2482,13 +2496,15 @@ def function( A module imported by the packaged source -- including a direct ``import`` inside a function or method body -- draws a warning at registration when - it resolves to local source outside ``code`` and no declared requirement - matches the imported module name. The client cannot reliably validate - imports provided only by the base image: ``pip``/``conda`` distribution - names need not match the modules they install, and the client does not - know the contents of a built or custom image. Declare every third-party - import in ``pip`` or ``conda`` even when it happens to be installed on the - registration host. + the client cannot resolve its top-level module and declares no package + dependencies, or when it resolves to local source outside ``code`` and + no declared requirement matches the imported module name. The warning + does not assert that the remote environment lacks the module: + ``pip``/``conda`` distribution names need not match the modules they + install, and the client cannot inspect the contents of a base or custom + image. Warnings follow normal Python warning filters and may be promoted + to errors. Declare every third-party import in ``pip`` or ``conda`` even + when it happens to be installed on the registration host. Closures, lambdas, nested definitions, mutable module-level objects, code that reaches the module namespace another way (``globals()``/``eval``, ``sys.modules``, ``builtins``), and a diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index f61d306f7..050aeb3ea 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -575,6 +575,94 @@ def test_local_module_imported_in_function_body_warns_at_registration( assert "import fx_body_local" in artifact(installed).decode() +def test_missing_module_without_declared_package_warns_at_registration( + tmp_path, monkeypatch +): + package = "fx_missing_remote_package_ent3448" + monkeypatch.syspath_prepend(str(tmp_path)) + + def define(name): + (tmp_path / f"{name}.py").write_text( + textwrap.dedent( + f""" + from lancedb import function + + + @function(pip=()) + def {name}(value: int) -> int: + import {package}.plugin + + return value + """ + ) + ) + importlib.invalidate_caches() + return getattr(importlib.import_module(name), name) + + with pytest.warns(UserWarning) as caught: + definition = define("fx_uses_missing_package") + + message = str(caught[0].message) + assert f"imports {package!r}" in message + assert "unavailable in the client environment" in message + assert "no declared pip/conda dependencies" in message + assert "Remote availability cannot be verified" in message + assert "confirm that the base image provides it" in message + assert "cannot import" not in message + assert f"import {package}.plugin" in artifact(definition).decode() + + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + with pytest.raises(UserWarning, match="Remote availability cannot be verified"): + define("fx_missing_package_as_error") + + +def test_resolved_or_declared_module_imports_do_not_warn(tmp_path, helper_package): + package = "fx_missing_remote_package_ent3448" + helper_package("fx_declared_code_package", {"__init__.py": ""}) + + def define(name, body, options, imports=""): + (tmp_path / f"{name}.py").write_text( + textwrap.dedent( + f""" + {imports} + from lancedb import function + + + @function({options}) + def {name}(value: int) -> int: + {body} + return value + """ + ) + ) + importlib.invalidate_caches() + return getattr(importlib.import_module(name), name) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + define("fx_imports_stdlib", "import os.path", "") + # Distribution names need not match the imported top-level module. + define( + "fx_imports_declared_pip", + f"import {package}.plugin", + "pip=['Pillow>=10']", + ) + define( + "fx_imports_declared_conda", + f"import {package}.plugin", + "conda=['numpy']", + ) + define( + "fx_imports_shipped_code", + "import fx_declared_code_package", + "code=[fx_declared_code_package]", + "import fx_declared_code_package", + ) + + assert not caught + + MMLB_HELPERS = { "__init__.py": "", "rate.py": """ From 0d7297718623f371226dd478109ccbcb6cfda53a Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:20:20 -0800 Subject: [PATCH 027/203] fix: avoid retrying remote branch deletions (#4854) --- docs/src/python/python.md | 12 ++++- python/python/lancedb/remote/errors.py | 18 +++++++ python/python/tests/test_errors.py | 18 +++++++ python/python/tests/test_remote_db.py | 38 ++++++++++++++ rust/lancedb/src/remote/table.rs | 71 +++++++++++++++++++++++++- 5 files changed, 154 insertions(+), 3 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index eb2c8d1db..3658f2ad3 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -813,8 +813,8 @@ so the fetch APIs cannot read their bytes yet. ## Exceptions Remote HTTP responses with structured resource details raise a subclass of -`HttpError`. Older servers that omit those details raise plain `HttpError`, so -`except HttpError` remains a compatible catch-all: +`HttpError`. Older servers that omit those details generally raise plain +`HttpError`, so `except HttpError` remains a compatible catch-all: ```python from lancedb.remote.errors import ( @@ -835,6 +835,12 @@ except HttpError as error: print("request failed:", error.request_id, error.status_code) ``` +Remote branch deletion sends a single request. If the server rejects it with +HTTP 409, it raises `ConflictError` with the server's reason, including when an +older server omits structured resource details. A structured `already_exists` +response keeps its more specific `AlreadyExistsError` type. Both are subclasses +of `HttpError`. + SQL response failures raise `SqlError`, retaining the numeric `grpc_code` and `request_id`. Servers that report a recognized `x-lancedb-error-code` select a specific input-error subclass. HTTP failures use the corresponding `HttpError` @@ -900,6 +906,8 @@ generic HTTP/SQL exceptions with their transport status and current request ID. ::: lancedb.remote.errors.AlreadyExistsError +::: lancedb.remote.errors.ConflictError + ::: lancedb.exceptions.MissingValueError ::: lancedb.exceptions.MissingColumnError diff --git a/python/python/lancedb/remote/errors.py b/python/python/lancedb/remote/errors.py index 56b5cc34d..4dc835e53 100644 --- a/python/python/lancedb/remote/errors.py +++ b/python/python/lancedb/remote/errors.py @@ -149,6 +149,8 @@ def _http_error_class( return input_class if error_code == "already_exists": return AlreadyExistsError + if status_code == 409: + return ConflictError if error_code != "not_found" or resource_kind is None: return None return { @@ -268,6 +270,22 @@ class AlreadyExistsError(HttpError): """A remote resource already exists.""" +class ConflictError(HttpError): + """A remote operation conflicts with the current state of a resource. + + For example, deleting a branch whose files are still needed by another + branch raises this error. The server's reason is included in the message. + + Examples + -------- + >>> error = HttpError("main depends on the branch's files", "req-1", 409) + >>> isinstance(error, ConflictError) + True + >>> error.status_code + 409 + """ + + class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError): """A remote table was not found. diff --git a/python/python/tests/test_errors.py b/python/python/tests/test_errors.py index 8721a2bb7..d5e92731f 100644 --- a/python/python/tests/test_errors.py +++ b/python/python/tests/test_errors.py @@ -10,6 +10,7 @@ from lance_namespace.errors import TableNotFoundError as NamespaceTableNotFoundE from lancedb.db import DBConnection from lancedb.remote.errors import ( AlreadyExistsError, + ConflictError, FunctionNotFoundError, HttpError, LanceDBClientError, @@ -72,6 +73,20 @@ def test_pickle_http_transport_error(): assert restored.request_id == "req-789" +@pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"]) +def test_http_conflict_error_preserves_reason_and_metadata(error_code): + reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files" + original = HttpError(reason, "req-conflict", 409, error_code) + for error in [original, pickle.loads(pickle.dumps(original))]: + assert type(error) is ConflictError + assert isinstance(error, HttpError) + assert str(error) == reason + assert error.request_id == "req-conflict" + assert error.status_code == 409 + assert error.error_code == error_code + assert error.is_transport_error is False + + @pytest.mark.parametrize( "error_code,resource_kind,status_code,expected_type", [ @@ -251,6 +266,9 @@ def test_sql_errors_use_only_server_codes(code, category, type_name): (400, "schema_mismatch", "SchemaMismatchError"), (404, "table_not_found", "TableNotFoundError"), (404, "reference_not_found", "ReferenceNotFoundError"), + (409, None, "ConflictError"), + (409, "conflict", "ConflictError"), + (500, "conflict", "HttpError"), (500, "column_not_found", "HttpError"), (503, "table_not_found", "HttpError"), ], diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 994655ef9..8e6d74e86 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -45,6 +45,7 @@ from lancedb.query import ( from lancedb.remote import ClientConfig from lancedb.remote.errors import ( AlreadyExistsError, + ConflictError, HttpError, NamespaceNotFoundError, RetryError, @@ -733,6 +734,43 @@ def test_remote_table_branches_sync(): table.branches.delete("exp") +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("json_response", [False, True]) +async def test_remote_branch_delete_conflict_is_not_retried(use_async, json_response): + request_ids = [] + reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files" + + def handler(request): + if request.path == "/v1/table/test/describe/": + _branch_open_handler(request) + return + + assert request.path == "/v1/table/test/branches/delete/" + content_len = int(request.headers["Content-Length"]) + assert json.loads(request.rfile.read(content_len)) == {"name": "exp"} + request_ids.append(request.headers["x-request-id"]) + request.send_response(409) + request.end_headers() + body = json.dumps({"code": 14, "error": reason}) if json_response else reason + request.wfile.write(body.encode()) + + if use_async: + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + with pytest.raises(ConflictError, match=re.escape(reason)) as exc_info: + await table.branches.delete("exp") + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + with pytest.raises(ConflictError, match=re.escape(reason)) as exc_info: + table.branches.delete("exp") + + assert request_ids == [exc_info.value.request_id] + assert exc_info.value.status_code == 409 + assert isinstance(exc_info.value, HttpError) + + def test_remote_table_cherry_pick_defaults_to_execute(): cherry_pick_bodies = [] diff = { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 5dee8eb1d..895cc9f12 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2796,7 +2796,9 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/branches/delete/", self.identifier)) .json(&serde_json::json!({ "name": name })); - let (request_id, response) = self.send(request, true).await?; + // Deletion is not idempotent: preserve conflicts and partial failures + // instead of replaying a request that may already have removed the ref. + let (request_id, response) = self.send(request, false).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::TableNotFound { name: format!("{} (branch: {})", self.name, name), @@ -16007,6 +16009,73 @@ mod tests { assert!(matches!(err, Error::TableNotFound { .. }), "got {err:?}"); } + #[tokio::test] + async fn test_delete_branch_conflict_is_not_retried() { + let requests = Arc::new(AtomicUsize::new(0)); + let captured = requests.clone(); + let reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"; + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/branches/delete/"); + captured.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(409) + .body(json!({ "code": 14, "error": reason }).to_string()) + .unwrap() + }); + + let err = table.delete_branch("exp").await.unwrap_err(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert!(err.to_string().contains(reason), "got {err:?}"); + assert!( + matches!( + err, + Error::Http { + status_code: Some(StatusCode::CONFLICT), + .. + } + ), + "expected the original conflict, got {err:?}" + ); + } + + #[tokio::test] + async fn test_delete_branch_partial_failure_is_not_retried() { + let requests = Arc::new(AtomicUsize::new(0)); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |_| { + // The ref was removed before the first response failed. Replaying + // the deletion would hide that failure behind a missing-branch error. + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + http::Response::builder() + .status(500) + .body("failed after removing branch ref") + .unwrap() + } else { + http::Response::builder() + .status(404) + .body("no such branch") + .unwrap() + } + }); + + let err = table.delete_branch("exp").await.unwrap_err(); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert!( + err.to_string().contains("failed after removing branch ref"), + "got {err:?}" + ); + assert!( + matches!( + err, + Error::Http { + status_code: Some(StatusCode::INTERNAL_SERVER_ERROR), + .. + } + ), + "expected the original server error, got {err:?}" + ); + } + fn sample_branch_diff_json() -> &'static str { r#"{ "fromBranch":"exp", From 4fac811028423f74ac8611e492473f70ae58794f Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 5 Nov 2026 14:45:32 -0800 Subject: [PATCH 028/203] ci: pass release workflow inputs through env vars (#4884) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary `make-release-commit.yml` interpolated `workflow_dispatch` inputs directly into `run:` scripts with `${{ }}`, which Aikido flags as template injection. This passes them through environment variables instead, so the shell never parses their values as code. ```diff - bash ci/bump_version.sh ${{ inputs.type }} ${{ inputs.bump-minor }} + bash ci/bump_version.sh "$RELEASE_TYPE" "$BUMP_MINOR" ``` The "Output Inputs" step gets the same treatment. This is hardening rather than a fix for an exploitable bug: the inputs are a choice and two booleans, and only users with write access can dispatch the workflow. ## Evidence Aikido local scan of the workflow: before, it reports "Template Injection in GitHub Workflows Action" (severity 80) on the Bump version step; after, that finding is gone. ## Merge Risk **Door:** Two-way. The values passed to `bump_version.sh` are the same strings as before. **Blast Radius:** release workflow 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .github/workflows/make-release-commit.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/make-release-commit.yml b/.github/workflows/make-release-commit.yml index c7187a6c7..a35bff7f1 100644 --- a/.github/workflows/make-release-commit.yml +++ b/.github/workflows/make-release-commit.yml @@ -39,7 +39,9 @@ jobs: contents: write steps: - name: Output Inputs - run: echo "${{ toJSON(github.event.inputs) }}" + env: + INPUTS_JSON: ${{ toJSON(github.event.inputs) }} + run: echo "$INPUTS_JSON" - uses: actions/checkout@v6 with: fetch-depth: 0 @@ -59,9 +61,11 @@ jobs: - name: Bump version env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TYPE: ${{ inputs.type }} + BUMP_MINOR: ${{ inputs.bump-minor }} run: | pip install bump-my-version PyGithub packaging - bash ci/bump_version.sh ${{ inputs.type }} ${{ inputs.bump-minor }} + bash ci/bump_version.sh "$RELEASE_TYPE" "$BUMP_MINOR" release_tag=$(git describe --tags --exact-match HEAD) bash ci/update_lockfiles.sh --amend # Keep the unpublished tag on the commit that includes the synced lockfile. From 2f496529ca39779468093d57abe2c71df263b2c9 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 5 Nov 2026 15:29:11 -0800 Subject: [PATCH 029/203] chore: bump dependencies with critical security advisories (#4883) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Bumps dependencies that Aikido flags with critical advisories, where a patched version is available without code changes. | Package | Where | From → To | Ships to users | |---|---|---|---| | jackson (BOM) | `java/pom.xml` | 2.18.11 → 2.18.12 | Yes, via the published pom | | zerovec / zerovec-derive | `Cargo.lock` | 0.11.6 → 0.11.8 / 0.11.3 → 0.11.7 | Yes, linked into the wheels and Node binaries | | pillow | `python/uv.lock` | 12.3.0 → 13.0.0 | No, dev lockfile | | pyarrow | `python/uv.lock` | 24.0.0 → 26.0.1 | No, dev lockfile | | pyjwt, urllib3, anyio, cryptography | `python/uv.lock` | → 2.15.1, 2.8.0, 4.16.0, 50.0.2 | No, dev lockfile | | pillow | `docs/web-tests/blob-v2/py/requirements.txt` | 12.1.1 → 13.0.0 | No | pyarrow was held at 24.0.0 by a `pyarrow<25` pin in the `tests` extra. It came in with #3675 without a stated reason, so this PR removes it. pillow 13 and pyarrow 26 require Python 3.11+, so the lockfile keeps pillow 12.3.0 and pyarrow 25.0.1 on Python 3.10, and those remain flagged. The sharp findings in the Node examples and docs are not addressed here. They come from the `@huggingface/transformers@3.0.2` optional dependency, which needs a major upgrade to 4.3+. ## Evidence With the pyarrow pin removed and pyarrow 26.0.1 installed, the Python suite (`-m "not slow and not s3_test"`) passed locally on Python 3.12: 3319 passed, 164 skipped. That run was on main as of #4879; this branch is based on a slightly newer main. ## Merge Risk **Door:** Two-way. Patch and minor version bumps that a revert undoes. **Blast Radius:** Java consumers (jackson patch release), native binaries (zerovec patch release), Python test environments. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 35 +- docs/web-tests/blob-v2/py/requirements.txt | 2 +- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 611 ++++++++++++++------- 5 files changed, 431 insertions(+), 221 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9735eebb1..c97a1fc5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10632,6 +10632,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "sysctl" version = "0.6.0" @@ -12582,9 +12593,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -12593,14 +12604,14 @@ 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", - "synstructure", + "syn 3.0.3", + "synstructure 0.14.0", ] [[package]] @@ -12641,7 +12652,7 @@ dependencies = [ "proc-macro2", "quote", "syn 2.0.117", - "synstructure", + "synstructure 0.13.2", ] [[package]] @@ -12664,9 +12675,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.6" +version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ "serde", "yoke", @@ -12676,13 +12687,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.3", ] [[package]] diff --git a/docs/web-tests/blob-v2/py/requirements.txt b/docs/web-tests/blob-v2/py/requirements.txt index c90c8d622..b0b1739a7 100644 --- a/docs/web-tests/blob-v2/py/requirements.txt +++ b/docs/web-tests/blob-v2/py/requirements.txt @@ -3,6 +3,6 @@ lancedb==0.41.0b10 numpy==2.2.6 pandas==2.3.3 -pillow==12.1.1 +pillow==13.0.0 pytest==8.4.2 pytest-asyncio==1.2.0 diff --git a/java/pom.xml b/java/pom.xml index 2d5df36c9..030b90f73 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -29,7 +29,7 @@ UTF-8 15.0.0 15.0.0-beta.8 - 2.18.11 + 2.18.12 false 2.30.0 1.7 diff --git a/python/pyproject.toml b/python/pyproject.toml index bd40b5828..1655dedcb 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -62,7 +62,7 @@ tests = [ "duckdb>=0.9.0", "pytz>=2023.3", "polars>=0.19, <=1.32.3", - "pyarrow<25", + "pyarrow>=16", "pyarrow-stubs>=16.0", "pylance==15.0.0b10", "requests>=2.31.0", diff --git a/python/uv.lock b/python/uv.lock index 47d0b7773..6abf904a4 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -232,16 +232,16 @@ wheels = [ [[package]] name = "anyio" -version = "4.14.1" +version = "4.16.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3b/72/5562aabb8dd7181e8e860622a38bea08d17842b99ecd4c91f84ac95251b0/anyio-4.14.1.tar.gz", hash = "sha256:8d648a3544c1a700e3ff78615cd679e4c5c3f149904287e73687b2596963629e", size = 254831, upload-time = "2026-06-24T20:56:06.017Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/7b/90df4a0a816d98d6ea26f559d87836d494a2cf1fcf063be67df50a7bcc30/anyio-4.14.1-py3-none-any.whl", hash = "sha256:4e5533c5b8ff0a24f5d7a176cbe6877129cd183893f66b537f8f227d10527d72", size = 124875, upload-time = "2026-06-24T20:56:04.413Z" }, + { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, ] [[package]] @@ -740,7 +740,8 @@ dependencies = [ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "peft" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "requests" }, { name = "scipy", version = "1.15.3", 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.11.*'" }, @@ -841,59 +842,72 @@ wheels = [ [[package]] name = "cryptography" -version = "49.0.0" +version = "50.0.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1f/99/d1c90d6041656cc6ee229dc99cd67fd0cd5aec3c5f7d72fffc27cc750054/cryptography-49.0.0.tar.gz", hash = "sha256:f89660a348f4f78a92366240a61404e337586ef7f5909a2fef59ca88ef505493", size = 854345, upload-time = "2026-06-12T20:02:30.512Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/22/adf66990e63584a68dfb50c24f48a125c07b1699899381c8151e63ed458c/cryptography-49.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:966fe0e9c67490071f14c0d2b1cb2dfb3023c5ce39457343931415f08382f2db", size = 4032100, upload-time = "2026-06-12T20:02:32.143Z" }, - { url = "https://files.pythonhosted.org/packages/09/41/3797cfaf69cae04a13ee78ebd83f0678d9c02b4779d21ce24445326f1a69/cryptography-49.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:36d1709f992593689b45bda411498d62c6e365f2ca00b84657d4dadd24de16db", size = 4692978, upload-time = "2026-06-12T20:01:21.305Z" }, - { url = "https://files.pythonhosted.org/packages/e6/8b/43011f7ebe515a8aa20d61f290a326cd890c2e738e16e59eaff8d9c3a412/cryptography-49.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0e959b578856a3924bc0cbb710fc12c387b9412a951389f3ca61704a9e25f325", size = 4716422, upload-time = "2026-06-12T20:01:48.566Z" }, - { url = "https://files.pythonhosted.org/packages/4a/91/01ce7303a4579e6d3a6abef01bd322848e9ea7a219adcabc5048b9033571/cryptography-49.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:53ecee2e23f7169b6117e99fc8a944e5e50f79e69758a83b52a00cb98ab2b2d2", size = 4700503, upload-time = "2026-06-12T20:02:47.091Z" }, - { url = "https://files.pythonhosted.org/packages/62/99/a2c95cf8293f07491e9e27c20cc4dcd18176d944e674679adeb1d0173fd6/cryptography-49.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:2eda353d8a27bcbcaa4cbed18994a74ab4d19a2ca897db188ea269ab9b71419b", size = 5309779, upload-time = "2026-06-12T20:02:08.987Z" }, - { url = "https://files.pythonhosted.org/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2afe9051da7ae7bd5905da5a949280c7d2bb75682e188f650a9d0f2756b834c6", size = 4749683, upload-time = "2026-06-12T20:02:03.335Z" }, - { url = "https://files.pythonhosted.org/packages/a3/5b/c5246635d5fd3b64e0d45ae10e99fd32fe9676a79915ccfe5a61ba9af1a5/cryptography-49.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:0b82e28ee398a386f0807bba7884d30f25218855690f45115831bcce5d90822c", size = 4337874, upload-time = "2026-06-12T20:02:54.323Z" }, - { url = "https://files.pythonhosted.org/packages/6d/88/05563c7fe2e914e87d1a536d06fe83e66b4e1d95cb593e05aea375531da8/cryptography-49.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:ccac2bfebc306b862133e3bb71f3f6ee8bb525240089b2d952e4144b3a6d5da7", size = 4700283, upload-time = "2026-06-12T20:01:34.822Z" }, - { url = "https://files.pythonhosted.org/packages/c4/b6/d7696e4e890d6ae1469935164c9e5215c557671cb78d6e3f458ccceaa632/cryptography-49.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:d0527ce944105f257f605a827d6ebead966c752038b6e8656abb9c5edee6fc68", size = 5265844, upload-time = "2026-06-12T20:01:24.09Z" }, - { url = "https://files.pythonhosted.org/packages/a9/3c/f3ad17eecc1a57b0ba236dc01f90e783c51f4a2f35f64777cc4f47a184b2/cryptography-49.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:cbc77da8c523d5abd028635ba850a6966fcee2c82e2bf65a41d1d8afe0f98be9", size = 4749290, upload-time = "2026-06-12T20:01:30.848Z" }, - { url = "https://files.pythonhosted.org/packages/4f/01/339573cf1023163a400b0b5d16f6d507de413b9f60be6fd1b77feeaf6737/cryptography-49.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b87e65d263b3e5d3bb92a57e2a6638e2f31110fa7aa890c7b2dbba42248d0a3f", size = 4834612, upload-time = "2026-06-12T20:01:29.246Z" }, - { url = "https://files.pythonhosted.org/packages/71/fd/577302e213a1be9468f92d1afef66fcf1ef83d516819d9992ca547f592bd/cryptography-49.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66ec79c3904820572d7e987abdf304281f141d37ad9a489b8e97066e7b9b6459", size = 4980804, upload-time = "2026-06-12T20:01:42.853Z" }, - { url = "https://files.pythonhosted.org/packages/1f/09/f42b1d190c5ba75f72062a387f8030d1d75f6ab035788f1d9c4b01de6525/cryptography-49.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:e5dfc1e64de5677cec922ffa8da89c546d0415bf6efdf081842e5d44c84e1f0e", size = 3810026, upload-time = "2026-06-12T20:02:39.262Z" }, - { url = "https://files.pythonhosted.org/packages/ec/9e/db72b3ae7fc9cfad53e630e56c6ae83b9b6ff0bf3718ffb8012d20b3aabf/cryptography-49.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:73a205dce83953d131a4aa1e0fd917a2fd1c5b1eef251e9d7152efefcbf5caf7", size = 4013892, upload-time = "2026-06-12T20:02:10.735Z" }, - { url = "https://files.pythonhosted.org/packages/86/12/c48a424f38db03027be9f7ed5c7dc5de9933dbee992865f98b13727a009d/cryptography-49.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:196ecd6a36e4e9aa10270393bb98d8df88fccee0bf1e5128b91ae4eb4375896d", size = 4678835, upload-time = "2026-06-12T20:02:48.743Z" }, - { url = "https://files.pythonhosted.org/packages/68/28/8a3ad4653662c93fc44dc4e5d8fd374c25c42e07b34bbfbadf49cf57a5a8/cryptography-49.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7abcee80084cda3f7691f3eb1ce480d8df49cec637b429aa35986c1de71738aa", size = 4697239, upload-time = "2026-06-12T20:02:56.03Z" }, - { url = "https://files.pythonhosted.org/packages/a8/b2/2193fc74f81aee4f9b62733133b73b5176718932ed8f2e4b03fa040480a6/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:4ae387c9cb68ea569ca17e490d66d8142b81c3cc814bf179974b7d146e490bbb", size = 4685593, upload-time = "2026-06-12T20:02:50.666Z" }, - { url = "https://files.pythonhosted.org/packages/47/f1/1d3eaa243bfc5de4a187b22aa8c048b3e4980bfbe830ac46e6bac2e66947/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:f37d847238971164fdbc68ade6f6574aecc9c0af714190e2083429ff68f4ce9d", size = 5289961, upload-time = "2026-06-12T20:01:46.468Z" }, - { url = "https://files.pythonhosted.org/packages/58/39/2d51306721330c486495853eda1c567880ff036de15a14c4b74f399934af/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:c2bc30226390d60ea19d9f82b19db005fe0452154a23c1c410c12ea801e43561", size = 4731145, upload-time = "2026-06-12T20:02:16.832Z" }, - { url = "https://files.pythonhosted.org/packages/17/50/983e838c7fd0d87fd8c969bcdd328edaf5f756e38df5281637424c155873/cryptography-49.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:07cab27cc7b7e0fd28e5e26bb9eeedde5c135c868b46de4a27845abe94af6122", size = 4321719, upload-time = "2026-06-12T20:02:52.611Z" }, - { url = "https://files.pythonhosted.org/packages/a7/f5/8f571d7e27c55bce9f76f026143bcb1e040a4233149ecca0bea5fa5dd5f7/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:b20133d204d2bb56ba047642199603876c872026ca53e79c35b83772ab2cc505", size = 4685209, upload-time = "2026-06-12T20:02:07.282Z" }, - { url = "https://files.pythonhosted.org/packages/e7/84/0e27016a6fc5a0886f797018b26aa42f40c09a82332bff77822a451deaaa/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:b970c6da94d5bb18629db453d14f2a1300f6bf59b61e9b82377931ef95504866", size = 5246285, upload-time = "2026-06-12T20:01:32.439Z" }, - { url = "https://files.pythonhosted.org/packages/11/2d/5e1fb307cb5931881516b464c98774b3f2c36b5d4bb9a2830253cf553cad/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:d8ecde755e2e91bf773fc94e8c9d730cd7f2007004cb492263a794ec3899a1c8", size = 4730441, upload-time = "2026-06-12T20:02:01.469Z" }, - { url = "https://files.pythonhosted.org/packages/e4/c0/bff5a02ee731d207d6a1ed51732549d8c53d2bc8da1d10ec6f2844201d68/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e3fb64c420688e5319ae25113a354015abbd8dffbfbc41781a1ea66fc7622ac3", size = 4815869, upload-time = "2026-06-12T20:01:36.574Z" }, - { url = "https://files.pythonhosted.org/packages/b9/26/814681d14248d95d73d5c3eea0c39a94eb8302df966f670a2c60de90974b/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:32703d93296f5c1f4b53349ad3a250c2cae0fdecd3a3dd5d47e616d8d616af27", size = 4960948, upload-time = "2026-06-12T20:02:18.688Z" }, - { url = "https://files.pythonhosted.org/packages/4c/fe/93ecac273d3738939d023612ad12cca9a3740a5345d69fda04134c43fd96/cryptography-49.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:33cd0565932807baddb67b96dbee92f2c374b5c89dee09fd74079aeb8c8dba61", size = 3799153, upload-time = "2026-06-12T20:01:39.059Z" }, - { url = "https://files.pythonhosted.org/packages/19/2a/5bb823f5bedcf80718cea7fbc95ec5515cca3769633c4b01a32be7f30e7c/cryptography-49.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ec5e529fb80935c94fe7b729f9972b50e351a0e6b50aa294fd5cabb109fcc29a", size = 4025947, upload-time = "2026-06-12T20:01:25.745Z" }, - { url = "https://files.pythonhosted.org/packages/3d/df/40577043ca124e17012f408ddddaeb213b856336ac82ddb3bc915f39e29f/cryptography-49.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f78ff2c9ed8dc2d036b0f4d640e22522213d047c1b14e61205a7e55c80a494d4", size = 4692429, upload-time = "2026-06-12T20:01:53.628Z" }, - { url = "https://files.pythonhosted.org/packages/2c/99/2d13299eb3dd27b02dcfaafcc91d6b5cb3329f7cbd6d8f51921acd566c1a/cryptography-49.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:35b151772baff2c74cba7fa290ceaff4c3b11c0c881eb93eb5dbc05a7cfbba18", size = 4700968, upload-time = "2026-06-12T20:02:45.383Z" }, - { url = "https://files.pythonhosted.org/packages/a5/4d/9c0cd02f95e2602dd5e563da149ee0830abef3537be8b34dc56281ebe27a/cryptography-49.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0f21641cf4b30fca7aee061ced0ec7ad7b073518088b7c9969a297c0ae796c69", size = 4697758, upload-time = "2026-06-12T20:01:41.13Z" }, - { url = "https://files.pythonhosted.org/packages/24/01/186c825898477d77e2324d5360fefe622ff1d8d1963ec0554e2cada8ec77/cryptography-49.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:9e82dcc8e56052715fb18b2429e3bca4823b1629136a2084fc45a9a5cecb9b64", size = 5298863, upload-time = "2026-06-12T20:02:24.579Z" }, - { url = "https://files.pythonhosted.org/packages/b8/7b/62cbbab75d0659865bf0273790031544a0b16c8072d258f9428dcd8190dc/cryptography-49.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6f2debedf9ca60cf1d5bd466475638af5130f89965605cd818484d19987d3a21", size = 4735983, upload-time = "2026-06-12T20:01:50.14Z" }, - { url = "https://files.pythonhosted.org/packages/6c/72/3e798c064bc39e471008075d0f9bc9daf77a80879c092e4a8e170c585ed4/cryptography-49.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:8c25ceb16df5b9435f3f6a9829204985b0e0cbee3b48aacd432c7d2c850b44d9", size = 4334173, upload-time = "2026-06-12T20:01:44.743Z" }, - { url = "https://files.pythonhosted.org/packages/f0/ee/6fca21d1ac73e06f8bef71940abfd4d2f6472b4bca284d770f32bd4086f6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:28d8b15e6275f12c8a207dc309dfa957903c927d08d0cc937ee3f63f200693cc", size = 4697298, upload-time = "2026-06-12T20:02:20.918Z" }, - { url = "https://files.pythonhosted.org/packages/67/d0/a5fcd3515f0bae49a7b6d0413cc1bdccdcc1fc0047037a0d480642cdc5d6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6fc361c34fb6aac015ce19435876635e5c6d21db31998b0920f675f131e043b8", size = 5254338, upload-time = "2026-06-12T20:02:22.737Z" }, - { url = "https://files.pythonhosted.org/packages/a0/84/84fe36f19caf857d61cb7fc9c63035a47ffabd84ea12d1d393148efa3615/cryptography-49.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:2400ef9c9e2299a25614eb1dea3db54a69b1349efd043bfac9c67630d136df36", size = 4735650, upload-time = "2026-06-12T20:02:41.389Z" }, - { url = "https://files.pythonhosted.org/packages/6c/a0/db537264e234f7273a73ec020873d6d6b39dfd8a53db78b550ca8320440e/cryptography-49.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:67e1d20ad9ef3a563c59ef22e7a8a0b8210bd26604369ea4a30a7c66aefe504e", size = 4834820, upload-time = "2026-06-12T20:01:51.847Z" }, - { url = "https://files.pythonhosted.org/packages/93/77/8df9eb486495979bccecd1062e2eaf435250e84437040295b57d09048b0b/cryptography-49.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:42b0684e0e40cf26122427802486f6d93aea593612603a94fbf260c7eb1e9c1b", size = 4967968, upload-time = "2026-06-12T20:02:12.524Z" }, - { url = "https://files.pythonhosted.org/packages/c2/e6/f60198ea8d9dfa15fff9ed4ca02ce362f6eadd9ba757dcc50634c4257b63/cryptography-49.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:026ac7423e6fa66872d3bf889be5974507da3944f866f704fa200eadacd00001", size = 3785547, upload-time = "2026-06-12T20:02:26.847Z" }, - { url = "https://files.pythonhosted.org/packages/63/d3/4a83af35d65e3fad632c926fad684c193ea4398569ccb0bbbc7fe8f5dc9a/cryptography-49.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:fc1e275c2f1d97b1a6450b8b0ea3ebfa6e087a611c2b26cb2404d48588abab7b", size = 3993685, upload-time = "2026-06-12T20:02:14.883Z" }, - { url = "https://files.pythonhosted.org/packages/d6/a7/f9dac0ab7f80368c56993a7bf638ef9935f825c91902798481fac0898138/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c83782480a4a9da4d0feb51950131ba32e12e70813848b3343f6e18c28a66838", size = 4676239, upload-time = "2026-06-12T20:02:28.793Z" }, - { url = "https://files.pythonhosted.org/packages/d7/70/2ba3769dd0ae167e2f33dfa9592d45db6ff9a61d62ca1a5b3d1bdd09068f/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b39efa323140595abd3ecca8529d321ae50f55f3aa3ba9cc81ea56a6011953d5", size = 4715584, upload-time = "2026-06-12T20:01:27.495Z" }, - { url = "https://files.pythonhosted.org/packages/94/64/2923570ac1c0bd3a737aa366ac3abbbbde273042308b8cde95e2364a6e6a/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:b47db11c2c3525083296069b98ac5221907455e989ae0c2e3008bde851921615", size = 4675885, upload-time = "2026-06-12T20:01:55.49Z" }, - { url = "https://files.pythonhosted.org/packages/ab/f8/614dc7e051418cfe53d55173c1e24c6b0085e89996fe90508c2fdf769aef/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:084ef1af862eb07ec46d25f68689f2102a9fc0e05ce7b80f14f5fe51e4eef0f6", size = 4715449, upload-time = "2026-06-12T20:02:05.469Z" }, - { url = "https://files.pythonhosted.org/packages/aa/50/a9caea39ad19c431c1a3f8a31114df65b260cdfe67786b6c7e7c040c4c44/cryptography-49.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:be9fcb48a55f023493482827d4f459bd263cc20efde64f204b97c123201850c6", size = 3783731, upload-time = "2026-06-12T20:02:43.319Z" }, + { url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" }, + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" }, + { url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" }, + { url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" }, + { url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" }, + { url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" }, + { url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" }, + { url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" }, + { url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" }, + { url = "https://files.pythonhosted.org/packages/36/8b/e6d153808bf353e152abd2fd4d8f09670d956ac78379ac46e60d7efbf04c/cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81", size = 3873097, upload-time = "2026-09-30T15:29:56.097Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" }, ] [[package]] @@ -901,7 +915,7 @@ name = "cuda-bindings" version = "13.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder", marker = "sys_platform == 'linux'" }, + { 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" }, @@ -936,37 +950,37 @@ wheels = [ [package.optional-dependencies] cublas = [ - { name = "nvidia-cublas", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cublas" }, ] cudart = [ - { name = "nvidia-cuda-runtime", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-runtime" }, ] cufft = [ - { name = "nvidia-cufft", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufft" }, ] cufile = [ - { name = "nvidia-cufile", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufile" }, ] cupti = [ - { name = "nvidia-cuda-cupti", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-cupti" }, ] curand = [ - { name = "nvidia-curand", marker = "sys_platform == 'linux'" }, + { name = "nvidia-curand" }, ] cusolver = [ - { name = "nvidia-cusolver", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusolver" }, ] cusparse = [ - { name = "nvidia-cusparse", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusparse" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-nvrtc" }, ] nvtx = [ - { name = "nvidia-nvtx", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvtx" }, ] [[package]] @@ -975,7 +989,8 @@ version = "54.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cloudpickle" }, - { name = "pyarrow" }, + { name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/60/90/886f7e9cf827f07ebd60bd293e54e0a028a50dd49bbaef0ee42aae1981ea/datafusion-54.0.0.tar.gz", hash = "sha256:cfe7e8dfc026efc05824f49b53ad6a72caf5c2d6820759b6212a09e245a427ed", size = 276448, upload-time = "2026-06-29T11:19:34.816Z" } @@ -1125,7 +1140,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 = [ @@ -1544,16 +1559,16 @@ resolution-markers = [ "python_full_version < '3.11' and sys_platform == 'darwin'", ] 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 = [ @@ -1578,17 +1593,17 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] 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 = [ @@ -1666,17 +1681,17 @@ resolution-markers = [ "python_full_version < '3.11' and sys_platform == 'darwin'", ] 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 = [ @@ -1701,18 +1716,18 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] 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 = [ @@ -1724,7 +1739,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 = [ @@ -2003,7 +2018,8 @@ dependencies = [ { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "overrides", marker = "python_full_version < '3.12'" }, { name = "packaging" }, - { name = "pyarrow" }, + { name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "pydantic" }, { name = "tqdm" }, ] @@ -2014,7 +2030,8 @@ azure = [ ] clip = [ { name = "open-clip-torch" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "torch" }, ] dev = [ @@ -2045,7 +2062,8 @@ embeddings = [ { name = "ollama" }, { name = "open-clip-torch" }, { name = "openai" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "requests" }, { name = "sentence-transformers" }, { name = "sentencepiece" }, @@ -2058,7 +2076,8 @@ pylance = [ { name = "pylance" }, ] siglip = [ - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "sentencepiece" }, { name = "torch" }, { name = "transformers" }, @@ -2073,7 +2092,8 @@ tests = [ { 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 = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" }, { name = "polars" }, - { name = "pyarrow" }, + { name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "pyarrow-stubs" }, { name = "pylance" }, { name = "pytest" }, @@ -2123,7 +2143,7 @@ requires-dist = [ { name = "polars", marker = "extra == 'tests'", specifier = ">=0.19,<=1.32.3" }, { name = "pre-commit", marker = "extra == 'dev'", specifier = ">=3.5.0" }, { name = "pyarrow", specifier = ">=16" }, - { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, + { name = "pyarrow", marker = "extra == 'tests'", specifier = ">=16" }, { 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" }, @@ -3020,7 +3040,7 @@ name = "nvidia-cudnn-cu13" version = "9.19.0.56" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "sys_platform == 'linux'" }, + { 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" }, @@ -3032,7 +3052,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { 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" }, @@ -3062,9 +3082,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cusparse", marker = "sys_platform == 'linux'" }, - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { 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" }, @@ -3076,7 +3096,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { 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" }, @@ -3277,10 +3297,10 @@ resolution-markers = [ "python_full_version < '3.11' and sys_platform == 'darwin'", ] 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 = [ @@ -3333,11 +3353,11 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] 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 = [ @@ -3402,9 +3422,9 @@ resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'darwin'", ] 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 = [ @@ -3512,7 +3532,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 = [ @@ -3523,6 +3543,11 @@ wheels = [ name = "pillow" version = "12.3.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", +] sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/25/c2/669d88644cddb1485bd9534e63e8cf476c8e51cb3c3a1297677023505c0e/pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a", size = 5392418, upload-time = "2026-07-01T11:53:27.808Z" }, @@ -3613,6 +3638,109 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" }, ] +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b8/58d79332229482eb0d27c82973850808c19d37e5bdc14443d3417bd373f5/pillow-13.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79", size = 5568643, upload-time = "2026-10-16T22:15:44.474Z" }, + { url = "https://files.pythonhosted.org/packages/39/4b/f2ed53d83aa44ac19599ac0a54897f867fafb95f406980d1e24083f8cbe3/pillow-13.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52", size = 4852329, upload-time = "2026-10-16T22:15:46.284Z" }, + { url = "https://files.pythonhosted.org/packages/3b/bb/9e30e8ed18c20800ee327a12107d5249ad8dc444867b3adfcc21654e3c71/pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d", size = 6519309, upload-time = "2026-10-16T22:15:48.14Z" }, + { url = "https://files.pythonhosted.org/packages/e6/99/fdf65cc539e266ab93546c261bdf98411fe165c6e4e13f9dbf597097192b/pillow-13.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca", size = 7144542, upload-time = "2026-10-16T22:15:50.093Z" }, + { url = "https://files.pythonhosted.org/packages/26/9b/f38b7c4d8f599537e2d1a6d546cec9beef7536ff8f5c49a3f9c78179d8ac/pillow-13.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620", size = 6618042, upload-time = "2026-10-16T22:15:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7c/45ee28531f89ee4582967d8a17f7a26d71ca64cd902b93c269590cd60a00/pillow-13.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40", size = 7228137, upload-time = "2026-10-16T22:15:54.009Z" }, + { url = "https://files.pythonhosted.org/packages/01/bc/9c2a969cb1b70201d04fa17fd5aedf02a732870b8da86bceaaa30b0ca385/pillow-13.0.0-cp312-cp312-win32.whl", hash = "sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27", size = 6515423, upload-time = "2026-10-16T22:15:56.25Z" }, + { url = "https://files.pythonhosted.org/packages/ff/cd/73a79ecdc822076002eb24b5e1e4a530b0bb5310fcb6d239abbec877110b/pillow-13.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b", size = 7272166, upload-time = "2026-10-16T22:15:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/4a/a3/be5a1236efd085b3984e4305da8f179ae9dab80c991d2ad78f2bd5c4c843/pillow-13.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51", size = 2698943, upload-time = "2026-10-16T22:16:00.637Z" }, + { url = "https://files.pythonhosted.org/packages/82/e2/9132d38df320e8099e2642d9fa538f18a7dfebf68a875a31725dc2a115aa/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00", size = 4190620, upload-time = "2026-10-16T22:16:02.527Z" }, + { url = "https://files.pythonhosted.org/packages/cb/be/436dac0996876f65ef1916ffb711c5ef4af2ebc57414b6f16642e07f6b47/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033", size = 4290286, upload-time = "2026-10-16T22:16:04.861Z" }, + { url = "https://files.pythonhosted.org/packages/60/16/7c1007162e4169ea0d5bec47e2e0b2174f56c50cf5b8c02a1dc23e41037e/pillow-13.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599", size = 3723169, upload-time = "2026-10-16T22:16:06.956Z" }, + { url = "https://files.pythonhosted.org/packages/08/bc/578ab2eaa04705a8978bd9be0fe15c3d43a8fc95097c4f7e39540e79e4fa/pillow-13.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe", size = 5568469, upload-time = "2026-10-16T22:16:08.664Z" }, + { url = "https://files.pythonhosted.org/packages/98/c8/ccede3dcc4f274b80fb49199eed1ef34ba05566c8b71976b9d1f111da2e3/pillow-13.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313", size = 4852187, upload-time = "2026-10-16T22:16:10.693Z" }, + { url = "https://files.pythonhosted.org/packages/fb/3c/cd0770e96d20bfd990db024bcbd43897ff3e88da1f4782cf90ea231b1d4f/pillow-13.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369", size = 6515908, upload-time = "2026-10-16T22:16:12.896Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fe/f5cdaa2d1c4086e757430f368c271a58ee29cfe7378e7ae7b9d964015c25/pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582", size = 7142544, upload-time = "2026-10-16T22:16:14.844Z" }, + { url = "https://files.pythonhosted.org/packages/fb/b5/a54f6d44adbcd23737c8c12953f42be107e4cca64e247c0ca3a5b563061c/pillow-13.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81", size = 6613097, upload-time = "2026-10-16T22:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/e6/b4/9e6c1207c21b2e91db0d15c16d30f3701ce5add1bd4da0e787761e66cb6e/pillow-13.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502", size = 7224846, upload-time = "2026-10-16T22:16:19.195Z" }, + { url = "https://files.pythonhosted.org/packages/78/9f/d3c3cb0518f3dd1eee0ef501535f53d15597a53c5c4118d178086143397a/pillow-13.0.0-cp313-cp313-win32.whl", hash = "sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8", size = 6516013, upload-time = "2026-10-16T22:16:21.389Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ed/1b16fb66a37e1b9e41370b93b2c614c7da761a5b2a41dc333f7af4639962/pillow-13.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42", size = 7284777, upload-time = "2026-10-16T22:16:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/7d/8d02eba9f7ecc87f8e90f731e032cc4773802f2a843763afd0c66a535ff4/pillow-13.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f", size = 2698826, upload-time = "2026-10-16T22:16:25.382Z" }, + { url = "https://files.pythonhosted.org/packages/8e/45/fbad9c7f5e2f1745c373a434d46072bc84eddfefaa28b852425ac957fda6/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c", size = 4190721, upload-time = "2026-10-16T22:16:27.524Z" }, + { url = "https://files.pythonhosted.org/packages/a2/bf/2074902a259a90692c5dbf132885d21671644cbbd3f690047516243a55db/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76", size = 4290236, upload-time = "2026-10-16T22:16:29.562Z" }, + { url = "https://files.pythonhosted.org/packages/ff/a5/3d1bb93b8ea38d15d21356c1b8e9f50971ac592aaa248f7fb71739094c0e/pillow-13.0.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981", size = 3723093, upload-time = "2026-10-16T22:16:31.249Z" }, + { url = "https://files.pythonhosted.org/packages/84/a1/be060135d85187b25fa8b2573786c0e45c62ae27527fff5257675eb97f4a/pillow-13.0.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4", size = 5572253, upload-time = "2026-10-16T22:16:33.103Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f4/0bf6f1ac9ba7ee2ffe9914aeb410a1035a0c1a3c42f122388d7fc950bc4b/pillow-13.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d", size = 4852269, upload-time = "2026-10-16T22:16:35.102Z" }, + { url = "https://files.pythonhosted.org/packages/83/16/b603274617b3e6728da3a0133d4fba1ea8d7fbe0c4ea5fef9cbffa398b8b/pillow-13.0.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6", size = 6516058, upload-time = "2026-10-16T22:16:37.228Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f2/1371707ce438ba9a43f9d24089828494ec6f9396e28cd7903aa704dd6306/pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d", size = 7142574, upload-time = "2026-10-16T22:16:39.172Z" }, + { url = "https://files.pythonhosted.org/packages/b9/a9/62cf68587f910bc87c5951bcb6e9430c7643a65076adf5f18b4bf350e2bd/pillow-13.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c", size = 6614295, upload-time = "2026-10-16T22:16:41.117Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c9/9e9b48178649730299be0bafbf5f810a5b6977538f5a92d47e4ba5f5d608/pillow-13.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0", size = 7224841, upload-time = "2026-10-16T22:16:43.118Z" }, + { url = "https://files.pythonhosted.org/packages/8f/48/c44e91384b1b6c072a714a63d00608acc16a6a968735e478e4be4384e5ac/pillow-13.0.0-cp314-cp314-win32.whl", hash = "sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055", size = 6508694, upload-time = "2026-10-16T22:16:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/50/e2/7ad17747517e4c813dca78257d6bb593466f8231baf1384bc98d92745edb/pillow-13.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a", size = 7281830, upload-time = "2026-10-16T22:16:47.725Z" }, + { url = "https://files.pythonhosted.org/packages/41/9f/e5b51f2ce8ef4563215334035403ce61a244f93a2e65c24a940131618f87/pillow-13.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4", size = 2695468, upload-time = "2026-10-16T22:16:49.515Z" }, + { url = "https://files.pythonhosted.org/packages/97/73/a53502f731f6c84805a4ce87a8881e86d07a65aee64728b900d112dc703e/pillow-13.0.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa", size = 5578196, upload-time = "2026-10-16T22:16:51.291Z" }, + { url = "https://files.pythonhosted.org/packages/21/50/7e949959a56b5559c78ef172b70fc6025706acb289f3f648a15329e4fa6f/pillow-13.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f", size = 4857276, upload-time = "2026-10-16T22:16:53.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/52/43ded0ac08e77e39d17bd6d894162572201b5e8fdc4a022b14c55a1960a4/pillow-13.0.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1", size = 6607008, upload-time = "2026-10-16T22:16:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/0d/2e/4a57ed216d5bf877387cba4d44c02aa87abe51ad2e06404aa6b597c4da39/pillow-13.0.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683", size = 7224281, upload-time = "2026-10-16T22:16:57.738Z" }, + { url = "https://files.pythonhosted.org/packages/5c/3d/2929b248e135752d63aaeabf53f6de797e905b7b6263f9c1e2adade20aba/pillow-13.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058", size = 6695600, upload-time = "2026-10-16T22:16:59.842Z" }, + { url = "https://files.pythonhosted.org/packages/bc/33/fb0da992cf084ed1ee6ee05e96b6191e35c351eb707ca2df874feb24ce47/pillow-13.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e", size = 7300589, upload-time = "2026-10-16T22:17:01.686Z" }, + { url = "https://files.pythonhosted.org/packages/bb/af/c30dd9ef6a3dce84ecb1b2393cac629047a32e66279056c6cb46c3ffd65c/pillow-13.0.0-cp314-cp314t-win32.whl", hash = "sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15", size = 6517204, upload-time = "2026-10-16T22:17:03.722Z" }, + { url = "https://files.pythonhosted.org/packages/85/d5/ef3a8ae7609c8ab26570abf18194882534b480d245a9148b895a2262c004/pillow-13.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0", size = 7286695, upload-time = "2026-10-16T22:17:05.543Z" }, + { url = "https://files.pythonhosted.org/packages/84/3c/0861db0c69a03689ebe3e7599d35668a414deb5aaafd8255215e4e62e3d3/pillow-13.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692", size = 2698098, upload-time = "2026-10-16T22:17:07.674Z" }, + { url = "https://files.pythonhosted.org/packages/6e/eb/e86a41962a3a31ad495a3d6a912d9002b01bba4a6fa71c28703abdca7f69/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521", size = 4191213, upload-time = "2026-10-16T22:17:09.449Z" }, + { url = "https://files.pythonhosted.org/packages/dd/04/7e7445e706afec84ef06dc25b2c77f9cecff242c23730c62928ad1089d4a/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc", size = 4290650, upload-time = "2026-10-16T22:17:11.196Z" }, + { url = "https://files.pythonhosted.org/packages/46/85/d534089068ac40c0f61f650389a296c812eab745a8a733f81feec39ae955/pillow-13.0.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac", size = 3723078, upload-time = "2026-10-16T22:17:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2b/00b5c3b401df538b5dbe311d3899730fae5ba1e21cb8b80a128887ac6747/pillow-13.0.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d", size = 5572292, upload-time = "2026-10-16T22:17:14.539Z" }, + { url = "https://files.pythonhosted.org/packages/72/f5/a6b0610f946e9b54ae888ba7ad29d6e2f8d9b11f69e212d70416b7186c09/pillow-13.0.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782", size = 4852222, upload-time = "2026-10-16T22:17:16.521Z" }, + { url = "https://files.pythonhosted.org/packages/1e/d0/c0ff25bb0427ec70f32aac995453321fc3c4494a46c7292ff02d9d260b04/pillow-13.0.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071", size = 6527349, upload-time = "2026-10-16T22:17:18.534Z" }, + { url = "https://files.pythonhosted.org/packages/85/11/e46fa0bcc0fc117f1eacc206b3d51f04d583fab328b4b740672d0438d83f/pillow-13.0.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf", size = 7152873, upload-time = "2026-10-16T22:17:20.415Z" }, + { url = "https://files.pythonhosted.org/packages/7c/53/2bdeca705f3a58679fa9201233193c86a30238340ca29b3a152c3fcc719b/pillow-13.0.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3", size = 6626871, upload-time = "2026-10-16T22:17:22.361Z" }, + { url = "https://files.pythonhosted.org/packages/14/de/3829030f209722ade3753bb456b805a0e7f885cf885b483407365c82e9ca/pillow-13.0.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932", size = 7236439, upload-time = "2026-10-16T22:17:24.352Z" }, + { url = "https://files.pythonhosted.org/packages/44/b1/67fc37388382bc036a74f04da5bb6fcbf90ec3ac1f45893e06176c373fd3/pillow-13.0.0-cp315-cp315-win32.whl", hash = "sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81", size = 6508688, upload-time = "2026-10-16T22:17:26.314Z" }, + { url = "https://files.pythonhosted.org/packages/44/05/fdb6a79aee10861165526b41b7b440e36ee1ff58613b2fbefe3acbf06d4f/pillow-13.0.0-cp315-cp315-win_amd64.whl", hash = "sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6", size = 7281107, upload-time = "2026-10-16T22:17:28.198Z" }, + { url = "https://files.pythonhosted.org/packages/e6/9c/6c6f7dc2a566467baf121394e83de25ac287cffe34cc030726beb4be0224/pillow-13.0.0-cp315-cp315-win_arm64.whl", hash = "sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0", size = 2695513, upload-time = "2026-10-16T22:17:30.013Z" }, + { url = "https://files.pythonhosted.org/packages/23/16/e9120defdb8bff693b582d035312acc6f530cdc2bc5238a87f410efccd82/pillow-13.0.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f", size = 5578129, upload-time = "2026-10-16T22:17:31.642Z" }, + { url = "https://files.pythonhosted.org/packages/47/22/76faf2bb2448f48a84cf894c1e2bb1090d7d2b1aa521ece131cb2f05d631/pillow-13.0.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88", size = 4857428, upload-time = "2026-10-16T22:17:33.43Z" }, + { url = "https://files.pythonhosted.org/packages/b3/64/0861ea4e03c50b14af9ed9dd8b9f388ab42f445c623a9fcbab19aef7aa55/pillow-13.0.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb", size = 6612582, upload-time = "2026-10-16T22:17:35.415Z" }, + { url = "https://files.pythonhosted.org/packages/5c/20/cd1e9b3f60a9f3d5ebe46da36955c26004092a501f7f2c42f9fcc26611bc/pillow-13.0.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe", size = 7230176, upload-time = "2026-10-16T22:17:37.362Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ef/ffb0a2fc85690714fb7ac662956949645d57f15bf4426f520da361e7b6e3/pillow-13.0.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22", size = 6703640, upload-time = "2026-10-16T22:17:39.313Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c2/6402ee3ccb3363aeed8fdb3f9fe56703ac5377a539f0b81b53999d7e121f/pillow-13.0.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630", size = 7309231, upload-time = "2026-10-16T22:17:41.021Z" }, + { url = "https://files.pythonhosted.org/packages/fc/96/d6b82e8b8c06ad143b66b12e0b31051e4bf489b4fabca1f390a14fe1ebde/pillow-13.0.0-cp315-cp315t-win32.whl", hash = "sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2", size = 6517200, upload-time = "2026-10-16T22:17:42.886Z" }, + { url = "https://files.pythonhosted.org/packages/60/d4/0062e6005e9b270b165015aafd343364ac378ec5a685431ea42baad33357/pillow-13.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43", size = 7287488, upload-time = "2026-10-16T22:17:45.56Z" }, + { url = "https://files.pythonhosted.org/packages/e4/81/b8eb349746be7bce47dd95337c6634e84910af91b59aaa9159c034c614fa/pillow-13.0.0-cp315-cp315t-win_arm64.whl", hash = "sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8", size = 2698073, upload-time = "2026-10-16T22:17:47.556Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, + { url = "https://files.pythonhosted.org/packages/60/da/f6d644e631c5b370c5d0b899f3ccadd2780aab070b29a110527cf4e1fd2c/pillow-13.0.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463", size = 5523188, upload-time = "2026-10-16T22:17:59.334Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b0/2594f202d743a35d4fe80682bfd96f277e5ca7aecb27cf64ef5bfc1d000b/pillow-13.0.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e", size = 4806808, upload-time = "2026-10-16T22:18:01.188Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ed/d504165ef79af6fafe25c76726cf30f544cc236002f7ed054f1d51adc4ff/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63", size = 5464358, upload-time = "2026-10-16T22:18:02.779Z" }, + { url = "https://files.pythonhosted.org/packages/7b/fe/a10aba5503ca13e9e009b8bd0a1a4ce5584bdce246245fd6f3a83701369c/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61", size = 6043514, upload-time = "2026-10-16T22:18:04.538Z" }, + { url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" }, +] + [[package]] name = "platformdirs" version = "4.10.0" @@ -3848,59 +3976,127 @@ wheels = [ [[package]] name = "pyarrow" -version = "24.0.0" +version = "25.0.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/91/13/13e1069b351bdc3881266e11147ffccf687505dbb0ea74036237f5d454a5/pyarrow-24.0.0.tar.gz", hash = "sha256:85fe721a14dd823aca09127acbb06c3ca723efbd436c004f16bca601b04dcc83", size = 1180261, upload-time = "2026-04-21T10:51:25.837Z" } +resolution-markers = [ + "python_full_version < '3.11' and sys_platform == 'linux'", + "python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version < '3.11' and sys_platform == 'darwin'", +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/e3/27f57f80141379d60defe6703eb50a707325706f07fedfd1312c7a751995/pyarrow-25.0.1.tar.gz", hash = "sha256:9150a83248bfed9813ea3c3af74c3856c1984d444aa28e58bf7733b9750ddf6a", size = 1201653, upload-time = "2026-08-10T12:40:53.904Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a5/bf/a34fee1d624152124fa8355c42f34195ad5fe5233ce5bb87946432047d52/pyarrow-24.0.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:7c2b98645d576a0b9616892ead22b64a83a5f043c5e2ca15ebcefcb5b70c80cb", size = 35076681, upload-time = "2026-04-21T08:51:46.845Z" }, - { url = "https://files.pythonhosted.org/packages/1d/41/64180033d7027afce12dc96d0fe1f504c6fa112190582b458acea2399530/pyarrow-24.0.0-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:644a246325b8c69c595ad1dd4b463eba4b0cdb731370e4a86137d433208d6147", size = 36684260, upload-time = "2026-04-21T08:51:53.642Z" }, - { url = "https://files.pythonhosted.org/packages/57/02/9b9320e673dd8a99411fac78690f3df92f6dd6f59754c750110bca66d64e/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:3a577bd840ca83f646f0a625dbc571dba7044c43c2d1503afc378b570954345c", size = 45698566, upload-time = "2026-04-21T10:46:02.133Z" }, - { url = "https://files.pythonhosted.org/packages/67/33/f75e91b9a64c3f33c787e263c93b871ad91b8a4a68c1d5cebddd9840e835/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:e3268e43984d0b1a185c89b4cfff282a7ead12fc93f56cfd7088bdbcbe727041", size = 48835562, upload-time = "2026-04-21T10:46:10.278Z" }, - { url = "https://files.pythonhosted.org/packages/a5/63/097510448e47e4091faa41c43ba92f97cecaab8f4535b56a3d149578f634/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:2392d954fcb920f42d230284b677605e4e2fbb11f2821e823e642abd67fbb491", size = 49394997, upload-time = "2026-04-21T10:46:18.08Z" }, - { url = "https://files.pythonhosted.org/packages/60/6b/c047d6222ab279024a062742d1807e2fbaf27bba88a98637299ff47b9236/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:bec9373df11544592b0ba7ec2af0e35059e5f0e7647c6183a854dedd193298f1", size = 51911424, upload-time = "2026-04-21T10:46:25.347Z" }, - { url = "https://files.pythonhosted.org/packages/3a/ba/464cc70761c2a525d97ebd84e21c31ebd47f3ef4bdcee117009f51c46f24/pyarrow-24.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:c42ab9439498270139cc63e18847a02afe5c8b3ed9c931266533cfe378bd3591", size = 27251730, upload-time = "2026-04-21T10:46:30.913Z" }, - { url = "https://files.pythonhosted.org/packages/62/c9/a47ab7ece0d86cbe6678418a0fbd1ac4bb493b9184a3891dfa0e7f287ae0/pyarrow-24.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:b0e131f880cda8d04e076cee175a46fc0e8bc8b65c99c6c09dff6669335fde74", size = 35068898, upload-time = "2026-04-21T10:46:36.599Z" }, - { url = "https://files.pythonhosted.org/packages/d1/bc/8db86617a9a58008acf8913d6fed68ea2a46acb6de928db28d724c891a68/pyarrow-24.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:1b2fe7f9a5566401a0ef2571f197eb92358925c1f0c8dba305d6e43ea0871bb3", size = 36679915, upload-time = "2026-04-21T10:46:42.602Z" }, - { url = "https://files.pythonhosted.org/packages/eb/8e/fb178720400ef69db251eb4a9c3ccf4af269bc1feb5055529b8fc87170d1/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:0b3537c00fb8d384f15ac1e79b6eb6db04a16514c8c1d22e59a9b95c8ba42868", size = 45697931, upload-time = "2026-04-21T10:46:48.403Z" }, - { url = "https://files.pythonhosted.org/packages/f3/27/99c42abe8e21b44f4917f62631f3aa31404882a2c41d8a4cd5c110e13d52/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:14e31a3c9e35f1ab6356c6378f6f72830e6d2d5f1791df3774a7b097d18a6a1e", size = 48837449, upload-time = "2026-04-21T10:46:55.329Z" }, - { url = "https://files.pythonhosted.org/packages/36/b6/333749e2666e9032891125bf9c691146e92901bece62030ac1430e2e7c88/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b7d9a514e73bc42711e6a35aaccf3587c520024fe0a25d830a1a8a27c15f4f57", size = 49395949, upload-time = "2026-04-21T10:47:01.869Z" }, - { url = "https://files.pythonhosted.org/packages/17/25/c5201706a2dd374e8ba6ee3fd7a8c89fb7ffc16eed5217a91fd2bd7f7626/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b196eb3f931862af3fa84c2a253514d859c08e0d8fe020e07be12e75a5a9780c", size = 51912986, upload-time = "2026-04-21T10:47:09.872Z" }, - { url = "https://files.pythonhosted.org/packages/f8/d2/4d1bbba65320b21a49678d6fbdc6ff7c649251359fdcfc03568c4136231d/pyarrow-24.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:35405aecb474e683fb36af650618fd5340ee5471fc65a21b36076a18bbc6c981", size = 27255371, upload-time = "2026-04-21T10:47:15.943Z" }, - { url = "https://files.pythonhosted.org/packages/b4/a9/9686d9f07837f91f775e8932659192e02c74f9d8920524b480b85212cc68/pyarrow-24.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:6233c9ed9ab9d1db47de57d9753256d9dcffbf42db341576099f0fd9f6bf4810", size = 34981559, upload-time = "2026-04-21T10:47:22.17Z" }, - { url = "https://files.pythonhosted.org/packages/80/b6/0ddf0e9b6ead3474ab087ae598c76b031fc45532bf6a63f3a553440fb258/pyarrow-24.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:f7616236ec1bc2b15bfdec22a71ab38851c86f8f05ff64f379e1278cf20c634a", size = 36663654, upload-time = "2026-04-21T10:47:28.315Z" }, - { url = "https://files.pythonhosted.org/packages/7c/3b/926382efe8ce27ba729071d3566ade6dfb86bdf112f366000196b2f5780a/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:1617043b99bd33e5318ae18eb2919af09c71322ef1ca46566cdafc6e6712fb66", size = 45679394, upload-time = "2026-04-21T10:47:34.821Z" }, - { url = "https://files.pythonhosted.org/packages/b3/7a/829f7d9dfd37c207206081d6dad474d81dde29952401f07f2ba507814818/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6165461f55ef6314f026de6638d661188e3455d3ec49834556a0ebbdbace18bb", size = 48863122, upload-time = "2026-04-21T10:47:42.056Z" }, - { url = "https://files.pythonhosted.org/packages/5f/e8/f88ce625fe8babaae64e8db2d417c7653adb3019b08aae85c5ed787dc816/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b13dedfe76a0ad2d1d859b0811b53827a4e9d93a0bcb05cf59333ab4980cc7e", size = 49376032, upload-time = "2026-04-21T10:47:48.967Z" }, - { url = "https://files.pythonhosted.org/packages/36/7a/82c363caa145fff88fb475da50d3bf52bb024f61917be5424c3392eaf878/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:25ea65d868eb04015cd18e6df2fbe98f07e5bda2abefabcb88fce39a947716f6", size = 51929490, upload-time = "2026-04-21T10:47:55.981Z" }, - { url = "https://files.pythonhosted.org/packages/66/1c/e3e72c8014ad2743ca64a701652c733cc5cbcee15c0463a32a8c55518d9e/pyarrow-24.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:295f0a7f2e242dabd513737cf076007dc5b2d59237e3eca37b05c0c6446f3826", size = 27355660, upload-time = "2026-04-21T10:48:01.718Z" }, - { url = "https://files.pythonhosted.org/packages/6f/d3/a1abf004482026ddc17f4503db227787fa3cfe41ec5091ff20e4fea55e57/pyarrow-24.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:02b001b3ed4723caa44f6cd1af2d5c86aa2cf9971dacc2ffa55b21237713dfba", size = 34976759, upload-time = "2026-04-21T10:48:07.258Z" }, - { url = "https://files.pythonhosted.org/packages/4f/4a/34f0a36d28a2dd32225301b79daad44e243dc1a2bb77d43b60749be255c4/pyarrow-24.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:04920d6a71aabd08a0417709efce97d45ea8e6fb733d9ca9ecffb13c67839f68", size = 36658471, upload-time = "2026-04-21T10:48:13.347Z" }, - { url = "https://files.pythonhosted.org/packages/1f/78/543b94712ae8bb1a6023bcc1acf1a740fbff8286747c289cd9468fced2a5/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a964266397740257f16f7bb2e4f08a0c81454004beab8ff59dd531b73610e9f2", size = 45675981, upload-time = "2026-04-21T10:48:20.201Z" }, - { url = "https://files.pythonhosted.org/packages/84/9f/8fb7c222b100d314137fa40ec050de56cd8c6d957d1cfff685ce72f15b17/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:6f066b179d68c413374294bc1735f68475457c933258df594443bb9d88ddc2a0", size = 48859172, upload-time = "2026-04-21T10:48:27.541Z" }, - { url = "https://files.pythonhosted.org/packages/a7/d3/1ea72538e6c8b3b475ed78d1049a2c518e655761ea50fe1171fc855fcab7/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1183baeb14c5f587b1ec52831e665718ce632caab84b7cd6b85fd44f96114495", size = 49385733, upload-time = "2026-04-21T10:48:34.7Z" }, - { url = "https://files.pythonhosted.org/packages/c3/be/c3d8b06a1ba35f2260f8e1f771abbee7d5e345c0937aab90675706b1690a/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:806f24b4085453c197a5078218d1ee08783ebbba271badd153d1ae22a3ee804f", size = 51934335, upload-time = "2026-04-21T10:48:42.099Z" }, - { url = "https://files.pythonhosted.org/packages/9c/62/89e07a1e7329d2cde3e3c6994ba0839a24977a2beda8be6005ea3d860b99/pyarrow-24.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:e4505fc6583f7b05ab854934896bcac8253b04ac1171a77dfb73efef92076d91", size = 27271748, upload-time = "2026-04-21T10:49:42.532Z" }, - { url = "https://files.pythonhosted.org/packages/17/1a/cff3a59f80b5b1658549d46611b67163f65e0664431c076ad728bf9d5af4/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:1a4e45017efbf115032e4475ee876d525e0e36c742214fbe405332480ecd6275", size = 35238554, upload-time = "2026-04-21T10:48:48.526Z" }, - { url = "https://files.pythonhosted.org/packages/a8/99/cce0f42a327bfef2c420fb6078a3eb834826e5d6697bf3009fe11d2ad051/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:7986f1fa71cee060ad00758bcc79d3a93bab8559bf978fab9e53472a2e25a17b", size = 36782301, upload-time = "2026-04-21T10:48:55.181Z" }, - { url = "https://files.pythonhosted.org/packages/2a/66/8e560d5ff6793ca29aca213c53eec0dd482dd46cb93b2819e5aab52e4252/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:d3e0b61e8efb24ed38898e5cdc5fffa9124be480008d401a1f8071500494ae42", size = 45721929, upload-time = "2026-04-21T10:49:03.676Z" }, - { url = "https://files.pythonhosted.org/packages/27/0c/a26e25505d030716e078d9f16eb74973cbf0b33b672884e9f9da1c83b871/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:55a3bc1e3df3b5567b7d27ef551b2283f0c68a5e86f1cd56abc569da4f31335b", size = 48825365, upload-time = "2026-04-21T10:49:11.714Z" }, - { url = "https://files.pythonhosted.org/packages/5f/eb/771f9ecb0c65e73fe9dccdd1717901b9594f08c4515d000c7c62df573811/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:641f795b361874ac9da5294f8f443dfdbee355cf2bd9e3b8d97aaac2306b9b37", size = 49451819, upload-time = "2026-04-21T10:49:21.474Z" }, - { url = "https://files.pythonhosted.org/packages/48/da/61ae89a88732f5a785646f3ec6125dbb640fa98a540eb2b9889caa561403/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8adc8e6ce5fccf5dc707046ae4914fd537def529709cc0d285d37a7f9cd442ca", size = 51909252, upload-time = "2026-04-21T10:49:31.164Z" }, - { url = "https://files.pythonhosted.org/packages/cb/1a/8dd5cafab7b66573fa91c03d06d213356ad4edd71813aa75e08ce2b3a844/pyarrow-24.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:9b18371ad2f44044b81a8d23bc2d8a9b6a6226dca775e8e16cfee640473d6c5d", size = 27388127, upload-time = "2026-04-21T10:49:37.334Z" }, - { url = "https://files.pythonhosted.org/packages/ad/80/d022a34ff05d2cbedd8ccf841fc1f532ecfa9eb5ed1711b56d0e0ea71fc9/pyarrow-24.0.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:1cc9057f0319e26333b357e17f3c2c022f1a83739b48a88b25bfd5fa2dc18838", size = 35007997, upload-time = "2026-04-21T10:49:48.796Z" }, - { url = "https://files.pythonhosted.org/packages/1a/ff/f01485fda6f4e5d441afb8dd5e7681e4db18826c1e271852f5d3957d6a80/pyarrow-24.0.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:e6f1278ee4785b6db21229374a1c9e54ec7c549de5d1efc9630b6207de7e170b", size = 36678720, upload-time = "2026-04-21T10:49:55.858Z" }, - { url = "https://files.pythonhosted.org/packages/9e/c2/2d2d5fea814237923f71b36495211f20b43a1576f9a4d6da7e751a64ec6f/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:adbbedc55506cbdabb830890444fb856bfb0060c46c6f8026c6c2f2cf86ae795", size = 45741852, upload-time = "2026-04-21T10:50:04.624Z" }, - { url = "https://files.pythonhosted.org/packages/8e/3a/28ba9c1c1ebdbb5f1b94dfebb46f207e52e6a554b7fe4132540fde29a3a0/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:ae8a1145af31d903fa9bb166824d7abe9b4681a000b0159c9fb99c11bc11ad26", size = 48889852, upload-time = "2026-04-21T10:50:12.293Z" }, - { url = "https://files.pythonhosted.org/packages/df/51/4a389acfd31dca009f8fb82d7f510bb4130f2b3a8e18cf00194d0687d8ac/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d7027eba1df3b2069e2e8d80f644fa0918b68c46432af3d088ddd390d063ecde", size = 49445207, upload-time = "2026-04-21T10:50:20.677Z" }, - { url = "https://files.pythonhosted.org/packages/19/4b/0bab2b23d2ae901b1b9a03c0efd4b2d070256f8ce3fc43f6e58c167b2081/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e56a1ffe9bf7b727432b89104cc0849c21582949dd7bdcb34f17b2001a351a76", size = 51954117, upload-time = "2026-04-21T10:50:29.14Z" }, - { url = "https://files.pythonhosted.org/packages/29/88/f4e9145da0417b3d2c12035a8492b35ff4a3dbc653e614fcfb51d9dedb38/pyarrow-24.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:38be1808cdd068605b787e6ca9119b27eb275a0234e50212c3492331680c3b1e", size = 28001155, upload-time = "2026-04-21T10:51:22.337Z" }, - { url = "https://files.pythonhosted.org/packages/79/4f/46a49a63f43526da895b1a45bbb51d5baf8e4d77159f8528fc3e5490007f/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:418e48ce50a45a6a6c73c454677203a9c75c966cb1e92ca3370959185f197a05", size = 35250387, upload-time = "2026-04-21T10:50:35.552Z" }, - { url = "https://files.pythonhosted.org/packages/a0/da/d5e0cd5ef00796922404806d5f00325cdadc3441ce2c13fe7115f2df9a64/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:2f16197705a230a78270cdd4ea8a1d57e86b2fdcbc34a1f6aebc72e65c986f9a", size = 36797102, upload-time = "2026-04-21T10:50:42.417Z" }, - { url = "https://files.pythonhosted.org/packages/34/c7/5904145b0a593a05236c882933d439b5720f0a145381179063722fbfc123/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:fb24ac194bfc5e86839d7dcd52092ee31e5fe6733fe11f5e3b06ef0812b20072", size = 45745118, upload-time = "2026-04-21T10:50:49.324Z" }, - { url = "https://files.pythonhosted.org/packages/13/d3/cca42fe166d1c6e4d5b80e530b7949104d10e17508a90ae202dac205ce2a/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:9700ebd9a51f5895ce75ff4ac4b3c47a7d4b42bc618be8e713e5d56bacf5f931", size = 48844765, upload-time = "2026-04-21T10:50:55.579Z" }, - { url = "https://files.pythonhosted.org/packages/b0/49/942c3b79878ba928324d1e17c274ed84581db8c0a749b24bcf4cbdf15bd3/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d8ddd2768da81d3ee08cfea9b597f4abb4e8e1dc8ae7e204b608d23a0d3ab699", size = 49471890, upload-time = "2026-04-21T10:51:02.439Z" }, - { url = "https://files.pythonhosted.org/packages/76/97/ff71431000a75d84135a1ace5ca4ba11726a231a8007bbb320a4c54075d5/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:61a3d7eaa97a14768b542f3d284dc6400dd2470d9f080708b13cd46b6ae18136", size = 51932250, upload-time = "2026-04-21T10:51:10.576Z" }, - { url = "https://files.pythonhosted.org/packages/51/be/6f79d55816d5c22557cf27533543d5d70dfe692adfbee4b99f2760674f38/pyarrow-24.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:c91d00057f23b8d353039520dc3a6c09d8608164c692e9f59a175a42b2ae0c19", size = 28131282, upload-time = "2026-04-21T10:51:16.815Z" }, + { url = "https://files.pythonhosted.org/packages/0a/3e/5cd70becb51e1d044c54ba5e627424a6e87df5b98008cbd22cc6abd409ca/pyarrow-25.0.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:0b1edbb2f385a6a65e9711b62ba86ac54a7816a3f8d17bb3e8a5929d65fb2485", size = 35954271, upload-time = "2026-08-10T12:36:33.857Z" }, + { url = "https://files.pythonhosted.org/packages/64/be/17599e086df264ea7dc221d1101e3131e181e00da428a2f9bd0358f0d06b/pyarrow-25.0.1-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:a4dd8bf99a8fac133efc0ed6a92f5fddbe2adba0d0f6dd720e39ba9855cea85c", size = 37647543, upload-time = "2026-08-10T12:36:39.486Z" }, + { url = "https://files.pythonhosted.org/packages/42/34/e138b451fd3970a6eda4599f68ae3b2b32b661bc958de3239d54a0bf6575/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:bddd0c4f7630c2a3ddf6347c1bdaa79d97bcf6bd445f9e60c816b7d77c85a5ae", size = 46837120, upload-time = "2026-08-10T12:36:46.58Z" }, + { url = "https://files.pythonhosted.org/packages/57/5c/f8fc0eb2de03464a557d5a4d0c15e972d73362414696618833b771f7eddd/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a4d6d5e9a3d1879a97c08ded0c797579b7965eafd0f0c26c30b45ccc06db939b", size = 50066460, upload-time = "2026-08-10T12:36:53.702Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d1/0dd64fd06de0333b808a02f60981635f067b71aad3a30698a9a104fae778/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:514ddb60285631af068875550c90eddc181db3e8e63a032b1559be189e82f056", size = 49937892, upload-time = "2026-08-10T12:37:00.349Z" }, + { url = "https://files.pythonhosted.org/packages/cb/3c/f89d1bd76d5f3284c2a44d7d7ebbd8204535e5ae2b41f4077069b4ff2ec6/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cab40b1edfef0262e0e5251aa2c58d75630f24d06dd7794480243acc001a1d7d", size = 53107240, upload-time = "2026-08-10T12:37:07.205Z" }, + { url = "https://files.pythonhosted.org/packages/67/67/b554a8e09f3f3decccf405eb8fbe86696321cbcb5b62d18b4a5057a4c113/pyarrow-25.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:60e89d8f13861a1f7f8d950fa54aebb8023b30734d0ac51ffa80beabe2df4bba", size = 27848683, upload-time = "2026-08-10T12:37:12.058Z" }, + { url = "https://files.pythonhosted.org/packages/ee/8b/0d23b47702fcfe8b3618d5292035099675c5a1c48258932350c08020f7b5/pyarrow-25.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:51093dd9e10325fbdb3c10a2ae7c4806e5c822d94e74ae4938b26524a3323fee", size = 35946180, upload-time = "2026-08-10T12:37:18.934Z" }, + { url = "https://files.pythonhosted.org/packages/d8/17/707d17a5476c55a9541fde0db8213ac30979a792864d72415f176ba50c45/pyarrow-25.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:eb6203482ff3746a5632303a7279ae0b5a304c46985b49ed1378cb350ea6728d", size = 37644787, upload-time = "2026-08-10T12:37:25.795Z" }, + { url = "https://files.pythonhosted.org/packages/c1/b2/cdc98ecf1a6408280bc3a6a07054cdd99a3f4670acc0545d383ce113e87d/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:880523be3d29efcf83d3998835d206118ccf35e3871dbd2fb60408cf6b007a80", size = 46834633, upload-time = "2026-08-10T12:37:33.604Z" }, + { url = "https://files.pythonhosted.org/packages/c8/6e/d3fafc41f378b2c65be43b827798c0fae42049a641c8526633ed3eb573e2/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:25f8720bf6387d5dc2ebd2622112de630760419e4b66134405dd24110d15f37e", size = 50065507, upload-time = "2026-08-10T12:37:40.565Z" }, + { url = "https://files.pythonhosted.org/packages/d5/12/8d0698954b8c3001844a898e0a6900bebe83d7ee40c11195174c5122f324/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4facd65742a024a4a366328a1d2292062d72d6e023c1b7dda8d4c37544933a25", size = 49955690, upload-time = "2026-08-10T12:37:46.644Z" }, + { url = "https://files.pythonhosted.org/packages/d3/0b/1ecb936ac6409e90a34d58eea1c7cec09a9ae6d2141b9e49ad01a2b1ea47/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:aa0559502e1cd6254d6814614085dd9c5a3dd0419362978a936a3f68a9e5c3df", size = 53128198, upload-time = "2026-08-10T12:37:52.531Z" }, + { url = "https://files.pythonhosted.org/packages/8e/1c/5236033550633c9b7377b2a53660b2bbb06cb06dc09c4356332d67643ca1/pyarrow-25.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:62cd0d785b8aa6675ee355f9fc02252a340f4441257c42674937826fd7594325", size = 27857263, upload-time = "2026-08-10T12:37:56.943Z" }, + { url = "https://files.pythonhosted.org/packages/a6/e2/9ab15b88cbfac28e16419ce5439ec29234c5172cb8259301b4ba639bdec0/pyarrow-25.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:df961f2e7ae9cf496459259d798652c70625f6c080650d6952f8c04053c58ee9", size = 35861559, upload-time = "2026-08-10T12:38:02.567Z" }, + { url = "https://files.pythonhosted.org/packages/58/79/a0036dbe1eabe1f73127427342f1d99982584c4a2cde2651d6c93499c6f6/pyarrow-25.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:cc4aa407fde9fc660be3939e49ea31f50f3e9fec17c0ec63159f7711edd3efc9", size = 37628383, upload-time = "2026-08-10T12:38:09.083Z" }, + { url = "https://files.pythonhosted.org/packages/13/49/d93a57d375f4bf0cf82913dd6bb54acafde83dd993be2282c81ac5616cad/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:4340f0ba6c1d2e13f21658de1d7c662ca2545018568d0030a1e9afca159d87e3", size = 46820190, upload-time = "2026-08-10T12:38:15.458Z" }, + { url = "https://files.pythonhosted.org/packages/60/c9/711ca85d79f1ec98f29a5eae2b051e25b4ecec5de3e3c0e2d5c5dcb15664/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:5389cdf79447ed1515c9e31620e6e1e2302249564d603f2ad727d4f6d313e4c3", size = 50102437, upload-time = "2026-08-10T12:38:22.487Z" }, + { url = "https://files.pythonhosted.org/packages/80/53/8fb8359ff17cfb6263a1cf3ebf7caec9fe197de118719e84fcb1d0618026/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d51592cb7561e87877c506113e7adbf1342ab579e6c21f0ef44b8ba41cb74c80", size = 49942424, upload-time = "2026-08-10T12:38:28.755Z" }, + { url = "https://files.pythonhosted.org/packages/e8/83/4e5ae02a9341571b18a6fca380ac7a58ce6ddae7ab3c060208c0a1e79f02/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6109c94d8b9f3b17a041daca16cacb2f651ad8f1ef70a4232c2c0f37a23da2a8", size = 53144206, upload-time = "2026-08-10T12:38:34.862Z" }, + { url = "https://files.pythonhosted.org/packages/65/ee/197cbf47e49f83e6ebeb946a5259a48a638dea27ac774db42fe78022179d/pyarrow-25.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:8858d7bfc22e3f51529aeaa4077225029724623e4595dc9eff8c793935c34140", size = 27953934, upload-time = "2026-08-10T12:38:39.808Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8d/8f271a7a034c834910ec925d56fa4b29733b1380f5289419f5aaa3b02777/pyarrow-25.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c7c534ec03c358a76ea3e505e74c1b6aef290af90c444dfd092dbfe23e755b85", size = 35855328, upload-time = "2026-08-10T12:38:45.489Z" }, + { url = "https://files.pythonhosted.org/packages/d2/cd/5bac242f4e841b9971d5eb94fdfe2577e2b70be983e27401e72055786037/pyarrow-25.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:dda9470024204d7bbf2042b47c6e8a0e47a3eeb8e34405882dfaea6577e0c153", size = 37622415, upload-time = "2026-08-10T12:38:51.107Z" }, + { url = "https://files.pythonhosted.org/packages/63/1f/96d03b4e1506524f7087adb0fd6b2f69f0c9c7aaff1ec36d8030082e15a5/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:44a9120ce5bd81936b8ab9a88076e3fd47c2c6838e0e43630fed83626aca81d9", size = 46813813, upload-time = "2026-08-10T12:38:57.773Z" }, + { url = "https://files.pythonhosted.org/packages/98/d6/33a411115b61dbfc16ad6ad73e71730f6fea654ee3667673bc53ab0e2fe7/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:0befcf816e45a1af33ac775a9970b749e4868a230c7372f0ae5e932bee27039f", size = 50104452, upload-time = "2026-08-10T12:39:04.579Z" }, + { url = "https://files.pythonhosted.org/packages/33/ae/b1b97c9ca87f9f9ddbb5230c798df94eccce61bd79b9b45458c69a478588/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f89685964f46e4216103c75483aac0c0692a5f72212d7ca835adba5ede56ce3", size = 49951343, upload-time = "2026-08-10T12:39:11.8Z" }, + { url = "https://files.pythonhosted.org/packages/98/9e/a112df5cfd5a68cb1d9fc31cfe38c28d5aec9f10865ce37ecef2e4450873/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6943e2fe7954d29d84de45d29d34c8dc36ce96570e67d89aa9976e650a4a9138", size = 53144784, upload-time = "2026-08-10T12:39:20.503Z" }, + { url = "https://files.pythonhosted.org/packages/31/24/97e8bd98f1e3b07e2ba08bcdff690674fbe16d69a7d2712cc3884665e615/pyarrow-25.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:31e49a7888fcdf3a835da33ae777f6bb9a866334e5a789282fc26dcf426f7f15", size = 27870159, upload-time = "2026-08-10T12:39:26.161Z" }, + { url = "https://files.pythonhosted.org/packages/36/4c/b525824ad3094076919273cd97db61fb3d78252dee76fa3b8dc8f76774aa/pyarrow-25.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:bf0b672390cdcb640d7288f96b826d71ff4e9abb254a86c89890baf51a29cee6", size = 35885255, upload-time = "2026-08-10T12:39:32.366Z" }, + { url = "https://files.pythonhosted.org/packages/08/62/448bb0e940de41aec31d1a956e63ad9c54afdf122a103cc3ab20c2a3ce33/pyarrow-25.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:38a9a4b4b9613380e200641891495a56c3d5a98a092db4a870af9975e220471d", size = 37644461, upload-time = "2026-08-10T12:39:38.142Z" }, + { url = "https://files.pythonhosted.org/packages/6e/9a/13587e38bd4806fd218f50fd13b8903fab60588a699ff0c406372e5b4043/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0b726ad7e7b669be982b0c71c07fe4b037d654354130da79a7902a669e93a66b", size = 46877146, upload-time = "2026-08-10T12:39:43.722Z" }, + { url = "https://files.pythonhosted.org/packages/8d/61/1c5d1229fa21da4cff5365e41e57177aaac57c563c727f35419b8513d1c1/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:9171748cdf796972d85a4b60157c279913e242992e350c90c7450182a9838b2a", size = 50131616, upload-time = "2026-08-10T12:39:49.304Z" }, + { url = "https://files.pythonhosted.org/packages/43/20/291e1d65cc0b09aa19f03cf25cf51a2f5fa94b5db315178f2d254ed5cad4/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b7a296aac7a71fa0886c08e155ddb6c636a50013f801f6178daafa0f9e726188", size = 50008879, upload-time = "2026-08-10T12:39:56.891Z" }, + { url = "https://files.pythonhosted.org/packages/8b/7c/1b7c9ec28e76576337e4f97b31141c9a181b89b6d1d6221e9d8205621a58/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0fe7c8b6c03969b49c8c66182e4a18e3819ab92d07cfab5d8370c531b9369ef0", size = 53170864, upload-time = "2026-08-10T12:40:04.918Z" }, + { url = "https://files.pythonhosted.org/packages/b7/75/f3d789dc06011a765d14d86bda799cf72ac1d715b6a6edecaa0d73d95062/pyarrow-25.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:f729cfdbd36fd99d543b67a914d2de044c84ebe45be8b34902b299b608c15c8f", size = 28620729, upload-time = "2026-08-10T12:40:51.41Z" }, + { url = "https://files.pythonhosted.org/packages/fc/05/647a8ee6f7c2662feb6921315617bc04dcd6034763fb61b1199720bf6162/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:59a2de54c0cbd954da861eee4d1d330f8e909c45b53455baef696380f2c55033", size = 36130288, upload-time = "2026-08-10T12:40:11.014Z" }, + { url = "https://files.pythonhosted.org/packages/93/f8/c9ee997554d7bea94520667dd1933f109ac1da3ee3556d2b49381e023484/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:35935cd5de130aa5cf4dea052a63e6bf2e17006c35c3a468194242b9b2bf5956", size = 37762187, upload-time = "2026-08-10T12:40:16.592Z" }, + { url = "https://files.pythonhosted.org/packages/a2/08/a28c01c7fe9e96e8233ce2d13df1d402f4f999f848f51d2daacd6bb4c036/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:f3831aaa25c67a99f99dc8b05873cb9d64560390372e2aa197ce9dd4a3f06a44", size = 46888003, upload-time = "2026-08-10T12:40:23.242Z" }, + { url = "https://files.pythonhosted.org/packages/1b/b9/58612e977d28dc58c878448866838369ee8da2f1e7cc8ed2c84b952aafee/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:6a1fdfc6659b6b19022f2e50627fb5cf7156a66c46bf4299379955cbe742382a", size = 50079036, upload-time = "2026-08-10T12:40:29.169Z" }, + { url = "https://files.pythonhosted.org/packages/72/13/66e1402dcc860e1dc2760b1e0292c9a569b62b3bccab69def1b3e907d006/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:169d3429d5be7c752125890620f75a60776d38b0035eddae939651640822332e", size = 50040226, upload-time = "2026-08-10T12:40:35.186Z" }, + { url = "https://files.pythonhosted.org/packages/78/10/3f1a5497a7ef732ab0f03ecca3e66d89d9c0f57fdc61b4794c456b781f01/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:119297a6dc197e45d9c6d4415f7814a67ffa36c180d26f68c154c58067ae782d", size = 53149035, upload-time = "2026-08-10T12:40:41.454Z" }, + { url = "https://files.pythonhosted.org/packages/93/c0/37d4a7e8e2f7a6076283673d5298018ca26478b934c6ee369e10505ab32c/pyarrow-25.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:4288f27577352d608ca08553b0865e4a9b3aa14820c5d95b53337218d609835b", size = 28753071, upload-time = "2026-08-10T12:40:46.623Z" }, +] + +[[package]] +name = "pyarrow" +version = "26.0.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", + "python_full_version == '3.11.*' and sys_platform == 'linux'", + "python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'", + "python_full_version == '3.11.*' and sys_platform == 'darwin'", +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/5e/9cb2a56d5e293aab4e2fbecc5b0620d93227d66b8d5a63c554c31e1f80fe/pyarrow-26.0.1.tar.gz", hash = "sha256:93affcbd8a343e98dc19e9ec8fe17271ebf8fe98102d8b7454175074409f8b72", size = 1237985, upload-time = "2026-11-03T10:54:17.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/aa/459f3f5adebf6427a8bf1e976168f55793a3732ec1c6c6fe9e05a060b63b/pyarrow-26.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:9a62748f6b1f9f438706f0307acbb26e6a15010ea58f202c9d2725bc6eac0871", size = 37327168, upload-time = "2026-11-03T09:54:01.046Z" }, + { url = "https://files.pythonhosted.org/packages/5f/ed/29218597cb38aa9058dffda7906749df9e9da02b4c4da4e88dd8bcfa85eb/pyarrow-26.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:0187cbe6558cb158e148dd7b779f59cab6104163d148d808d04f293dc897b7ec", size = 39778863, upload-time = "2026-11-03T09:57:58.046Z" }, + { url = "https://files.pythonhosted.org/packages/03/f9/44489f525c73cc469f23fd02c0a3009882a8dcf45d0d9fb6ca1bb84a53e2/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:22a96a225de107eb9acd1ad9a818198ca832df2a4c0952412f754a7ed2105a98", size = 51836882, upload-time = "2026-11-03T10:48:50.544Z" }, + { url = "https://files.pythonhosted.org/packages/e6/87/6bf528898ef82dc3e8d762cbec7b42ae127a543895cc78c5df26a1f497f5/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:39cb0f2418282c24bea6ceda77b03e5a8f0a5766b63a8bf194d4e2a2c423548c", size = 55016622, upload-time = "2026-11-03T10:48:58.916Z" }, + { url = "https://files.pythonhosted.org/packages/97/e8/3b4898693744efb5aa60a859774ee3874a2635b288f309f1afb78a698f38/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:24350194bc83f1fde74aa321b6b43cd78bfdbfe613a795a6b9145fd4beaf4827", size = 55452257, upload-time = "2026-11-03T10:49:05.872Z" }, + { url = "https://files.pythonhosted.org/packages/86/96/bbeb5152a27406c65b80b72ecba4451fea18d549a5aea1fbb2c097d86b08/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ed1e19bfaf79565b74e3b0a45a0ba6d05620e68d5a5b48a8193c2bbee7cf5484", size = 58605344, upload-time = "2026-11-03T10:49:14.145Z" }, + { url = "https://files.pythonhosted.org/packages/bf/aa/afb7321eaed5f65332aa691fcd892bf67d0289e2ba884c8ce592d3188a26/pyarrow-26.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:5f681458e4fb81aefef50d3a8a432fe92f8480a87693616f9d95e95ceac8844c", size = 29034160, upload-time = "2026-11-03T10:49:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/61/81/dc5814d61f8c956363e81bcaba61b4712a5d227324d40c766b3858160711/pyarrow-26.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:217497a51fd41abb74502ba2f4900872e0944c226945c02ee8a1cb4f81df3392", size = 37290209, upload-time = "2026-11-03T10:49:25.185Z" }, + { url = "https://files.pythonhosted.org/packages/f7/c8/dcc42b1cceb69ff032fa16430bd82c086b933e35ef05ab521e56313b76be/pyarrow-26.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:a2c5e9cec45b318917b630dc040cf197aef624d94866ab2c8e709708057123d2", size = 39757493, upload-time = "2026-11-03T10:49:30.886Z" }, + { url = "https://files.pythonhosted.org/packages/ab/7e/da9831bfcaaa908ae6d5d049c04c2233a5a7e216d6b961e22861056ef3fd/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6c18167774fb599d42444b7ac558a893d49e750fb14232b538955e6f0d1d51ea", size = 51818506, upload-time = "2026-11-03T10:49:37.89Z" }, + { url = "https://files.pythonhosted.org/packages/d3/79/e2fc9b1317b7a21e7bcd57eb035cac3fe72f47af3efe2ec3b4dea9a08a04/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c718bf97a92a6dea97fd1062c3b9f9e2e83cb9cc926e752289fa4ffff41738f9", size = 55043763, upload-time = "2026-11-03T10:49:45.732Z" }, + { url = "https://files.pythonhosted.org/packages/e3/66/dbe72f5fa21a92b645d56410bacac605defe63e5d3e9794b2fd8c7d77030/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:40aea57ab8bd3cf35a11e604cd7d0c7436dc90d1ce9b88b6711ef2f1a232968e", size = 55438656, upload-time = "2026-11-03T10:49:53.74Z" }, + { url = "https://files.pythonhosted.org/packages/d1/b1/c91322fc4c1800c1f7dd78f911b1dd74187acaeb246d86478a0f064f6af5/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:73534fbda7f73cab0791b569b93112d4c9e1546cedd0f309d1f69889beb6a08f", size = 58625736, upload-time = "2026-11-03T10:50:01.442Z" }, + { url = "https://files.pythonhosted.org/packages/30/61/d94decccacb4dd40a4ebeed0ff3b2cea8f0b680f50184ea7eb0264db779b/pyarrow-26.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:9379f0d1056cad6866c4697aec83a15830202ec7e0bd52f8bd508b316260fa61", size = 29078866, upload-time = "2026-11-03T10:50:06.854Z" }, + { url = "https://files.pythonhosted.org/packages/15/b8/c31c51fbe7df901817d88c73eeec25079d0da5f7c7b67fc0bf071f6a2df5/pyarrow-26.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:4cb739ccb87292c673e1f69819b68432a73bb8bb456e8599641bba9183a8a1dd", size = 37292947, upload-time = "2026-11-03T10:50:12.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/63/0c2559ae33ce59d2ca5ce74117676f8ff8da4cf102729a158ea46415eb50/pyarrow-26.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:50b40aea92f43b2b6da3427548a5337741b4b93b92e8015a8a3eefc0e75acca2", size = 39767535, upload-time = "2026-11-03T10:50:18.254Z" }, + { url = "https://files.pythonhosted.org/packages/31/02/d9462d1ae4e54c3964af38316a802b29c28970b7d375722ef190af736640/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a3a79661404ba3d41b7c9a45cb56113246a244b38cb1393fadae289bc66b91b4", size = 51815955, upload-time = "2026-11-03T10:50:25.332Z" }, + { url = "https://files.pythonhosted.org/packages/96/54/33c2df56948d88a4d83a52999a4a81a4871b2de481ff25ccd6f5ccd2589a/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:f71221bbc7707e3fad920d0478db9350791d4714ec445299ee0d56559fbc156c", size = 55038406, upload-time = "2026-11-03T10:50:32.551Z" }, + { url = "https://files.pythonhosted.org/packages/99/57/8e1f886ee96c7edab89ab6f15fbb00c85c2bb2173f3cb504925731d00564/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8ccfb9958bcd09f34678c64fb42a0e270b47cd092ae79578da51e0d7bb144296", size = 55437362, upload-time = "2026-11-03T10:50:39.89Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c3/d87939a5f6cd30bb406bad6c20926fcedafc52ec5629f6eb27e4cd5db709/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:029e881af986375a2731da79c999fe734a72547fabb16503d65fc079d4bc7eb2", size = 58618865, upload-time = "2026-11-03T10:50:48.029Z" }, + { url = "https://files.pythonhosted.org/packages/c1/9e/b6c8afec2ffc06bbd00a88326826f9d66e4bbca752c0837ee8e2dbf2238f/pyarrow-26.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:8196f36a2f4cb8d2d6ef3651941b80e5ccf125d7653657d99af5bb298e7a7026", size = 28989592, upload-time = "2026-11-03T10:50:53.384Z" }, + { url = "https://files.pythonhosted.org/packages/de/48/999f6e30323e2e95a4439180b62f6308023970e4a37d31497080ea2a1a78/pyarrow-26.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:15435b595c14583f6ac8495c3ef89ac3fed6bc94f168467bfd3b6ba53ad3a643", size = 37334639, upload-time = "2026-11-03T10:50:59.462Z" }, + { url = "https://files.pythonhosted.org/packages/7f/3a/4458972c69ead95af5d3b701c80885133c351075895382499df49ed92d36/pyarrow-26.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:a44a244867cac106cd326dd0a04be0850d2b8af3b1418ed7aeb8146d13aba360", size = 39802150, upload-time = "2026-11-03T10:51:05.743Z" }, + { url = "https://files.pythonhosted.org/packages/86/d0/fa4bc5d66f78cbc4ec8482b210c2fc3b8cb59564efe171f3ca9be416f8ee/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0044cb9303c3ae082cc52a2493312109c955bcfa84e87be768736f7d6d8f6257", size = 51880097, upload-time = "2026-11-03T10:51:12.75Z" }, + { url = "https://files.pythonhosted.org/packages/f3/57/755a1b54d37c2a9e2c283d8bc648a50aa4ce57f977ce6a4b1d65eba29f51/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:7ae48ab53610b85e004b03bccff593fbdf22186d0ab48ed42c90797915dac814", size = 55063542, upload-time = "2026-11-03T10:51:20.417Z" }, + { url = "https://files.pythonhosted.org/packages/45/ba/7cd1d78c2ef5a36b1f8d137d1790179875639f197ed90702268084a2470a/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a97df0c52c966ae8970ac0899ae75d81083c5400eca267de2608ca0f13e6e118", size = 55490507, upload-time = "2026-11-03T10:51:28.295Z" }, + { url = "https://files.pythonhosted.org/packages/9f/02/39e18c5381ad908d7161cc16a02dce03b3db236d3c3ac99fc020878287fb/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5f665e73790222779613ae3d23d2a1d72f0f13a4646862277e9784bb46e14fca", size = 58648328, upload-time = "2026-11-03T10:51:36.303Z" }, + { url = "https://files.pythonhosted.org/packages/1c/18/2cd453cc2e282d465e9c9b60834d6ca17601dc08e2d402751cb40af92356/pyarrow-26.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:492dc499097968e51cac46e03e0054c68dd3c5f39d75098343f5ad05ec79f7df", size = 29757743, upload-time = "2026-11-03T10:52:35.061Z" }, + { url = "https://files.pythonhosted.org/packages/db/46/b97f117adb46f93620aa94bf13747a81ccc5e099be534cc195c94b281ba7/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ec196b35270263eda71fc3f43bd31a89b778c6787f19872df5abb9d4264057ff", size = 37452099, upload-time = "2026-11-03T10:51:42.419Z" }, + { url = "https://files.pythonhosted.org/packages/a6/40/ac1796654fc8591049d200f6bcd646a2319509010784f47c1cf6b09d1000/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:8af2b4e004dc18da8dc77bce27d97c675d2f71348e3ade2741cecac85c3f0c21", size = 39888805, upload-time = "2026-11-03T10:51:48.766Z" }, + { url = "https://files.pythonhosted.org/packages/6c/93/bcff79148416896738a707992570c4ae8e3bb087bc9e0dca8df7dbf6e983/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:c2bf4444a7e86f109dc03e28b2c98eb6671e2eb95e6057c25043d25684e337e9", size = 51884587, upload-time = "2026-11-03T10:51:56.701Z" }, + { url = "https://files.pythonhosted.org/packages/fa/62/cb05e81d31cd1dc97c2e16151425e61fe3a19274ccd1254cafab3a173f96/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:b121de63e2f92704b6b9881fbe69cb3eeca786ea882379b59ce80b8012c1bd8c", size = 55018252, upload-time = "2026-11-03T10:52:05.813Z" }, + { url = "https://files.pythonhosted.org/packages/f8/f5/e8dbbb803bb28a32411491d502679e272c569af7f590816327e84725c748/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:40b9c1a5841559030ba8d1b8c15d6160bccb702ff2596b4ce296e1efd7665781", size = 55522075, upload-time = "2026-11-03T10:52:14.577Z" }, + { url = "https://files.pythonhosted.org/packages/9b/7a/5000d6082b116359d3db3ee6073a8f708f41cb4bb7d6414f94cd40a90fe7/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9519f70bd847f7628a2d16324d1ea8827e2ec1da347ee0bf96cc7c248195e923", size = 58625604, upload-time = "2026-11-03T10:52:23.045Z" }, + { url = "https://files.pythonhosted.org/packages/41/70/74a5a07eeee1a84cd51e81813b7fd2d5ffc90192a95981a51e97a8ced99e/pyarrow-26.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:6d9b558e1bce3270f1f422c61fd682615cfb34ffd320a51e765e868e8c155a72", size = 29925653, upload-time = "2026-11-03T10:52:29.188Z" }, + { url = "https://files.pythonhosted.org/packages/77/09/4e9461479930e3f4367cc0b4f4356d4444a23be9cb350272b159cd0c7fa9/pyarrow-26.0.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:2c118754a0abe0bf20ef17432f95534ebb0ded37a48b6e8690cdd02625a86d97", size = 37329458, upload-time = "2026-11-03T10:52:41.622Z" }, + { url = "https://files.pythonhosted.org/packages/40/5a/9e44840924b0939defacc2561e54dc9aba10eff1fc5dadcf41921202d99f/pyarrow-26.0.1-cp315-cp315-macosx_12_0_x86_64.whl", hash = "sha256:99574d8eabad06cc4bb3fed327b298c8a44a3596abd2d575738fa019df7ac59e", size = 39799948, upload-time = "2026-11-03T10:52:47.507Z" }, + { url = "https://files.pythonhosted.org/packages/70/3a/5fe40369653a082d86fdb6ce2b7c40a4ef435d90a68da60c05dda0c554fc/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:12c5edbdf9b8a0f121a0a222be150c3a711149bc4322736d6a04693fbfd8c723", size = 51875337, upload-time = "2026-11-03T10:52:54.59Z" }, + { url = "https://files.pythonhosted.org/packages/5e/87/f768a458cf975c17c73912fb25a1e0693ceef8d76d78cf83ffdf1f63ec70/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:8cb5bcfe627ee6b910fbec27871d38cf4f28f331ea6328902ce6a6272851ac70", size = 55060370, upload-time = "2026-11-03T10:53:02.19Z" }, + { url = "https://files.pythonhosted.org/packages/e0/30/280c24a7da9085b782cd6960ccae6763b0170f51385b9122385c12226ff2/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e2ee5f01f84996109405759cba8bb92a16455c50deb6526a535ab3b8d5f4e326", size = 55488705, upload-time = "2026-11-03T10:53:09.8Z" }, + { url = "https://files.pythonhosted.org/packages/42/e7/8e7b7f7bd58c88fd8da93db0d0869c69175c3ddccf365afbcc13fbd691da/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e25d4a886868c5ce136d194f308bd690e1335aebf6b8bcae3511b0becdb3a65a", size = 58646822, upload-time = "2026-11-03T10:53:17.902Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c7/6094fa2c0b5602d81b1177ac7f5b2de8a386862d08e57a75931da774f3e0/pyarrow-26.0.1-cp315-cp315-win_amd64.whl", hash = "sha256:6cdad5f67a30bbcea54c3c2a27ea45bd5a170377bf45f80f4d7e3a726e8e3283", size = 29755706, upload-time = "2026-11-03T10:54:14.582Z" }, + { url = "https://files.pythonhosted.org/packages/41/0f/86747650c8218bcea7443884e7c8ba9d3fe9a13fb5a4be99acdd5c2b9144/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:12dc85cec96aa62d429d7c43749c072e9330c373b67d6ee458edeef444c8941f", size = 37445268, upload-time = "2026-11-03T10:53:25.531Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ec/4159b2362267009b754a7c2f138f16bdfd6623b308005678eb7cf1b65863/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_x86_64.whl", hash = "sha256:52e4daba8f1b4316b7b9ba7e84903a339cbc52998ebddc9a7c78b5ea37c23bbb", size = 39877540, upload-time = "2026-11-03T10:53:33.046Z" }, + { url = "https://files.pythonhosted.org/packages/a8/0e/df0501e93eef78402f94f33f948aba996181b3d3c54f97a3f16544916d05/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:322f6fc80c6db1ec87c9d905df3ce259cd22e922f47fbad3c58d0dd6f63bc7a9", size = 51874165, upload-time = "2026-11-03T10:53:41.281Z" }, + { url = "https://files.pythonhosted.org/packages/fb/30/0d43bf6a49fca51142a96c73d693ec34d229c902a46e007c25f3b9798b52/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:68b91f34e3424d55564e9d4d4f7491aaebd6db3998039cc33ba795a63167f04e", size = 55012741, upload-time = "2026-11-03T10:53:49.153Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ff/0e6cd73832d97c3852284eda9bee2428c53a92bcf6f6aa4bda1e15314a59/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b801300d65859adaf611c9c0a4cb39bd3cb1713b60b974ad20650a8a0f8af2fd", size = 55512474, upload-time = "2026-11-03T10:53:56.512Z" }, + { url = "https://files.pythonhosted.org/packages/f0/1e/43cdcf9719169f0228b3e516e5004ed0acfc3a4c70ce35e3f2a80a485baf/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:2623b6c20637c0e2c40be96bda3d127dde49d6e6734ad6e71df91a013e40a3c4", size = 58616300, upload-time = "2026-11-03T10:54:04.472Z" }, + { url = "https://files.pythonhosted.org/packages/df/bf/8e29b47c61fc961e92e96db129d5dc7b716c2091dfe05359e70f20d712b9/pyarrow-26.0.1-cp315-cp315t-win_amd64.whl", hash = "sha256:55b1d871f21c8ed249c93f7375a35c35aa9b7b3af6896405cb8a6b67ad9bc7f9", size = 29909417, upload-time = "2026-11-03T10:54:09.613Z" }, ] [[package]] @@ -3908,7 +4104,8 @@ name = "pyarrow-stubs" version = "20.0.0.20260625" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyarrow" }, + { name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ff/7d/a3eadf94131428ec61b44bc40a52acca2b093bf0f6a90a0596c44aa9fe62/pyarrow_stubs-20.0.0.20260625.tar.gz", hash = "sha256:cae81ae0900d0710e5b8a6271fef34ccfacb08663bb5f805d94f129baf13130e", size = 237707, upload-time = "2026-06-25T07:27:47.496Z" } wheels = [ @@ -4087,14 +4284,14 @@ wheels = [ [[package]] name = "pyjwt" -version = "2.13.0" +version = "2.15.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" } +sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, + { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" }, ] [package.optional-dependencies] @@ -4111,7 +4308,8 @@ dependencies = [ { name = "numpy", version = "2.2.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.11.*'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "pyarrow" }, + { name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ { url = "https://pypi.fury.io/lance-format/-/ver_1aEUT6/pylance-15.0.0b10-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:fe34d42c5d58008a65f41acb659474c43848104414a2af94461454377c9f5276" }, @@ -4939,10 +5137,10 @@ resolution-markers = [ "python_full_version < '3.11' and sys_platform == 'darwin'", ] 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 = [ @@ -4996,13 +5194,13 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] 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 = [ @@ -5048,7 +5246,7 @@ resolution-markers = [ "python_full_version < '3.11' and sys_platform == 'darwin'", ] 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 = [ @@ -5109,7 +5307,7 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform == 'darwin'", ] 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 = [ @@ -5190,7 +5388,7 @@ resolution-markers = [ "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'", ] 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 = [ @@ -5594,7 +5792,8 @@ dependencies = [ { name = "numpy", version = "2.2.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.11.*'" }, { name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "pillow" }, + { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "torch" }, ] wheels = [ @@ -5768,11 +5967,11 @@ wheels = [ [[package]] name = "urllib3" -version = "2.7.0" +version = "2.8.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, ] [[package]] From 1b40e479d3ea9d056a259166e4ece9f49056b592 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 6 Nov 2026 10:32:20 +0800 Subject: [PATCH 030/203] fix(python): surface Function drop warnings (#4880) Remote Python `drop_function` currently discards the dependent-view warnings returned by SQL DROP. Both the synchronous and coroutine APIs now emit those warnings through `warnings.warn` while preserving their boolean result and executing DROP once. The server support is already merged in lancedb/sophon#9820. The Rust decoder reads warnings across every result batch, including an empty first batch. Missing warning columns remain compatible with older servers; malformed or null warning lists are rejected. The hidden binding bridge carries the warnings to Python. The separate `drop_function_async` API and its `(bool, Job)` contract are unchanged. Python warning filters can raise after the catalog mutation has completed. Validation: a compiled PyO3/public-server reproduction failed before the fix and passed afterward; the public async path also returned `true` with the expected dependent-view warning. Final source passes two focused Rust tests, two Python wrapper tests, strict targeted Clippy, formatting, and Ruff. Three decoder tests cover batch/null/type and older-server behavior. The public runs preceded a two-file simplification of the completed Job projection; focused final-source checks cover that delta. Current-main integration is conflict-free, and its overlapping changes concern independent retry-policy APIs/tests. Documentation now covers warning filters, the post-removal warnings-as-errors behavior, and silent compatibility with older servers. The follow-up changes only prose and a Python docstring; the runtime validation above remains applicable. Refs ENT-3659. Whole-issue independent acceptance remains pending. --- docs/web/management/function.mdx | 8 ++ python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/db.py | 29 ++++- python/python/lancedb/remote/db.py | 7 +- .../tests/test_first_class_function_slice2.py | 39 ++++++ python/src/connection.rs | 17 +++ rust/lancedb/src/connection.rs | 15 +++ rust/lancedb/src/database.rs | 12 ++ rust/lancedb/src/remote/db.rs | 17 +++ rust/lancedb/src/remote/sql/function.rs | 52 +++++--- rust/lancedb/src/remote/sql/objects.rs | 112 +++++++++++++++++- rust/lancedb/src/remote/sql_test.rs | 41 ++++++- 12 files changed, 330 insertions(+), 22 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 4709264c7..c8fa0626c 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -530,6 +530,14 @@ returns as a [background job](/basics/jobs#teardown). handle. Waiting confirms the revision's catalog removal; physical cleanup can continue afterward. +When a deployment reports dependency warnings for a boolean drop, +`db.drop_function` emits each warning as a `UserWarning`. This also applies to +`await db.drop_function(...)` on an async connection. The warnings are emitted +after catalog removal, and standard Python warnings filters apply. If warnings +are configured as errors, the call can raise after the revision has been +removed; the drop is not rolled back. Servers whose DROP response omits the +warning field remain silent. + A deployment refuses the drop unless it also allows changes to a function's lifecycle, which is a separate setting, off by default even where Functions are enabled. diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index d1cee5091..f0f6027ad 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -201,6 +201,9 @@ class Connection(object): async def drop_function( self, name: str, version: str, namespace_path: Optional[List[str]] = None ) -> bool: ... + async def _drop_function_with_warnings( + self, name: str, version: str, namespace_path: Optional[List[str]] = None + ) -> Tuple[bool, list[str]]: ... async def drop_function_async( self, name: str, version: str, namespace_path: Optional[List[str]] = None ) -> Tuple[bool, Job]: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 9df75a794..3ff657a6c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -11,6 +11,7 @@ from pathlib import Path from dataclasses import asdict import json import sys +import warnings from typing import ( TYPE_CHECKING, Any, @@ -1085,7 +1086,9 @@ class DBConnection(EnforceOverrides): Returns True when the revision was removed and False for a repeated drop or a missing name. A revision never published under an existing name is an error. Dropping the last visible revision releases the name and - schedules physical cleanup in the background. Use + schedules physical cleanup in the background. When the remote server + reports dependent warnings, they are emitted as ``UserWarning`` before + this method returns. Use :meth:`drop_function_async` to access the query job, whose completion confirms catalog removal of the revision. Local connections raise NotImplementedError. @@ -3647,9 +3650,29 @@ class AsyncConnection(object): Returns True when the requested revision was removed and False for a repeated drop or a missing name. A revision never published under an existing name is an error. Only the last visible revision's removal - releases the name and schedules background object cleanup. + releases the name and schedules background object cleanup. When the + remote server reports a warning, it is emitted as ``UserWarning`` + before this method returns, subject to the standard ``warnings`` + filters. A warnings-as-errors setting can therefore raise after the + catalog removal; it does not roll back the drop. Older servers that + omit the warning field remain silent. """ - return await self._inner.drop_function(name, version, namespace_path) + dropped, drop_warnings = await self._drop_function_with_warnings( + name, version, namespace_path + ) + for warning in drop_warnings: + warnings.warn(warning, UserWarning, stacklevel=2) + return dropped + + async def _drop_function_with_warnings( + self, + name: str, + version: str, + namespace_path: Optional[List[str]] = None, + ) -> Tuple[bool, List[str]]: + return await self._inner._drop_function_with_warnings( + name, version, namespace_path + ) async def drop_function_async( self, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 655391b1f..2cc6bf056 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1024,11 +1024,14 @@ class RemoteDBConnection(DBConnection): version: str, namespace_path: Optional[List[str]] = None, ) -> bool: - return LOOP.run( - self._conn.drop_function( + dropped, drop_warnings = LOOP.run( + self._conn._drop_function_with_warnings( name, version=version, namespace_path=namespace_path ) ) + for warning in drop_warnings: + warnings.warn(warning, UserWarning, stacklevel=2) + return dropped @override def drop_function_async( diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 9b435b256..53b0189f5 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1972,6 +1972,45 @@ def test_sync_catalog_path_preserves_execution_controls(): assert _assert_execution_control_encoding(version) == definition +def test_sync_drop_function_emits_server_warnings_without_changing_bool_api(): + class _DropConnection: + async def drop_function(self, name, *, version, namespace_path=None): + return True + + async def _drop_function_with_warnings( + self, name, *, version, namespace_path=None + ): + return True, [ + 'materialized view "pinned" references Function "embed" version "1"' + ] + + connection = object.__new__(RemoteDBConnection) + connection._conn = _DropConnection() + + with pytest.warns(UserWarning, match="references Function"): + assert connection.drop_function("embed", version="1") is True + + +@pytest.mark.asyncio +async def test_async_drop_function_emits_server_warnings_without_changing_bool_api(): + class _Inner: + async def _drop_function_with_warnings( + self, name, version, namespace_path=None + ): + return True, [ + 'materialized view "pinned" references Function "embed" version "1"' + ] + + async def drop_function(self, name, version, namespace_path=None): + return True + + connection = object.__new__(AsyncConnection) + connection._inner = _Inner() + + with pytest.warns(UserWarning, match="references Function"): + assert await connection.drop_function("embed", version="1") is True + + @contextlib.contextmanager def _mock_remote_function_catalog(): state = {"requests": [], "version": None} diff --git a/python/src/connection.rs b/python/src/connection.rs index d88991235..bffa167d8 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -928,6 +928,23 @@ impl Connection { }) } + #[pyo3(signature = (name, version, namespace_path=None))] + pub fn _drop_function_with_warnings( + self_: PyRef<'_, Self>, + name: String, + version: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let namespace_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .drop_function_with_warnings(name, version, &namespace_path) + .await + .infer_error() + }) + } + #[pyo3(signature = (name, version, namespace_path=None))] pub fn drop_function_async( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 7d751bdb7..dec5e1359 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -738,6 +738,21 @@ impl Connection { .await } + /// Internal bridge for the Python binding to preserve the public bool API + /// while forwarding advisory SQL warnings to Python's existing warning + /// mechanism. + #[doc(hidden)] + pub async fn drop_function_with_warnings( + &self, + name: impl AsRef, + version: impl AsRef, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + self.internal + .drop_function_with_warnings(name.as_ref(), version.as_ref(), namespace_path) + .await + } + /// Drop one Function revision and return its SQL query handle. /// /// The boolean reports removal of the requested revision from the catalog. diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index daa7f3f29..44d038521 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -581,6 +581,18 @@ pub trait Database: let dropped = self.drop_function(name, version, namespace_path).await?; Ok((dropped, crate::job::Job::new_done())) } + /// Internal bridge for the Python binding to preserve the public bool API + /// while making advisory SQL warnings available to the wrapper. + #[doc(hidden)] + async fn drop_function_with_warnings( + &self, + name: &str, + version: &str, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + let dropped = self.drop_function(name, version, namespace_path).await?; + Ok((dropped, Vec::new())) + } /// Create a database-owned storage integration in a namespace. async fn create_storage_integration( &self, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 9af99dced..c33c7267d 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -932,6 +932,23 @@ impl Database for RemoteDatabase { .await } + #[doc(hidden)] + async fn drop_function_with_warnings( + &self, + name: &str, + version: &str, + namespace_path: &[String], + ) -> Result<(bool, Vec)> { + validate_function_name(name)?; + validate_namespace(namespace_path)?; + let (outcome, job) = self + .sql_client()? + .drop_function_outcome(name, version, namespace_path) + .await?; + job.wait().await?; + Ok((outcome.dropped, outcome.warnings)) + } + async fn create_storage_integration( &self, name: &str, diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index 7682b11c1..e90792a8a 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -4,7 +4,7 @@ use super::{ SqlClient, materialized_view::quote_identifier, - objects::{definition, literal, strings}, + objects::{definition, literal, string_lists, strings}, }; use crate::{ database::ExecuteQueryRequest, @@ -16,6 +16,14 @@ use crate::{ }; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +/// The SQL result of one Function drop, before the public boolean wrapper +/// discards the advisory details. +#[derive(Clone, serde::Deserialize, serde::Serialize)] +pub(in crate::remote) struct DropFunctionOutcome { + pub(in crate::remote) dropped: bool, + pub(in crate::remote) warnings: Vec, +} + impl SqlClient { pub(in crate::remote) async fn register_function( &self, @@ -146,12 +154,12 @@ impl SqlClient { }; Ok(ListingPage { items, page_token }) } - pub(in crate::remote) async fn drop_function( + pub(in crate::remote) async fn drop_function_outcome( &self, name: &str, version: &str, namespace: &[String], - ) -> Result<(bool, Job)> { + ) -> Result<(DropFunctionOutcome, Job)> { validate_function_name(name)?; validate_namespace(namespace)?; let job = self @@ -167,23 +175,37 @@ impl SqlClient { }, |batches| { let rows = strings(&batches, "status")?; - match rows.as_slice() { - [status] if status == "dropped" => Ok(true), - [status] if status == "not_found" => Ok(false), - _ => Err(Error::Runtime { - message: "invalid DROP FUNCTION result".into(), - }), - } + let dropped = match rows.as_slice() { + [status] if status == "dropped" => true, + [status] if status == "not_found" => false, + _ => { + return Err(Error::Runtime { + message: "invalid DROP FUNCTION result".into(), + }); + } + }; + Ok(DropFunctionOutcome { + dropped, + warnings: string_lists(&batches, "warnings")?, + }) }, ) .await?; let id = job.id().unwrap().parse().map_err(|_| Error::Runtime { message: "invalid SQL query job id".into(), })?; - let dropped = job.wait().await?; - Ok(( - dropped, - Job::from_query_task(id, tokio::spawn(async { Ok(()) }), || async { Ok(()) }), - )) + let outcome = job.wait().await?; + let job = Job::from_query_task(id, tokio::spawn(async { Ok(()) }), || async { Ok(()) }); + Ok((outcome, job)) + } + + pub(in crate::remote) async fn drop_function( + &self, + name: &str, + version: &str, + namespace: &[String], + ) -> Result<(bool, Job)> { + let (outcome, job) = self.drop_function_outcome(name, version, namespace).await?; + Ok((outcome.dropped, job)) } } diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index 2c4d33614..ff87e0000 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -7,7 +7,7 @@ use crate::{ error::{Error, Result}, job::Job, }; -use arrow_array::{Array, RecordBatch, StringArray}; +use arrow_array::{Array, ListArray, RecordBatch, StringArray}; use futures::TryStreamExt; use serde::{Serialize, de::DeserializeOwned}; use std::sync::Arc; @@ -38,6 +38,45 @@ pub(super) fn strings(batches: &[RecordBatch], name: &str) -> Result .collect::>>() .map(|rows| rows.into_iter().flatten().collect()) } + +/// Read an optional `List` column. Older servers do not return the +/// column, so a missing column means no warnings rather than a bad result. +pub(super) fn string_lists(batches: &[RecordBatch], name: &str) -> Result> { + let mut values = Vec::new(); + for batch in batches { + let Some(column) = batch.column_by_name(name) else { + continue; + }; + let lists = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: format!("SQL result column '{name}' is not a string list"), + })?; + for index in 0..lists.len() { + if lists.is_null(index) { + return Err(Error::Runtime { + message: format!("SQL result contains null '{name}'"), + }); + } + let list = lists.value(index); + let strings = + list.as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: format!("SQL result column '{name}' contains a non-string value"), + })?; + if strings.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result column '{name}' contains null values"), + }); + } + values.extend(strings.iter().map(|value| value.unwrap().to_owned())); + } + } + Ok(values) +} + pub(super) fn definition(batches: Vec) -> Result { let values = strings(&batches, "definition")?; let [value]: [String; 1] = values.try_into().map_err(|_| Error::Runtime { @@ -70,3 +109,74 @@ impl SqlClient { })) } } + +#[cfg(test)] +mod tests { + use super::string_lists; + use arrow_array::builder::{ListBuilder, StringBuilder}; + use arrow_array::{ArrayRef, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + fn warning_schema() -> Arc { + Arc::new(Schema::new(vec![Field::new( + "warnings", + DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))), + true, + )])) + } + + #[test] + fn reads_warnings_after_an_empty_first_batch() { + let schema = warning_schema(); + let empty = RecordBatch::new_empty(schema.clone()); + let mut builder = ListBuilder::new(StringBuilder::new()); + builder.values().append_value( + "materialized view \"pinned\" references Function \"embed\" version \"1\"", + ); + builder.append(true); + let non_empty = + RecordBatch::try_new(schema.clone(), vec![Arc::new(builder.finish()) as ArrayRef]) + .unwrap(); + + assert_eq!( + string_lists(&[empty, non_empty], "warnings").unwrap(), + ["materialized view \"pinned\" references Function \"embed\" version \"1\""] + ); + } + + #[test] + fn missing_warning_column_remains_an_empty_result() { + let schema = Arc::new(Schema::new(vec![Field::new( + "status", + DataType::Utf8, + false, + )])); + let batch = RecordBatch::new_empty(schema); + + assert_eq!( + string_lists(&[batch], "warnings").unwrap(), + Vec::::new() + ); + } + + #[test] + fn null_or_non_list_warning_values_are_rejected() { + let mut builder = ListBuilder::new(StringBuilder::new()); + builder.append(false); + let null_list = RecordBatch::try_new( + warning_schema(), + vec![Arc::new(builder.finish()) as ArrayRef], + ) + .unwrap(); + assert!(string_lists(&[null_list], "warnings").is_err()); + + let non_list_schema = Arc::new(Schema::new(vec![Field::new( + "warnings", + DataType::Utf8, + false, + )])); + let non_list = RecordBatch::new_empty(non_list_schema); + assert!(string_lists(&[non_list], "warnings").is_err()); + } +} diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 37125c1fd..1211263d8 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3,7 +3,7 @@ use std::sync::atomic::AtomicUsize; -use arrow_array::builder::StringDictionaryBuilder; +use arrow_array::builder::{ListBuilder, StringBuilder, StringDictionaryBuilder}; use arrow_array::types::{Float32Type, Int32Type}; use arrow_array::{Array, ArrayRef, FixedSizeListArray, Float32Array, Int64Array, StringArray}; use arrow_flight::encode::FlightDataEncoderBuilder; @@ -2944,6 +2944,45 @@ async fn function_drop_keeps_the_query_id_and_reports_catalog_removal() { } } +#[tokio::test] +async fn function_drop_decodes_server_warnings_for_the_binding_bridge() { + let mut warning_values = ListBuilder::new(StringBuilder::new()); + warning_values + .values() + .append_value("materialized view \"pinned\" references Function \"embed\" version \"1\""); + warning_values.append(true); + let result = RecordBatch::try_from_iter(vec![ + ( + "status", + Arc::new(StringArray::from(vec!["dropped"])) as ArrayRef, + ), + ("warnings", Arc::new(warning_values.finish()) as ArrayRef), + ]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + result, + ..Default::default() + }; + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request"); + }) + .with_sql_client(client); + + let (dropped, warnings) = db + .drop_function_with_warnings("embed", "1", &[]) + .await + .unwrap(); + assert!(dropped); + assert_eq!( + warnings, + ["materialized view \"pinned\" references Function \"embed\" version \"1\""] + ); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { for defer in [false, true] { From c08e2ccc355bb15b78153567f8a3afca951c48d7 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Fri, 6 Nov 2026 10:47:05 +0800 Subject: [PATCH 031/203] chore(deps): update Lance to 15.0.0-beta.11 (#4881) Downstream workspaces adopting Lance 15.0.0-beta.11 currently also resolve beta.10 because the SDK pins every Lance crate exactly. This produces incompatible Lance types across the SDK and the consumer. Update the workspace pins and lockfile to the published [v15.0.0-beta.11](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.11). This release includes payload-free list length reads and preserves those read modes across serialized plans (lance-format/lance#10759, lance-format/lance#10766). Existing feature flags and unrelated locked packages are unchanged. The release also includes the metric/k-dependent search-effort calibration from lance-format/lance#10695. Update the Node and Python execution tests to its exact probe budgets (for example, effort 0.25 with L2, k=8 and Auto=6 now probes 4 partitions), and cover the 0.1 tier. Recall, caller bounds and probe-precedence assertions remain in place. Validation: - `cargo fmt --all --check` - `cargo clippy --quiet --features remote --tests --examples` - Downstream metadata fixture with SDK source and the released Lance beta.11 path overrides resolves exactly one Lance version. - `cargo test --quiet --features remote --tests`: 2,271 passed, 0 failed, 79 existing ignored tests. - Node native/TypeScript build, lint and API documentation generation passed; 41 query tests passed. - Python native binding build and package Ruff checks passed; 208 query tests passed, 1 slow test deselected, 5 existing deprecation warnings. - Rust results remain applicable: the follow-up changes only binding tests, with product source and dependency graph unchanged from the tested dependency update. Repository-root Ruff currently reports 59 lint findings and 6 formatting failures in untouched documentation snippets. Their blobs match the PR base; the changed Python test and the entire Python package pass lint/format checks. --- Cargo.lock | 96 +++++++++++++++---------------- Cargo.toml | 30 +++++----- nodejs/__test__/query.test.ts | 3 +- python/python/tests/test_query.py | 15 +++-- 4 files changed, 76 insertions(+), 68 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c97a1fc5f..a4e95d624 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arc-swap", "arrow", @@ -5318,8 +5318,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "arrow-buffer", @@ -5341,7 +5341,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "arrow-buffer", @@ -5355,7 +5355,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "arrow-schema", @@ -5364,8 +5364,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrayref", "crunchy", @@ -5375,8 +5375,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "arrow-buffer", @@ -5414,8 +5414,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow", "arrow-array", @@ -5446,8 +5446,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow", "arrow-array", @@ -5472,8 +5472,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow", "arrow-array", @@ -5490,8 +5490,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "proc-macro2", "quote", @@ -5500,8 +5500,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-arith", "arrow-array", @@ -5534,8 +5534,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-arith", "arrow-array", @@ -5566,8 +5566,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "geo-traits", "geo-types", @@ -5579,8 +5579,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arc-swap", "arrow", @@ -5655,8 +5655,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "arrow-schema", @@ -5679,8 +5679,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow", "arrow-array", @@ -5725,8 +5725,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "byteorder", "ethnum", @@ -5743,8 +5743,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5759,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow", "async-trait", @@ -5774,8 +5774,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arc-swap", "arrow", @@ -5829,8 +5829,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "arrow-buffer", @@ -5844,8 +5844,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow", "arrow-array", @@ -5886,8 +5886,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "arrow-array", "arrow-schema", @@ -5900,8 +5900,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.10#f56a08d40b5630ce1124535c4c3b1406d5ceedf1" +version = "15.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 8cd8d7292..3dfcf3ef3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.10", default-features = false, "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.10", default-features = false, "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.10", default-features = false, "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.10", "tag" = "v15.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.11", default-features = false, "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.11", default-features = false, "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.11", default-features = false, "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index 068e55c2f..c0b30ac63 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -564,7 +564,8 @@ describe("IVF search effort", () => { it.each([ [null, 6], [0, 1], - [0.25, 3], + [0.1, 2], + [0.25, 4], [0.5, 6], [0.75, 10], [1, 16], diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index d39f01a39..95148dcf9 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -2658,17 +2658,24 @@ def test_blob_v2_to_batches_row_id(tmp_db): assert [blobs[i].as_py() for i in range(len(blobs))] == [b"one", b"two"] -@pytest.mark.parametrize("metric", ["l2", "cosine", "dot"]) @pytest.mark.parametrize( - "effort,probes", [(None, 4), (0, 1), (0.25, 2), (0.5, 4), (0.75, 8), (1, 16)] + "metric,probes80,probes90", [("l2", 2, 3), ("cosine", 1, 2), ("dot", 1, 2)] ) -def test_search_effort_probe_budget(tmp_path, monkeypatch, metric, effort, probes): +@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1]) +def test_search_effort_probe_budget( + tmp_path, monkeypatch, metric, effort, probes80, probes90 +): import re from lancedb.index import IvfFlat monkeypatch.setenv("LANCE_AUTO_PROBE_MARGIN", "0") monkeypatch.setenv("LANCE_AUTO_MIN_INITIAL_NPROBES", "4") monkeypatch.setenv("LANCE_AUTO_MAX_INITIAL_NPROBES", "4") + # The lower tiers use metric/k calibration; Auto and the upper tiers retain + # their existing budgets. Keep exact execution counts and precedence checks. + probes = {None: 4, 0: 1, 0.1: probes80, 0.25: probes90, 0.5: 4, 0.75: 8, 1: 16}[ + effort + ] rng = np.random.default_rng(42) vectors = np.repeat(np.eye(16, dtype=np.float32), 32, axis=0) vectors += rng.normal(0, 0.001, vectors.shape).astype(np.float32) @@ -2752,7 +2759,7 @@ def test_search_effort_invalid_sync(table, effort): @pytest.mark.asyncio @pytest.mark.parametrize("hybrid", [False, True]) -@pytest.mark.parametrize("effort", [None, 0, 0.25, 0.5, 0.75, 1]) +@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1]) async def test_search_effort_async_roundtrip(table_async, hybrid, effort): query = table_async.vector_search([0, 0]) if hybrid: From b3c1e58fe7e53092f2d23836480d1428939e52bc Mon Sep 17 00:00:00 2001 From: Lance Release Date: Fri, 6 Nov 2026 02:57:10 +0000 Subject: [PATCH 032/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.5=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 9a83cbcb8..7c0e08a6e 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.5" +current_version = "0.42.0-beta.6" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a4e95d624..37bc9431f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5914,7 +5914,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" dependencies = [ "ahash", "anyhow", @@ -6025,7 +6025,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" dependencies = [ "anyhow", "arrow-array", @@ -6068,7 +6068,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" dependencies = [ "arrow-array", "arrow-buffer", @@ -6093,7 +6093,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index edf7c1dd4..5dc452e7b 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.42.0-beta.5 + 0.42.0-beta.6 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index a253fe1b6..e47d74ab6 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.5 + 0.42.0-beta.6 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 030b90f73..09cadbe1e 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.5 + 0.42.0-beta.6 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 52615cfec..b17a9df4c 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" 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 084d1ce9d..0b444ac1f 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.42.0-beta.5", + "version": "0.42.0-beta.6", "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 a7804bbae..adb255d7d 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.42.0-beta.5", + "version": "0.42.0-beta.6", "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 59cbef7df..efe97711f 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.42.0-beta.5", + "version": "0.42.0-beta.6", "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 4d407e557..7016af395 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.42.0-beta.5", + "version": "0.42.0-beta.6", "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 dac2d1cb7..4ab682b73 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.42.0-beta.5", + "version": "0.42.0-beta.6", "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 a01e6ba19..6ca3e36d8 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.42.0-beta.5", + "version": "0.42.0-beta.6", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 187da18c9..d0108ae01 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.42.0-beta.5", + "version": "0.42.0-beta.6", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 57ca0f03b..150f358cf 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.5", + "version": "0.42.0-beta.6", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 3c60244c2..be511189d 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 26ae4f1d7..c2dabe4f9 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 681604aad..8ef396b5f 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.5" +version = "0.42.0-beta.6" edition = "2021" license.workspace = true repository.workspace = true From d812fe86ae7eb22b7dfc4ece95762507d5e21cff Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Fri, 6 Nov 2026 15:57:49 +0800 Subject: [PATCH 033/203] chore(deps): upgrade Lance to v15.0.0-beta.12 (#4888) Upgrade the exact Lance Git dependencies from v15.0.0-beta.11 to the published [v15.0.0-beta.12](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.12). This includes `Dataset::file_reader_options()`, which downstream consumers need to preserve dataset defaults when constructing per-read list-structure options. Update all 15 workspace pins and 25 Lance lockfile package records to release commit `635d412cde01e5d4203a91be47ddbfd0f2a6e068`. Non-Lance package records, including their dependency edges, remain unchanged. The `geo` validation covers the release's R-tree crate relocation. Validation on macOS arm64 / Rust 1.97.0: - `cargo test --locked --features remote,geo --tests`: 2,278 passed, 79 existing ignored, 0 failed. - `cargo clippy --locked --features remote,geo --tests --examples -- -D warnings`: passed. - `cargo fmt --all -- --check` and `git diff --check`: passed. Sophon adoption and PE integration validation remain separate. --- Cargo.lock | 120 ++++++++++++++++++++++++++++++----------------------- Cargo.toml | 30 +++++++------- 2 files changed, 83 insertions(+), 67 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 37bc9431f..30c22ca3f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arc-swap", "arrow", @@ -5285,6 +5285,7 @@ dependencies = [ "lance-datafusion", "lance-encoding", "lance-file", + "lance-geo", "lance-index", "lance-io", "lance-linalg", @@ -5318,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "arrow-buffer", @@ -5341,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "arrow-buffer", @@ -5355,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "arrow-schema", @@ -5364,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrayref", "crunchy", @@ -5375,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "arrow-buffer", @@ -5414,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow", "arrow-array", @@ -5446,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow", "arrow-array", @@ -5472,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow", "arrow-array", @@ -5490,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "proc-macro2", "quote", @@ -5500,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-arith", "arrow-array", @@ -5534,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-arith", "arrow-array", @@ -5566,21 +5567,40 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ + "arrow-array", + "arrow-schema", + "arrow-select", + "async-trait", + "datafusion-common", + "datafusion-execution", + "datafusion-expr", + "datafusion-physical-expr", + "datafusion-physical-plan", + "futures", "geo-traits", "geo-types", "geoarrow-array", "geoarrow-schema", + "lance-arrow", "lance-core", + "lance-datafusion-exec", + "lance-index", + "lance-index-core", + "lance-io", + "lance-select", + "prost-types", + "roaring", "serde", + "serde_json", ] [[package]] name = "lance-index" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arc-swap", "arrow", @@ -5607,9 +5627,6 @@ dependencies = [ "dirs", "fst", "futures", - "geo-types", - "geoarrow-array", - "geoarrow-schema", "half", "hashbrown 0.16.1", "hex", @@ -5622,7 +5639,6 @@ dependencies = [ "lance-datafusion-exec", "lance-encoding", "lance-file", - "lance-geo", "lance-index-core", "lance-io", "lance-jsonb", @@ -5655,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "arrow-schema", @@ -5679,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow", "arrow-array", @@ -5725,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "byteorder", "ethnum", @@ -5743,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5759,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow", "async-trait", @@ -5774,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arc-swap", "arrow", @@ -5829,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "arrow-buffer", @@ -5844,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow", "arrow-array", @@ -5886,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "arrow-array", "arrow-schema", @@ -5900,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.11#01052c56a308ed915a046ed42b0d39ce8c09c2d8" +version = "15.0.0-beta.12" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 3dfcf3ef3..532c2c2ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.11", default-features = false, "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.11", default-features = false, "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.11", default-features = false, "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.11", "tag" = "v15.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.12", default-features = false, "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.12", default-features = false, "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.12", default-features = false, "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" From 06fcd628cf6db30eadf288e18aa6a082bd722bf5 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Fri, 6 Nov 2026 08:08:01 +0000 Subject: [PATCH 034/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.6=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 7c0e08a6e..1a29e14cd 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.6" +current_version = "0.42.0-beta.7" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 30c22ca3f..53d6d970f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5930,7 +5930,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" dependencies = [ "ahash", "anyhow", @@ -6041,7 +6041,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" dependencies = [ "anyhow", "arrow-array", @@ -6084,7 +6084,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" dependencies = [ "arrow-array", "arrow-buffer", @@ -6109,7 +6109,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 5dc452e7b..dbc071627 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.42.0-beta.6 + 0.42.0-beta.7 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index e47d74ab6..da9e817c3 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.6 + 0.42.0-beta.7 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 09cadbe1e..91833b915 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.6 + 0.42.0-beta.7 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index b17a9df4c..c091a6116 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" 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 0b444ac1f..4eb32dabe 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.42.0-beta.6", + "version": "0.42.0-beta.7", "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 adb255d7d..a1e084617 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.42.0-beta.6", + "version": "0.42.0-beta.7", "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 efe97711f..0ea788c08 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.42.0-beta.6", + "version": "0.42.0-beta.7", "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 7016af395..224debf13 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.42.0-beta.6", + "version": "0.42.0-beta.7", "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 4ab682b73..abd60fd2b 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.42.0-beta.6", + "version": "0.42.0-beta.7", "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 6ca3e36d8..ae4c80c2e 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.42.0-beta.6", + "version": "0.42.0-beta.7", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index d0108ae01..1f3764880 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.42.0-beta.6", + "version": "0.42.0-beta.7", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 150f358cf..8a250f230 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.6", + "version": "0.42.0-beta.7", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index be511189d..20426db54 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index c2dabe4f9..e94df328f 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 8ef396b5f..dab312eae 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.6" +version = "0.42.0-beta.7" edition = "2021" license.workspace = true repository.workspace = true From a9028ef44171ac55f5f7bef9517c6eb9175d474e Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Fri, 6 Nov 2026 17:37:52 +0800 Subject: [PATCH 035/203] feat(search): document and validate calibrated effort tiers (#4882) Lance beta.11 calibrates lower `search_effort` tiers by metric and requested `k`. With the Rust dependency and Python/Node execution tests already on main via #4881, document the tiers across Rust, Python, Node and the search guide, extend the remote request matrix to cover `0.1` and `0.25`, and align the Python test package with beta.11. `0.1` and `0.25` target empirical mean partition-routing recall of 80% and 90% for L2, cosine and dot through `k=100000`. These are not per-query or final Recall@k guarantees. Default Auto is unchanged; Hamming and larger `k` remain uncalibrated, and remote queries require corresponding server support. This PR makes no additional performance claim. See [Lance #10695](https://github.com/lance-format/lance/pull/10695) for measurements and limitations. Validation: both strict workspace Clippy configurations, Rust formatting, 13 Rust effort tests, 208 Python query tests, 41 Node query tests, native binding builds, TypeScript, Node lint/generated docs, Python lint/format, full lockfile check and two dependency guards passed on `a8b09170`. All validated Rust/Python/Node source and dependency files are byte-identical at `2a82d07c`; the only subsequent change restores the Java POM to main. Root Ruff has 59 existing diagnostics and six formatting files, all byte-identical to the base; the Python package passes. The Java REST/Namespace client has no changed API here, and its dependency remains identical to main. The separate [Java beta publication failure](https://github.com/lance-format/lance/issues/10773) is not claimed resolved or validated. Official SDK release, automatic mirror, Sophon adoption and measured consumer acceptance remain follow-up stages. --- docs/src/js/classes/VectorQuery.md | 5 +++++ docs/web/search/vector-search.mdx | 18 ++++++++++++++++++ nodejs/lancedb/query.ts | 5 +++++ python/pyproject.toml | 2 +- python/python/lancedb/query.py | 15 +++++++++++++++ python/uv.lock | 16 ++++++++-------- rust/lancedb/src/query.rs | 6 +++++- rust/lancedb/src/remote/table.rs | 3 ++- 8 files changed, 59 insertions(+), 11 deletions(-) diff --git a/docs/src/js/classes/VectorQuery.md b/docs/src/js/classes/VectorQuery.md index e4cc0f1cc..2eef209bf 100644 --- a/docs/src/js/classes/VectorQuery.md +++ b/docs/src/js/classes/VectorQuery.md @@ -686,6 +686,11 @@ searchEffort(searchEffort): VectorQuery Set the initial IVF search effort to a finite value in [0, 1]. +Efforts 0.1 and 0.25 target empirical mean partition-routing recall of +80% and 90% for L2, cosine and dot through k=100000. The probe budget +adapts to the metric and k. Hamming and larger k remain uncalibrated; +100000 is not an API limit. Remote queries also require server support. + The default, null, uses Auto (internally 0.5). Zero starts at the caller minimum; one searches all partitions within the caller maximum. Later probing may continue when too few candidates are found. diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index ed8e686b4..3fb0a2fe8 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -268,6 +268,24 @@ Use `search_effort` to tune how much work a search does. It accepts values from too low, or decrease it when you can trade some recall for lower latency. `search_effort(0.95)` does **not** mean 95% recall. +SDK builds using Lance 15.0.0-beta.11 or later provide these calibrated tiers: + +| Effort | Empirical mean partition-routing target | +| :--- | :--- | +| `0.1` | 80% | +| `0.25` | 90% | +| `0.5` (default) | Approximately 95%; existing Auto behavior | + +The probe budget adapts to the distance metric and requested `k`, so you can +keep the same effort when changing the result count. The lower tiers were +calibrated for `l2`, `cosine` and `dot` through `k=100000`. This is the tested +range, not a limit on `k`; Hamming and larger requests remain uncalibrated. + +These are average routing objectives, not guarantees for each query or final +Recall@k. Quantization, filtering and explicit probe bounds can lower final +recall. Remote queries require a server with the corresponding Lance version; +upgrading only the client does not change server-side routing. + {PyVectorIndexSearchEffort} diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 8f16defbf..cbd927925 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -854,6 +854,11 @@ export class VectorQuery extends StandardQueryBase { /** * Set the initial IVF search effort to a finite value in [0, 1]. * + * Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + * 80% and 90% for L2, cosine and dot through k=100000. The probe budget + * adapts to the metric and k. Hamming and larger k remain uncalibrated; + * 100000 is not an API limit. Remote queries also require server support. + * * The default, null, uses Auto (internally 0.5). Zero starts at the caller * minimum; one searches all partitions within the caller maximum. Later * probing may continue when too few candidates are found. diff --git a/python/pyproject.toml b/python/pyproject.toml index 1655dedcb..3a19fd826 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b10", + "pylance==15.0.0b11", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index ce313c610..08ea3b9bc 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2060,6 +2060,11 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): def search_effort(self, search_effort: Optional[float]) -> LanceVectorQueryBuilder: """Set the initial IVF search effort to a finite value in [0, 1]. + Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + 80% and 90% for L2, cosine and dot through k=100000. The probe budget + adapts to the metric and k. Hamming and larger k remain uncalibrated; + 100000 is not an API limit. Remote queries also require server support. + None (the default) uses Auto, internally 0.5. Zero starts at the caller minimum; one searches all partitions within the caller maximum. Later probing may continue when too few candidates are found. Any explicit @@ -3019,6 +3024,11 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): def search_effort(self, search_effort: Optional[float]) -> LanceHybridQueryBuilder: """Set the initial IVF search effort to a finite value in [0, 1]. + Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + 80% and 90% for L2, cosine and dot through k=100000. The probe budget + adapts to the metric and k. Hamming and larger k remain uncalibrated; + 100000 is not an API limit. Remote queries also require server support. + None (the default) uses Auto, internally 0.5. Zero starts at the caller minimum; one searches all partitions within the caller maximum. Later probing may continue when too few candidates are found. Any explicit @@ -4426,6 +4436,11 @@ class AsyncVectorQueryBase: def search_effort(self, search_effort: Optional[float]) -> Self: """Set the initial IVF search effort to a finite value in [0, 1]. + Efforts 0.1 and 0.25 target empirical mean partition-routing recall of + 80% and 90% for L2, cosine and dot through k=100000. The probe budget + adapts to the metric and k. Hamming and larger k remain uncalibrated; + 100000 is not an API limit. Remote queries also require server support. + None preserves Auto (internally 0.5) and fixed nprobes. Any explicit effort, including 0.5, overrides nprobes in either call order; explicit minimum and maximum bounds remain effective. Zero starts at the caller diff --git a/python/uv.lock b/python/uv.lock index 6abf904a4..d8a1c118a 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b10" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b11" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b10" +version = "15.0.0b11" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,12 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1aEUT6/pylance-15.0.0b10-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:fe34d42c5d58008a65f41acb659474c43848104414a2af94461454377c9f5276" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1YU4YL/pylance-15.0.0b10-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1042942b4df0ea42d263bf2e12ac2fa04e24ea49482f55349687df439686f614" }, - { url = "https://pypi.fury.io/lance-format/-/ver_LnRBy/pylance-15.0.0b10-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f0954e2a3855bc161a9ffebfcdf7f7086da3fa71ef1f3a92bd38212076963b08" }, - { url = "https://pypi.fury.io/lance-format/-/ver_pjVe1/pylance-15.0.0b10-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:eb6bc476f79d4c1b786377ae8366afc1718f54a9314141e65c57ad0f47906df6" }, - { url = "https://pypi.fury.io/lance-format/-/ver_RENd/pylance-15.0.0b10-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4dc325458b5b959bc644487c2ade6cdbcc89c4bc14ee7bb7487d9e145426207c" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1I5wzV/pylance-15.0.0b10-cp310-abi3-win_amd64.whl", hash = "sha256:10226cf5c224c0a47d18d7a323ce64473026acd7a4f08e7c6a59e787ee93a73c" }, + { url = "https://pypi.fury.io/lance-format/-/ver_oRP5O/pylance-15.0.0b11-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:54524c1bd04065516aeb97c5d06e1f6c88d1b1d5191d40077b104c5879893ea2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1LdITz/pylance-15.0.0b11-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8f6b2496b4b20787ff7780907f3017cf7b17c1f2bd1fa8cb7ed4d0a450445dfc" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1ONuyB/pylance-15.0.0b11-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:903283401e222dea532a36b91ffa60e7eaaf4d1fc08602cb29eef4ac2d04a8ff" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2bWLjt/pylance-15.0.0b11-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ce8bb0242b1647ce0b9355a48339b8fe8415f3556209214d0b490afb6ee60b38" }, + { url = "https://pypi.fury.io/lance-format/-/ver_168GWI/pylance-15.0.0b11-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:387ad2b455ab5b00476d7a60ce96e6014239df239691ac219f0025a29ee19f6e" }, + { url = "https://pypi.fury.io/lance-format/-/ver_aU9I7/pylance-15.0.0b11-cp310-abi3-win_amd64.whl", hash = "sha256:7022c2afcdaf6f9e9444db5addc72033ad20ad301930b38238e246687628cd75" }, ] [[package]] diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 866bfbc0d..ad2dbdcbf 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -1329,7 +1329,11 @@ impl VectorQuery { /// /// None (the default) resolves to 0.5, preserving Auto probing. At 0 the /// search starts at the caller minimum; at 1 it searches all partitions - /// within the caller maximum. Intermediate values interpolate around Auto. + /// within the caller maximum. Efforts 0.1 and 0.25 target empirical mean + /// partition-routing recall of 80% and 90%, respectively, for L2, cosine + /// and dot with k up to 100,000. The budget adapts to the metric and k; + /// this is a calibration boundary, not a limit on k. Hamming and larger k + /// retain uncalibrated behavior. Other values interpolate between tiers. /// Later probing may continue when too few candidates are found. /// Any explicit value, including 0.5, overrides [`Self::nprobes`] regardless /// of setter order. Explicit minimum and maximum bounds still apply. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 895cc9f12..abba7ff94 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -7374,7 +7374,8 @@ mod tests { #[rstest] #[case::unset(None)] #[case::minimum(Some(0.0))] - #[case::low(Some(0.25))] + #[case::recall80(Some(0.1))] + #[case::recall90(Some(0.25))] #[case::auto(Some(0.5))] #[case::high(Some(0.75))] #[case::maximum(Some(1.0))] From d379bbb7226dffb6f291d2113b2b023eb5702c3e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:50:29 -0800 Subject: [PATCH 036/203] chore(deps): bump the rust-minor-patch group across 1 directory with 6 updates (#4798) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the rust-minor-patch group with 6 updates in the / directory: | Package | From | To | | --- | --- | --- | | [tonic](https://github.com/grpc/grpc-rust) | `0.14.6` | `0.14.9` | | [clap](https://github.com/clap-rs/clap) | `4.6.1` | `4.6.7` | | [unicode-width](https://github.com/unicode-rs/unicode-width) | `0.2.2` | `0.2.3` | | [tokio-stream](https://github.com/tokio-rs/tokio) | `0.1.18` | `0.1.19` | | [napi](https://github.com/napi-rs/napi-rs) | `3.15.0` | `3.16.0` | | [napi-derive](https://github.com/napi-rs/napi-rs) | `3.6.13` | `3.7.0` | Updates `tonic` from 0.14.6 to 0.14.9
Release notes

Sourced from tonic's releases.

tonic-build-v0.14.9

Fixed

  • fix/silence all clippy warnings (#2807)

Other

  • fix changelog duplicate and update repository URLs (#2943)
  • License update (#2749)

tonic-health-v0.14.9

Other

  • fix changelog duplicate and update repository URLs (#2943)
  • License update (#2749)

tonic-prost-build-v0.14.9

Fixed

  • fix/silence all clippy warnings (#2807)

Other

  • fix changelog duplicate and update repository URLs (#2943)
  • License update (#2749)

tonic-prost-v0.14.9

Fixed

  • fix/silence all clippy warnings (#2807)

Other

  • fix changelog duplicate and update repository URLs (#2943)
  • relax codec Default bounds (#2681)
  • License update (#2749)

tonic-reflection-v0.14.9

Fixed

  • (reflection) preserve custom options in served descriptors (#2730)

Other

  • fix changelog duplicate and update repository URLs (#2943)
  • enable missing feature for test build (#2820)
  • License update (#2749)

tonic-types-v0.14.9

Fixed

... (truncated)

Commits
  • 4c0f455 chore: release v0.14.9 (#2979)
  • 4ee0483 fix(server): set a timer on HTTP/1 connections so hyper's header read timeout...
  • a47b608 feat(transport): expose h2 reset stream settings on Endpoint (#2972)
  • 349166e grpc/load_balancing: Add address-checked subchannel helpers to TestEnv. (#2938)
  • 78a8f2d feat(tonic-xds): expose ADS keepalive knob in config (#2973)
  • 954d6d7 xds-client: align ADS keepalive defaults with other gRPC languages (#2970)
  • 4b61ef9 xds-client: add grpc crate transport implementation (#2920)
  • 5413799 chore: release v0.14.8 (#2966)
  • b8282b9 fix(tonic-web): fix dropped trailers in combined streaming call. (#2474)
  • 818532d chore: release v0.14.7 (#2800)
  • Additional commits viewable in compare view

Updates `clap` from 4.6.1 to 4.6.7
Release notes

Sourced from clap's releases.

v4.6.7

[4.6.7] - 2026-09-14

Features

  • (derive) Add #[command(defer = <bool>)] attribute to opt-in to lazy initialisation of subcommands

v4.6.6

[4.6.6] - 2026-08-06

Features

  • Add Command::get_overridden_usage

v4.6.5

[4.6.5] - 2026-07-31

Fixes

  • (help) Correctly mark which value_names are optional with num_args

v4.6.4

[4.6.4] - 2026-07-21

Internal

  • Update to syn v3

v4.6.3

[4.6.3] - 2026-07-20

Fixes

  • (derive) Allow "literal".function() as attribute values

v4.6.2

[4.6.2] - 2026-07-15

Fixes

  • (help) Say alias when there is only one
Changelog

Sourced from clap's changelog.

[4.6.7] - 2026-09-14

Features

  • (derive) Add #[command(defer = <bool>)] attribute to opt-in to lazy initialisation of subcommands

[4.6.6] - 2026-08-06

Features

  • Add Command::get_overridden_usage

[4.6.5] - 2026-07-31

Fixes

  • (help) Correctly mark which value_names are optional with num_args

[4.6.4] - 2026-07-21

Internal

  • Update to syn v3

[4.6.3] - 2026-07-20

Fixes

  • (derive) Allow "literal".function() as attribute values

[4.6.2] - 2026-07-15

Fixes

  • (help) Say alias when there is only one
Commits
  • d3e59a9 chore: Release
  • d997f87 docs: Update changelog
  • fb6058c Merge pull request #6409 from heaths/pwsh-support
  • 2310870 test(complete): Add tests for completer_for_path
  • 5967c17 refactor(complete): Move shell detection to Shells
  • 594602b fix(complete): Detect pwsh for PowerShell
  • 3a4f2d0 Merge pull request #6427 from clap-rs/renovate/shlex-2.x
  • 67ebaed Merge pull request #6426 from clap-rs/renovate/actions-checkout-7.x
  • c968b13 chore(deps): Update Rust crate shlex to v2
  • 8f247cb chore(deps): Update actions/checkout action to v7
  • Additional commits viewable in compare view

Updates `unicode-width` from 0.2.2 to 0.2.3
Commits
  • f8c8b20 Publish 0.2.3 (#100)
  • 5180748 Fix documentation of Kirat Rai rules (#97)
  • 0b85fb8 Update to Unicode 18 (#96)
  • 832f7ca Fix typo in docs (#90)
  • c7b4d42 Fix halfwidth katakana voiced and semi-voiced sound marks in width calculatio...
  • a3d4ee6 Fix mistake in the specification of Arabic lam-alef ligature (#92)
  • d8654db Split generated file into multiple files, separating static code from generat...
  • ab7a6dc Support char iter width (#83)
  • b10a4d5 Exclude development scripts from published packages (#80)
  • See full diff in compare view

Updates `tokio-stream` from 0.1.18 to 0.1.19
Commits
  • bc0933c chore: prepare tokio-stream v0.1.19 (#8310)
  • e3786d0 readme: remove obsolete TokioConf notices (#8311)
  • f2189d3 chore: prepare tokio-util v0.7.19 (#8309)
  • 52f2745 net: re-enable tcp_stream::try_read_buf test for WASI (#8305)
  • ac6869a rt: remove unstable cfgs leftovers after local runtime stabilization (#8298)
  • 75fef53 chore: prepare Tokio v1.53.1 (#8303)
  • ae9d011 signal: restore MSRV by removing OnceLock::wait from the Windows handler (#8300)
  • eb4988d time: fix the loom test of the race between cancellation/insertion (#8302)
  • 91d3b4c time: fix alt timer cancellation and insertion race (#8252)
  • a463384 runtime: remove dead link definition in Runtime::block_on (#8301)
  • Additional commits viewable in compare view

Updates `napi` from 3.15.0 to 3.16.0
Release notes

Sourced from napi's releases.

napi-v3.16.0

Added

  • (napi) support well-known symbol keys for class members (#3665)
  • (napi) support symbol_for keys for class members (#3661)

Fixed

  • (napi) compact class identity metadata (#3667)
  • (napi) keep the registered classes when a later load fails (#3666)
  • (napi) free define_class closures, honour static flags, avoid TS1016 in constructors (#3662)
  • (napi) free threadsafe function call data when the call fails (#3656)
Commits
  • f89400d chore: release (#3637)
  • 192cbaa chore(deps): update dependency @​types/inquirer to v10 (#3668)
  • 9188219 chore(deps): update dependency electron to v45 (#3634)
  • 1d93a4e fix(napi): compact class identity metadata (#3667)
  • e9de902 fix(napi): keep the registered classes when a later load fails (#3666)
  • cad7ff7 feat(napi): support well-known symbol keys for class members (#3665)
  • c01ce60 fix(napi): free define_class closures, honour static flags, avoid TS1016 in c...
  • 5a49dad feat(napi): support symbol_for keys for class members (#3661)
  • 0c58903 fix(napi): free threadsafe function call data when the call fails (#3656)
  • ada66a3 chore(deps): update release-plz/action action to v0.5.147 (#3659)
  • Additional commits viewable in compare view

Updates `napi-derive` from 3.6.13 to 3.7.0
Release notes

Sourced from napi-derive's releases.

napi-derive-v3.7.0

Added

  • (napi) support well-known symbol keys for class members (#3665)
  • (napi) support symbol_for keys for class members (#3661)

Fixed

  • (napi) free define_class closures, honour static flags, avoid TS1016 in constructors (#3662)
Commits
  • f89400d chore: release (#3637)
  • 192cbaa chore(deps): update dependency @​types/inquirer to v10 (#3668)
  • 9188219 chore(deps): update dependency electron to v45 (#3634)
  • 1d93a4e fix(napi): compact class identity metadata (#3667)
  • e9de902 fix(napi): keep the registered classes when a later load fails (#3666)
  • cad7ff7 feat(napi): support well-known symbol keys for class members (#3665)
  • c01ce60 fix(napi): free define_class closures, honour static flags, avoid TS1016 in c...
  • 5a49dad feat(napi): support symbol_for keys for class members (#3661)
  • 0c58903 fix(napi): free threadsafe function call data when the call fails (#3656)
  • ada66a3 chore(deps): update release-plz/action action to v0.5.147 (#3659)
  • Additional commits viewable in compare view

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Cargo.lock | 55 +++++++++++++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 53d6d970f..ca3ea29d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1808,9 +1808,9 @@ 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", @@ -1818,9 +1818,9 @@ dependencies = [ [[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", @@ -1830,14 +1830,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.1" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -1903,7 +1903,7 @@ checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47" dependencies = [ "crossterm", "unicode-segmentation", - "unicode-width 0.2.2", + "unicode-width 0.2.3", ] [[package]] @@ -1956,7 +1956,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "windows-sys 0.59.0", ] @@ -4572,9 +4572,9 @@ dependencies = [ [[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", @@ -4934,7 +4934,7 @@ dependencies = [ "console", "number_prefix", "portable-atomic", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "web-time", ] @@ -6077,7 +6077,7 @@ dependencies = [ "toml", "tonic", "tracing", - "unicode-width 0.2.2", + "unicode-width 0.2.3", "url", "which", ] @@ -6735,9 +6735,9 @@ dependencies = [ [[package]] name = "napi" -version = "3.15.0" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a746ad50efbfb632ade1de4025519a477decbbd798cea1a6ac41d7c44f80083" +checksum = "e4febd3f6e8b57aa986853be5b24f80a1856753535219aec431cce854cd666fc" dependencies = [ "bitflags 2.11.1", "chrono", @@ -6761,9 +6761,9 @@ checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" [[package]] name = "napi-derive" -version = "3.6.13" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff48271a0f61abb83f3e2d1989fa71169143db95f6f948c3a8903961f2855dc" +checksum = "d32eb00f92f84cf462fc328f49082b29c2a7d2eebeb1d447d19c1f9fdd9f89ee" dependencies = [ "convert_case", "ctor", @@ -6775,9 +6775,9 @@ dependencies = [ [[package]] name = "napi-derive-backend" -version = "6.1.6" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2639052c5aff9956a21d7b6202fc61d5e89c5f19c72d289b7a0641ea94e8159" +checksum = "d1fe28c64d8fc12e69f9b817d0febdbe7914555760f1e353106281b8ff99cc90" dependencies = [ "convert_case", "proc-macro2", @@ -11061,9 +11061,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", @@ -11181,9 +11181,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "tonic" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +checksum = "e2cdfc673aabd30fe8fee92e65837b644c37c5d47f0f97ae6d5e0f1237d15e1b" dependencies = [ "async-trait", "axum 0.8.9", @@ -11204,6 +11204,7 @@ dependencies = [ "tokio", "tokio-rustls", "tokio-stream", + "tokio-util", "tower", "tower-layer", "tower-service", @@ -11472,9 +11473,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "unicode-xid" @@ -11611,9 +11612,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", ] From 2af85bea8999c8cd23ec01ff62ba110c54652c10 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 6 Nov 2026 09:19:27 -0800 Subject: [PATCH 037/203] feat: expose the remaining refresh options on the SDKs (#4890) The server's backfill request takes a row filter, failure limits, per-call timeouts and worker sizing, and SQL exposes all of them through `REFRESH COLUMN ... WHERE ... WITH (...)`, but the typed SDKs could send only batch_size, GPU placement and the retry and error policies. Anyone needing a filtered refresh or a bounded skip policy had to drop to SQL. This adds `where`, `max_failed_fraction`, `max_failed_rows`, `row_timeout_seconds`, `init_timeout_seconds`, `num_workers` and `max_executor_processes_per_worker` to Python, Rust and Node, passed through unchanged. `RefreshColumnOptions` now serializes straight into the request body, so the three SDKs share one producer. Node gets a `RefreshColumnOptions` object, which also carries the options it lacked before. A LanceDB Embedded refresh rejects every option other than batch_size and GPU placement, naming the option. --- docs/src/js/classes/Table.md | 25 ++- docs/src/js/globals.md | 1 + .../src/js/interfaces/RefreshColumnOptions.md | 124 +++++++++++++++ .../feature-engineering/refresh-column.mdx | 53 ++++++- nodejs/__test__/remote.test.ts | 74 +++++++++ nodejs/__test__/table.test.ts | 11 ++ nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 42 ++++- nodejs/src/table.rs | 88 +++++++++- python/python/lancedb/_lancedb.pyi | 14 ++ python/python/lancedb/remote/table.py | 28 ++++ python/python/lancedb/table.py | 150 ++++++++++++++++++ python/python/tests/test_remote_db.py | 31 ++++ python/python/tests/test_table.py | 25 ++- python/src/table.rs | 104 +++++++++++- rust/lancedb/src/remote/table.rs | 107 +++++++++++-- rust/lancedb/src/table.rs | 14 +- rust/lancedb/src/table/refresh.rs | 135 +++++++++++++++- 18 files changed, 974 insertions(+), 53 deletions(-) create mode 100644 docs/src/js/interfaces/RefreshColumnOptions.md diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 1226d5a1c..8bdc6b5f8 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1082,7 +1082,7 @@ for await (const batch of table.query()) { ### refreshColumn() ```ts -abstract refreshColumn(column): Promise +abstract refreshColumn(column, options?): Promise ``` Fill the rows of a computed column that hold no value yet. @@ -1098,6 +1098,10 @@ Enterprise a refresh runs as a server job, through [Table#refreshColumnAsync](Ta * **column**: `string` The name of the computed column to fill. +* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md) + Refresh options, all LanceDB + Enterprise only; see [Table#refreshColumnAsync](Table.md#refreshcolumnasync). + #### Returns `Promise`<[`RefreshColumnResult`](../interfaces/RefreshColumnResult.md)> @@ -1110,7 +1114,7 @@ number of rows filled and the new version number of the table. ### refreshColumnAsync() ```ts -abstract refreshColumnAsync(column): Promise +abstract refreshColumnAsync(column, options?): Promise ``` Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh @@ -1130,6 +1134,16 @@ LanceDB Enterprise it is the server's backfill job. * **column**: `string` The name of the computed column to fill. +* **options?**: [`RefreshColumnOptions`](../interfaces/RefreshColumnOptions.md) + Refresh options, mirroring the SQL + `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, + `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` + and `initTimeoutSeconds` govern failing rows, and `batchSize`, + `gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker` + size the workers. All are LanceDB Enterprise only; a LanceDB Embedded + refresh rejects every option other than `batchSize`, `gpuClass` and + `gpuCount`. + #### Returns `Promise`<[`Job`](Job.md)> @@ -1137,7 +1151,12 @@ LanceDB Enterprise it is the server's backfill job. #### Example ```ts -const job = await table.refreshColumnAsync("doubled"); +const job = await table.refreshColumnAsync("embedding", { + where: "published_at > '2026-01-01'", + errorPolicy: "skip", + maxFailedFraction: 0.01, + rowTimeoutSeconds: 30, +}); await job.wait(); console.log(await job.status()); // "finished" ``` diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index d6437219e..46f8db833 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -122,6 +122,7 @@ - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) +- [RefreshColumnOptions](interfaces/RefreshColumnOptions.md) - [RefreshColumnResult](interfaces/RefreshColumnResult.md) - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md) - [RemovalStats](interfaces/RemovalStats.md) diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md new file mode 100644 index 000000000..840012040 --- /dev/null +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -0,0 +1,124 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RefreshColumnOptions + +# Interface: RefreshColumnOptions + +Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every +option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores +`batchSize`, `gpuClass` and `gpuCount` and rejects the rest. + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Maximum rows per Function call; must be greater than zero. + +*** + +### errorPolicy? + +```ts +optional errorPolicy: string; +``` + +`"fail"` (default) stops on a row error; `"skip"` writes null and +records the error, subject to the failure limits. + +*** + +### gpuClass? + +```ts +optional gpuClass: string; +``` + +GPU class for Function workers. + +*** + +### gpuCount? + +```ts +optional gpuCount: number; +``` + +Positive aggregate GPU budget for Function workers. + +*** + +### initTimeoutSeconds? + +```ts +optional initTimeoutSeconds: number; +``` + +Deadline for Function initialization, in seconds. + +*** + +### maxExecutorProcessesPerWorker? + +```ts +optional maxExecutorProcessesPerWorker: number; +``` + +Cap on executor processes per Function worker. + +*** + +### maxFailedFraction? + +```ts +optional maxFailedFraction: number; +``` + +Under a skip policy, fail the job once more than this share of rows +(0 to 1) has failed. + +*** + +### maxFailedRows? + +```ts +optional maxFailedRows: number; +``` + +Under a skip policy, fail the job once more than this many rows have +failed. + +*** + +### numWorkers? + +```ts +optional numWorkers: number; +``` + +Worker count for an expression column; Function columns reject it. + +*** + +### rowTimeoutSeconds? + +```ts +optional rowTimeoutSeconds: number; +``` + +Deadline for one Function call, in seconds. + +*** + +### where? + +```ts +optional where: string; +``` + +Only refresh the rows matching this SQL filter. diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 24d050362..8f5726307 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -241,10 +241,59 @@ GPU class discovery. The Rust GPU discovery and refresh controls are not in the latest Rust -release. TypeScript does not expose GPU class discovery or placement; a -tracking issue is needed before adding equivalent controls. +release. TypeScript does not expose GPU class discovery; pass `gpuClass` +and `gpuCount` in the `refreshColumnAsync` options. +The job APIs also take the row filter and failure handling of the SQL +`REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed +to new rows and told to skip rows whose Function call fails: + + +```python +job = table.refresh_column_async( + "embedding", + where="published_at > '2026-01-01'", + error_policy="skip", + max_failed_fraction=0.01, + row_timeout_seconds=30, +) +``` + +```typescript +const job = await table.refreshColumnAsync("embedding", { + where: "published_at > '2026-01-01'", + errorPolicy: "skip", + maxFailedFraction: 0.01, + rowTimeoutSeconds: 30, +}); +``` + +```rust +use lancedb::{function::FunctionErrorPolicy, table::RefreshColumnOptions}; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default() + .where_clause("published_at > '2026-01-01'") + .error_policy(FunctionErrorPolicy::Skip) + .max_failed_fraction(0.01) + .row_timeout_seconds(30.0), + ) + .await?; +``` + + +`max_failed_rows`, `init_timeout_seconds`, `num_workers` and +`max_executor_processes_per_worker` are accepted the same way; the +[SQL refresh options](/sql/dml/refresh-column#options) describe each one. +The SDK rejects a blank `where`, a `max_failed_fraction` outside 0 to 1, a +timeout that is not a positive number and a zero worker or process count +before sending the request; the server validates everything else. A LanceDB +Embedded refresh rejects every option other than `batch_size`, `gpu_class` +and `gpu_count`. + ## When a refresh fails {#failures} What a failure keeps depends on where the refresh ran. The local, blocking diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index b11a79a67..242be6101 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -647,6 +647,80 @@ describe("remote connection", () => { ]); }); + it("forwards refresh options to the backfill request", async () => { + const bodies: unknown[] = []; + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 1, + schema: { fields: [] }, + }), + ); + return; + } + if (path === "/v1/table/docs/backfill_column") { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + bodies.push(JSON.parse(body)); + res + .writeHead(202, { "Content-Type": "application/json" }) + .end('{"job_id": "j-9"}'); + }); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.refreshColumnAsync("embedding", { + where: "id % 2 = 0", + batchSize: 16, + gpuClass: "a10g", + gpuCount: 2, + errorPolicy: "skip", + maxFailedFraction: 0.01, + maxFailedRows: 50, + rowTimeoutSeconds: 30, + initTimeoutSeconds: 120, + maxExecutorProcessesPerWorker: 2, + }); + expect(job.id).toBe("j-9"); + await table.refreshColumnAsync("embedding"); + // Invalid options reject before any request is sent. + for (const [options, message] of [ + [{ maxFailedRows: -1 }, "maxFailedRows"], + [{ errorPolicy: "retry" }, "errorPolicy"], + [{ where: " " }, "where"], + [{ maxFailedFraction: 2 }, "max_failed_fraction"], + [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], + [{ numWorkers: 0 }, "num_workers"], + [{ gpuCount: 0 }, "gpu_count"], + ] as const) { + await expect( + table.refreshColumnAsync("embedding", options), + ).rejects.toThrow(message); + } + }, + ); + expect(bodies).toEqual([ + JSON.parse( + `{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16, + "gpu_class": "a10g", "gpu_count": 2, "error_policy": "skip", + "max_failed_fraction": 0.01, "max_failed_rows": 50, + "row_timeout_seconds": 30, "init_timeout_seconds": 120, + "max_executor_processes_per_worker": 2}`, + ), + { column: "embedding" }, + ]); + }); + it("surfaces JSON server errors from remote table operations", async () => { await withMockDatabase( (req, res) => { diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index bbe1d6a71..af66ebb60 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5590,6 +5590,17 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([2, 4]); }); + it("rejects Enterprise refresh options on local tables", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("refresh_options_local", [{ x: 1 }]); + await expect(table.refreshColumn("x", { where: "x > 0" })).rejects.toThrow( + "where requires a LanceDB Enterprise refresh", + ); + await expect( + table.refreshColumnAsync("x", { errorPolicy: "skip" }), + ).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh"); + }); + it("records Function errors only on remote tables", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("errors_local", [{ x: 1 }]); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 58f687e1a..0e054d70e 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -56,6 +56,7 @@ export { MergeResult, AddResult, AddColumnsResult, + RefreshColumnOptions, RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index e84704803..de22ef0f8 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -38,6 +38,7 @@ import { Branches as NativeBranches, OptimizeStats, RTEStats, + RefreshColumnOptions, RefreshColumnResult, RefreshMaterializedViewResult, TableStatistics, @@ -671,10 +672,15 @@ export abstract class Table { * everything else is left as it is. LanceDB Embedded only: in LanceDB * Enterprise a refresh runs as a server job, through {@link Table#refreshColumnAsync}. * @param {string} column The name of the computed column to fill. + * @param {RefreshColumnOptions} options Refresh options, all LanceDB + * Enterprise only; see {@link Table#refreshColumnAsync}. * @returns {Promise} A promise that resolves to the * number of rows filled and the new version number of the table. */ - abstract refreshColumn(column: string): Promise; + abstract refreshColumn( + column: string, + options?: RefreshColumnOptions, + ): Promise; /** * Like {@link Table#refreshColumn}, but returns a handle to the refresh @@ -689,14 +695,30 @@ export abstract class Table { * than failing the job. In LanceDB Embedded the job runs in-process; in * LanceDB Enterprise it is the server's backfill job. * @param {string} column The name of the computed column to fill. + * @param {RefreshColumnOptions} options Refresh options, mirroring the SQL + * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, + * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` + * and `initTimeoutSeconds` govern failing rows, and `batchSize`, + * `gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker` + * size the workers. All are LanceDB Enterprise only; a LanceDB Embedded + * refresh rejects every option other than `batchSize`, `gpuClass` and + * `gpuCount`. * @example * ```ts - * const job = await table.refreshColumnAsync("doubled"); + * const job = await table.refreshColumnAsync("embedding", { + * where: "published_at > '2026-01-01'", + * errorPolicy: "skip", + * maxFailedFraction: 0.01, + * rowTimeoutSeconds: 30, + * }); * await job.wait(); * console.log(await job.status()); // "finished" * ``` */ - abstract refreshColumnAsync(column: string): Promise; + abstract refreshColumnAsync( + column: string, + options?: RefreshColumnOptions, + ): Promise; /** * The per-row errors Function refreshes recorded on this table. @@ -1472,12 +1494,18 @@ export class LocalTable extends Table { throw new Error("Invalid input type for addColumns"); } - async refreshColumn(column: string): Promise { - return await this.inner.refreshColumn(column); + async refreshColumn( + column: string, + options?: RefreshColumnOptions, + ): Promise { + return await this.inner.refreshColumn(column, options); } - async refreshColumnAsync(column: string): Promise { - return new Job(await this.inner.refreshColumnAsync(column)); + async refreshColumnAsync( + column: string, + options?: RefreshColumnOptions, + ): Promise { + return new Job(await this.inner.refreshColumnAsync(column, options)); } async functionErrors( diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index c480ba042..5c3805f51 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -421,20 +421,30 @@ impl Table { } #[napi(catch_unwind)] - pub async fn refresh_column(&self, column: String) -> napi::Result { + pub async fn refresh_column( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default().try_into()?; let res = self .inner_ref()? - .refresh_column(column) + .refresh_column_with_options(column, options) .await .default_error()?; Ok(res.into()) } #[napi(catch_unwind)] - pub async fn refresh_column_async(&self, column: String) -> napi::Result { + pub async fn refresh_column_async( + &self, + column: String, + options: Option, + ) -> napi::Result { + let options = options.unwrap_or_default().try_into()?; let job = self .inner_ref()? - .refresh_column_async(column) + .refresh_column_async_with_options(column, options) .await .default_error()?; Ok(crate::job::Job::new(job)) @@ -1515,6 +1525,76 @@ pub struct FunctionErrorsOptions { pub limit: Option, } +/// Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every +/// option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores +/// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest. +#[napi(object)] +#[derive(Clone, Debug, Default)] +pub struct RefreshColumnOptions { + /// Only refresh the rows matching this SQL filter. + #[napi(js_name = "where")] + pub where_clause: Option, + /// Maximum rows per Function call; must be greater than zero. + pub batch_size: Option, + /// GPU class for Function workers. + pub gpu_class: Option, + /// Positive aggregate GPU budget for Function workers. + pub gpu_count: Option, + /// `"fail"` (default) stops on a row error; `"skip"` writes null and + /// records the error, subject to the failure limits. + pub error_policy: Option, + /// Under a skip policy, fail the job once more than this share of rows + /// (0 to 1) has failed. + pub max_failed_fraction: Option, + /// Under a skip policy, fail the job once more than this many rows have + /// failed. + pub max_failed_rows: Option, + /// Deadline for one Function call, in seconds. + pub row_timeout_seconds: Option, + /// Deadline for Function initialization, in seconds. + pub init_timeout_seconds: Option, + /// Worker count for an expression column; Function columns reject it. + pub num_workers: Option, + /// Cap on executor processes per Function worker. + pub max_executor_processes_per_worker: Option, +} + +impl TryFrom for lancedb::table::RefreshColumnOptions { + type Error = napi::Error; + + fn try_from(value: RefreshColumnOptions) -> napi::Result { + let mut options = Self::default(); + options.where_clause = value.where_clause; + options.batch_size = value.batch_size.map(|size| size as usize); + options.gpu_class = value.gpu_class; + options.gpu_count = value.gpu_count; + options.error_policy = match value.error_policy.as_deref() { + None => None, + Some("fail") => Some(lancedb::function::FunctionErrorPolicy::Fail), + Some("skip") => Some(lancedb::function::FunctionErrorPolicy::Skip), + Some(other) => { + return Err(napi::Error::from_reason(format!( + "errorPolicy must be \"fail\" or \"skip\", got \"{other}\"" + ))); + } + }; + options.max_failed_fraction = value.max_failed_fraction; + options.max_failed_rows = value + .max_failed_rows + .map(|rows| { + u64::try_from(rows).map_err(|_| { + napi::Error::from_reason("maxFailedRows must be a non-negative integer") + }) + }) + .transpose()?; + options.row_timeout_seconds = value.row_timeout_seconds; + options.init_timeout_seconds = value.init_timeout_seconds; + options.num_workers = value.num_workers.map(|workers| workers as usize); + options.max_executor_processes_per_worker = value.max_executor_processes_per_worker; + Ok(options) + } +} + /// One row a Function refresh skipped, as the server recorded it. #[napi(object)] #[derive(Clone, Debug)] diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index f0f6027ad..a1a893f8b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -617,21 +617,35 @@ class Table: self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, error_policy: Optional[str] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> RefreshColumnResult: ... async def refresh_column_async( self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, error_policy: Optional[str] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> Job: ... async def function_errors( self, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index c916fcb92..6bef59922 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1138,20 +1138,34 @@ class RemoteTable(Table): self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ): return LOOP.run( self._table.refresh_column( column, + where=where, batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, ) ) @@ -1159,21 +1173,35 @@ class RemoteTable(Table): self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> Job[RefreshColumnResult]: return Job( LOOP.run( self._table.refresh_column_async( column, + where=where, batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, ) ) ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 559552cee..f43df8b40 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3164,11 +3164,18 @@ class Table(ABC): self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> "RefreshColumnResult": """ Fill the rows of a computed column that hold no value yet. @@ -3189,6 +3196,10 @@ class Table(ABC): ---------- column: str The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. batch_size: int, optional Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on @@ -3209,6 +3220,22 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- @@ -3222,11 +3249,18 @@ class Table(ABC): self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> Job[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -3245,6 +3279,10 @@ class Table(ABC): ---------- column: str The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. batch_size: int, optional Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Lower this for @@ -3266,6 +3304,22 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- @@ -5374,11 +5428,18 @@ class LanceTable(Table): self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose inputs changed. See @@ -5386,11 +5447,18 @@ class LanceTable(Table): return LOOP.run( self._table.refresh_column( column, + where=where, batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, ) ) @@ -5398,11 +5466,18 @@ class LanceTable(Table): self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> Job[RefreshColumnJobResult]: """Fill a computed column's unfilled rows and recompute those whose inputs changed, returning a handle to the refresh job. See @@ -5412,11 +5487,18 @@ class LanceTable(Table): LOOP.run( self._table.refresh_column_async( column, + where=where, batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, ) ) ) @@ -7769,11 +7851,18 @@ class AsyncTable: self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> RefreshColumnResult: """ Fill the rows of a computed column that hold no value yet. @@ -7794,6 +7883,10 @@ class AsyncTable: ---------- column: str The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. batch_size: int, optional Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on @@ -7814,6 +7907,22 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- @@ -7822,6 +7931,7 @@ class AsyncTable: """ return await self._inner.refresh_column( column, + where=where, batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, @@ -7829,6 +7939,12 @@ class AsyncTable: if retry_policy is None else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, ) async def function_errors( @@ -7924,11 +8040,18 @@ class AsyncTable: self, column: str, *, + where: Optional[str] = None, batch_size: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, error_policy: Optional[Literal["fail", "skip"]] = None, + max_failed_fraction: Optional[float] = None, + max_failed_rows: Optional[int] = None, + row_timeout_seconds: Optional[float] = None, + init_timeout_seconds: Optional[float] = None, + num_workers: Optional[int] = None, + max_executor_processes_per_worker: Optional[int] = None, ) -> AsyncJob[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -7947,6 +8070,10 @@ class AsyncTable: ---------- column: str The name of the computed column to fill. + where: str, optional + SQL filter selecting the rows to refresh, as in ``REFRESH COLUMN + ... WHERE``. Unfilled rows outside it stay unfilled. LanceDB + Enterprise only; local refreshes reject this option. batch_size: int, optional Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Lower this for @@ -7968,6 +8095,22 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + max_failed_fraction: float, optional + Under a skip policy, fail the job once more than this share of + rows (0 to 1) has failed. LanceDB Enterprise only. + max_failed_rows: int, optional + Under a skip policy, fail the job once more than this many rows + have failed. LanceDB Enterprise only. + row_timeout_seconds: float, optional + Deadline for one Function call. LanceDB Enterprise only. + init_timeout_seconds: float, optional + Deadline for Function initialization. LanceDB Enterprise only. + num_workers: int, optional + Worker count for an expression column; registered Function + columns reject it. LanceDB Enterprise only. + max_executor_processes_per_worker: int, optional + Cap on executor processes per Function worker. LanceDB + Enterprise only. Returns ------- @@ -7993,6 +8136,7 @@ class AsyncTable: return _typed_job( await self._inner.refresh_column_async( column, + where=where, batch_size=batch_size, gpu_class=gpu_class, gpu_count=gpu_count, @@ -8000,6 +8144,12 @@ class AsyncTable: if retry_policy is None else FunctionRetryPolicy.model_validate(retry_policy).model_dump_json(), error_policy=error_policy, + max_failed_fraction=max_failed_fraction, + max_failed_rows=max_failed_rows, + row_timeout_seconds=row_timeout_seconds, + init_timeout_seconds=init_timeout_seconds, + num_workers=num_workers, + max_executor_processes_per_worker=max_executor_processes_per_worker, ), RefreshColumnJobResult.from_json, ) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8e6d74e86..8a65a2a1c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1868,6 +1868,16 @@ def test_remote_create_index_async_returns_job(): "error_policy": "skip", }, {"retry_policy": {"max_attempts": 1}, "error_policy": "fail"}, + { + "where": "id % 2 = 0", + "error_policy": "skip", + "max_failed_fraction": 0.01, + "max_failed_rows": 50, + "row_timeout_seconds": 30, + "init_timeout_seconds": 120, + "num_workers": 4, + "max_executor_processes_per_worker": 2, + }, ], ) async def test_remote_refresh_async_returns_typed_terminal_result( @@ -1898,6 +1908,17 @@ async def test_remote_refresh_async_returns_typed_terminal_result( ).model_dump(mode="json") if refresh_kwargs.get("error_policy") is not None: expected["error_policy"] = refresh_kwargs["error_policy"] + for key in ( + "where", + "max_failed_fraction", + "max_failed_rows", + "row_timeout_seconds", + "init_timeout_seconds", + "num_workers", + "max_executor_processes_per_worker", + ): + if refresh_kwargs.get(key) is not None: + expected[key] = refresh_kwargs[key] assert json.loads(body) == expected request.send_response(202) request.send_header("Content-Type", "application/json") @@ -2061,6 +2082,16 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"gpu_count": -1}, "gpu_count"), ({"retry_policy": {"transient": True, "max_attempts": 0}}, "retry_policy"), ({"error_policy": "retry"}, "error_policy"), + ({"where": " "}, "where"), + ({"max_failed_fraction": 1.5}, "max_failed_fraction"), + ({"max_failed_rows": -1}, "max_failed_rows"), + ({"row_timeout_seconds": 0}, "row_timeout_seconds"), + ({"init_timeout_seconds": -5}, "init_timeout_seconds"), + ({"num_workers": 0}, "num_workers"), + ( + {"max_executor_processes_per_worker": -2}, + "max_executor_processes_per_worker", + ), ], ) @pytest.mark.asyncio diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 45ce9276e..2a502fe62 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5985,11 +5985,28 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) @pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"]) -def test_local_refresh_rejects_function_retry_policy(tmp_path, method): +@pytest.mark.parametrize( + "refresh_kwargs,option", + [ + ({"retry_policy": lancedb.FunctionRetryPolicy(transient=True)}, "retry_policy"), + ({"where": "x > 0"}, "where"), + ({"error_policy": "skip"}, "error_policy"), + ({"max_failed_fraction": 0.5}, "max_failed_fraction"), + ({"max_failed_rows": 10}, "max_failed_rows"), + ({"row_timeout_seconds": 30}, "row_timeout_seconds"), + ({"init_timeout_seconds": 60}, "init_timeout_seconds"), + ({"num_workers": 2}, "num_workers"), + ({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"), + ], +) +def test_local_refresh_rejects_enterprise_options( + tmp_path, method, refresh_kwargs, option +): table = lancedb.connect(tmp_path).create_table("rows", [{"x": 1}]) - policy = lancedb.FunctionRetryPolicy(transient=True) - with pytest.raises(NotImplementedError, match="Enterprise Function refresh"): - getattr(table, method)("x", retry_policy=policy) + with pytest.raises( + NotImplementedError, match=f"{option} requires a LanceDB Enterprise refresh" + ): + getattr(table, method)("x", **refresh_kwargs) @pytest.mark.asyncio diff --git a/python/src/table.rs b/python/src/table.rs index 4c5a919d2..6371d94c0 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -42,14 +42,62 @@ use pyo3::{ mod scannable; -fn refresh_column_options( +/// Keyword arguments shared by `refresh_column` and `refresh_column_async`. +struct RefreshColumnArgs { + where_clause: Option, batch_size: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, error_policy: Option, -) -> PyResult { + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, +} + +fn positive_count>(value: Option, name: &str) -> PyResult> { + value + .map(|v| { + T::try_from(v) + .ok() + .filter(|_| v > 0) + .ok_or_else(|| PyValueError::new_err(format!("{name} must be greater than zero"))) + }) + .transpose() +} + +fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { + let RefreshColumnArgs { + where_clause, + batch_size, + gpu_class, + gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + } = args; let mut options = RefreshColumnOptions::default(); + options.where_clause = where_clause; + options.max_failed_fraction = max_failed_fraction; + options.max_failed_rows = max_failed_rows + .map(u64::try_from) + .transpose() + .map_err(|_| PyValueError::new_err("max_failed_rows must be a non-negative integer"))?; + options.row_timeout_seconds = row_timeout_seconds; + options.init_timeout_seconds = init_timeout_seconds; + options.num_workers = positive_count(num_workers, "num_workers")?; + options.max_executor_processes_per_worker = positive_count( + max_executor_processes_per_worker, + "max_executor_processes_per_worker", + )?; options.retry_policy = retry_policy .map(|json| { serde_json::from_str(&json) @@ -2142,18 +2190,38 @@ impl Table { }) } - #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[allow(clippy::too_many_arguments)] pub fn refresh_column( self_: PyRef<'_, Self>, column: String, + r#where: Option, batch_size: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, ) -> PyResult> { - let options = - refresh_column_options(batch_size, gpu_class, gpu_count, retry_policy, error_policy)?; + let options = refresh_column_options(RefreshColumnArgs { + where_clause: r#where, + batch_size, + gpu_class, + gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let result = inner @@ -2164,18 +2232,38 @@ impl Table { }) } - #[pyo3(signature = (column, *, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[allow(clippy::too_many_arguments)] pub fn refresh_column_async( self_: PyRef<'_, Self>, column: String, + r#where: Option, batch_size: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, error_policy: Option, + max_failed_fraction: Option, + max_failed_rows: Option, + row_timeout_seconds: Option, + init_timeout_seconds: Option, + num_workers: Option, + max_executor_processes_per_worker: Option, ) -> PyResult> { - let options = - refresh_column_options(batch_size, gpu_class, gpu_count, retry_policy, error_policy)?; + let options = refresh_column_options(RefreshColumnArgs { + where_clause: r#where, + batch_size, + gpu_class, + gpu_count, + retry_policy, + error_policy, + max_failed_fraction, + max_failed_rows, + row_timeout_seconds, + init_timeout_seconds, + num_workers, + max_executor_processes_per_worker, + })?; let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let job = inner diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index abba7ff94..b781531fe 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3969,22 +3969,10 @@ impl BaseTable for RemoteTable { ) -> Result> { options.validate()?; self.check_mutable().await?; - let mut body = serde_json::json!({ "column": column }); - if let Some(batch_size) = options.batch_size { - body["batch_size"] = serde_json::json!(batch_size); - } - if let Some(gpu_class) = options.gpu_class { - body["gpu_class"] = serde_json::json!(gpu_class); - } - if let Some(gpu_count) = options.gpu_count { - body["gpu_count"] = serde_json::json!(gpu_count); - } - if let Some(policy) = options.retry_policy { - body["retry_policy"] = serde_json::json!(policy); - } - if let Some(policy) = options.error_policy { - body["error_policy"] = serde_json::json!(policy); - } + let mut body = serde_json::to_value(&options).map_err(|e| Error::Runtime { + message: format!("failed to serialize refresh options: {e}"), + })?; + body["column"] = serde_json::json!(column); self.apply_branch_body(&mut body); let request = self .client @@ -11021,6 +11009,93 @@ mod tests { ); } + #[tokio::test] + async fn test_refresh_column_async_filter_and_failure_options() { + use crate::function::FunctionErrorPolicy; + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "where": "id % 2 = 0", + "error_policy": "skip", + "max_failed_fraction": 0.01, + "max_failed_rows": 50, + "row_timeout_seconds": 30.0, + "init_timeout_seconds": 120.0, + "num_workers": 4, + "max_executor_processes_per_worker": 2, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-filtered"}"#) + .unwrap() + }); + let options = RefreshColumnOptions::default() + .where_clause("id % 2 = 0") + .error_policy(FunctionErrorPolicy::Skip) + .max_failed_fraction(0.01) + .max_failed_rows(50) + .row_timeout_seconds(30.0) + .init_timeout_seconds(120.0) + .num_workers(4) + .max_executor_processes_per_worker(2); + let job = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-filtered")); + } + + #[tokio::test] + async fn test_refresh_column_rejects_invalid_filter_and_limit_options_before_request() { + use crate::table::RefreshColumnOptions; + + let table = Table::new_with_handler("my_table", |_| -> http::Response { + panic!("invalid refresh options must not send a request") + }); + for (options, expected) in [ + (RefreshColumnOptions::default().where_clause(" "), "where"), + ( + RefreshColumnOptions::default().max_failed_fraction(1.5), + "max_failed_fraction", + ), + ( + RefreshColumnOptions::default().max_failed_fraction(f64::NAN), + "max_failed_fraction", + ), + ( + RefreshColumnOptions::default().row_timeout_seconds(0.0), + "row_timeout_seconds", + ), + ( + RefreshColumnOptions::default().init_timeout_seconds(f64::INFINITY), + "init_timeout_seconds", + ), + ( + RefreshColumnOptions::default().num_workers(0), + "num_workers", + ), + ( + RefreshColumnOptions::default().max_executor_processes_per_worker(0), + "max_executor_processes_per_worker", + ), + ] { + let error = table + .refresh_column_async_with_options("quality", options) + .await + .unwrap_err(); + assert!( + matches!(&error, Error::InvalidInput { message } if message.contains(expected)), + "{error:?}" + ); + } + } + #[tokio::test] async fn test_refresh_column_rejects_invalid_gpu_options_before_request() { use crate::table::RefreshColumnOptions; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 94a934c43..aefc0ac91 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -883,18 +883,17 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "this operation is only supported on LanceDB Embedded".into(), }) } - /// Refresh with options; expression-backed local refreshes ignore the - /// Function batch size. + /// Refresh with options. A local refresh ignores the Function batch size + /// and GPU placement and rejects every other option. async fn refresh_column_with_options( &self, column: &str, options: RefreshColumnOptions, ) -> Result { options.validate()?; - if options.retry_policy.is_some() || options.error_policy.is_some() { + if let Some(name) = options.enterprise_only_option() { return Err(Error::NotSupported { - message: "Function retry and error policies require an Enterprise Function refresh" - .into(), + message: format!("{name} requires a LanceDB Enterprise refresh"), }); } self.refresh_column(column).await @@ -916,10 +915,9 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { options: RefreshColumnOptions, ) -> Result> { options.validate()?; - if options.retry_policy.is_some() || options.error_policy.is_some() { + if let Some(name) = options.enterprise_only_option() { return Err(Error::NotSupported { - message: "Function retry and error policies require an Enterprise Function refresh" - .into(), + message: format!("{name} requires a LanceDB Enterprise refresh"), }); } self.refresh_column_async(column).await diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index a9e69452d..a8ae3c286 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -56,31 +56,107 @@ use crate::job::Job; use crate::{Error, Result}; /// Options for refreshing a computed column. -#[derive(Debug, Clone, Default)] +/// +/// Serializes to the Enterprise backfill request body, one key per set +/// option; the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form takes the +/// same names. +#[derive(Debug, Clone, Default, Serialize)] #[non_exhaustive] pub struct RefreshColumnOptions { + /// Only refresh the rows matching this SQL filter. Enterprise only. + #[serde(rename = "where", skip_serializing_if = "Option::is_none")] + pub where_clause: Option, /// Override the Function's default user-code retry policy. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] pub retry_policy: Option, /// Action after user-code failure or retry exhaustion. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] pub error_policy: Option, + /// Under a skip policy, fail the job once more than this share of rows + /// has failed, 0 to 1. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_failed_fraction: Option, + /// Under a skip policy, fail the job once more than this many rows have + /// failed. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_failed_rows: Option, + /// Deadline for one Function call, in seconds. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub row_timeout_seconds: Option, + /// Deadline for Function initialization, in seconds. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub init_timeout_seconds: Option, + /// Worker count for an expression column in LanceDB Enterprise; + /// registered Function columns reject it. + #[serde(skip_serializing_if = "Option::is_none")] + pub num_workers: Option, + /// At most this many executor processes per Function worker. Enterprise + /// only. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_executor_processes_per_worker: Option, /// Maximum rows per Function call in LanceDB Enterprise. /// /// Must be greater than zero. `None` uses the server default. This has no /// effect on expression-backed columns in LanceDB Embedded. + #[serde(skip_serializing_if = "Option::is_none")] pub batch_size: Option, /// GPU class for Function workers in LanceDB Enterprise. /// /// `None` keeps the Function's registered class, or the deployment default /// when the Function does not declare one. + #[serde(skip_serializing_if = "Option::is_none")] pub gpu_class: Option, /// Positive aggregate GPU budget for Function workers in LanceDB /// Enterprise. /// /// `None` leaves the server's configured budget unchanged. + #[serde(skip_serializing_if = "Option::is_none")] pub gpu_count: Option, } impl RefreshColumnOptions { + /// Only refresh the rows matching `filter`. + pub fn where_clause(mut self, filter: impl Into) -> Self { + self.where_clause = Some(filter.into()); + self + } + + /// Fail the job once more than `fraction` of its rows has failed. + pub fn max_failed_fraction(mut self, fraction: f64) -> Self { + self.max_failed_fraction = Some(fraction); + self + } + + /// Fail the job once more than `rows` rows have failed. + pub fn max_failed_rows(mut self, rows: u64) -> Self { + self.max_failed_rows = Some(rows); + self + } + + /// Give each Function call at most `seconds` to return. + pub fn row_timeout_seconds(mut self, seconds: f64) -> Self { + self.row_timeout_seconds = Some(seconds); + self + } + + /// Give Function initialization at most `seconds` to complete. + pub fn init_timeout_seconds(mut self, seconds: f64) -> Self { + self.init_timeout_seconds = Some(seconds); + self + } + + /// Request `num_workers` workers for an expression column refresh. + pub fn num_workers(mut self, num_workers: usize) -> Self { + self.num_workers = Some(num_workers); + self + } + + /// Cap executor processes per Function worker at `processes`. + pub fn max_executor_processes_per_worker(mut self, processes: u32) -> Self { + self.max_executor_processes_per_worker = Some(processes); + self + } + /// Override retries of failed Function calls for this refresh. pub fn retry_policy(mut self, policy: crate::function::FunctionRetryPolicy) -> Self { self.retry_policy = Some(policy); @@ -110,11 +186,68 @@ impl RefreshColumnOptions { self } + /// The first set option a LanceDB Embedded refresh cannot honor, if any. + pub fn enterprise_only_option(&self) -> Option<&'static str> { + [ + ("where", self.where_clause.is_some()), + ("retry_policy", self.retry_policy.is_some()), + ("error_policy", self.error_policy.is_some()), + ("max_failed_fraction", self.max_failed_fraction.is_some()), + ("max_failed_rows", self.max_failed_rows.is_some()), + ("row_timeout_seconds", self.row_timeout_seconds.is_some()), + ("init_timeout_seconds", self.init_timeout_seconds.is_some()), + ("num_workers", self.num_workers.is_some()), + ( + "max_executor_processes_per_worker", + self.max_executor_processes_per_worker.is_some(), + ), + ] + .into_iter() + .find_map(|(name, set)| set.then_some(name)) + } + /// Validate client-side constraints before any request is sent. pub fn validate(&self) -> Result<()> { + if self + .where_clause + .as_deref() + .is_some_and(|f| f.trim().is_empty()) + { + return Err(Error::InvalidInput { + message: "where must not be empty".into(), + }); + } if let Some(policy) = &self.retry_policy { policy.validate()?; } + if self + .max_failed_fraction + .is_some_and(|f| !f.is_finite() || !(0.0..=1.0).contains(&f)) + { + return Err(Error::InvalidInput { + message: "max_failed_fraction must be a finite number between 0 and 1".into(), + }); + } + for (name, seconds) in [ + ("row_timeout_seconds", self.row_timeout_seconds), + ("init_timeout_seconds", self.init_timeout_seconds), + ] { + if seconds.is_some_and(|s| !s.is_finite() || s <= 0.0) { + return Err(Error::InvalidInput { + message: format!("{name} must be a positive finite number"), + }); + } + } + if self.num_workers == Some(0) { + return Err(Error::InvalidInput { + message: "num_workers must be greater than zero".into(), + }); + } + if self.max_executor_processes_per_worker == Some(0) { + return Err(Error::InvalidInput { + message: "max_executor_processes_per_worker must be greater than zero".into(), + }); + } if self.batch_size == Some(0) { return Err(Error::InvalidInput { message: "batch_size must be greater than zero".into(), From 003d5e522f62fbffe322b46f48dd47aa70f7648a Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:46:18 -0800 Subject: [PATCH 038/203] docs: fix Rust example download links (#4896) The Rust example downloads in the ingestion, search, reranking and SQL guides point to `/static/code/*.zip` URLs that return HTTP 404 on the published docs site. Replace all 15 references across 13 pages with public GitHub downloads pinned to commit `2af85bea8999c8cd23ec01ff62ba110c54652c10`. The three archives already exist in this repository. Pinning their URLs preserves the exact source, dependency manifests and lockfiles used by the existing `cargo run --locked` instructions. Only link destinations change. Validation: - All three public download URLs return HTTP 200 with ZIP content. Downloaded bytes match the repository archives and the deployed docs source archives exactly, and ZIP integrity checks pass. - Verified that the diff contains exactly 15 URL replacements in 13 pages. No example code, run instructions, manifests or lockfiles changed. - `git diff --check` passes. - `mint broken-links` reports the same 16 existing missing internal links on both the unchanged `main` baseline and this branch. - `mint validate` reports four existing missing snippet exports (`RsExampleBody` and `RsExampleTail` in the reranking and vector-search pages); the unchanged baseline has the same warnings. The combined docs build and internal-link check pass with the equivalent download-link fix. --- docs/web/basics/sql.mdx | 2 +- docs/web/ingestion/create-table.mdx | 2 +- docs/web/ingestion/delete.mdx | 4 ++-- docs/web/ingestion/index.mdx | 2 +- docs/web/ingestion/insert.mdx | 4 ++-- docs/web/ingestion/merge-insert.mdx | 2 +- docs/web/ingestion/update.mdx | 2 +- docs/web/reranking/index.mdx | 2 +- docs/web/search/filtering.mdx | 2 +- docs/web/search/full-text-search.mdx | 2 +- docs/web/search/hybrid-search.mdx | 2 +- docs/web/search/index.mdx | 2 +- docs/web/search/vector-search.mdx | 2 +- 13 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 46f54ce53..31e3af1f3 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -274,7 +274,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `query_plan.py`, then run `python query_plan.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `query_plan.mts`, then run `node query_plan.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin query_plan` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin query_plan` from the extracted directory. diff --git a/docs/web/ingestion/create-table.mdx b/docs/web/ingestion/create-table.mdx index cd5a941f5..5bae930a5 100644 --- a/docs/web/ingestion/create-table.mdx +++ b/docs/web/ingestion/create-table.mdx @@ -366,7 +366,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/delete.mdx b/docs/web/ingestion/delete.mdx index 900d763ce..b80ab1c33 100644 --- a/docs/web/ingestion/delete.mdx +++ b/docs/web/ingestion/delete.mdx @@ -34,7 +34,7 @@ database is removed when the program finishes. `python delete_rows.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `delete_rows.mts`, and run `node delete_rows.mts` with Node.js 22.18 or later. -- **Rust:** download the [Rust examples](/static/code/ingestion-feedback-rust.zip), +- **Rust:** download the [Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-feedback-rust.zip), extract the project, and run `cargo run --locked --bin delete`. @@ -85,7 +85,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/index.mdx b/docs/web/ingestion/index.mdx index 28cfce650..26628c017 100644 --- a/docs/web/ingestion/index.mdx +++ b/docs/web/ingestion/index.mdx @@ -55,7 +55,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index 0b3c1b369..befc1c37b 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -112,7 +112,7 @@ Each program uses a temporary local database and removes it when finished. `python insert_progress.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `insert_progress.mts`, and run `node insert_progress.mts` with Node.js 22.18 or later. -- **Rust:** download the [Rust examples](/static/code/ingestion-feedback-rust.zip), +- **Rust:** download the [Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-feedback-rust.zip), extract the project, and run `cargo run --locked --bin progress`. @@ -214,7 +214,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index baf241b30..8106e7706 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -243,7 +243,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/ingestion/update.mdx b/docs/web/ingestion/update.mdx index 20afba962..4e2c2160c 100644 --- a/docs/web/ingestion/update.mdx +++ b/docs/web/ingestion/update.mdx @@ -105,7 +105,7 @@ prints the result, and removes its temporary data when finished. `python ingestion.py`. - **TypeScript:** install `@lancedb/lancedb`, save the code as `ingestion.mts`, and run `node ingestion.mts` with Node.js 22.18 or later. -- **Rust:** download the [complete Rust project](/static/code/ingestion-rust.zip), +- **Rust:** download the [complete Rust project](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/ingestion-rust.zip), extract it, and run `cargo run --locked`. It includes `src/main.rs`, the Cargo manifest and a lockfile for the example's dependencies. The code is shown below. diff --git a/docs/web/reranking/index.mdx b/docs/web/reranking/index.mdx index 1de69a2a8..38efc8843 100644 --- a/docs/web/reranking/index.mdx +++ b/docs/web/reranking/index.mdx @@ -44,7 +44,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `rerank_search.py`, then run `python rerank_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `rerank_search.mts`, then run `node rerank_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. diff --git a/docs/web/search/filtering.mdx b/docs/web/search/filtering.mdx index c97b5c17a..58c974614 100644 --- a/docs/web/search/filtering.mdx +++ b/docs/web/search/filtering.mdx @@ -25,7 +25,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `filtered_search.py`, then run `python filtered_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `filtered_search.mts`, then run `node filtered_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin filter_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin filter_search` from the extracted directory. diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 3132930e1..9c17fc50b 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -34,7 +34,7 @@ table when finished. No embedding model is needed for a text query. - **Python:** Install with `pip install lancedb`, save as `text_search.py`, then run `python text_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `text_search.mts`, then run `node text_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin text_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin text_search` from the extracted directory. diff --git a/docs/web/search/hybrid-search.mdx b/docs/web/search/hybrid-search.mdx index 79d340ce3..b94d9e460 100644 --- a/docs/web/search/hybrid-search.mdx +++ b/docs/web/search/hybrid-search.mdx @@ -33,7 +33,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `hybrid_search.py`, then run `python hybrid_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `hybrid_search.mts`, then run `node hybrid_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin hybrid_search` from the extracted directory. diff --git a/docs/web/search/index.mdx b/docs/web/search/index.mdx index 22178a852..3503954e6 100644 --- a/docs/web/search/index.mdx +++ b/docs/web/search/index.mdx @@ -50,7 +50,7 @@ and removes it when finished. - **Python:** Install with `pip install lancedb`, save as `search.py`, then run `python search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `search.mts`, then run `node search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index 3fb0a2fe8..2c37fef43 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -74,7 +74,7 @@ an embedding model. The temporary table is removed when the program finishes. - **Python:** Install with `pip install lancedb`, save as `vector_search.py`, then run `python vector_search.py`. - **TypeScript:** Install with `npm install @lancedb/lancedb`, save as `vector_search.mts`, then run `node vector_search.mts` with Node.js 22.18 or later. -- **Rust:** Download and extract the [complete Rust examples](/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. +- **Rust:** Download and extract the [complete Rust examples](https://raw.githubusercontent.com/lancedb/lancedb/2af85bea8999c8cd23ec01ff62ba110c54652c10/docs/web/static/code/search-rust.zip), then run `cargo run --locked --bin vector_search` from the extracted directory. From 96328f6e08f243cebec5bd00f541d4605a71ef94 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 6 Nov 2026 11:07:44 -0800 Subject: [PATCH 039/203] fix(node): upgrade transformers.js to 4.3.2 to pick up patched sharp (#4885) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary `@lancedb/lancedb` pins the optional dependency `@huggingface/transformers` at 3.0.2, which requires `sharp ^0.33.5`. Every npm install of LanceDB therefore pulled in a sharp version with critical advisories (GHSA-wq5f-xc86-pv6w, GHSA-rgj7-g3m4-5g8c). No 3.x release of transformers allows a patched sharp, so this upgrades to 4.3.2, which requires `sharp ^0.35.4`. A fresh install resolves that range to 0.35.5, the first release that fixes both advisories. - `nodejs/package.json`: `@huggingface/transformers` 3.0.2 → 4.3.2. - `nodejs/pnpm-workspace.yaml`: remove the `sharp: ^0.35.4` override. It only covered our own install, not consumers, and transformers now requires that range itself. - `nodejs/examples`: transformers 3.0.2 → 4.3.2, sharp 0.33.5 → 0.35.5. - Both lockfiles resolve sharp to 0.35.5; `pnpm audit` reports no sharp advisories in either. `TransformersEmbeddingFunction` needed no code changes. The transformers types are only used in private fields, so the published typings don't change. `docs/web-tests/ts` and `docs/web-tests/blob-v2/ts` are left alone: they resolve transformers through a published `@lancedb/lancedb`, so they pick this up after a release. ## Evidence Embeddings from the built-in `huggingface` embedding function (default `Xenova/all-MiniLM-L6-v2`) on 4.3.2, compared with the same mean pooling on 3.0.2, for three sentences: ``` transformers 4.3.2: 3 x 384 text 0: max|diff|=6.62e-07 cosine=1.00000000 text 1: max|diff|=6.26e-07 cosine=1.00000000 text 2: max|diff|=7.33e-07 cosine=1.00000000 ``` End to end through a table, `search("a feline sat down")` returns `["The cat sat on the mat.", "A dog barked at the mailman."]`. ## Merge Risk **Door:** Two-way. A revert restores the 3.0.2 pin. **Blast Radius:** Node `huggingface` embedding function, and install footprint of the optional dependency (onnxruntime-node 1.19.2 → 1.30.0, which still downloads the CUDA provider on Linux x64 by default, as 1.19.2 did). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- nodejs/examples/package.json | 4 +- nodejs/examples/pnpm-lock.yaml | 615 +++++++++++++++++++-------------- nodejs/package.json | 2 +- nodejs/pnpm-lock.yaml | 457 +++++++++++++----------- nodejs/pnpm-workspace.yaml | 7 - 5 files changed, 612 insertions(+), 473 deletions(-) diff --git a/nodejs/examples/package.json b/nodejs/examples/package.json index c3f962b79..5b514aaf8 100644 --- a/nodejs/examples/package.json +++ b/nodejs/examples/package.json @@ -19,10 +19,10 @@ "license": "Apache-2.0", "packageManager": "pnpm@11.1.1", "dependencies": { - "@huggingface/transformers": "3.0.2", + "@huggingface/transformers": "4.3.2", "@lancedb/lancedb": "file:../dist", "openai": "4.29.2", - "sharp": "0.33.5" + "sharp": "0.35.5" }, "devDependencies": { "@biomejs/biome": "^1.7.3", diff --git a/nodejs/examples/pnpm-lock.yaml b/nodejs/examples/pnpm-lock.yaml index 6adbd99d1..408cf7ebb 100644 --- a/nodejs/examples/pnpm-lock.yaml +++ b/nodejs/examples/pnpm-lock.yaml @@ -9,8 +9,8 @@ importers: .: dependencies: '@huggingface/transformers': - specifier: 3.0.2 - version: 3.0.2 + specifier: 4.3.2 + version: 4.3.2(@types/node@25.7.0) '@lancedb/lancedb': specifier: file:../dist version: file:../dist @@ -18,8 +18,8 @@ importers: specifier: 4.29.2 version: 4.29.2 sharp: - specifier: 0.33.5 - version: 0.33.5 + specifier: 0.35.5 + version: 0.35.5(@types/node@25.7.0) devDependencies: '@biomejs/biome': specifier: ^1.7.3 @@ -264,137 +264,181 @@ packages: cpu: [x64] os: [win32] - '@emnapi/runtime@1.10.0': - resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} - '@huggingface/jinja@0.3.4': - resolution: {integrity: sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==} + '@huggingface/jinja@0.5.11': + resolution: {integrity: sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==} engines: {node: '>=18'} - '@huggingface/transformers@3.0.2': - resolution: {integrity: sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==} + '@huggingface/tokenizers@0.2.0': + resolution: {integrity: sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==} - '@img/sharp-darwin-arm64@0.33.5': - resolution: {integrity: sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@huggingface/transformers@4.3.2': + resolution: {integrity: sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==} + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.33.5': - resolution: {integrity: sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-libvips-darwin-arm64@1.0.4': - resolution: {integrity: sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.0.4': - resolution: {integrity: sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.0.4': - resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.0.5': - resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.0.4': - resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.0.4': - resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-linux-arm64@0.33.5': - resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.33.5': - resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} + engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.33.5': - resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} + engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.33.5': - resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-linuxmusl-arm64@0.33.5': - resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} + engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.33.5': - resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-wasm32@0.33.5': - resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} + engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-ia32@0.33.5': - resolution: {integrity: sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} + engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.33.5': - resolution: {integrity: sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] - '@isaacs/fs-minipass@4.0.1': - resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} - engines: {node: '>=18.0.0'} - '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} engines: {node: '>=8'} @@ -573,6 +617,10 @@ packages: resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} engines: {node: '>=6.5'} + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} + engines: {node: '>=14.0'} + agentkeepalive@4.6.0: resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} engines: {node: '>= 8.0.0'} @@ -691,10 +739,6 @@ packages: charenc@0.0.2: resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==} - chownr@3.0.0: - resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} - engines: {node: '>=18'} - ci-info@3.9.0: resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} engines: {node: '>=8'} @@ -720,13 +764,6 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - color-string@1.9.1: - resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==} - - color@4.2.3: - resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} - engines: {node: '>=12.5.0'} - combined-stream@1.0.8: resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} engines: {node: '>= 0.8'} @@ -770,6 +807,14 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -830,6 +875,10 @@ packages: resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==} engines: {node: '>=8'} + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + esprima@4.0.1: resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} engines: {node: '>=4'} @@ -865,8 +914,8 @@ packages: resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} engines: {node: '>=8'} - flatbuffers@1.12.0: - resolution: {integrity: sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} form-data-encoder@1.7.2: resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==} @@ -918,6 +967,14 @@ packages: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + global-agent@4.1.6: + resolution: {integrity: sha512-V9u791atI/bS7RryfRTK2oixDWo6/RCrIikjwuQ4kADPRZZml1C6LUJXc7y6qRhaAF8geo3bIvE/siAGJCw38A==} + engines: {node: '>=10.0'} + + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + gopd@1.2.0: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} @@ -937,6 +994,9 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -978,9 +1038,6 @@ packages: is-arrayish@0.2.1: resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} - is-arrayish@0.3.4: - resolution: {integrity: sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==} - is-buffer@1.1.6: resolution: {integrity: sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==} @@ -1218,6 +1275,10 @@ packages: makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} + matcher@4.0.0: + resolution: {integrity: sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==} + engines: {node: '>=10'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -1250,14 +1311,6 @@ packages: minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - - minizlib@3.1.0: - resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} - engines: {node: '>= 18'} - ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -1295,6 +1348,10 @@ packages: resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} engines: {node: '>=8'} + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} @@ -1302,18 +1359,18 @@ packages: resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} engines: {node: '>=6'} - onnxruntime-common@1.19.2: - resolution: {integrity: sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==} + onnxruntime-common@1.30.0: + resolution: {integrity: sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: - resolution: {integrity: sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: + resolution: {integrity: sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==} - onnxruntime-node@1.19.2: - resolution: {integrity: sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==} + onnxruntime-node@1.30.0: + resolution: {integrity: sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==} os: [win32, darwin, linux] - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: - resolution: {integrity: sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==} + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: + resolution: {integrity: sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==} openai@4.29.2: resolution: {integrity: sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==} @@ -1415,14 +1472,23 @@ packages: resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} hasBin: true - semver@7.8.0: - resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==} + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} engines: {node: '>=10'} hasBin: true - sharp@0.33.5: - resolution: {integrity: sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + serialize-error@8.1.0: + resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==} + engines: {node: '>=10'} + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} + engines: {node: '>=20.9.0'} + peerDependencies: + '@types/node': '*' + peerDependenciesMeta: + '@types/node': + optional: true shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} @@ -1435,9 +1501,6 @@ packages: signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} - simple-swizzle@0.2.4: - resolution: {integrity: sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==} - sisteransi@1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} @@ -1495,10 +1558,6 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} - tar@7.5.15: - resolution: {integrity: sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==} - engines: {node: '>=18'} - test-exclude@6.0.0: resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} engines: {node: '>=8'} @@ -1547,6 +1606,10 @@ packages: resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} engines: {node: '>=4'} + type-fest@0.20.2: + resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} + engines: {node: '>=10'} + type-fest@0.21.3: resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==} engines: {node: '>=10'} @@ -1624,10 +1687,6 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - yallist@5.0.0: - resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} - engines: {node: '>=18'} - yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -1866,98 +1925,130 @@ snapshots: '@biomejs/cli-win32-x64@1.9.4': optional: true - '@emnapi/runtime@1.10.0': + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 optional: true - '@huggingface/jinja@0.3.4': {} + '@huggingface/jinja@0.5.11': {} - '@huggingface/transformers@3.0.2': + '@huggingface/tokenizers@0.2.0': {} + + '@huggingface/transformers@4.3.2(@types/node@25.7.0)': dependencies: - '@huggingface/jinja': 0.3.4 - onnxruntime-node: 1.19.2 - onnxruntime-web: 1.21.0-dev.20241024-d9ca84ef96 - sharp: 0.33.5 + '@huggingface/jinja': 0.5.11 + '@huggingface/tokenizers': 0.2.0 + onnxruntime-node: 1.30.0 + onnxruntime-web: 1.31.0-dev.20260914-8d85527a0 + sharp: 0.35.5(@types/node@25.7.0) + transitivePeerDependencies: + - '@types/node' - '@img/sharp-darwin-arm64@0.33.5': + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.0.4 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.33.5': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.0.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-libvips-darwin-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-darwin-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm@1.0.5': - optional: true - - '@img/sharp-libvips-linux-s390x@1.0.4': - optional: true - - '@img/sharp-libvips-linux-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - optional: true - - '@img/sharp-linux-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.0.4 - optional: true - - '@img/sharp-linux-arm@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.0.5 - optional: true - - '@img/sharp-linux-s390x@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.0.4 - optional: true - - '@img/sharp-linux-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.0.4 - optional: true - - '@img/sharp-wasm32@0.33.5': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@emnapi/runtime': 1.10.0 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-ia32@0.33.5': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-win32-x64@0.33.5': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@isaacs/fs-minipass@4.0.1': + '@img/sharp-libvips-linux-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.4': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.4': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + optional: true + + '@img/sharp-linux-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.4 + optional: true + + '@img/sharp-linux-arm@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.4 + optional: true + + '@img/sharp-linux-ppc64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.4 + optional: true + + '@img/sharp-linux-riscv64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.4 + optional: true + + '@img/sharp-linux-s390x@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.4 + optional: true + + '@img/sharp-linux-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + optional: true + + '@img/sharp-wasm32@0.35.5': dependencies: - minipass: 7.1.3 + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.5': + dependencies: + '@img/sharp-wasm32': 0.35.5 + optional: true + + '@img/sharp-win32-arm64@0.35.5': + optional: true + + '@img/sharp-win32-ia32@0.35.5': + optional: true + + '@img/sharp-win32-x64@0.35.5': + optional: true '@istanbuljs/load-nyc-config@1.1.0': dependencies: @@ -2222,7 +2313,7 @@ snapshots: '@types/node-fetch@2.6.13': dependencies: - '@types/node': 18.19.130 + '@types/node': 25.7.0 form-data: 4.0.5 '@types/node@18.19.130': @@ -2245,6 +2336,8 @@ snapshots: dependencies: event-target-shim: 5.0.1 + adm-zip@0.6.1: {} + agentkeepalive@4.6.0: dependencies: humanize-ms: 1.2.1 @@ -2382,8 +2475,6 @@ snapshots: charenc@0.0.2: {} - chownr@3.0.0: {} - ci-info@3.9.0: {} cjs-module-lexer@1.4.3: {} @@ -2404,16 +2495,6 @@ snapshots: color-name@1.1.4: {} - color-string@1.9.1: - dependencies: - color-name: 1.1.4 - simple-swizzle: 0.2.4 - - color@4.2.3: - dependencies: - color-convert: 2.0.1 - color-string: 1.9.1 - combined-stream@1.0.8: dependencies: delayed-stream: 1.0.0 @@ -2453,6 +2534,18 @@ snapshots: deepmerge@4.3.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + delayed-stream@1.0.0: {} detect-libc@2.1.2: {} @@ -2501,6 +2594,8 @@ snapshots: escape-string-regexp@2.0.0: {} + escape-string-regexp@4.0.0: {} + esprima@4.0.1: {} event-target-shim@5.0.1: {} @@ -2542,7 +2637,7 @@ snapshots: locate-path: 5.0.0 path-exists: 4.0.0 - flatbuffers@1.12.0: {} + flatbuffers@25.9.23: {} form-data-encoder@1.7.2: {} @@ -2601,6 +2696,18 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 + global-agent@4.1.6: + dependencies: + globalthis: 1.0.4 + matcher: 4.0.0 + semver: 7.8.6 + serialize-error: 8.1.0 + + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + gopd@1.2.0: {} graceful-fs@4.2.11: {} @@ -2618,6 +2725,10 @@ snapshots: has-flag@4.0.0: {} + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -2652,8 +2763,6 @@ snapshots: is-arrayish@0.2.1: {} - is-arrayish@0.3.4: {} - is-buffer@1.1.6: {} is-core-module@2.16.2: @@ -2688,7 +2797,7 @@ snapshots: '@babel/parser': 7.29.3 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 - semver: 7.8.0 + semver: 7.8.6 transitivePeerDependencies: - supports-color @@ -2971,7 +3080,7 @@ snapshots: jest-util: 29.7.0 natural-compare: 1.4.0 pretty-format: 29.7.0 - semver: 7.8.0 + semver: 7.8.6 transitivePeerDependencies: - supports-color @@ -3056,7 +3165,7 @@ snapshots: make-dir@4.0.0: dependencies: - semver: 7.8.0 + semver: 7.8.6 make-error@1.3.6: {} @@ -3064,6 +3173,10 @@ snapshots: dependencies: tmpl: 1.0.5 + matcher@4.0.0: + dependencies: + escape-string-regexp: 4.0.0 + math-intrinsics@1.1.0: {} md5@2.3.0: @@ -3093,12 +3206,6 @@ snapshots: minimist@1.2.8: {} - minipass@7.1.3: {} - - minizlib@3.1.0: - dependencies: - minipass: 7.1.3 - ms@2.1.3: {} natural-compare@1.4.0: {} @@ -3121,6 +3228,8 @@ snapshots: dependencies: path-key: 3.1.1 + object-keys@1.1.1: {} + once@1.4.0: dependencies: wrappy: 1.0.2 @@ -3129,21 +3238,22 @@ snapshots: dependencies: mimic-fn: 2.1.0 - onnxruntime-common@1.19.2: {} + onnxruntime-common@1.30.0: {} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: {} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: {} - onnxruntime-node@1.19.2: + onnxruntime-node@1.30.0: dependencies: - onnxruntime-common: 1.19.2 - tar: 7.5.15 + adm-zip: 0.6.1 + global-agent: 4.1.6 + onnxruntime-common: 1.30.0 - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: dependencies: - flatbuffers: 1.12.0 + flatbuffers: 25.9.23 guid-typescript: 1.0.9 long: 5.3.2 - onnxruntime-common: 1.20.0-dev.20241016-2b8fc5529b + onnxruntime-common: 1.31.0-dev.20260911-2a43ec07e platform: 1.3.6 protobufjs: 7.5.7 @@ -3251,33 +3361,44 @@ snapshots: semver@6.3.1: {} - semver@7.8.0: {} + semver@7.8.6: {} - sharp@0.33.5: + serialize-error@8.1.0: dependencies: - color: 4.2.3 + type-fest: 0.20.2 + + sharp@0.35.5(@types/node@25.7.0): + dependencies: + '@img/colour': 1.1.0 detect-libc: 2.1.2 - semver: 7.8.0 + semver: 7.8.6 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 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 + '@types/node': 25.7.0 shebang-command@2.0.0: dependencies: @@ -3287,10 +3408,6 @@ snapshots: signal-exit@3.0.7: {} - simple-swizzle@0.2.4: - dependencies: - is-arrayish: 0.3.4 - sisteransi@1.0.5: {} slash@3.0.0: {} @@ -3339,14 +3456,6 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} - tar@7.5.15: - dependencies: - '@isaacs/fs-minipass': 4.0.1 - chownr: 3.0.0 - minipass: 7.1.3 - minizlib: 3.1.0 - yallist: 5.0.0 - test-exclude@6.0.0: dependencies: '@istanbuljs/schema': 0.1.6 @@ -3370,7 +3479,7 @@ snapshots: json5: 2.2.3 lodash.memoize: 4.1.2 make-error: 1.3.6 - semver: 7.8.0 + semver: 7.8.6 type-fest: 4.41.0 typescript: 5.9.3 yargs-parser: 21.1.1 @@ -3386,6 +3495,8 @@ snapshots: type-detect@4.0.8: {} + type-fest@0.20.2: {} + type-fest@0.21.3: {} type-fest@4.41.0: {} @@ -3449,8 +3560,6 @@ snapshots: yallist@3.1.1: {} - yallist@5.0.0: {} - yargs-parser@21.1.1: {} yargs@17.7.2: diff --git a/nodejs/package.json b/nodejs/package.json index 8a250f230..348f15e56 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -102,7 +102,7 @@ "reflect-metadata": "^0.2.2" }, "optionalDependencies": { - "@huggingface/transformers": "3.0.2", + "@huggingface/transformers": "4.3.2", "openai": "4.29.2" }, "peerDependencies": { diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index faf0ad428..e57bb68d3 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -4,9 +4,6 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false -overrides: - sharp: ^0.35.4 - importers: .: @@ -104,8 +101,8 @@ importers: version: 7.18.0(eslint@8.57.1)(typescript@5.5.4) optionalDependencies: '@huggingface/transformers': - specifier: 3.0.2 - version: 3.0.2(@types/node@22.7.4) + specifier: 4.3.2 + version: 4.3.2(@types/node@22.7.4) openai: specifier: 4.29.2 version: 4.29.2 @@ -569,12 +566,15 @@ packages: resolution: {integrity: sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - '@huggingface/jinja@0.3.4': - resolution: {integrity: sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==} + '@huggingface/jinja@0.5.11': + resolution: {integrity: sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ==} engines: {node: '>=18'} - '@huggingface/transformers@3.0.2': - resolution: {integrity: sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==} + '@huggingface/tokenizers@0.2.0': + resolution: {integrity: sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==} + + '@huggingface/transformers@4.3.2': + resolution: {integrity: sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==} '@humanwhocodes/config-array@0.13.0': resolution: {integrity: sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==} @@ -593,160 +593,160 @@ packages: resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} - '@img/sharp-darwin-arm64@0.35.4': - resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==} + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.35.4': - resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-freebsd-wasm32@0.35.4': - resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] - '@img/sharp-libvips-darwin-arm64@1.3.3': - resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==} + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.3.3': - resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.3.3': - resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.3.3': - resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-ppc64@1.3.3': - resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-riscv64@1.3.3': - resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==} + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.3.3': - resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==} + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.3.3': - resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': - resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.3.3': - resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-linux-arm64@0.35.4': - resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.35.4': - resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-ppc64@0.35.4': - resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-linux-riscv64@0.35.4': - resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==} + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.35.4': - resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==} + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.35.4': - resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-linuxmusl-arm64@0.35.4': - resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.35.4': - resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-wasm32@0.35.4': - resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} - '@img/sharp-webcontainers-wasm32@0.35.4': - resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==} + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-arm64@0.35.4': - resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] - '@img/sharp-win32-ia32@0.35.4': - resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==} + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.35.4': - resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] @@ -885,10 +885,6 @@ packages: '@types/node': optional: true - '@isaacs/fs-minipass@4.0.1': - resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} - engines: {node: '>=18.0.0'} - '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} engines: {node: '>=8'} @@ -1805,6 +1801,10 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} + engines: {node: '>=14.0'} + agent-base@6.0.2: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} @@ -2001,10 +2001,6 @@ packages: charenc@0.0.2: resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==} - chownr@3.0.0: - resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} - engines: {node: '>=18'} - ci-info@3.9.0: resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} engines: {node: '>=8'} @@ -2108,6 +2104,14 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -2331,9 +2335,6 @@ packages: resolution: {integrity: sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==} engines: {node: ^10.12.0 || >=12.0.0} - flatbuffers@1.12.0: - resolution: {integrity: sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==} - flatbuffers@23.5.26: resolution: {integrity: sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==} @@ -2413,10 +2414,18 @@ packages: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + global-agent@4.1.6: + resolution: {integrity: sha512-V9u791atI/bS7RryfRTK2oixDWo6/RCrIikjwuQ4kADPRZZml1C6LUJXc7y6qRhaAF8geo3bIvE/siAGJCw38A==} + engines: {node: '>=10.0'} + globals@13.24.0: resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==} engines: {node: '>=8'} + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + globby@11.1.0: resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} engines: {node: '>=10'} @@ -2443,6 +2452,9 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -2809,6 +2821,10 @@ packages: resolution: {integrity: sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==} hasBin: true + matcher@4.0.0: + resolution: {integrity: sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==} + engines: {node: '>=10'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -2870,14 +2886,6 @@ packages: minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - - minizlib@3.1.0: - resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} - engines: {node: '>= 18'} - mnemonist@0.38.3: resolution: {integrity: sha512-2K9QYubXx/NAjv4VLq1d1Ly8pWNC5L3BrixtdkyTegXWJIqY+zLNDhhX/A+ZwWt70tB1S8H4BE8FLYEFyNoOBw==} @@ -2923,6 +2931,10 @@ packages: resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} engines: {node: '>=8'} + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + obliterator@1.6.1: resolution: {integrity: sha512-9WXswnqINnnhOG/5SLimUlzuU1hFJUc8zkwyD59Sd+dPOMf05PmnYG/d6Q7HZ+KmgkZJa1PxRso6QdM3sTNHig==} @@ -2939,18 +2951,18 @@ packages: oniguruma-to-es@2.3.0: resolution: {integrity: sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g==} - onnxruntime-common@1.19.2: - resolution: {integrity: sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==} + onnxruntime-common@1.30.0: + resolution: {integrity: sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==} - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: - resolution: {integrity: sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==} + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: + resolution: {integrity: sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==} - onnxruntime-node@1.19.2: - resolution: {integrity: sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==} + onnxruntime-node@1.30.0: + resolution: {integrity: sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==} os: [win32, darwin, linux] - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: - resolution: {integrity: sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==} + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: + resolution: {integrity: sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==} openai@4.29.2: resolution: {integrity: sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==} @@ -3139,8 +3151,12 @@ packages: engines: {node: '>=10'} hasBin: true - sharp@0.35.4: - resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==} + serialize-error@8.1.0: + resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==} + engines: {node: '>=10'} + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' @@ -3246,10 +3262,6 @@ packages: resolution: {integrity: sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==} engines: {node: '>=12.17'} - tar@7.5.22: - resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} - engines: {node: '>=18'} - test-exclude@6.0.0: resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} engines: {node: '>=8'} @@ -3310,6 +3322,9 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + typanion@3.14.0: resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==} @@ -3481,10 +3496,6 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - yallist@5.0.0: - resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} - engines: {node: '>=18'} - yaml@2.9.0: resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} engines: {node: '>= 14.6'} @@ -4327,17 +4338,17 @@ snapshots: '@emnapi/core@1.10.0': dependencies: '@emnapi/wasi-threads': 1.2.1 - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@emnapi/runtime@1.11.3': dependencies: - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@emnapi/wasi-threads@1.2.1': dependencies: - tslib: 2.8.1 + tslib: 2.9.1 optional: true '@eslint-community/eslint-utils@4.9.1(eslint@8.57.1)': @@ -4363,15 +4374,19 @@ snapshots: '@eslint/js@8.57.1': {} - '@huggingface/jinja@0.3.4': + '@huggingface/jinja@0.5.11': optional: true - '@huggingface/transformers@3.0.2(@types/node@22.7.4)': + '@huggingface/tokenizers@0.2.0': + optional: true + + '@huggingface/transformers@4.3.2(@types/node@22.7.4)': dependencies: - '@huggingface/jinja': 0.3.4 - onnxruntime-node: 1.19.2 - onnxruntime-web: 1.21.0-dev.20241024-d9ca84ef96 - sharp: 0.35.4(@types/node@22.7.4) + '@huggingface/jinja': 0.5.11 + '@huggingface/tokenizers': 0.2.0 + onnxruntime-node: 1.30.0 + onnxruntime-web: 1.31.0-dev.20260914-8d85527a0 + sharp: 0.35.5(@types/node@22.7.4) transitivePeerDependencies: - '@types/node' optional: true @@ -4391,108 +4406,108 @@ snapshots: '@img/colour@1.1.0': optional: true - '@img/sharp-darwin-arm64@0.35.4': + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.3 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.35.4': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.3 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-freebsd-wasm32@0.35.4': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-libvips-darwin-arm64@1.3.3': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-libvips-darwin-x64@1.3.3': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm64@1.3.3': + '@img/sharp-libvips-linux-arm64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm@1.3.3': + '@img/sharp-libvips-linux-arm@1.3.4': optional: true - '@img/sharp-libvips-linux-ppc64@1.3.3': + '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.3.3': + '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true - '@img/sharp-libvips-linux-s390x@1.3.3': + '@img/sharp-libvips-linux-s390x@1.3.4': optional: true - '@img/sharp-libvips-linux-x64@1.3.3': + '@img/sharp-libvips-linux-x64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-x64@1.3.3': + '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true - '@img/sharp-linux-arm64@0.35.4': + '@img/sharp-linux-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.3 + '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true - '@img/sharp-linux-arm@0.35.4': + '@img/sharp-linux-arm@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.3 + '@img/sharp-libvips-linux-arm': 1.3.4 optional: true - '@img/sharp-linux-ppc64@0.35.4': + '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.3 + '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true - '@img/sharp-linux-riscv64@0.35.4': + '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.3 + '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true - '@img/sharp-linux-s390x@0.35.4': + '@img/sharp-linux-s390x@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.3 + '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true - '@img/sharp-linux-x64@0.35.4': + '@img/sharp-linux-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.3 + '@img/sharp-libvips-linux-x64': 1.3.4 optional: true - '@img/sharp-linuxmusl-arm64@0.35.4': + '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true - '@img/sharp-linuxmusl-x64@0.35.4': + '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true - '@img/sharp-wasm32@0.35.4': + '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true - '@img/sharp-webcontainers-wasm32@0.35.4': + '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-arm64@0.35.4': + '@img/sharp-win32-arm64@0.35.5': optional: true - '@img/sharp-win32-ia32@0.35.4': + '@img/sharp-win32-ia32@0.35.5': optional: true - '@img/sharp-win32-x64@0.35.4': + '@img/sharp-win32-x64@0.35.5': optional: true '@inquirer/ansi@2.0.5': {} @@ -4614,11 +4629,6 @@ snapshots: optionalDependencies: '@types/node': 22.7.4 - '@isaacs/fs-minipass@4.0.1': - dependencies: - minipass: 7.1.3 - optional: true - '@istanbuljs/load-nyc-config@1.1.0': dependencies: camelcase: 5.3.1 @@ -5659,6 +5669,9 @@ snapshots: acorn@8.16.0: {} + adm-zip@0.6.1: + optional: true + agent-base@6.0.2: dependencies: debug: 4.4.3 @@ -5933,9 +5946,6 @@ snapshots: charenc@0.0.2: optional: true - chownr@3.0.0: - optional: true - ci-info@3.9.0: {} cjs-module-lexer@1.4.3: {} @@ -6029,6 +6039,20 @@ snapshots: deepmerge@4.3.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + optional: true + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + optional: true + delayed-stream@1.0.0: {} dequal@2.0.3: {} @@ -6274,9 +6298,6 @@ snapshots: keyv: 4.5.4 rimraf: 3.0.2 - flatbuffers@1.12.0: - optional: true - flatbuffers@23.5.26: {} flatbuffers@24.12.23: {} @@ -6354,10 +6375,24 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 + global-agent@4.1.6: + dependencies: + globalthis: 1.0.4 + matcher: 4.0.0 + semver: 7.8.5 + serialize-error: 8.1.0 + optional: true + globals@13.24.0: dependencies: type-fest: 0.20.2 + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + optional: true + globby@11.1.0: dependencies: array-union: 2.1.0 @@ -6387,6 +6422,11 @@ snapshots: has-flag@4.0.0: {} + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + optional: true + has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -6928,6 +6968,11 @@ snapshots: punycode.js: 2.3.1 uc.micro: 2.1.0 + matcher@4.0.0: + dependencies: + escape-string-regexp: 4.0.0 + optional: true + math-intrinsics@1.1.0: {} md5@2.3.0: @@ -6995,14 +7040,6 @@ snapshots: minimist@1.2.8: {} - minipass@7.1.3: - optional: true - - minizlib@3.1.0: - dependencies: - minipass: 7.1.3 - optional: true - mnemonist@0.38.3: dependencies: obliterator: 1.6.1 @@ -7033,6 +7070,9 @@ snapshots: dependencies: path-key: 3.1.1 + object-keys@1.1.1: + optional: true + obliterator@1.6.1: {} obug@2.1.1: {} @@ -7051,24 +7091,25 @@ snapshots: regex: 5.1.1 regex-recursion: 5.1.1 - onnxruntime-common@1.19.2: + onnxruntime-common@1.30.0: optional: true - onnxruntime-common@1.20.0-dev.20241016-2b8fc5529b: + onnxruntime-common@1.31.0-dev.20260911-2a43ec07e: optional: true - onnxruntime-node@1.19.2: + onnxruntime-node@1.30.0: dependencies: - onnxruntime-common: 1.19.2 - tar: 7.5.22 + adm-zip: 0.6.1 + global-agent: 4.1.6 + onnxruntime-common: 1.30.0 optional: true - onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: + onnxruntime-web@1.31.0-dev.20260914-8d85527a0: dependencies: - flatbuffers: 1.12.0 + flatbuffers: 25.9.23 guid-typescript: 1.0.9 long: 5.3.2 - onnxruntime-common: 1.20.0-dev.20241016-2b8fc5529b + onnxruntime-common: 1.31.0-dev.20260911-2a43ec07e platform: 1.3.6 protobufjs: 7.6.5 optional: true @@ -7247,37 +7288,42 @@ snapshots: semver@7.8.5: {} - sharp@0.35.4(@types/node@22.7.4): + serialize-error@8.1.0: + dependencies: + type-fest: 0.20.2 + optional: true + + sharp@0.35.5(@types/node@22.7.4): dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.5 optionalDependencies: - '@img/sharp-darwin-arm64': 0.35.4 - '@img/sharp-darwin-x64': 0.35.4 - '@img/sharp-freebsd-wasm32': 0.35.4 - '@img/sharp-libvips-darwin-arm64': 1.3.3 - '@img/sharp-libvips-darwin-x64': 1.3.3 - '@img/sharp-libvips-linux-arm': 1.3.3 - '@img/sharp-libvips-linux-arm64': 1.3.3 - '@img/sharp-libvips-linux-ppc64': 1.3.3 - '@img/sharp-libvips-linux-riscv64': 1.3.3 - '@img/sharp-libvips-linux-s390x': 1.3.3 - '@img/sharp-libvips-linux-x64': 1.3.3 - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 - '@img/sharp-linux-arm': 0.35.4 - '@img/sharp-linux-arm64': 0.35.4 - '@img/sharp-linux-ppc64': 0.35.4 - '@img/sharp-linux-riscv64': 0.35.4 - '@img/sharp-linux-s390x': 0.35.4 - '@img/sharp-linux-x64': 0.35.4 - '@img/sharp-linuxmusl-arm64': 0.35.4 - '@img/sharp-linuxmusl-x64': 0.35.4 - '@img/sharp-webcontainers-wasm32': 0.35.4 - '@img/sharp-win32-arm64': 0.35.4 - '@img/sharp-win32-ia32': 0.35.4 - '@img/sharp-win32-x64': 0.35.4 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 '@types/node': 22.7.4 optional: true @@ -7375,15 +7421,6 @@ snapshots: array-back: 6.2.3 wordwrapjs: 5.1.1 - tar@7.5.22: - dependencies: - '@isaacs/fs-minipass': 4.0.1 - chownr: 3.0.0 - minipass: 7.1.3 - minizlib: 3.1.0 - yallist: 5.0.0 - optional: true - test-exclude@6.0.0: dependencies: '@istanbuljs/schema': 0.1.6 @@ -7431,6 +7468,9 @@ snapshots: tslib@2.8.1: {} + tslib@2.9.1: + optional: true + typanion@3.14.0: {} type-check@0.4.0: @@ -7588,9 +7628,6 @@ snapshots: yallist@3.1.1: {} - yallist@5.0.0: - optional: true - yaml@2.9.0: {} yargs-parser@21.1.1: {} diff --git a/nodejs/pnpm-workspace.yaml b/nodejs/pnpm-workspace.yaml index b6be57977..222b3fb1c 100644 --- a/nodejs/pnpm-workspace.yaml +++ b/nodejs/pnpm-workspace.yaml @@ -47,10 +47,3 @@ minimumReleaseAgeExclude: - js-yaml@4.3.1 - tar@7.5.21 - '@opentelemetry/core@2.8.0' - -# @huggingface/transformers pins sharp ^0.33.5 and no released version has moved -# past ^0.34.5, all of which inherit the libvips CVEs in GHSA-f88m-g3jw-g9cj. -# Force the patched line. sharp is only reached by transformers' image pipeline, -# which LanceDB's text embedding function never uses. -overrides: - sharp: ^0.35.4 From e2501b0dab81b76d9612a65eef7f9cb06161fa5a Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Fri, 6 Nov 2026 11:32:48 -0800 Subject: [PATCH 040/203] docs: update example names (#4887) Use neutral placeholder names and values in a few code examples in the docs and Python docstrings. Text-only; no behavior change. --- _Generated by [Claude Code](https://claude.ai/code/session_019iqZdtD3ZMnvTMeoNsULgX)_ --------- Co-authored-by: Claude --- docs/web/curation/vend-secret.mdx | 12 +++++++----- docs/web/governance/authorization.mdx | 4 ++-- docs/web/governance/principals.mdx | 8 ++++---- docs/web/governance/privileges.mdx | 10 +++++----- docs/web/management/secret.mdx | 24 ++++++++++++------------ docs/web/sql/ddl/grant.mdx | 6 +++--- docs/web/sql/ddl/secret.mdx | 26 +++++++++++++------------- python/python/lancedb/db.py | 4 ++-- python/python/lancedb/secrets.py | 6 +++--- 9 files changed, 51 insertions(+), 49 deletions(-) diff --git a/docs/web/curation/vend-secret.mdx b/docs/web/curation/vend-secret.mdx index 801f16436..cdebc0b8d 100644 --- a/docs/web/curation/vend-secret.mdx +++ b/docs/web/curation/vend-secret.mdx @@ -29,7 +29,7 @@ code already reads: import os from lancedb import EnvVarSecret, udf -db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"]) +db.create_secret("embedding-api-key", os.environ["EMBEDDING_API_KEY"]) @udf class embed_remote: @@ -37,7 +37,7 @@ class embed_remote: import os from openai import OpenAI - self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) + self.client = OpenAI(api_key=os.environ["EMBEDDING_API_KEY"]) self.model = model def __call__(self, text: str) -> list[float]: @@ -46,13 +46,15 @@ class embed_remote: version = db.create_function_async( embed_remote, - secrets=[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")], + secrets=[ + EnvVarSecret(secret_name="embedding-api-key", env_variable="EMBEDDING_API_KEY") + ], ).wait() ``` The function's own code never names the Secret -- it reads -`OPENAI_API_KEY` the same way it would outside LanceDB. The binding, in +`EMBEDDING_API_KEY` the same way it would outside LanceDB. The binding, in `secrets=[...]`, is what connects that variable to the stored credential. It is checked for shape at registration (valid variable name, not reserved, not repeated) but not resolved yet: the Secret does not have to exist until @@ -205,7 +207,7 @@ privilege. The error names the object you are missing. **The Function runs but its provider rejects the key**: a misspelled *environment variable* cannot be caught at registration, because nothing knows which variables a Function reads. Check that `env_variable` matches -what the library expects, for example `OPENAI_API_KEY`. +what the Function's code reads, such as `EMBEDDING_API_KEY` above. ## Related guides {#next} diff --git a/docs/web/governance/authorization.mdx b/docs/web/governance/authorization.mdx index 68d33370c..41d4f67f0 100644 --- a/docs/web/governance/authorization.mdx +++ b/docs/web/governance/authorization.mdx @@ -25,8 +25,8 @@ often, looks like this: ```sql SQL icon="database" -GRANT USAGE ON SECRET platform.`openai-prod` TO ROLE research -REVOKE USAGE ON SECRET platform.`openai-prod` FROM ROLE research +GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research +REVOKE USAGE ON SECRET platform.`model-api-key` FROM ROLE research ``` diff --git a/docs/web/governance/principals.mdx b/docs/web/governance/principals.mdx index 346b7a8bc..a56d2b2d8 100644 --- a/docs/web/governance/principals.mdx +++ b/docs/web/governance/principals.mdx @@ -24,9 +24,9 @@ optional keyword to disambiguate: ```sql SQL icon="database" -GRANT USAGE ON SECRET platform.`openai-prod` TO ROLE research -GRANT USAGE ON SECRET platform.`openai-prod` TO USER alice -GRANT USAGE ON SECRET platform.`openai-prod` TO GROUP `data-science` +GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE research +GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice +GRANT USAGE ON SECRET platform.`model-api-key` TO GROUP `data-science` ``` @@ -41,7 +41,7 @@ keyword after the first: ```sql SQL icon="database" -GRANT USAGE ON SECRET platform.`openai-prod` TO ROLE etl, rotation_service +GRANT USAGE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service ``` diff --git a/docs/web/governance/privileges.mdx b/docs/web/governance/privileges.mdx index 44f9928ba..e437b916f 100644 --- a/docs/web/governance/privileges.mdx +++ b/docs/web/governance/privileges.mdx @@ -73,11 +73,11 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl GRANT SELECT ON VIEW dashboard TO ROLE analysts GRANT SELECT, UPDATE ON MATERIALIZED VIEW daily_rollup TO ROLE analysts GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins -GRANT USAGE, UPDATE ON SECRET platform.`openai-prod` TO ROLE etl, rotation_service -GRANT OWNERSHIP ON SECRET platform.`openai-prod` TO ROLE platform_admins +GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service +GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins GRANT USAGE ON FUNCTION platform.embed TO ROLE etl GRANT USAGE ON STORAGE INTEGRATION platform.hub TO ROLE research -REVOKE UPDATE ON SECRET platform.`openai-prod` FROM ROLE etl +REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl ``` @@ -123,10 +123,10 @@ own. ### Example: sharing one key {#example} - A **platform operator** owns the `platform` namespace. They create - `platform$openai-prod`, then grant the `research` group `USAGE` on that + `platform$model-api-key`, then grant the `research` group `USAGE` on that one Secret. - A **researcher** in `research` registers a Function bound to - `platform$openai-prod`. Binding any other Secret in `platform` is + `platform$model-api-key`. Binding any other Secret in `platform` is refused. - A **table owner** in `research` adds a column computed by that Function. They hold `USAGE` on the Secret through the group, but are refused until diff --git a/docs/web/management/secret.mdx b/docs/web/management/secret.mdx index b8a37fb51..66d71afd7 100644 --- a/docs/web/management/secret.mdx +++ b/docs/web/management/secret.mdx @@ -32,29 +32,29 @@ namespace. ```python Python -db.create_secret("openai-prod", value, namespace_path=["platform"]) +db.create_secret("model-api-key", value, namespace_path=["platform"]) -db.alter_secret("openai-prod", new_value, namespace_path=["platform"]) +db.alter_secret("model-api-key", new_value, namespace_path=["platform"]) for name in db.list_secrets(namespace_path=["platform"]): print(name) -info = db.describe_secret("openai-prod", namespace_path=["platform"]) +info = db.describe_secret("model-api-key", namespace_path=["platform"]) info.created_at_millis, info.updated_at_millis -db.drop_secret("openai-prod", namespace_path=["platform"]) +db.drop_secret("model-api-key", namespace_path=["platform"]) ``` ```sql SQL -CREATE SECRET platform.`openai-prod` TYPE = GENERIC_STRING SECRET_STRING = 'sk-...'; +CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = ''; -ALTER SECRET platform.`openai-prod` SET SECRET_STRING = 'sk-...'; +ALTER SECRET platform.`model-api-key` SET SECRET_STRING = ''; SHOW SECRETS IN platform; -DESCRIBE SECRET platform.`openai-prod`; +DESCRIBE SECRET platform.`model-api-key`; -DROP SECRET platform.`openai-prod`; +DROP SECRET platform.`model-api-key`; ``` ```rust @@ -62,19 +62,19 @@ use futures::TryStreamExt; let namespace = vec!["platform".to_string()]; -db.create_secret("openai-prod", &value, &namespace).await?; +db.create_secret("model-api-key", &value, &namespace).await?; -db.alter_secret("openai-prod", &new_value, &namespace).await?; +db.alter_secret("model-api-key", &new_value, &namespace).await?; let mut names = db.list_secrets(&namespace, Default::default()); while let Some(name) = names.try_next().await? { println!("{name}"); } -let info = db.describe_secret("openai-prod", &namespace).await?; +let info = db.describe_secret("model-api-key", &namespace).await?; println!("{} {}", info.created_at_millis, info.updated_at_millis); -db.drop_secret("openai-prod", &namespace).await?; +db.drop_secret("model-api-key", &namespace).await?; ``` diff --git a/docs/web/sql/ddl/grant.mdx b/docs/web/sql/ddl/grant.mdx index 723aa0d77..370529209 100644 --- a/docs/web/sql/ddl/grant.mdx +++ b/docs/web/sql/ddl/grant.mdx @@ -26,10 +26,10 @@ GRANT OPERATE, USAGE ON SYSTEM TO ROLE ops GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE readers GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE events TO ROLE etl GRANT CREATE SECRET, CREATE FUNCTION ON SCHEMA platform TO ROLE platform_admins -GRANT USAGE, UPDATE ON SECRET platform.`openai-prod` TO ROLE etl, rotation_service -GRANT USAGE ON SECRET platform.`openai-prod` TO USER alice, GROUP ID 'g1' +GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service +GRANT USAGE ON SECRET platform.`model-api-key` TO USER alice, GROUP ID 'g1' GRANT USAGE ON FUNCTION platform.embed TO ROLE research -GRANT OWNERSHIP ON SECRET platform.`openai-prod` TO ROLE platform_admins +GRANT OWNERSHIP ON SECRET platform.`model-api-key` TO ROLE platform_admins REVOKE USAGE ON FUNCTION platform.embed FROM ROLE research ``` diff --git a/docs/web/sql/ddl/secret.mdx b/docs/web/sql/ddl/secret.mdx index 6c6e3c4c6..922dec247 100644 --- a/docs/web/sql/ddl/secret.mdx +++ b/docs/web/sql/ddl/secret.mdx @@ -21,8 +21,8 @@ and `-`, so quote one that contains `.` or `-`: ```sql SQL icon="database" api_key -platform.`openai-prod` -analytics.`ml$vision`.`openai-prod` +platform.`model-api-key` +analytics.`ml$vision`.`model-api-key` ``` @@ -34,8 +34,8 @@ Secret (for `ALTER` and `DROP`) is an error rather than a status. ```sql SQL icon="database" -CREATE SECRET platform.`openai-prod` TYPE = GENERIC_STRING SECRET_STRING = 'sk-...' -CREATE SECRET IF NOT EXISTS api_key TYPE = GENERIC_STRING SECRET_STRING = $$sk-...$$ +CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = '' +CREATE SECRET IF NOT EXISTS api_key TYPE = GENERIC_STRING SECRET_STRING = $$$$ ``` @@ -47,8 +47,8 @@ value never has to appear in the SQL text itself: ```python Python icon="python" db.execute_query( - "CREATE SECRET platform.`openai-prod` TYPE = GENERIC_STRING SECRET_STRING = $1", - parameters=["sk-..."], + "CREATE SECRET platform.`model-api-key` TYPE = GENERIC_STRING SECRET_STRING = $1", + parameters=[""], ) ``` @@ -63,8 +63,8 @@ overwrites an existing Secret; use `ALTER SECRET`. ```sql SQL icon="database" -ALTER SECRET platform.`openai-prod` SET SECRET_STRING = 'sk-...' -ALTER SECRET IF EXISTS api_key SET SECRET_STRING = $$sk-...$$ +ALTER SECRET platform.`model-api-key` SET SECRET_STRING = '' +ALTER SECRET IF EXISTS api_key SET SECRET_STRING = $$$$ ``` @@ -81,7 +81,7 @@ The status is `altered`, or `not_found` with `IF EXISTS`. ```sql SQL icon="database" -DROP SECRET platform.`openai-prod` +DROP SECRET platform.`model-api-key` DROP SECRET IF EXISTS api_key ``` @@ -104,7 +104,7 @@ SHOW SECRETS SHOW SECRETS IN platform SHOW SECRETS IN analytics.`ml$vision` SHOW SECRETS IN public -SHOW SECRETS IN platform WHERE name > 'openai-prod' LIMIT 50 +SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50 ``` @@ -118,7 +118,7 @@ bounds the page size; `WHERE` must compare `name` with `>`. Requires ```sql SQL icon="database" -DESCRIBE SECRET platform.`openai-prod` +DESCRIBE SECRET platform.`model-api-key` DESC SECRET api_key ``` @@ -139,8 +139,8 @@ A missing Secret is an error. Requires `USAGE` on the Secret. ```sql SQL icon="database" GRANT CREATE SECRET ON SCHEMA platform TO ROLE platform_admins -GRANT USAGE, UPDATE ON SECRET platform.`openai-prod` TO ROLE etl, rotation_service -REVOKE UPDATE ON SECRET platform.`openai-prod` FROM ROLE etl +GRANT USAGE, UPDATE ON SECRET platform.`model-api-key` TO ROLE etl, rotation_service +REVOKE UPDATE ON SECRET platform.`model-api-key` FROM ROLE etl ``` diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 3ff657a6c..e73a44aec 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -986,12 +986,12 @@ class DBConnection(EnforceOverrides): Examples -------- ```python - db.create_secret("openai-prod", os.environ["OPENAI_API_KEY"]) + db.create_secret("model-api-key", os.environ["MODEL_API_KEY"]) db.create_function( analyze_caption, secrets=[ EnvVarSecret( - secret_name="openai-prod", env_variable="OPENAI_API_KEY" + secret_name="model-api-key", env_variable="MODEL_API_KEY" ) ], ) diff --git a/python/python/lancedb/secrets.py b/python/python/lancedb/secrets.py index 75ac9e340..ebafadbc5 100644 --- a/python/python/lancedb/secrets.py +++ b/python/python/lancedb/secrets.py @@ -72,7 +72,7 @@ class EnvVarSecret: Pass these in the ``secrets`` sequence of [DBConnection.create_function][lancedb.db.DBConnection.create_function]. The - Function's source is unchanged by binding: it reads ``OPENAI_API_KEY`` the + Function's source is unchanged by binding: it reads ``MODEL_API_KEY`` the way it always did, and the binding is what puts a value there. This is a local value. Constructing it contacts no server, so it always @@ -101,10 +101,10 @@ class EnvVarSecret: -------- >>> from lancedb import EnvVarSecret >>> binding = EnvVarSecret( - ... secret_name="openai-prod", env_variable="OPENAI_API_KEY" + ... secret_name="model-api-key", env_variable="MODEL_API_KEY" ... ) >>> binding.secret_name, binding.env_variable - ('openai-prod', 'OPENAI_API_KEY') + ('model-api-key', 'MODEL_API_KEY') """ __slots__ = ("_secret_name", "_env_variable", "_secret_namespace_path") From 1b3b2c2da98f3ab581603366279059db2ab2d85d Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 6 Nov 2026 18:14:43 -0800 Subject: [PATCH 041/203] chore: update lance dependency to v15.0.0-beta.13 (#4899) Update the Rust workspace Lance dependencies to [v15.0.0-beta.13](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.13), synchronize the Python test dependency to published pylance 15.0.0b13, and refresh both lockfiles; no compatibility fixes were needed. The Java SDK stays on `lance-core` 15.0.0-beta.8, as in the beta.9 and beta.10 updates: Maven Central has no `lance-core` artifact for 15.0.0-beta.9 through beta.13. Validation passed: workspace Clippy with all features and warnings denied, Cargo formatting, Python lockfile checks, and all 35 CI-script tests. Repository-wide Ruff reports 163 diagnostics, all verified identical on unchanged HEAD; unrelated formatter changes were reverted. --------- Co-authored-by: Vivek --- Cargo.lock | 96 +++++++++++++++++++++---------------------- Cargo.toml | 30 +++++++------- python/pyproject.toml | 2 +- python/uv.lock | 19 +++++---- 4 files changed, 74 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ca3ea29d1..6241b9f0e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arc-swap", "arrow", @@ -5671,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.12" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.12#635d412cde01e5d4203a91be47ddbfd0f2a6e068" +version = "15.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 532c2c2ad..468eb04d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.12", default-features = false, "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.12", default-features = false, "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.12", default-features = false, "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.12", "tag" = "v15.0.0-beta.12", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.13", default-features = false, "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.13", default-features = false, "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.13", default-features = false, "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/python/pyproject.toml b/python/pyproject.toml index 3a19fd826..edcdf903f 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b11", + "pylance==15.0.0b13", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index d8a1c118a..9c228aef9 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'", @@ -2147,7 +2147,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.0b11" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b13" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b11" +version = "15.0.0b13" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_oRP5O/pylance-15.0.0b11-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:54524c1bd04065516aeb97c5d06e1f6c88d1b1d5191d40077b104c5879893ea2" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1LdITz/pylance-15.0.0b11-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8f6b2496b4b20787ff7780907f3017cf7b17c1f2bd1fa8cb7ed4d0a450445dfc" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1ONuyB/pylance-15.0.0b11-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:903283401e222dea532a36b91ffa60e7eaaf4d1fc08602cb29eef4ac2d04a8ff" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2bWLjt/pylance-15.0.0b11-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ce8bb0242b1647ce0b9355a48339b8fe8415f3556209214d0b490afb6ee60b38" }, - { url = "https://pypi.fury.io/lance-format/-/ver_168GWI/pylance-15.0.0b11-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:387ad2b455ab5b00476d7a60ce96e6014239df239691ac219f0025a29ee19f6e" }, - { url = "https://pypi.fury.io/lance-format/-/ver_aU9I7/pylance-15.0.0b11-cp310-abi3-win_amd64.whl", hash = "sha256:7022c2afcdaf6f9e9444db5addc72033ad20ad301930b38238e246687628cd75" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1UqLiw/pylance-15.0.0b13-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bbbf6e42624275d1559a4887a11f6cb1c34f10c560ca7209b59219d3614a444f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_wto7I/pylance-15.0.0b13-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b8730195df05fa7242d12f4c759019b658f668b90d7ceba380059597bb5951a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_13UO9X/pylance-15.0.0b13-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a41f292084694a681773990e6d96a675b45e4d232d7a67b21b05762dd5976e8a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1Mjytl/pylance-15.0.0b13-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:76d2f6a5a8ac150bee990006cc7b7c920e1af2532e4d3ff6a142ab5a5412483e" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1XuqE6/pylance-15.0.0b13-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ac2b50bf8af53aac65d56703010cdf9c1567fdfe230c7fbac1d69584933d7793" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Fj6Go/pylance-15.0.0b13-cp310-abi3-win_amd64.whl", hash = "sha256:7e6556db1a812cb0846cc0e30c0f273468d5e58dc210f3ee9955d9cdc3bc762a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_zqD9j/pylance-15.0.0b13-cp310-abi3-win_arm64.whl", hash = "sha256:b3aecc63299a687d9ae69d80655f869321d922d5b462f4657efc83d73456551e" }, ] [[package]] From bff93ff314eee34f625d05bd92b73d95867fe787 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sat, 7 Nov 2026 02:15:39 +0000 Subject: [PATCH 042/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.7=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 1a29e14cd..febe6b48f 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.7" +current_version = "0.42.0-beta.8" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 6241b9f0e..11968b42c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5930,7 +5930,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" dependencies = [ "ahash", "anyhow", @@ -6041,7 +6041,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" dependencies = [ "anyhow", "arrow-array", @@ -6084,7 +6084,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" dependencies = [ "arrow-array", "arrow-buffer", @@ -6109,7 +6109,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index dbc071627..d94230240 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.42.0-beta.7 + 0.42.0-beta.8 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index da9e817c3..094e8fdbc 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.7 + 0.42.0-beta.8 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 91833b915..3539ed0f7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.7 + 0.42.0-beta.8 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index c091a6116..e1663329f 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" 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 4eb32dabe..fa4dc453c 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.42.0-beta.7", + "version": "0.42.0-beta.8", "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 a1e084617..8ade7188f 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.42.0-beta.7", + "version": "0.42.0-beta.8", "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 0ea788c08..c9b4cfe22 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.42.0-beta.7", + "version": "0.42.0-beta.8", "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 224debf13..d51434285 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.42.0-beta.7", + "version": "0.42.0-beta.8", "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 abd60fd2b..49391feaa 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.42.0-beta.7", + "version": "0.42.0-beta.8", "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 ae4c80c2e..d652c6a5f 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.42.0-beta.7", + "version": "0.42.0-beta.8", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 1f3764880..838693e35 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.42.0-beta.7", + "version": "0.42.0-beta.8", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 348f15e56..1576c0cd5 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.7", + "version": "0.42.0-beta.8", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 20426db54..2118ab6e7 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index e94df328f..f489f5e51 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index dab312eae..d1780e899 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.7" +version = "0.42.0-beta.8" edition = "2021" license.workspace = true repository.workspace = true From bd8cbfd4f2a39e6bdda01a379f12c767bd69f0ac Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Mon, 9 Nov 2026 00:08:12 +0800 Subject: [PATCH 043/203] chore: update lance dependency to v15.0.0-beta.14 (#4909) Update the Rust workspace Lance crates and Python test dependency to [Lance v15.0.0-beta.14](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.14), which includes JSON cache reuse across request stores and stable-row-ID JSON index support. The Python lock contains all seven published wheels. The independent Java module retains beta.8, as in the previous beta.13 update; its separate beta.14 publisher repair is outside this Rust consumer upgrade. Preserve all CI coverage while reclaiming completed workspace lancedb artifacts before the package-level feature-test build, which otherwise exhausted the Linux runner disk. Give only the Linux ARM64 release-wheel job two hours after its one-hour timeout, retaining the same runner, fat-LTO release profile and build flags. Validation: 2,280 Rust tests passed (79 existing ignores), strict workspace/all-feature Clippy, Rust formatting, and remote example checks passed on unchanged Rust source and dependency lock. Python dependency guards, lock validation, locked sync, and the published macOS wheel import passed. The new Windows ARM64 wheel was downloaded and its SHA-256 verified. Workflow YAML/shell checks and independent review passed. Root Python Ruff/format checks still fail on unchanged documentation examples; no suppressions or unrelated cleanup were added. The CI repairs require a complete new run before readiness. This dependency update does not establish corrected Sophon performance; downstream native acceptance and the paired S3 replay remain separate. --- .github/workflows/pypi-publish.yml | 3 +- .github/workflows/rust.yml | 7 +++ Cargo.lock | 96 +++++++++++++++--------------- Cargo.toml | 30 +++++----- python/pyproject.toml | 2 +- python/uv.lock | 18 +++--- 6 files changed, 82 insertions(+), 74 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index d45833def..b2db765d0 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -36,7 +36,8 @@ concurrency: jobs: linux: name: Python ${{ matrix.config.package_name }} ${{ matrix.config.platform }} manylinux${{ matrix.config.manylinux }} - timeout-minutes: 60 + # The ARM64 release build can exceed an hour with fat LTO on a cold runner. + timeout-minutes: ${{ matrix.config.platform == 'aarch64' && 120 || 60 }} strategy: matrix: config: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 687b8a54c..a628c6fa0 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -241,6 +241,13 @@ jobs: sudo swapon "$swapfile" - name: Build run: cargo build --profile ci --all-features --tests --locked --examples + - name: Reclaim completed workspace build artifacts + run: | + # Package-level tests resolve a different feature graph from the workspace + # build. Reclaim its lancedb outputs before linking the test graph. + df -h . + cargo clean --profile ci -p lancedb + df -h . - name: Run feature tests run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests - name: Run examples diff --git a/Cargo.lock b/Cargo.lock index 11968b42c..9deed7de3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arc-swap", "arrow", @@ -5671,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" +version = "15.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 468eb04d3..90bfbb608 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.13", default-features = false, "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.13", default-features = false, "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.13", default-features = false, "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.13", "tag" = "v15.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.14", default-features = false, "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.14", default-features = false, "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.14", default-features = false, "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/python/pyproject.toml b/python/pyproject.toml index edcdf903f..2e822deb9 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b13", + "pylance==15.0.0b14", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 9c228aef9..61fec64ac 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b13" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b14" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b13" +version = "15.0.0b14" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,13 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1UqLiw/pylance-15.0.0b13-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bbbf6e42624275d1559a4887a11f6cb1c34f10c560ca7209b59219d3614a444f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_wto7I/pylance-15.0.0b13-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b8730195df05fa7242d12f4c759019b658f668b90d7ceba380059597bb5951a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_13UO9X/pylance-15.0.0b13-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a41f292084694a681773990e6d96a675b45e4d232d7a67b21b05762dd5976e8a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1Mjytl/pylance-15.0.0b13-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:76d2f6a5a8ac150bee990006cc7b7c920e1af2532e4d3ff6a142ab5a5412483e" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1XuqE6/pylance-15.0.0b13-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ac2b50bf8af53aac65d56703010cdf9c1567fdfe230c7fbac1d69584933d7793" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Fj6Go/pylance-15.0.0b13-cp310-abi3-win_amd64.whl", hash = "sha256:7e6556db1a812cb0846cc0e30c0f273468d5e58dc210f3ee9955d9cdc3bc762a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_zqD9j/pylance-15.0.0b13-cp310-abi3-win_arm64.whl", hash = "sha256:b3aecc63299a687d9ae69d80655f869321d922d5b462f4657efc83d73456551e" }, + { url = "https://pypi.fury.io/lance-format/-/ver_b88Zw/pylance-15.0.0b14-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:48bcdfda408d1f8eaabbd066236bdb0ae9539acb3186b246c5c1ad4e8e5dcf23" }, + { url = "https://pypi.fury.io/lance-format/-/ver_J0evn/pylance-15.0.0b14-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:958d7cf0c8f31e09be94d6785c45158121073e79eb3bdb6f7ed25f7dde22c9a2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_18gbAN/pylance-15.0.0b14-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80814eff77dd0b83ee3c18280895a8d2cadf6d49818d7047a4540b773618738d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1gqym0/pylance-15.0.0b14-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:bb59f5d5b8740eb5df57c1777bce61f3e2a9f7d47ab31068e2ccf43549627103" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1FHTtC/pylance-15.0.0b14-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:357357f9f419efe9f90ba63d4dc371fc93e191aa692cf6f88d327607680f77da" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1LzfL9/pylance-15.0.0b14-cp310-abi3-win_amd64.whl", hash = "sha256:916fcc39051bdd2e8ca50950ee4d8afb941c130fd278ac7cea252c2059beab58" }, + { url = "https://pypi.fury.io/lance-format/-/ver_nDQ2x/pylance-15.0.0b14-cp310-abi3-win_arm64.whl", hash = "sha256:e1449bbb7a207cb2890d9afeef41f816d2ab4a459ed73cc46c919d463e46fe10" }, ] [[package]] From 1157a0709d66ad747a995ed833f8d45f11e7d382 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 8 Nov 2026 16:14:30 +0000 Subject: [PATCH 044/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.8=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index febe6b48f..bbf036dc8 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.8" +current_version = "0.42.0-beta.9" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 9deed7de3..1ac7a4f6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5930,7 +5930,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" dependencies = [ "ahash", "anyhow", @@ -6041,7 +6041,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" dependencies = [ "anyhow", "arrow-array", @@ -6084,7 +6084,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" dependencies = [ "arrow-array", "arrow-buffer", @@ -6109,7 +6109,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index d94230240..6b0ac9492 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.42.0-beta.8 + 0.42.0-beta.9 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 094e8fdbc..f915a6a64 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.8 + 0.42.0-beta.9 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 3539ed0f7..161e13c2c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.8 + 0.42.0-beta.9 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index e1663329f..d8f16adb1 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" 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 fa4dc453c..f04147d46 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.42.0-beta.8", + "version": "0.42.0-beta.9", "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 8ade7188f..af781ae92 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.42.0-beta.8", + "version": "0.42.0-beta.9", "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 c9b4cfe22..c08a81137 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.42.0-beta.8", + "version": "0.42.0-beta.9", "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 d51434285..624b22de3 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.42.0-beta.8", + "version": "0.42.0-beta.9", "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 49391feaa..d200c24c3 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.42.0-beta.8", + "version": "0.42.0-beta.9", "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 d652c6a5f..a0b3cfd48 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.42.0-beta.8", + "version": "0.42.0-beta.9", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 838693e35..0544af0c7 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.42.0-beta.8", + "version": "0.42.0-beta.9", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 1576c0cd5..c2424cd55 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.8", + "version": "0.42.0-beta.9", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 2118ab6e7..2c577766b 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index f489f5e51..6f5d45232 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index d1780e899..601d0f58b 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.8" +version = "0.42.0-beta.9" edition = "2021" license.workspace = true repository.workspace = true From 94f366a11a368b0d8e1bf0f24313aef586a8fd43 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Mon, 9 Nov 2026 09:51:48 -0800 Subject: [PATCH 045/203] docs: show the Python filtered refresh next to the SQL form (#4923) Adds Python where= examples next to the SQL ones. Also fixes two examples that fail: - Date filters now use date '2026-01-01'. A bare string fails on DATE and TIMESTAMP columns (see [Dates, Timestamps, Decimals](https://docs.lancedb.com/search/filtering#dates-timestamps-decimals)). - The first example reads results with table.search().to_arrow(), because table.to_arrow() raises on Enterprise. where= needs lancedb 0.42.0 or later. --- .../feature-engineering/refresh-column.mdx | 37 ++++++++++++++----- docs/web/sql/dml/refresh-column.mdx | 4 +- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 8f5726307..ac4ff93fe 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -22,7 +22,7 @@ Computed columns require LanceDB Enterprise. job = table.refresh_column_async("doubled") job.wait() -table.to_arrow().sort_by("x").to_pandas() +table.search().to_arrow().sort_by("x").to_pandas() # x doubled # 0 1 2 # 1 2 4 @@ -77,13 +77,21 @@ catch-up works when it's re-enabled after being off. ## Refreshing part of a table {#partial} -Enterprise In SQL a refresh can be scoped to a -predicate, which is useful for filling a slice first and checking it before -committing to the whole table: +Enterprise A refresh can be scoped to a predicate, +with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice +first and checking it before committing to the whole table: +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + where="created_at > date '2026-01-01'", +) +job.wait() +``` + ```sql SQL icon="database" -REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' +REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' ``` @@ -92,9 +100,17 @@ whose outputs are already current. Repeating the same predicate repeats those Function calls and their cost. To select only null outputs within a slice: +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + where="created_at > date '2026-01-01' AND embedding IS NULL", +) +job.wait() +``` + ```sql SQL icon="database" REFRESH COLUMN embedding ON documents - WHERE created_at > '2026-01-01' AND embedding IS NULL + WHERE created_at > date '2026-01-01' AND embedding IS NULL ``` @@ -247,13 +263,14 @@ and `gpuCount` in the `refreshColumnAsync` options. The job APIs also take the row filter and failure handling of the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed -to new rows and told to skip rows whose Function call fails: +to new rows (see [what a filter recomputes](#partial)) and told to skip rows +whose Function call fails: ```python job = table.refresh_column_async( "embedding", - where="published_at > '2026-01-01'", + where="created_at > date '2026-01-01'", error_policy="skip", max_failed_fraction=0.01, row_timeout_seconds=30, @@ -262,7 +279,7 @@ job = table.refresh_column_async( ```typescript const job = await table.refreshColumnAsync("embedding", { - where: "published_at > '2026-01-01'", + where: "created_at > date '2026-01-01'", errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, @@ -276,7 +293,7 @@ let _job = table .refresh_column_async_with_options( "embedding", RefreshColumnOptions::default() - .where_clause("published_at > '2026-01-01'") + .where_clause("created_at > date '2026-01-01'") .error_policy(FunctionErrorPolicy::Skip) .max_failed_fraction(0.01) .row_timeout_seconds(30.0), diff --git a/docs/web/sql/dml/refresh-column.mdx b/docs/web/sql/dml/refresh-column.mdx index 98a360366..fcb78bd35 100644 --- a/docs/web/sql/dml/refresh-column.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -24,7 +24,7 @@ REFRESH COLUMN ON [TABLE] ```sql SQL icon="database" REFRESH COLUMN doubled ON my_table -REFRESH COLUMN embedding ON documents WHERE created_at > '2026-01-01' +REFRESH COLUMN embedding ON documents WHERE created_at > date '2026-01-01' ``` @@ -39,7 +39,7 @@ calls and their cost. To select only null outputs within a slice: ```sql SQL icon="database" REFRESH COLUMN embedding ON documents - WHERE created_at > '2026-01-01' AND embedding IS NULL + WHERE created_at > date '2026-01-01' AND embedding IS NULL ``` From 546a28ad2c8e8bd8a95540afc80f27091de514db Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Mon, 9 Nov 2026 11:19:47 -0800 Subject: [PATCH 046/203] feat: support remote compaction tuning and table inheritance (#4886) --- docs/src/js/classes/Table.md | 3 + docs/src/js/globals.md | 1 + docs/src/js/interfaces/CompactionOptions.md | 49 +++++++++ docs/src/js/interfaces/OptimizeOptions.md | 22 ++++ docs/src/python/python.md | 24 +++- docs/web/maintenance/compaction.mdx | 7 +- nodejs/__test__/table.test.ts | 89 ++++++++++++++- nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 41 +++++++ nodejs/src/table.rs | 65 ++++++++++- python/python/lancedb/remote/table.py | 11 +- python/python/lancedb/table.py | 32 ++++-- python/python/tests/test_remote_db.py | 116 +++++++++++++++++--- python/src/table.rs | 24 +++- rust/lancedb/src/remote/sql_test.rs | 112 ++++++++++++++++++- rust/lancedb/src/remote/table.rs | 56 ++++++---- rust/lancedb/src/remote/table/optimize.rs | 98 +++++++++++++++++ rust/lancedb/src/table.rs | 69 +++++++++++- rust/lancedb/src/table/optimize.rs | 85 +++++++++++++- 19 files changed, 830 insertions(+), 75 deletions(-) create mode 100644 docs/src/js/interfaces/CompactionOptions.md create mode 100644 rust/lancedb/src/remote/table/optimize.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 8bdc6b5f8..1fad723fe 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -948,6 +948,9 @@ supported. Pruning old versions and index optimization are silently skipped there instead of being attempted, so this call resolves successfully, with zeroed pruning statistics, once the compaction job has been submitted; it does not wait for that job to finish. +`compactionOptions` can tune the four per-job settings documented in +[CompactionOptions](../interfaces/CompactionOptions.md). Older-server errors are propagated without +retrying with the settings removed. #### Parameters diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 46f8db833..dab1c61bc 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -74,6 +74,7 @@ - [ClientConfig](interfaces/ClientConfig.md) - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) +- [CompactionOptions](interfaces/CompactionOptions.md) - [CompactionStats](interfaces/CompactionStats.md) - [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md) - [ConnectionOptions](interfaces/ConnectionOptions.md) diff --git a/docs/src/js/interfaces/CompactionOptions.md b/docs/src/js/interfaces/CompactionOptions.md new file mode 100644 index 000000000..135266567 --- /dev/null +++ b/docs/src/js/interfaces/CompactionOptions.md @@ -0,0 +1,49 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CompactionOptions + +# Interface: CompactionOptions + +Per-invocation compaction settings. Values must be safe integers. + +## Properties + +### batchSize? + +```ts +optional batchSize: number; +``` + +Positive scanner batch size in rows. + +*** + +### ioBufferSize? + +```ts +optional ioBufferSize: number; +``` + +Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure. + +*** + +### maxSourceRows? + +```ts +optional maxSourceRows: number; +``` + +Positive live-source-row budget across whole tasks; an oversized first task can produce no work. + +*** + +### targetRowsPerFragment? + +```ts +optional targetRowsPerFragment: number; +``` + +Positive target rows per output fragment; also affects candidate selection. diff --git a/docs/src/js/interfaces/OptimizeOptions.md b/docs/src/js/interfaces/OptimizeOptions.md index 110eb3813..faf1d2724 100644 --- a/docs/src/js/interfaces/OptimizeOptions.md +++ b/docs/src/js/interfaces/OptimizeOptions.md @@ -33,6 +33,28 @@ tbl.optimize({cleanupOlderThan: new Date()}); *** +### compactionOptions? + +```ts +optional compactionOptions: CompactionOptions; +``` + +Compaction settings for this invocation. Omitted remote values inherit table +tuning, then deployment/built-in defaults. +Remote tables require a server supporting these SQL options; settings do +not change table policy. This is not a runtime or total-memory limit. + +#### Example + +```ts +await tbl.optimize({ compactionOptions: { + targetRowsPerFragment: 1000, maxSourceRows: 5000, + ioBufferSize: 64 * 1024 * 1024, batchSize: 128, +} }); +``` + +*** + ### deleteUnverified ```ts diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 3658f2ad3..7e5140928 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -352,9 +352,27 @@ accept the LanceDB Embedded options: cleanup and compaction warn that they are n `optimize` submits a durable compaction job and returns once that submission is accepted, not once compaction itself finishes. Pruning and index optimization are not yet supported remotely, so it silently skips them and returns with -zeroed pruning statistics rather than attempting and failing. A non-default -`compaction_options` raises `NotImplementedError` before anything is -submitted, since there is no way yet to forward those settings to the server. +zeroed pruning statistics. Remote `compaction_options` support per-job +`target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and `batch_size` +on compatible servers. Other non-default settings raise `NotImplementedError` +before submission; older-server errors are returned without dropping options. +The source-row budget selects whole tasks and can produce no work if the first +task exceeds it. An I/O buffer size of zero disables byte-based I/O backpressure. +Use a positive size to limit I/O read-ahead; this is not a total-memory limit. +Each field resolves as invocation option → table tuning → deployment/built-in +default. These options apply only to the submitted job and leave table policy +unchanged. Table `enabled` controls automatic scheduling; explicit manual runs +remain allowed. + +```python +table.optimize(compaction_options={ + "target_rows_per_fragment": 100_000, + "max_source_rows": 1_000_000, + "io_buffer_size": 64 * 1024 * 1024, + "batch_size": 1024, +}) +``` + Removed Tantivy options produce the same explanatory errors on both backends. The old LanceDB Enterprise keyword names `predicate` for `delete`, `index_name` for diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 3110c0858..9c8765293 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -150,9 +150,10 @@ task at a time can also reduce memory use. 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 tables in LanceDB Embedded. +TypeScript's `optimize()` exposes the fragment row target through +`compactionOptions.targetRowsPerFragment` and the scanner batch size through +`compactionOptions.batchSize`. Compaction thread count is not exposed. The tuning +examples above use 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/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index af66ebb60..c3888d6c0 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -11,6 +11,7 @@ import { AutoQuery, type BlobInput, type BlobMode, + type CompactionOptions, Connection, MatchQuery, PhraseQuery, @@ -3997,7 +3998,93 @@ it("passes cleanupOlderThan to the native binding as an absolute timestamp", asy await table.optimize({ cleanupOlderThan: cutoff, deleteUnverified: true }); - expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true); + expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true, undefined); +}); + +it("forwards per-job compaction options to the native binding", async () => { + const optimize = jest.fn().mockResolvedValue({}); + const table = new LocalTable({ optimize } as never); + const compactionOptions = { + targetRowsPerFragment: 20, + maxSourceRows: 25, + ioBufferSize: 0, + batchSize: 8, + }; + await table.optimize({ compactionOptions }); + expect(optimize).toHaveBeenCalledWith( + undefined, + undefined, + compactionOptions, + ); +}); + +it("rejects unsupported JavaScript compaction options before native submission", async () => { + const optimize = jest.fn(); + const table = new LocalTable({ optimize } as never); + await expect( + table.optimize({ + compactionOptions: { + maxSourceBytes: 1024, + } as unknown as CompactionOptions, + }), + ).rejects.toThrow("Unsupported compaction option: maxSourceBytes"); + expect(optimize).not.toHaveBeenCalled(); +}); + +describe("per-job compaction options", () => { + let tmpDir: tmp.DirResult; + let table: Table; + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + table = await db.createTable( + "bounded", + Array.from({ length: 10 }, (_, id) => ({ id })), + ); + for (let f = 1; f < 8; f++) { + await table.add( + Array.from({ length: 10 }, (_, id) => ({ id: f * 10 + id })), + ); + } + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + it("bounds source work and preserves zero I/O buffering", async () => { + const stats = await table.optimize({ + compactionOptions: { + targetRowsPerFragment: 20, + maxSourceRows: 25, + ioBufferSize: 0, + batchSize: 8, + }, + }); + expect(stats.compaction.fragmentsRemoved).toBe(2); + expect(stats.compaction.fragmentsAdded).toBe(1); + expect(await table.countRows()).toBe(80); + const defaults = await table.optimize(); + expect(defaults.compaction.fragmentsRemoved).toBe(7); + expect(defaults.compaction.fragmentsAdded).toBe(1); + expect(await table.countRows()).toBe(80); + }); + const invalid: CompactionOptions[] = [ + { targetRowsPerFragment: 0 }, + { maxSourceRows: 0 }, + { batchSize: 0 }, + { ioBufferSize: -1 }, + { batchSize: 1.5 }, + { maxSourceRows: Number.NaN }, + { ioBufferSize: Number.POSITIVE_INFINITY }, + { maxSourceRows: Number.MAX_SAFE_INTEGER + 1 }, + { targetRowsPerFragment: 2 ** 32 }, + { batchSize: 2 ** 32 }, + ]; + it.each(invalid)("rejects invalid settings %p", async (compactionOptions) => { + await expect(table.optimize({ compactionOptions })).rejects.toThrow( + /safe integer/, + ); + expect(await table.countRows()).toBe(80); + }); }); describe.each(arrowVersions)( diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 0e054d70e..9644b0060 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -165,6 +165,7 @@ export { AddDataOptions, UpdateOptions, OptimizeOptions, + CompactionOptions, Version, WriteProgress, FtsToken, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index de22ef0f8..5ef298c8c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -152,7 +152,31 @@ export interface UpdateOptions { where: string; } +/** Per-invocation compaction settings. Values must be safe integers. */ +export interface CompactionOptions { + /** Positive target rows per output fragment; also affects candidate selection. */ + targetRowsPerFragment?: number; + /** Positive live-source-row budget across whole tasks; an oversized first task can produce no work. */ + maxSourceRows?: number; + /** Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure. */ + ioBufferSize?: number; + /** Positive scanner batch size in rows. */ + batchSize?: number; +} + export interface OptimizeOptions { + /** + * Compaction settings for this invocation. Omitted remote values inherit table + * tuning, then deployment/built-in defaults. + * Remote tables require a server supporting these SQL options; settings do + * not change table policy. This is not a runtime or total-memory limit. + * @example + * await tbl.optimize({ compactionOptions: { + * targetRowsPerFragment: 1000, maxSourceRows: 5000, + * ioBufferSize: 64 * 1024 * 1024, batchSize: 128, + * } }); + */ + compactionOptions?: CompactionOptions; /** * If set then all versions older than the given date * be removed. The current version will never be removed. @@ -1047,6 +1071,9 @@ export abstract class Table { * skipped there instead of being attempted, so this call resolves * successfully, with zeroed pruning statistics, once the compaction job * has been submitted; it does not wait for that job to finish. + * `compactionOptions` can tune the four per-job settings documented in + * {@link CompactionOptions}. Older-server errors are propagated without + * retrying with the settings removed. */ abstract optimize(options?: Partial): Promise; /** @@ -1646,9 +1673,23 @@ export class LocalTable extends Table { } async optimize(options?: Partial): Promise { + // JavaScript callers can supply extra keys that TypeScript would reject. + // Refuse them before the native binding can silently discard a work limit. + const supported = new Set([ + "targetRowsPerFragment", + "maxSourceRows", + "ioBufferSize", + "batchSize", + ]); + for (const key of Object.keys(options?.compactionOptions ?? {})) { + if (!supported.has(key)) { + throw new Error(`Unsupported compaction option: ${key}`); + } + } return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, + options?.compactionOptions, ); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 5c3805f51..ebbc4a060 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -23,6 +23,63 @@ use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; +/// Per-invocation file-compaction settings. All numbers must be safe integers. +#[napi(object)] +pub struct CompactionOptions { + pub target_rows_per_fragment: Option, + pub max_source_rows: Option, + pub io_buffer_size: Option, + pub batch_size: Option, +} + +impl CompactionOptions { + fn into_overrides(self) -> napi::Result { + const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; + fn integer( + value: Option, + name: &str, + max: u64, + allow_zero: bool, + ) -> napi::Result> { + let Some(value) = value else { + return Ok(None); + }; + let min = if allow_zero { 0 } else { 1 }; + let max = max.min(MAX_SAFE_INTEGER); + if !value.is_finite() + || value.fract() != 0.0 + || value < min as f64 + || value > max as f64 + { + return Err(napi::Error::from_reason(format!( + "{name} must be a safe integer between {min} and {max}" + ))); + } + Ok(Some(value as u64)) + } + let mut options = lancedb::table::optimize::CompactionOverrides::default(); + if let Some(target) = integer( + self.target_rows_per_fragment, + "targetRowsPerFragment", + u32::MAX as u64, + false, + )? { + options.target_rows_per_fragment = Some(target as usize); + } + options.max_source_rows = integer( + self.max_source_rows, + "maxSourceRows", + usize::MAX as u64, + false, + )? + .map(|v| v as usize); + options.io_buffer_size = integer(self.io_buffer_size, "ioBufferSize", u64::MAX, true)?; + options.batch_size = + integer(self.batch_size, "batchSize", u32::MAX as u64, false)?.map(|v| v as usize); + Ok(options) + } +} + #[napi] pub struct Table { // We keep a duplicate of the table name so we can use it for error @@ -732,6 +789,7 @@ impl Table { &self, before_timestamp_ms: Option, delete_unverified: Option, + compaction_options: Option, ) -> napi::Result { let inner = self.inner_ref()?; @@ -746,8 +804,11 @@ impl Table { .transpose()?; let stats = inner - .optimize_full( - lancedb::table::CompactionOptions::default(), + .optimize_full_with_overrides( + compaction_options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(), None, before_timestamp, delete_unverified, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 6bef59922..8f1f741fb 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1091,10 +1091,13 @@ class RemoteTable(Table): Enterprise job. Pruning old versions and index optimization are not yet supported remotely, so this call skips them and returns successfully with zeroed pruning statistics once the compaction job - has been submitted; it does not wait for that job to finish. Passing - a non-default ``compaction_options`` raises ``NotImplementedError`` - before anything is submitted, since there is no way yet to forward - those settings to the server. + has been submitted; it does not wait for that job to finish. The + per-job options ``target_rows_per_fragment``, ``max_source_rows``, + ``io_buffer_size``, and ``batch_size`` are supported on compatible + servers. Omitted fields inherit table tuning, then deployment/built-in + defaults. Other non-default settings raise ``NotImplementedError`` + before submission. Errors from older servers are propagated without + retrying with the settings removed. """ return LOOP.run( self._table.optimize( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index f43df8b40..75975a2c3 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -307,7 +307,12 @@ IndexConfigType = Union[ class CompactionOptions(TypedDict, total=False): """Options that control file compaction during table optimization. - Unspecified options use Lance's defaults. + Unspecified options use Lance's defaults for local tables. Remote tables + forward ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, + and ``batch_size`` as per-job SQL options; other non-default settings are + unsupported. Omitted remote options inherit table tuning, then deployment/built-in + defaults. The server must support these SQL options. These settings do not + change table policy. Compaction planning is row based. Lowering ``target_rows_per_fragment`` based on the expected row size can bound later compaction passes once @@ -353,7 +358,10 @@ class CompactionOptions(TypedDict, total=False): """Number of rows per input scan batch.""" io_buffer_size: Optional[int] - """Maximum number of bytes queued in the input scan I/O buffer.""" + """Input scan I/O read-ahead budget in bytes. + + Zero disables byte-based I/O backpressure. + """ defer_index_remap: bool """Whether to defer index remapping during compaction (default: False).""" @@ -2943,9 +2951,13 @@ class Table(ABC): are silently skipped there instead of being attempted, so this call returns successfully, with zeroed pruning statistics, once the compaction job has been submitted; it does not wait for that - job to finish. A non-default ``compaction_options`` raises - ``NotImplementedError`` before anything is submitted, since - there is no way yet to forward those settings to the server. + job to finish. Remote compaction supports per-job + ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, + and ``batch_size``. Omitted fields inherit table tuning, then + deployment/built-in defaults. Other non-default compaction settings raise + ``NotImplementedError`` before submission. The server must support + these SQL options; older-server errors are propagated without + dropping the requested settings. Modeled after ``VACUUM`` in PostgreSQL. @@ -8477,9 +8489,13 @@ class AsyncTable: are silently skipped there instead of being attempted, so this call returns successfully, with zeroed pruning statistics, once the compaction job has been submitted; it does not wait for that - job to finish. A non-default ``compaction_options`` raises - ``NotImplementedError`` before anything is submitted, since - there is no way yet to forward those settings to the server. + job to finish. Remote compaction supports per-job + ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, + and ``batch_size``. Omitted fields inherit table tuning, then + deployment/built-in defaults. Other non-default compaction settings raise + ``NotImplementedError`` before submission. The server must support + these SQL options; older-server errors are propagated without + dropping the requested settings. Modeled after ``VACUUM`` in PostgreSQL. diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8a65a2a1c..25d9db22a 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5837,10 +5837,8 @@ def _create_table_handler(request): @contextlib.contextmanager -def _mock_remote_table_with_sql(flight_server): - """A remote table backed by a mock REST server (for create/open) and the - given mock Flight SQL server (for the SQL statements `optimize()` submits - as jobs).""" +def _mock_remote_sql_connection(flight_server): + """Connection arguments for mock REST and Flight SQL servers.""" with http.server.ThreadingHTTPServer( ("127.0.0.1", 0), make_mock_http_handler(_create_table_handler) ) as rest_server: @@ -5848,18 +5846,106 @@ def _mock_remote_table_with_sql(flight_server): handle = start_server_thread(rest_server) try: with flight_server: - db = lancedb.connect( - "db://dev", - api_key="fake", - host_override=f"http://127.0.0.1:{rest_port}", - sql_host_override=f"grpc://127.0.0.1:{flight_server.port}", - ) - yield db.create_table("test", [{"id": 1}]) + yield { + "uri": "db://dev", + "api_key": "fake", + "host_override": f"http://127.0.0.1:{rest_port}", + "sql_host_override": f"grpc://127.0.0.1:{flight_server.port}", + } finally: rest_server.shutdown() handle.join() +@contextlib.contextmanager +def _mock_remote_table_with_sql(flight_server): + with _mock_remote_sql_connection(flight_server) as kwargs: + yield lancedb.connect(**kwargs).create_table("test", [{"id": 1}]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options,sql_options", + [ + ({"target_rows_per_fragment": 100}, [b"target_rows_per_fragment = 100"]), + ( + {"target_rows_per_fragment": 1_048_576}, + [b"target_rows_per_fragment = 1048576"], + ), + ({"max_source_rows": 500}, [b"max_source_rows = 500"]), + ({"io_buffer_size": 0}, [b"io_buffer_size = 0"]), + ({"batch_size": 16}, [b"batch_size = 16"]), + ( + { + "target_rows_per_fragment": 100, + "max_source_rows": 500, + "io_buffer_size": 65536, + "batch_size": 16, + }, + [ + b"target_rows_per_fragment = 100", + b"max_source_rows = 500", + b"io_buffer_size = 65536", + b"batch_size = 16", + ], + ), + ({}, []), + ], +) +async def test_remote_optimize_forwards_per_job_compaction_options( + asynchronous, options, sql_options +): + flight = pytest.importorskip("pyarrow.flight") + + class AckServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table({"ok": pa.array([], type=pa.bool_())}) + ) + + server = AckServer() + with _mock_remote_sql_connection(server) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + stats = await table.optimize(compaction_options=options) + else: + table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}]) + stats = table.optimize(compaction_options=options) + assert len(server.tickets) == 1 + assert b"OPTIMIZE" in server.tickets[0] + assert all(option in server.tickets[0] for option in sql_options) + if not sql_options: + assert b"WITH (" not in server.tickets[0] + assert stats.prune.bytes_removed == 0 + + +def test_remote_optimize_does_not_drop_options_after_server_rejection(): + flight = pytest.importorskip("pyarrow.flight") + + class OldServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + raise flight.FlightServerError("Unknown OPTIMIZE option 'max_source_rows'") + + server = OldServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(Exception, match="max_source_rows"): + table.optimize(compaction_options={"max_source_rows": 500}) + assert server.tickets + assert all(b"max_source_rows = 500" in ticket for ticket in server.tickets) + + def test_remote_optimize_skips_prune_and_index(): """Regression test: a remote table's `optimize()` used to submit a compaction job and then raise `NotImplementedError` once it went on to @@ -5868,7 +5954,7 @@ def test_remote_optimize_skips_prune_and_index(): zeroed pruning statistics, once compaction is submitted. The SQL job submission for a query without parameters (like - `OPTIMIZE TABLE ... REWRITE DATA`) goes over plain Flight `do_get`, not + `OPTIMIZE ... REWRITE DATA`) goes over plain Flight `do_get`, not `do_exchange`: the client sends a ticket wrapping the statement and reads back whatever the server returns as the job's result stream. """ @@ -5890,12 +5976,12 @@ def test_remote_optimize_skips_prune_and_index(): stats = table.optimize() assert len(server.tickets) == 1 - assert b"OPTIMIZE TABLE" in server.tickets[0] + assert b"OPTIMIZE" in server.tickets[0] assert stats.prune.bytes_removed == 0 assert stats.prune.old_versions_removed == 0 -def test_remote_optimize_rejects_non_default_compaction_options_before_submitting(): +def test_remote_optimize_rejects_unsupported_compaction_options_before_submitting(): """Regression test: `RemoteTable.optimize()` used to drop `compaction_options` instead of forwarding it to the Rust layer, so a non-default value was silently ignored -- the server-side guard against @@ -5917,7 +6003,7 @@ def test_remote_optimize_rejects_non_default_compaction_options_before_submittin ) server = UnreachableServer() - options: CompactionOptions = {"target_rows_per_fragment": 5} + options: CompactionOptions = {"max_source_bytes": 1024} with _mock_remote_table_with_sql(server) as table: with pytest.raises(NotImplementedError, match="CompactionOptions"): table.optimize(compaction_options=options) diff --git a/python/src/table.rs b/python/src/table.rs index 6371d94c0..db3a88f7f 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1838,6 +1838,10 @@ impl Table { compaction_options: Option<&Bound<'py, PyDict>>, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); + let target_specified = compaction_options + .map(|options| options.contains("target_rows_per_fragment")) + .transpose()? + .unwrap_or(false); let compaction_options = parse_compaction_options(compaction_options)?; let older_than = if let Some(ms) = cleanup_since_ms { if ms > i64::MAX as u64 { @@ -1852,10 +1856,22 @@ impl Table { None }; future_into_py(self_.py(), async move { - let stats = inner - .optimize_full(compaction_options, older_than, None, delete_unverified) - .await - .infer_error()?; + let stats = if inner.as_native().is_some() { + inner + .optimize_full(compaction_options, older_than, None, delete_unverified) + .await + } else { + let mut overrides = + lancedb::table::optimize::CompactionOverrides::try_from(compaction_options) + .infer_error()?; + if !target_specified { + overrides.target_rows_per_fragment = None; + } + inner + .optimize_full_with_overrides(overrides, older_than, None, delete_unverified) + .await + } + .infer_error()?; let compaction_stats = stats.compaction.unwrap(); let prune_stats = stats.prune.unwrap(); Ok(OptimizeStats { diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 1211263d8..aa41f2c86 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -2318,7 +2318,7 @@ async fn remote_optimize_submits_a_compaction_job_over_sql() { assert!(stats.prune.is_none()); assert_eq!( *statements.lock().unwrap(), - ["OPTIMIZE TABLE \"events\" REWRITE DATA"] + ["OPTIMIZE \"events\" REWRITE DATA"] ); assert!( headers @@ -2362,7 +2362,7 @@ async fn remote_optimize_on_a_branch_submits_a_with_clause_over_sql() { assert_eq!( *statements.lock().unwrap(), - ["OPTIMIZE TABLE \"events\" REWRITE DATA WITH (branch = 'o''brien')"] + ["OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'o''brien')"] ); shutdown.send(()).unwrap(); } @@ -2426,7 +2426,7 @@ async fn remote_optimize_full_skips_prune_and_index() { ); assert_eq!( *statements.lock().unwrap(), - ["OPTIMIZE TABLE \"events\" REWRITE DATA"] + ["OPTIMIZE \"events\" REWRITE DATA"] ); shutdown.send(()).unwrap(); } @@ -3612,3 +3612,109 @@ fn sql_status_reports_structured_resource_identity() { assert_eq!(resource.name, "missing"); assert_eq!(resource.namespace_path, ["ns"]); } + +#[tokio::test] +async fn remote_optimize_forwards_per_job_options_on_main_and_branch() { + for branch in [None, Some("o'brien")] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into()], + "team$events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(branch.map(str::to_string)); + table + .optimize(crate::table::optimize::OptimizeAction::Compact { + options: crate::table::optimize::CompactionOptions { + target_rows_per_fragment: 100, + max_source_rows: Some(500), + io_buffer_size: Some(0), + batch_size: Some(16), + ..Default::default() + }, + remap_options: None, + }) + .await + .unwrap(); + let prefix = if branch.is_some() { + "branch = 'o''brien', " + } else { + "" + }; + assert_eq!( + *statements.lock().unwrap(), + [format!( + "OPTIMIZE \"events\" REWRITE DATA WITH ({prefix}target_rows_per_fragment = 100, max_source_rows = 500, io_buffer_size = 0, batch_size = 16)" + )] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team") + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_compact_preserves_omissions_and_explicit_default_values() { + use crate::table::{CompactionOptions, CompactionOverrides}; + let target = CompactionOptions::default().target_rows_per_fragment; + for (options, suffix) in [ + (CompactionOverrides::default(), String::new()), + ( + CompactionOverrides { + target_rows_per_fragment: Some(target), + ..Default::default() + }, + format!(" WITH (target_rows_per_fragment = {target})"), + ), + ( + CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }, + " WITH (io_buffer_size = 0)".into(), + ), + ] { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ); + table.compact(options).await.unwrap(); + assert_eq!( + *statements.lock().unwrap(), + [format!("OPTIMIZE \"events\" REWRITE DATA{suffix}")] + ); + shutdown.send(()).unwrap(); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index b781531fe..3801405eb 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3,6 +3,7 @@ pub mod blobs; pub mod insert; +mod optimize; use self::insert::{RemoteWriteExec, WriteOp}; use super::client::RequestResultExt; @@ -3662,9 +3663,9 @@ impl BaseTable for RemoteTable { Ok(()) } - /// Only `OptimizeAction::Compact` with default `options` and no custom + /// Only `OptimizeAction::Compact` with supported `options` and no custom /// `remap_options` is supported remotely: it submits a durable - /// compaction job through the server's `OPTIMIZE TABLE ... REWRITE DATA` + /// compaction job through the server's `OPTIMIZE ... REWRITE DATA` /// SQL statement, the same atomic, single-worker, index-safe path the /// server uses for its own automatic compaction. `.wait()` below waits /// for that SQL statement's own execution to finish, which only confirms @@ -3680,11 +3681,12 @@ impl BaseTable for RemoteTable { /// optimization. A branch-scoped table handle submits a /// `WITH (branch = '')` clause; the statement does not itself /// validate the branch exists, so a nonexistent branch surfaces as an - /// async job failure rather than an error from this call. A non-default - /// `CompactionOptions` (for example `target_rows_per_fragment` or - /// `max_source_bytes`) is rejected: the SQL statement has no `WITH` - /// clause to carry it yet, so accepting it would silently ignore - /// settings a caller may be relying on to bound the job. + /// async job failure rather than an error from this call. Per-job + /// `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and + /// `batch_size` are forwarded in the SQL `WITH` clause. Other non-default + /// options are rejected before submission. Servers must support these + /// SQL options; an older server's error is returned without retrying + /// with the settings removed. async fn optimize(&self, action: OptimizeAction) -> Result { self.check_mutable().await?; let OptimizeAction::Compact { @@ -3707,26 +3709,34 @@ impl BaseTable for RemoteTable { .into(), }); } - if *options != lance::dataset::optimize::CompactionOptions::default() { - return Err(Error::NotSupported { - message: "custom CompactionOptions are not supported in LanceDB \ - Enterprise; the OPTIMIZE TABLE ... REWRITE DATA SQL \ - statement has no WITH clause to carry them yet, so a \ - non-default value would be silently ignored rather than \ - applied. Omit options to use the server's managed \ - compaction settings." - .into(), - }); + let mut overrides = crate::table::optimize::CompactionOverrides::try_from(options.clone())?; + // The legacy Lance options type has no presence bit for this field. + // Use Table::compact to explicitly send a target equal to Lance's default. + if options.target_rows_per_fragment + == crate::table::CompactionOptions::default().target_rows_per_fragment + { + overrides.target_rows_per_fragment = None; } + self.compact(overrides).await + } + + async fn compact( + &self, + options: crate::table::optimize::CompactionOverrides, + ) -> Result { + self.check_mutable().await?; + let compaction_options = optimize::compaction_sql_options(&options)?; let sql_client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { message: "SQL is unavailable for this remote table client".to_string(), })?; - let mut statement = format!( - "OPTIMIZE TABLE {} REWRITE DATA", - quote_sql_identifier(&self.name) - ); + let mut statement = format!("OPTIMIZE {} REWRITE DATA", quote_sql_identifier(&self.name)); + let mut sql_options = Vec::new(); if let Some(branch) = &self.branch { - statement.push_str(&format!(" WITH (branch = {})", quote_sql_string(branch))); + sql_options.push(format!("branch = {}", quote_sql_string(branch))); + } + sql_options.extend(compaction_options); + if !sql_options.is_empty() { + statement.push_str(&format!(" WITH ({})", sql_options.join(", "))); } // `OptimizeStats` carries `lance::dataset::optimize` metric types that // are not `Serialize`/`Deserialize`/`Clone`, which `Job` requires, @@ -15863,7 +15873,7 @@ mod tests { } #[tokio::test] - async fn test_optimize_rejects_non_default_compaction_options() { + async fn test_optimize_rejects_unsupported_compaction_options() { let table = Table::new_with_handler("my_table", move |_| -> http::Response { panic!("custom compaction options must be rejected before any request is sent") }); diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs new file mode 100644 index 000000000..2a42dd3ab --- /dev/null +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Compaction options supported by the remote SQL submission protocol. +use crate::error::{Error, Result}; + +pub(super) fn compaction_sql_options( + options: &crate::table::optimize::CompactionOverrides, +) -> Result> { + for (name, value) in [ + ("target_rows_per_fragment", options.target_rows_per_fragment), + ("max_source_rows", options.max_source_rows), + ("batch_size", options.batch_size), + ] { + if value == Some(0) { + return Err(Error::InvalidInput { + message: format!("{name} must be greater than 0"), + }); + } + } + let mut result = Vec::new(); + for (name, value) in [ + ( + "target_rows_per_fragment", + options.target_rows_per_fragment.map(|v| v as u64), + ), + ("max_source_rows", options.max_source_rows.map(|v| v as u64)), + ("io_buffer_size", options.io_buffer_size), + ("batch_size", options.batch_size.map(|v| v as u64)), + ] { + if let Some(value) = value { + result.push(format!("{name} = {value}")); + } + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::table::{CompactionOptions, CompactionOverrides}; + + #[test] + fn omissions_and_explicit_default_target_are_distinct() { + assert!( + compaction_sql_options(&CompactionOverrides::default()) + .unwrap() + .is_empty() + ); + let target = CompactionOptions::default().target_rows_per_fragment; + assert_eq!( + compaction_sql_options(&CompactionOverrides { + target_rows_per_fragment: Some(target), + io_buffer_size: Some(0), + ..Default::default() + }) + .unwrap(), + [ + format!("target_rows_per_fragment = {target}"), + "io_buffer_size = 0".into() + ] + ); + } + + #[test] + fn unsupported_settings_are_rejected() { + assert!(matches!( + CompactionOverrides::try_from(CompactionOptions { + max_source_bytes: Some(1024), + ..Default::default() + }), + Err(Error::NotSupported { .. }) + )); + } + + #[test] + fn invalid_row_settings_are_rejected() { + for options in [ + CompactionOverrides { + target_rows_per_fragment: Some(0), + ..Default::default() + }, + CompactionOverrides { + max_source_rows: Some(0), + ..Default::default() + }, + CompactionOverrides { + batch_size: Some(0), + ..Default::default() + }, + ] { + assert!(matches!( + compaction_sql_options(&options), + Err(Error::InvalidInput { .. }) + )); + } + } +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index aefc0ac91..4691d33f1 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -111,7 +111,8 @@ pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTa pub use lance::dataset::scanner::DatasetRecordBatchStream; pub use lance_index::optimize::OptimizeOptions; pub use optimize::{ - CompactionMode, CompactionOptions, IndexRemapMode, OptimizeAction, OptimizeStats, + CompactionMode, CompactionOptions, CompactionOverrides, IndexRemapMode, OptimizeAction, + OptimizeStats, }; pub use refresh::{RefreshColumnOptions, RefreshColumnResult}; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; @@ -842,6 +843,14 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn tags(&self) -> Result>; /// Optimize the dataset. async fn optimize(&self, action: OptimizeAction) -> Result; + /// Compact with optional fields, preserving remote policy inheritance. + async fn compact(&self, options: optimize::CompactionOverrides) -> Result { + self.optimize(OptimizeAction::Compact { + options: options.into_options(), + remap_options: None, + }) + .await + } /// Add columns to the table. async fn add_columns( &self, @@ -1925,14 +1934,62 @@ impl Table { /// /// # LanceDB Enterprise (remote tables) /// - /// Only [`OptimizeAction::Compact`] with default `options` and no custom - /// `remap_options` is supported; `All`, `Prune`, and `Index` return + /// [`OptimizeAction::Compact`] supports per-job `target_rows_per_fragment`, + /// `max_source_rows`, `io_buffer_size`, and `batch_size`, with no custom + /// `remap_options`. Other non-default options, `All`, `Prune`, and `Index` return /// [`crate::Error::NotSupported`]. See [`OptimizeAction::Compact`] for /// what a remote call submits and what it does and does not wait for. pub async fn optimize(&self, action: OptimizeAction) -> Result { self.inner.optimize(action).await } + /// Compact data files with optional tuning fields. On remote tables, + /// omitted fields inherit table tuning, then deployment/built-in defaults. + /// Returns after job submission; remote statistics are placeholders. + /// + /// ``` + /// use lancedb::{Table, table::optimize::CompactionOverrides}; + /// # async fn compact(table: &Table) -> lancedb::Result<()> { + /// table.compact(CompactionOverrides { + /// io_buffer_size: Some(64 * 1024 * 1024), + /// ..Default::default() + /// }).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn compact(&self, options: optimize::CompactionOverrides) -> Result { + self.inner.compact(options).await + } + + /// Language-binding entry point retaining optional compaction fields. + #[doc(hidden)] + pub async fn optimize_full_with_overrides( + &self, + options: optimize::CompactionOverrides, + older_than: Option, + before_timestamp: Option>, + delete_unverified: Option, + ) -> Result { + if self.as_native().is_some() { + return self + .optimize_full( + options.into_options(), + older_than, + before_timestamp, + delete_unverified, + ) + .await; + } + if older_than.is_some() || before_timestamp.is_some() || delete_unverified == Some(true) { + return Err(Error::NotSupported { message: "pruning is not supported in LanceDB Enterprise; omit pruning options to run compaction only".into() }); + } + let stats = self.compact(options).await?; + Ok(OptimizeStats { + compaction: stats.compaction, + prune: Some(RemovalStats::default()), + }) + } + /// Prune versions committed before an absolute timestamp. /// /// This is an internal entry point for language bindings whose public API @@ -1966,10 +2023,10 @@ impl Table { /// /// This is an internal entry point for language bindings. On a remote /// table (LanceDB Enterprise) only [`OptimizeAction::Compact`] with its - /// defaults is supported. A caller asking for anything pruning-related + /// supported per-job options is supported. A caller asking for anything pruning-related /// (`older_than`, `before_timestamp`, or `delete_unverified: Some(true)`) - /// gets `NotSupported` before anything is submitted, the same way a - /// non-default `CompactionOptions` is already rejected -- rather than a + /// gets `NotSupported` before anything is submitted, the same way + /// unsupported `CompactionOptions` are rejected -- rather than a /// success that silently reports zero bytes pruned when nothing was /// pruned at all. A plain call with none of those set only compacts: /// `Prune` and `Index` are skipped here rather than attempted and diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index a5346afef..ab34e05c6 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -184,6 +184,53 @@ async fn validate_sq_index_remapping( Ok(plan) } +/// Optional compaction tuning. Remote tables inherit omitted values from table +/// policy, then deployment/built-in defaults. Explicit values, including a zero +/// I/O budget, take precedence. Local tables use Lance defaults for omissions. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CompactionOverrides { + pub target_rows_per_fragment: Option, + pub max_source_rows: Option, + /// Read-ahead budget in bytes; zero disables byte-based I/O backpressure. + pub io_buffer_size: Option, + pub batch_size: Option, +} + +impl CompactionOverrides { + pub(crate) fn into_options(self) -> CompactionOptions { + let mut options = CompactionOptions::default(); + if let Some(target) = self.target_rows_per_fragment { + options.target_rows_per_fragment = target; + } + options.max_source_rows = self.max_source_rows; + options.io_buffer_size = self.io_buffer_size; + options.batch_size = self.batch_size; + options + } +} + +impl TryFrom for CompactionOverrides { + type Error = Error; + + fn try_from(options: CompactionOptions) -> Result { + let mut remaining = options.clone(); + let defaults = CompactionOptions::default(); + remaining.target_rows_per_fragment = defaults.target_rows_per_fragment; + remaining.max_source_rows = defaults.max_source_rows; + remaining.io_buffer_size = defaults.io_buffer_size; + remaining.batch_size = defaults.batch_size; + if remaining != defaults { + return Err(Error::NotSupported { message: "remote CompactionOptions support only target_rows_per_fragment, max_source_rows, io_buffer_size, and batch_size; other options must retain their defaults".into() }); + } + Ok(Self { + target_rows_per_fragment: Some(options.target_rows_per_fragment), + max_source_rows: options.max_source_rows, + io_buffer_size: options.io_buffer_size, + batch_size: options.batch_size, + }) + } +} + /// Optimize the dataset. /// /// Similar to `VACUUM` in PostgreSQL, it offers different options to @@ -209,9 +256,24 @@ pub enum OptimizeAction { /// /// # LanceDB Enterprise (remote tables) /// - /// A remote table only supports `Compact` with default `options` and no - /// custom `remap_options`; both are rejected with - /// [`crate::Error::NotSupported`] otherwise. It submits a durable + /// A remote table supports per-job `target_rows_per_fragment`, + /// `max_source_rows`, `io_buffer_size`, and `batch_size`. Other non-default + /// options and custom `remap_options` return [`crate::Error::NotSupported`] + /// before submission. The server must support these SQL options; errors + /// from older servers are returned without dropping the settings. + /// The source-row budget admits whole tasks and may perform no work when + /// the first task exceeds it. Zero I/O buffer size disables byte-based I/O + /// backpressure. Use a positive size to limit I/O read-ahead; this is not a + /// total-memory limit. Row targets, source-row budgets, and batch sizes must + /// be positive. + /// The legacy Lance options type cannot distinguish an omitted fragment target + /// from its default value; that default is treated as unspecified remotely. + /// Use [`crate::Table::compact`] with [`CompactionOverrides`] to explicitly + /// override a table target with the Lance default value. + /// Omitted options inherit table tuning, then deployment/built-in defaults; options + /// affect only this job, without changing ongoing table policy. + /// + /// It submits a durable /// compaction job to the server over SQL and waits for that submission to /// be confirmed, not for compaction itself to finish: the job then runs /// asynchronously on the server, so this call can return well before the @@ -219,6 +281,23 @@ pub enum OptimizeAction { /// [`OptimizeStats::compaction`] is a zeroed [`CompactionMetrics`] /// placeholder rather than the real counts a local table reports. /// + /// ``` + /// use lancedb::{Table, table::{CompactionOptions, OptimizeAction}}; + /// # async fn compact(table: &Table) -> lancedb::Result<()> { + /// table.optimize(OptimizeAction::Compact { + /// options: CompactionOptions { + /// target_rows_per_fragment: 100_000, + /// max_source_rows: Some(1_000_000), + /// io_buffer_size: Some(64 * 1024 * 1024), + /// batch_size: Some(1024), + /// ..Default::default() + /// }, + /// remap_options: None, + /// }).await?; + /// # Ok(()) + /// # } + /// ``` + /// /// A branch-scoped table handle compacts that branch. The branch is not /// validated to exist before the job is submitted, so a nonexistent /// branch fails the compaction job asynchronously rather than failing From 1eeb2007051cde7661f23854600f0dff37bf242c Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Mon, 9 Nov 2026 14:51:07 -0800 Subject: [PATCH 047/203] chore: update lance dependency to v15.0.0-beta.15 (#4926) Update Rust and Java Lance dependencies to [v15.0.0-beta.15](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.15), pin Python tests to published pylance 15.0.0b15, and refresh both lockfiles; no compatibility fixes were needed. Validation passed: workspace Clippy with all features/tests and warnings denied, cargo fmt, uv lock --check, and all 35 CI-script tests. The [upstream wheel workflow](https://github.com/lance-format/lance/actions/runs/42669437482) canceled Windows ARM64 and manylinux_2_28 x86_64 builds after an hour, so the lockfile contains the five published variants (Linux x86_64 remains covered by manylinux2014); Windows ARM64 is unavailable until upstream publishes its wheel and the lockfile is refreshed. --- Cargo.lock | 96 +++++++++++++++++++++---------------------- Cargo.toml | 30 +++++++------- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 16 ++++---- 5 files changed, 72 insertions(+), 74 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1ac7a4f6a..893fb21d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arc-swap", "arrow", @@ -5671,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.14#3bb1550f4f27adf90948ff36c2318768e675b599" +version = "15.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 90bfbb608..ab8e86f97 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.14", default-features = false, "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.14", default-features = false, "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.14", default-features = false, "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.14", "tag" = "v15.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 161e13c2c..88b66b3ad 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.8 + 15.0.0-beta.15 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 2e822deb9..153d138b4 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b14", + "pylance==15.0.0b15", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 61fec64ac..2cd4ac496 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b14" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b15" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b14" +version = "15.0.0b15" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,13 +4312,11 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_b88Zw/pylance-15.0.0b14-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:48bcdfda408d1f8eaabbd066236bdb0ae9539acb3186b246c5c1ad4e8e5dcf23" }, - { url = "https://pypi.fury.io/lance-format/-/ver_J0evn/pylance-15.0.0b14-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:958d7cf0c8f31e09be94d6785c45158121073e79eb3bdb6f7ed25f7dde22c9a2" }, - { url = "https://pypi.fury.io/lance-format/-/ver_18gbAN/pylance-15.0.0b14-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80814eff77dd0b83ee3c18280895a8d2cadf6d49818d7047a4540b773618738d" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1gqym0/pylance-15.0.0b14-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:bb59f5d5b8740eb5df57c1777bce61f3e2a9f7d47ab31068e2ccf43549627103" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1FHTtC/pylance-15.0.0b14-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:357357f9f419efe9f90ba63d4dc371fc93e191aa692cf6f88d327607680f77da" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1LzfL9/pylance-15.0.0b14-cp310-abi3-win_amd64.whl", hash = "sha256:916fcc39051bdd2e8ca50950ee4d8afb941c130fd278ac7cea252c2059beab58" }, - { url = "https://pypi.fury.io/lance-format/-/ver_nDQ2x/pylance-15.0.0b14-cp310-abi3-win_arm64.whl", hash = "sha256:e1449bbb7a207cb2890d9afeef41f816d2ab4a459ed73cc46c919d463e46fe10" }, + { url = "https://pypi.fury.io/lance-format/-/ver_29HO58/pylance-15.0.0b15-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:46c870c3d650f911eccb7406ec77f72fa448f80b2f827ff35dd86bbc0b9e08ca" }, + { url = "https://pypi.fury.io/lance-format/-/ver_OBkXR/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f418584cdee98d27aac538ebe5203051a0b78a98668aff22bc29aebe3dd3c9" }, + { url = "https://pypi.fury.io/lance-format/-/ver_TMbLm/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3656d52ba65d297b41f1973d1a3efbb888f761cf7c934ff15e0c1aecc560b2d5" }, + { url = "https://pypi.fury.io/lance-format/-/ver_mmYmR/pylance-15.0.0b15-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a50d06e3a86d68acf8edf5a83736890a648a16a1cb8c8ccde9ef5b6c82ebef76" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1aYiTc/pylance-15.0.0b15-cp310-abi3-win_amd64.whl", hash = "sha256:6451499f0612d0326d54168bedcc6df29c1e0700c4f92902f5f00a6ecdf17745" }, ] [[package]] From 794fa023cd9a74b28af1c0d5aa344c5fc7da60d2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Mon, 9 Nov 2026 15:02:13 -0800 Subject: [PATCH 048/203] feat: add materialized view refresh resource budgets (#4902) Expose aggregate CPU, memory, and GPU budgets plus GPU-class placement on materialized-view refreshes in Python and Rust. Forward options through SQL and reject invalid or unsupported Embedded requests instead of silently dropping constraints. ```python job = view.refresh_async( cpu_millis=8000, memory_bytes=16 * 1024**3, gpu_count=2, gpu_class="h100", ) job.wait() ``` ```sql REFRESH MATERIALIZED VIEW curated_training_set WITH (cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2, gpu_class = 'h100'); ``` The same options apply to blocking refreshes, async Python connections, and the Rust refresh builder. CPU/memory budgets require all three resource fields; GPU-only caps and class-only placement are also supported. These are execution-wide caps and require a supporting Enterprise server with an isolated execution backend. A cap does not increase refresh parallelism; current MV refreshes use at most one GPU. Updates API documentation and SQL reference, with Python sync/async and Rust remote-submission regression coverage. Formatting and Python lint pass; local builds and tests are intentionally skipped. The Linux CI build and example steps explicitly select the LanceDB package, matching the feature-test step. This avoids rebuilding and retaining a second dependency graph after a workspace-wide build, which exhausted runner disk space on both this branch and main. Related: [ENT-3386](https://linear.app/lancedb/issue/ENT-3386) --- .github/workflows/rust.yml | 11 +- .../refresh-materialized-view.mdx | 59 +++++++++ .../web/sql/dml/refresh-materialized-view.mdx | 36 ++++- python/python/lancedb/_lancedb.pyi | 18 ++- python/python/lancedb/materialized_view.py | 103 +++++++++++++-- .../python/tests/test_materialized_views.py | 37 +++++- python/src/table.rs | 38 +++++- rust/lancedb/src/materialized_view.rs | 124 +++++++++++++++++- rust/lancedb/src/remote/sql_test.rs | 26 +++- rust/lancedb/src/remote/table.rs | 13 +- rust/lancedb/src/table.rs | 19 +++ 11 files changed, 456 insertions(+), 28 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a628c6fa0..9d28ac5e4 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -240,18 +240,11 @@ jobs: sudo mkswap "$swapfile" sudo swapon "$swapfile" - name: Build - run: cargo build --profile ci --all-features --tests --locked --examples - - name: Reclaim completed workspace build artifacts - run: | - # Package-level tests resolve a different feature graph from the workspace - # build. Reclaim its lancedb outputs before linking the test graph. - df -h . - cargo clean --profile ci -p lancedb - df -h . + run: cargo build --profile ci -p lancedb --all-features --tests --locked --examples - name: Run feature tests run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests - name: Run examples - run: cargo run --profile ci --all-features --example simple --locked + run: cargo run --profile ci -p lancedb --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 diff --git a/docs/web/feature-engineering/refresh-materialized-view.mdx b/docs/web/feature-engineering/refresh-materialized-view.mdx index eca66d230..74fcce2fb 100644 --- a/docs/web/feature-engineering/refresh-materialized-view.mdx +++ b/docs/web/feature-engineering/refresh-materialized-view.mdx @@ -59,6 +59,65 @@ Use `view.table.count_rows()` for the view's row count at any time; on LanceDB Embedded it always matches `rows_written` from the most recent refresh. +{/* +Draft: publish this section after the Python/Rust resource-budget SDK support +is released. TypeScript parity is tracked separately in issue #4903. + +## Resource budgets {#resources} + +For training-data curation, bound the resources used to recompute a view: + + +```python Python icon="python" +job = view.refresh_async( + cpu_millis=8000, + memory_bytes=16 * 1024**3, + gpu_count=2, + gpu_class="h100", +) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::materialized_view::MaterializedView; + +async fn refresh(view: &MaterializedView) -> lancedb::Result<()> { + let job = view + .refresh() + .cpu_millis(8000) + .memory_bytes(16_u64 << 30) + .gpu_count(2) + .gpu_class("h100") + .execute_async() + .await?; + job.wait().await?; + Ok(()) +} +``` + + +The same options are available on `refresh`, asynchronous Python connections, +and the Rust refresh builder (`cpu_millis`, `memory_bytes`, `gpu_count`, and +`gpu_class`). CPU is in millicores (8000 means eight cores), memory is bytes, +and GPU count is an aggregate concurrent cap. CPU or memory requires all three +budget fields. Use zero GPUs for a CPU-only view, or specify a GPU cap alone. + +The cap covers the refresh execution and its Function processes together. +It does not allocate that budget separately to each Function. A GPU class +selects placement for this execution; discover configured classes with +`db.list_gpu_classes()`. A cap does not promise more parallelism: current MV +refreshes use at most one GPU. Omitted settings keep existing defaults. + +These controls require an Enterprise server with an isolated backend that can +enforce them; Embedded and unsupported execution backends reject them. Earlier +Enterprise servers reject the new SQL options. See the +[SQL resource options](/sql/dml/refresh-materialized-view#resources). + +TypeScript does not expose these options yet; SDK parity is tracked in +[issue #4903](https://github.com/lancedb/lancedb/issues/4903). + +*/} + ## Automatic refresh {#auto-refresh} A materialized view can refresh itself on a schedule instead of waiting diff --git a/docs/web/sql/dml/refresh-materialized-view.mdx b/docs/web/sql/dml/refresh-materialized-view.mdx index ecb4e84d1..e83337c7d 100644 --- a/docs/web/sql/dml/refresh-materialized-view.mdx +++ b/docs/web/sql/dml/refresh-materialized-view.mdx @@ -14,7 +14,8 @@ A LanceDB extension with no DataFusion equivalent. ```sql SQL icon="database" REFRESH MATERIALIZED VIEW - [WITH (full = )] + [WITH (full = , cpu_millis = , memory_bytes = , + gpu_count = , gpu_class = '')] ``` @@ -36,6 +37,39 @@ regardless of what a local SDK's `refresh()` method accepts -- do not assume the two option sets match. +## Resource budgets {#resources} + +Set budgets for one refresh execution: + +```sql +REFRESH MATERIALIZED VIEW curated_training_set WITH ( + cpu_millis = 8000, + memory_bytes = 17179869184, + gpu_count = 2, + gpu_class = 'h100' +); +``` + +`cpu_millis` is CPU capacity in millicores (1000 = one core), not CPU time. +`memory_bytes` caps memory in bytes. `gpu_count` caps concurrent GPUs for the +refresh. These are aggregate caps across its SQL execution and Function +processes; they are not multiplied by the number of Functions in the query. + +CPU or memory requires all three budget fields. CPU and memory must be positive; +`gpu_count = 0` is allowed for CPU-only views. A GPU budget alone is also accepted. +A cap does not reserve all of its GPUs or increase refresh parallelism. Current +MV refreshes use at most one GPU, shared by their GPU Function calls. + +`gpu_class` selects an operator-configured class for this execution, leaving the +Function registration and saved MV placement unchanged. Use `SHOW GPU CLASSES` +to discover configured classes. Omitted budgets and class preserve defaults. +Options can be combined with `full = true`. + +This requires an Enterprise server and an isolated execution backend that can +enforce resource budgets. Unsupported backends reject constrained refreshes. +Older servers reject the new options. Saved defaults and automatic refresh +configuration are unchanged. + ## Watching a refresh {#watching} A refresh submits work that outlives the call. Track it with diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a1a893f8b..2ac4dde58 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -654,10 +654,24 @@ class Table: limit: Optional[int] = None, ) -> FunctionErrors: ... async def refresh_materialized_view( - self, source_version: Optional[int] = None, *, full: bool = False + self, + source_version: Optional[int] = None, + *, + full: bool = False, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> RefreshMaterializedViewResult: ... async def refresh_materialized_view_async( - self, source_version: Optional[int] = None, *, full: bool = False + self, + source_version: Optional[int] = None, + *, + full: bool = False, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> Job: ... async def materialized_view_definition(self) -> str: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index a1c83dd6d..7b8c8c6a4 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union import json from dataclasses import dataclass +from .functions import _validate_gpu_class_name from .background_loop import LOOP from .job import AsyncJob, Job, _typed_job @@ -156,6 +157,34 @@ def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]: return normalized +def _refresh_execution_options(cpu_millis, memory_bytes, gpu_count, gpu_class): + values = { + "cpu_millis": cpu_millis, + "memory_bytes": memory_bytes, + "gpu_count": gpu_count, + } + for name, value in values.items(): + maximum = 2**32 - 1 if name == "gpu_count" else 2**64 - 1 + minimum = 0 if name == "gpu_count" else 1 + if value is not None and ( + type(value) is not int or not minimum <= value <= maximum + ): + raise ValueError( + f"{name} must be an integer between {minimum} and {maximum}" + ) + if (cpu_millis is not None or memory_bytes is not None) and any( + value is None for value in values.values() + ): + raise ValueError( + "cpu_millis, memory_bytes, and gpu_count must be specified together" + ) + if gpu_class is not None: + values["gpu_class"] = _validate_gpu_class_name(gpu_class) + if gpu_count == 0: + raise ValueError("gpu_class requires a positive GPU budget") + return {name: value for name, value in values.items() if value is not None} + + class AsyncMaterializedView: """A handle on a materialized view: its table plus its definition. @@ -185,7 +214,14 @@ class AsyncMaterializedView: return _definition_from_json(raw) async def refresh( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. @@ -194,16 +230,35 @@ class AsyncMaterializedView: and ``source_version`` selects a source version instead of the latest. LanceDB Enterprise SQL refreshes do not support source-version pinning. + ``cpu_millis`` (1000 = one core), ``memory_bytes``, and ``gpu_count`` + cap aggregate resources for this execution, including its Function + processes. CPU or memory requires all three budget fields; GPU count + may be zero for CPU-only views. ``gpu_class`` selects an operator-defined + GPU class for this execution only. Omitted options preserve defaults. + These options require an Enterprise backend that enforces isolation; + Embedded refreshes reject them. Other servers may reject the new options. + LanceDB Enterprise 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 + source_version=source_version, + full=full, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), ) async def refresh_async( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "AsyncJob[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. @@ -221,7 +276,11 @@ class AsyncMaterializedView: return _typed_job( await self._table._inner.refresh_materialized_view_async( - source_version=source_version, full=full + source_version=source_version, + full=full, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), ), RefreshMaterializedViewResult.from_json, ) @@ -253,14 +312,36 @@ class MaterializedView: return LOOP.run(self._async.definition()) def refresh( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "RefreshMaterializedViewResult": """Recompute the view from its source. See [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].""" - return LOOP.run(self._async.refresh(full=full, source_version=source_version)) + return LOOP.run( + self._async.refresh( + full=full, + source_version=source_version, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), + ) + ) def refresh_async( - self, *, full: bool = False, source_version: Optional[int] = None + self, + *, + full: bool = False, + source_version: Optional[int] = None, + cpu_millis: Optional[int] = None, + memory_bytes: Optional[int] = None, + gpu_count: Optional[int] = None, + gpu_class: Optional[str] = None, ) -> "Job[RefreshMaterializedViewResult]": """Submit a refresh and return its job without waiting. @@ -269,6 +350,12 @@ class MaterializedView: """ return Job( LOOP.run( - self._async.refresh_async(full=full, source_version=source_version) + self._async.refresh_async( + full=full, + source_version=source_version, + **_refresh_execution_options( + cpu_millis, memory_bytes, gpu_count, gpu_class + ), + ) ) ) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index ebb632300..bf964102b 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -63,7 +63,17 @@ def mock_remote_materialized_view_refresh(): @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): +@pytest.mark.parametrize( + "resources", + [ + {}, + {"gpu_count": 2, "gpu_class": "h100"}, + {"cpu_millis": 8000, "memory_bytes": 16 * 1024**3, "gpu_count": 0}, + ], +) +async def test_remote_refresh_reports_unknown_metrics( + sync, background, full, resources +): flight = pytest.importorskip("pyarrow.flight") class RefreshServer(flight.FlightServerBase): @@ -90,7 +100,7 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full): mock_remote_materialized_view_refresh() as (host, requests), RefreshServer() as server, ): - options = {"full": True} if full else {} + options = {"full": full, **resources} connect = lancedb.connect if sync else lancedb.connect_async db = connect( "db://dev", @@ -140,7 +150,28 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full): ) (refresh,) = refreshes assert b'REFRESH MATERIALIZED VIEW "view"' in refresh - assert (b"WITH (full = true)" in refresh) is full + assert (b"full = true" in refresh) is full + for key, value in resources.items(): + expected = ( + f"{key} = '{value}'" if key == "gpu_class" else f"{key} = {value}" + ) + assert expected.encode() in refresh + previous = len(server.commands) + for invalid in [ + {"cpu_millis": 0}, + {"memory_bytes": 1}, + {"gpu_count": -1}, + {"gpu_count": True}, + {"gpu_count": 2**32}, + {"gpu_class": "H200:8"}, + {"gpu_count": 0, "gpu_class": "h100"}, + ]: + with pytest.raises(ValueError): + if sync: + view.refresh(**invalid) + else: + await view.refresh(**invalid) + assert len(server.commands) == previous assert not any("count_rows" in path for path in requests) diff --git a/python/src/table.rs b/python/src/table.rs index db3a88f7f..92a6ef835 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2309,11 +2309,16 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false))] + #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] + #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view( self_: PyRef<'_, Self>, source_version: Option, full: bool, + cpu_millis: Option, + memory_bytes: Option, + gpu_count: Option, + gpu_class: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2321,6 +2326,18 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); + if let Some(value) = cpu_millis { + builder = builder.cpu_millis(value); + } + if let Some(value) = memory_bytes { + builder = builder.memory_bytes(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } if let Some(version) = source_version { builder = builder.source_version(version); } @@ -2329,11 +2346,16 @@ impl Table { }) } - #[pyo3(signature = (source_version=None, *, full=false))] + #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] + #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view_async( self_: PyRef<'_, Self>, source_version: Option, full: bool, + cpu_millis: Option, + memory_bytes: Option, + gpu_count: Option, + gpu_class: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2341,6 +2363,18 @@ impl Table { .await .infer_error()?; let mut builder = view.refresh().full(full); + if let Some(value) = cpu_millis { + builder = builder.cpu_millis(value); + } + if let Some(value) = memory_bytes { + builder = builder.memory_bytes(value); + } + if let Some(value) = gpu_count { + builder = builder.gpu_count(value); + } + if let Some(value) = gpu_class { + builder = builder.gpu_class(value); + } 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 536b1c72c..c263dc001 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1863,18 +1863,119 @@ impl MaterializedView { view: self.clone(), source_version: None, full: false, + options: Default::default(), } } } +/// Per-execution resource caps and GPU placement for Enterprise MV refreshes. +/// +/// CPU is in millicores (1000 = one core), memory is bytes, and GPUs are a +/// simultaneous cap across the refresh, not a per-Function allocation. CPU or +/// memory requires all three budget fields. Embedded refreshes reject options. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct RefreshMaterializedViewOptions { + pub cpu_millis: Option, + pub memory_bytes: Option, + pub gpu_count: Option, + pub gpu_class: Option, +} + +impl RefreshMaterializedViewOptions { + pub(crate) fn is_empty(&self) -> bool { + self.cpu_millis.is_none() + && self.memory_bytes.is_none() + && self.gpu_count.is_none() + && self.gpu_class.is_none() + } + + pub(crate) fn validate(&self) -> Result<()> { + let invalid = |message: &str| Error::InvalidInput { + message: message.into(), + }; + if self.cpu_millis == Some(0) || self.memory_bytes == Some(0) { + return Err(invalid( + "cpu_millis and memory_bytes must be positive integers", + )); + } + if (self.cpu_millis.is_some() || self.memory_bytes.is_some()) + && !(self.cpu_millis.is_some() + && self.memory_bytes.is_some() + && self.gpu_count.is_some()) + { + return Err(invalid( + "cpu_millis, memory_bytes, and gpu_count must be specified together", + )); + } + if let Some(class) = &self.gpu_class { + crate::function::validate_gpu_class_name(class)?; + if self.gpu_count == Some(0) { + return Err(invalid("gpu_class requires a positive GPU budget")); + } + } + Ok(()) + } + + pub(crate) fn sql_clause(&self, full: bool) -> Result { + self.validate()?; + let mut values = Vec::new(); + if full { + values.push("full = true".to_string()); + } + if let Some(cpu) = self.cpu_millis { + values.push(format!("cpu_millis = {cpu}")); + } + if let Some(memory) = self.memory_bytes { + values.push(format!("memory_bytes = {memory}")); + } + if let Some(gpu) = self.gpu_count { + values.push(format!("gpu_count = {gpu}")); + } + if let Some(class) = &self.gpu_class { + values.push(format!("gpu_class = '{class}'")); + } + Ok(if values.is_empty() { + String::new() + } else { + format!(" WITH ({})", values.join(", ")) + }) + } +} + /// Builds a refresh. Created by [`MaterializedView::refresh`]. pub struct RefreshMaterializedViewBuilder { view: MaterializedView, source_version: Option, full: bool, + options: RefreshMaterializedViewOptions, } impl RefreshMaterializedViewBuilder { + /// Cap total CPU capacity in millicores; requires memory and GPU budgets. + pub fn cpu_millis(mut self, cpu_millis: u64) -> Self { + self.options.cpu_millis = Some(cpu_millis); + self + } + + /// Cap total memory in bytes; requires CPU and GPU budgets. + pub fn memory_bytes(mut self, memory_bytes: u64) -> Self { + self.options.memory_bytes = Some(memory_bytes); + self + } + + /// Cap concurrent GPUs for this refresh. Zero is CPU-only. + pub fn gpu_count(mut self, gpu_count: u32) -> Self { + self.options.gpu_count = Some(gpu_count); + self + } + + /// Select an operator-configured GPU class for this execution only. + pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { + self.options.gpu_class = Some(gpu_class.into()); + self + } + /// Force a complete rebuild instead of letting the server choose /// the refresh mode. Defaults to `false`. LanceDB Embedded views always rebuild. /// @@ -1900,14 +2001,22 @@ impl RefreshMaterializedViewBuilder { /// Submit the refresh and return a job that settles with its result. pub async fn execute_async(self) -> Result> { + self.options.validate()?; if self.view.table.as_native().is_none() { return self .view .table .base_table() - .refresh_materialized_view_async(self.source_version, self.full) + .refresh_materialized_view_async_with_options( + self.source_version, + self.full, + self.options, + ) .await; } + if !self.options.is_empty() { + return Err(Error::NotSupported { message: "resource budgets and GPU placement require an Enterprise materialized-view refresh".into() }); + } crate::require_experimental_functions()?; Ok(Job::spawned(tokio::spawn(async move { refresh::execute_refresh(&self.view.table, self.source_version).await @@ -1916,6 +2025,10 @@ impl RefreshMaterializedViewBuilder { /// Refresh the view, waiting for the job to finish. pub async fn execute(self) -> Result { + self.options.validate()?; + if self.view.table.as_native().is_some() && !self.options.is_empty() { + return Err(Error::NotSupported { message: "resource budgets and GPU placement require an Enterprise materialized-view refresh".into() }); + } if self.view.table.as_native().is_some() { return refresh::execute_refresh(&self.view.table, self.source_version).await; } @@ -2151,6 +2264,15 @@ mod tests { .await .unwrap(); + assert!(matches!( + view.refresh().gpu_count(0).execute().await, + Err(Error::NotSupported { .. }) + )); + assert!(matches!( + view.refresh().gpu_class("h100").execute_async().await, + Err(Error::NotSupported { .. }) + )); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); assert!( view.table() diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index aa41f2c86..65d08c984 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1329,7 +1329,30 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { .await .unwrap(); - for result in [first, second] { + let third = view + .refresh() + .full(true) + .cpu_millis(8000) + .memory_bytes(16 << 30) + .gpu_count(2) + .gpu_class("h100") + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + for invalid in [ + view.refresh().cpu_millis(1), + view.refresh().gpu_class("H200:8"), + view.refresh().gpu_count(0).gpu_class("h100"), + ] { + assert!(matches!( + invalid.execute_async().await, + Err(Error::InvalidInput { .. }) + )); + } + for result in [first, second, third] { assert_eq!(result.mode, None); assert_eq!(result.rows_written, None); assert_eq!(result.source_version, None); @@ -1350,6 +1373,7 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { "DESCRIBE MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", + "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true, cpu_millis = 8000, memory_bytes = 17179869184, gpu_count = 2, gpu_class = 'h100')", ] ); assert!( diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3801405eb..a19f4d0d9 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2379,6 +2379,17 @@ impl BaseTable for RemoteTable { source_version: Option, full: bool, ) -> Result> { + self.refresh_materialized_view_async_with_options(source_version, full, Default::default()) + .await + } + + async fn refresh_materialized_view_async_with_options( + &self, + source_version: Option, + full: bool, + options: crate::materialized_view::RefreshMaterializedViewOptions, + ) -> Result> { + let with_clause = options.sql_clause(full)?; self.check_mutable().await?; if source_version.is_some() { return Err(Error::NotSupported { @@ -2392,7 +2403,7 @@ impl BaseTable for RemoteTable { let statement = format!( "REFRESH MATERIALIZED VIEW {}{}", quote_sql_identifier(&self.name), - if full { " WITH (full = true)" } else { "" }, + with_clause, ); let namespace = self.namespace.clone(); let client = self.client.clone(); diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4691d33f1..cc7b820f9 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -596,6 +596,25 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("remote materialized-view refresh is not supported on this table type"), }) } + /// Submit an Enterprise refresh with aggregate resource caps and GPU placement. + #[doc(hidden)] + async fn refresh_materialized_view_async_with_options( + &self, + source_version: Option, + full: bool, + options: crate::materialized_view::RefreshMaterializedViewOptions, + ) -> Result> { + options.validate()?; + if !options.is_empty() { + return Err(Error::NotSupported { + message: + "this table cannot enforce materialized-view resource budgets or GPU placement" + .into(), + }); + } + self.refresh_materialized_view_async(source_version, full) + .await + } /// Create a read-only handle pinned to the table's current active revision. /// /// The returned handle is independent from later refreshes or checkouts on From d8957238bf7c428a9fdda3350e3b02a627e487bc Mon Sep 17 00:00:00 2001 From: Sarwar Bhuiyan Date: Mon, 9 Nov 2026 20:40:59 -0500 Subject: [PATCH 049/203] fix(remote): stream query responses instead of buffering them (#4929) --- .../js/interfaces/QueryExecutionOptions.md | 3 + docs/src/python/python.md | 9 + nodejs/lancedb/query.ts | 3 + python/python/lancedb/query.py | 21 + python/python/lancedb/remote/errors.py | 58 ++ python/python/tests/test_errors.py | 12 + python/python/tests/test_remote_db.py | 95 +++ python/src/error.rs | 22 + rust/lancedb/src/error.rs | 167 ++++ rust/lancedb/src/query.rs | 9 + rust/lancedb/src/remote/table.rs | 114 ++- rust/lancedb/src/remote/table/ipc_stream.rs | 729 ++++++++++++++++++ rust/lancedb/src/utils/mod.rs | 16 + 13 files changed, 1216 insertions(+), 42 deletions(-) create mode 100644 rust/lancedb/src/remote/table/ipc_stream.rs diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index f18ada7aa..fb9bada29 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -64,3 +64,6 @@ optional timeoutMs: number; ``` Timeout for query execution in milliseconds + +The timeout also covers reading the results, so consuming them slowly can +exceed it. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 7e5140928..7f28d8804 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -859,6 +859,13 @@ older server omits structured resource details. A structured `already_exists` response keeps its more specific `AlreadyExistsError` type. Both are subclasses of `HttpError`. +A remote query whose streamed response stops partway raises +`ResponseInterruptedError`, also a subclass of `HttpError`. It carries the number +of batches and rows already returned and, when the server reports it, the table +version the response reflected, so the query can be run again against that +version. It is never retried automatically, because the batches already returned +would be returned again. + SQL response failures raise `SqlError`, retaining the numeric `grpc_code` and `request_id`. Servers that report a recognized `x-lancedb-error-code` select a specific input-error subclass. HTTP failures use the corresponding `HttpError` @@ -926,6 +933,8 @@ generic HTTP/SQL exceptions with their transport status and current request ID. ::: lancedb.remote.errors.ConflictError +::: lancedb.remote.errors.ResponseInterruptedError + ::: lancedb.exceptions.MissingValueError ::: lancedb.exceptions.MissingColumnError diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index cbd927925..bb845276f 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -237,6 +237,9 @@ export interface QueryExecutionOptions { /** * Timeout for query execution in milliseconds + * + * The timeout also covers reading the results, so consuming them slowly can + * exceed it. */ timeoutMs?: number; diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 08ea3b9bc..4a3fea2e2 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1335,6 +1335,9 @@ class LanceQueryBuilder(ABC): and also the "_distance" column which is the distance between the query vector and the returned vectors. + This collects all results in memory. To process a large result a batch + at a time, use [to_batches][lancedb.query.LanceQueryBuilder.to_batches]. + Parameters ---------- timeout: Optional[timedelta] @@ -1366,6 +1369,11 @@ class LanceQueryBuilder(ABC): ``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide automatic row ids. + A remote table decodes batches as they arrive when the server streams + query results. If the response stops partway, reading raises + [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError] + after the batches already returned, which are valid but incomplete. + Parameters ---------- batch_size: int @@ -1373,6 +1381,8 @@ class LanceQueryBuilder(ABC): timeout: Optional[timedelta] The maximum time to wait for the query to complete. If None, wait indefinitely. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. 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 @@ -2303,6 +2313,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): timeout: timedelta, default None The maximum time to wait for the query to complete. If None, wait indefinitely. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" Controls blob conversion as described in :meth:`LanceQueryBuilder.to_batches`. @@ -3570,6 +3582,11 @@ class AsyncQueryBase(object): """ Execute the query and return the results as an Apache Arrow RecordBatchReader. + A remote table decodes batches as they arrive when the server streams + query results. If the response stops partway, reading raises + [ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError] + after the batches already returned, which are valid but incomplete. + Parameters ---------- @@ -3582,6 +3599,8 @@ 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. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. 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 @@ -5114,6 +5133,8 @@ 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. + The timeout also covers reading the batches, so consuming them + slowly can exceed it. blob_mode: str, default "lazy" Controls blob conversion as described in :meth:`AsyncQueryBase.to_batches`. diff --git a/python/python/lancedb/remote/errors.py b/python/python/lancedb/remote/errors.py index 4dc835e53..ee92ddf53 100644 --- a/python/python/lancedb/remote/errors.py +++ b/python/python/lancedb/remote/errors.py @@ -286,6 +286,64 @@ class ConflictError(HttpError): """ +class ResponseInterruptedError(HttpError): + """A streamed query response stopped before the server finished sending it. + + The batches already returned are valid, but the result is incomplete. The + query is not retried automatically, because a new attempt would return those + rows a second time. To read the same data in a new attempt, check out + ``table_version`` first. + + Attributes + ---------- + batches: int + The number of batches returned before the interruption. + rows: int + The number of rows in those batches. + table_version: int or None + The table version the response reflected, if the server reported it. + + Examples + -------- + >>> error = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7) + >>> isinstance(error, HttpError) + True + >>> (error.rows, error.table_version) + (2048, 7) + """ + + # HttpError.__new__ takes HttpError's arguments, to choose a subclass. + def __new__(cls, *args, **kwargs): + return RuntimeError.__new__(cls) + + def __init__( + self, + message: str, + request_id: str, + batches: int, + rows: int, + table_version: Optional[int] = None, + is_transport_error: bool = False, + ): + super().__init__(message, request_id, is_transport_error=is_transport_error) + self.batches = batches + self.rows = rows + self.table_version = table_version + + def __reduce__(self) -> tuple[type, tuple]: + return ( + self.__class__, + ( + str(self), + self.request_id, + self.batches, + self.rows, + self.table_version, + self.is_transport_error, + ), + ) + + class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError): """A remote table was not found. diff --git a/python/python/tests/test_errors.py b/python/python/tests/test_errors.py index d5e92731f..12a193074 100644 --- a/python/python/tests/test_errors.py +++ b/python/python/tests/test_errors.py @@ -15,6 +15,7 @@ from lancedb.remote.errors import ( HttpError, LanceDBClientError, NamespaceNotFoundError, + ResponseInterruptedError, RetryError, SecretNotFoundError, TableNotFoundError, @@ -73,6 +74,17 @@ def test_pickle_http_transport_error(): assert restored.request_id == "req-789" +def test_pickle_response_interrupted_error(): + err = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7, True) + restored = pickle.loads(pickle.dumps(err)) + assert type(restored) is ResponseInterruptedError + assert str(restored) == "interrupted" + assert restored.request_id == "req-1" + assert (restored.batches, restored.rows, restored.table_version) == (2, 2048, 7) + assert restored.is_transport_error is True + assert restored.status_code is None + + @pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"]) def test_http_conflict_error_preserves_reason_and_metadata(error_code): reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 25d9db22a..685bc809d 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -48,6 +48,7 @@ from lancedb.remote.errors import ( ConflictError, HttpError, NamespaceNotFoundError, + ResponseInterruptedError, RetryError, ) import pytest @@ -3398,6 +3399,100 @@ def test_query_sync_minimal(): assert data == expected +def _arrow_stream(batches): + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batches[0].schema) as writer: + for batch in batches: + writer.write_batch(batch) + return sink.getvalue().to_pybytes() + + +@contextlib.contextmanager +def streamed_query_table(write_body): + """Yield a remote table and the headers of each query request it sends. + + Queries get a 200 response with stream framing, whose body ``write_body`` + writes after the other headers. + """ + queries = [] + + def handler(request): + if request.path == "/v1/table/test/describe/": + id_field = {"name": "id", "type": {"type": "int32"}, "nullable": True} + schema = {"fields": [id_field]} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps({"version": 7, "schema": schema}).encode()) + elif request.path == "/v1/table/test/query/": + queries.append(request.headers) + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", "7") + write_body(request) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + yield db.open_table("test"), queries + + +def test_query_sync_to_batches_yields_before_the_body_is_complete(): + batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)] + body = _arrow_stream(batches) + # The schema and first batch, without the 8-byte end-of-stream marker. + head = _arrow_stream(batches[:1])[:-8] + first_batch_read = threading.Event() + waited_for_client = [] + + def write_body(request): + request.end_headers() + request.wfile.write(head) + waited_for_client.append(first_batch_read.wait(10)) + request.wfile.write(body[len(head) :]) + + with streamed_query_table(write_body) as (table, queries): + reader = table.search().to_batches() + assert reader.read_next_batch()["id"].to_pylist() == [0] + first_batch_read.set() + assert reader.read_all()["id"].to_pylist() == [1, 2] + + # The wait times out if the client needs the whole body for the first batch. + assert waited_for_client == [True] + assert queries[0]["Accept"] == ( + "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9" + ) + + +@pytest.mark.parametrize("abort", [False, True], ids=["clean_end", "abort"]) +def test_query_sync_interrupted_response_raises(abort): + batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)] + head = _arrow_stream(batches[:1])[:-8] + + def write_body(request): + if abort: + # Closing before the promised length is a transport error. Otherwise + # the body ends cleanly, but without the end-of-stream marker. + request.send_header("Content-Length", str(len(head) + 100)) + request.end_headers() + request.wfile.write(head) + + with streamed_query_table(write_body) as (table, queries): + reader = table.search().to_batches() + assert reader.read_next_batch()["id"].to_pylist() == [0] + with pytest.raises(ResponseInterruptedError) as exc_info: + reader.read_next_batch() + + error = exc_info.value + assert isinstance(error, HttpError) + assert (error.batches, error.rows, error.table_version) == (1, 1, 7) + assert error.request_id == queries[0]["x-request-id"] + assert error.is_transport_error is abort + assert len(queries) == 1 + + @pytest.mark.parametrize("query_type", ["auto", "vector", "hybrid"]) @pytest.mark.parametrize("vector_column_name", [None, "embedding"]) def test_query_sync_text_embedding(query_type, vector_column_name): diff --git a/python/src/error.rs b/python/src/error.rs index c4f20e884..1ac9f7ac3 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -168,6 +168,28 @@ impl PythonErrorExt for std::result::Result { err.setattr(intern!(py, "__cause__"), cause_err)?; Err(PyErr::from_value(err)) }), + LanceError::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } => Python::attach(|py| { + let error = py + .import(intern!(py, "lancedb.remote.errors"))? + .getattr(intern!(py, "ResponseInterruptedError"))? + .call1(( + err.to_string(), + request_id, + *batches, + *rows, + *table_version, + is_transport_error(&**source), + ))?; + let cause = http_from_rust_error(py, &**source, request_id, None)?; + error.setattr(intern!(py, "__cause__"), cause)?; + Err(PyErr::from_value(error)) + }), LanceError::Sql { message, request_id, diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index cc5bd1f4e..7499641fc 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -205,6 +205,48 @@ fn http_timeout_hint(source: &(dyn std::error::Error + 'static)) -> &'static str } } +/// The error that ended a streamed response. +/// +/// It is shared so that a copy of [`Error::ResponseInterrupted`] keeps it: +/// DataFusion hands one error to every partition that reads the failed input. +/// It dereferences to the underlying error, which is also the next error in the +/// source chain. +#[cfg(feature = "remote")] +#[derive(Debug, Clone)] +pub struct InterruptionSource(Arc); + +#[cfg(feature = "remote")] +impl From for InterruptionSource { + fn from(source: BoxError) -> Self { + Self(source.into()) + } +} + +#[cfg(feature = "remote")] +impl std::ops::Deref for InterruptionSource { + type Target = dyn std::error::Error + Send + Sync; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} + +#[cfg(feature = "remote")] +impl Display for InterruptionSource { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +// Not `Error`: an `Arc` in the source chain hides the error it holds from +// `downcast_ref`, and so would a wrapper that implements `Error`. +#[cfg(feature = "remote")] +impl snafu::AsErrorSource for InterruptionSource { + fn as_error_source(&self) -> &(dyn std::error::Error + 'static) { + self.0.as_ref() + } +} + /// 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`]. @@ -362,6 +404,27 @@ pub enum Error { source: Box, status_code: Option, }, + /// A streamed response stopped before the server signalled that it was complete. + /// + /// The batches already returned are valid, but the result is incomplete. The + /// request is not retried, because re-issuing it would return those batches + /// again. `table_version` is the table version the response reflected, when + /// the server reported one, so a caller can re-issue the request against it. + #[cfg(feature = "remote")] + #[snafu(display( + "Response for request_id={request_id} interrupted after {batches} batches \ + ({rows} rows): {source}{}", + http_timeout_hint(&**source) + ))] + ResponseInterrupted { + request_id: String, + /// Batches returned before the interruption. + batches: u64, + /// Rows in those batches. + rows: u64, + table_version: Option, + source: InterruptionSource, + }, #[snafu(display("Arrow error: {source}"))] Arrow { source: ArrowError }, #[snafu(display("LanceDBError: not supported: {message}"))] @@ -393,6 +456,20 @@ impl From for Error { match source { DataFusionError::ArrowError(source, _) => (*source).into(), DataFusionError::External(source) => Self::from_box_error(source), + // DataFusion adds context to an error, and shares one error between + // the partitions that read a failed input. An error of ours beneath + // either keeps its type; other errors keep the wrapper's message. + DataFusionError::Context(_, inner) if find_error(inner.as_ref()).is_some() => { + (*inner).into() + } + DataFusionError::Shared(shared) => match Arc::try_unwrap(shared) { + Ok(inner) => inner.into(), + Err(shared) => find_error(shared.as_ref()) + .and_then(Self::clone_shared) + .unwrap_or_else(|| Self::External { + source: Box::new(DataFusionError::Shared(shared)), + }), + }, other => Self::External { source: Box::new(other), }, @@ -400,6 +477,12 @@ impl From for Error { } } +/// The first error of ours in an error's source chain. +fn find_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Error> { + std::iter::successors(Some(error), |error| error.source()) + .find_map(|error| error.downcast_ref::()) +} + impl From for Error { fn from(source: lance::Error) -> Self { if has_unsupported_local_filesystem_source(&source) { @@ -509,6 +592,29 @@ impl Error { } } + /// A copy of an error that other partitions of a DataFusion plan still hold. + /// Only an interrupted response can be copied, because it shares its source. + fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + if let Self::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = self + { + return Some(Self::ResponseInterrupted { + request_id: request_id.clone(), + batches: *batches, + rows: *rows, + table_version: *table_version, + source: source.clone(), + }); + } + None + } + fn from_box_error(mut source: Box) -> Self { source = match source.downcast::() { Ok(e) => match *e { @@ -619,6 +725,67 @@ mod tests { assert!(matches!(Error::from(source), Error::InvalidInput { .. })); } + /// DataFusion shares an error between the partitions that read a failed + /// input, and may add context to it. Whether or not another partition still + /// holds it, an interrupted response keeps its fields and its source. + #[cfg(feature = "remote")] + #[rstest::rstest] + fn shared_interruption_keeps_its_type_and_source( + #[values(false, true)] still_held: bool, + #[values(false, true)] with_context: bool, + ) { + let reset = BoxError::from(std::io::Error::from(std::io::ErrorKind::ConnectionReset)); + let interrupted = Error::ResponseInterrupted { + request_id: "req-1".into(), + batches: 2, + rows: 2048, + table_version: Some(7), + source: reset.into(), + }; + let shared = Arc::new(DataFusionError::External(Box::new(interrupted))); + let held = still_held.then(|| shared.clone()); + let mut error = DataFusionError::Shared(shared); + if with_context { + error = error.context("merging query results"); + } + + let error = Error::from(error); + + assert!( + matches!( + &error, + Error::ResponseInterrupted { + request_id, + batches: 2, + rows: 2048, + table_version: Some(7), + .. + } if request_id == "req-1" + ), + "{error:?}" + ); + let source = std::error::Error::source(&error).unwrap(); + assert_eq!( + source.downcast_ref::().map(|e| e.kind()), + Some(std::io::ErrorKind::ConnectionReset) + ); + drop(held); + } + + #[test] + fn other_shared_errors_keep_their_message() { + let shared = Arc::new(DataFusionError::Execution("boom".into())); + let _held = shared.clone(); + + let error = Error::from(DataFusionError::Shared(shared).context("merging")); + + assert!(matches!(error, Error::External { .. }), "{error:?}"); + assert_eq!( + error.to_string(), + "merging\ncaused by\nExecution error: boom" + ); + } + #[cfg(feature = "remote")] #[test] fn non_timeout_http_error_message_is_unchanged() { diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index ad2dbdcbf..f96e84e96 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -661,6 +661,10 @@ pub struct QueryExecutionOptions { /// By default, this is 1024 pub max_batch_length: u32, /// Max duration to wait for the query to execute before timing out. + /// + /// The timeout also covers reading the results, so a caller that consumes + /// the stream slowly can exceed it. For a remote table it counts from when + /// the query is sent, and the server is given the same timeout. pub timeout: Option, /// How distributed worker metrics should be displayed by /// [`ExecutableQuery::analyze_plan`]. @@ -747,6 +751,11 @@ pub trait ExecutableQuery { /// stream is consumed slowly (this constrains the maximum memory used by a /// single query. /// + /// A remote table decodes batches as they arrive when the server streams + /// query results. If the response stops partway, the stream ends with + /// `Error::ResponseInterrupted`. The batches already returned are valid but + /// incomplete, and the query is not retried. + /// /// For simpler access or row-based access we recommend creating extension traits /// to convert Arrow data into your internal data model. fn execute_with_options( diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index a19f4d0d9..6956905c4 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3,6 +3,7 @@ pub mod blobs; pub mod insert; +mod ipc_stream; mod optimize; use self::insert::{RemoteWriteExec, WriteOp}; @@ -61,15 +62,15 @@ use crate::{ }, }; use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader}; -use arrow_ipc::reader::{FileReader, StreamReader}; -use arrow_schema::{ArrowError, DataType, SchemaRef}; +use arrow_ipc::reader::FileReader; +use arrow_schema::{DataType, SchemaRef}; use async_trait::async_trait; use chrono::{DateTime, Utc}; use datafusion_common::DataFusionError; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream}; use futures::{StreamExt, TryStreamExt}; -use http::header::CONTENT_TYPE; +use http::header::{ACCEPT, CONTENT_TYPE}; use http::{HeaderName, StatusCode}; use lance::arrow::json::{JsonDataType, JsonSchema}; use lance::dataset::refs::TagContents; @@ -91,6 +92,10 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp"); const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version"); const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); +/// Asks for stream framing, which is decoded as it arrives. Servers that do not +/// stream query results ignore this and answer with file framing. +const QUERY_ACCEPT: &str = + "application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9"; const METRIC_TYPE_KEY: &str = "metric_type"; const INDEX_TYPE_KEY: &str = "index_type"; const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(30); @@ -1155,25 +1160,30 @@ impl RemoteTable { .map(str::to_owned); let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?; - // Buffer the whole body. File framing keeps its footer at the end, so /query - // cannot decode incrementally. Stream framing could, via - // arrow_ipc::reader::StreamDecoder, but fetch_blobs concatenates every batch - // before returning, so no caller would see data sooner. - let body = response.bytes().await.err_to_http(request_id.into())?; - type IpcBatchIterator = - Box> + Send>; - let (schema, batches): (SchemaRef, IpcBatchIterator) = match framing { + match framing { ArrowIpcFraming::Stream => { - let reader = StreamReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + let table_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse().ok()); + ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.to_string(), + table_version, + ) + .await } ArrowIpcFraming::File => { + // File framing keeps its footer at the end, so the whole body is + // needed before anything can be decoded. + let body = response.bytes().await.err_to_http(request_id.into())?; let reader = FileReader::try_new(Cursor::new(body), None)?; - (reader.schema(), Box::new(reader)) + let schema = reader.schema(); + let stream = futures::stream::iter(reader).map_err(DataFusionError::from); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) } - }; - let stream = futures::stream::iter(batches).map_err(DataFusionError::from); - Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + } } fn apply_query_params( @@ -1544,8 +1554,15 @@ impl RemoteTable { ) -> Result>>> { let mut request = self .client - .post(&format!("/v1/table/{}/query/", self.identifier)); + .post(&format!("/v1/table/{}/query/", self.identifier)) + .header(ACCEPT, QUERY_ACCEPT); + // The timeout bounds the whole query, including reading the response, as + // the server's own deadline for this request does. A deadline too far + // away to represent is never reached. + let deadline = options + .timeout + .and_then(|timeout| Some((tokio::time::Instant::now().checked_add(timeout)?, timeout))); if let Some(timeout) = options.timeout { // Also send to server, so it can abort the query if it takes too long. // (If it doesn't fit into u64, it's not worth sending anyways.) @@ -1569,28 +1586,28 @@ impl RemoteTable { }); let streams = futures::future::try_join_all(futures); - let streams = if let Some(timeout) = options.timeout { - let timeout_future = tokio::time::sleep(timeout); - tokio::pin!(timeout_future); - tokio::pin!(streams); - tokio::select! { - _ = &mut timeout_future => { - return Err(Error::Other { - message: format!("Query timeout after {} ms", timeout.as_millis()), - source: None, - }) - } - result = &mut streams => { - result? - } - } + let streams = if let Some((deadline, timeout)) = deadline { + tokio::time::timeout_at(deadline, streams) + .await + .map_err(|_| Error::Other { + message: format!("Query timeout after {} ms", timeout.as_millis()), + source: None, + })?? } else { streams.await? }; Ok(streams .into_iter() - .map(|stream| restore_projection_order(stream, &query.base().select)) + .map(|stream| { + let stream = restore_projection_order(stream, &query.base().select); + match deadline { + Some((deadline, timeout)) => { + Box::pin(TimeoutStream::with_deadline(stream, timeout, deadline)) + } + None => stream, + } + }) .collect()) } @@ -1714,8 +1731,9 @@ fn schema_from_description(schema: JsonSchema) -> Result { ))) } -/// How a response body frames its Arrow IPC payload. `/query` answers with file framing -/// and `fetch_blobs` with stream framing, so the reader is picked per response. +/// How a response body frames its Arrow IPC payload. `fetch_blobs` answers with stream +/// framing, and `/query` with stream framing only on servers that stream query results, +/// so the reader is picked per response. enum ArrowIpcFraming { File, Stream, @@ -4439,6 +4457,7 @@ mod tests { BinaryArray, Int32Array, Int64Array, RecordBatch, RecordBatchIterator, StringArray, StructArray, record_batch, }; + use arrow_ipc::reader::StreamReader; use arrow_schema::{DataType, Field, Schema}; use chrono::{DateTime, Utc}; use futures::{StreamExt, TryFutureExt, TryStreamExt, future::BoxFuture}; @@ -7093,25 +7112,36 @@ mod tests { assert_eq!(blobs.value(0), b"alpha"); } + // Read as a stream, a file's leading magic declares a message longer than the + // whole body, so the body ends before the stream does. #[rstest] - #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")))] + #[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")), true)] #[case( ARROW_FILE_CONTENT_TYPE, - write_ipc_stream_uncompressed(&one_row_blob_batch("image")) + write_ipc_stream_uncompressed(&one_row_blob_batch("image")), + false )] #[tokio::test] async fn test_fetch_blobs_fails_when_the_body_contradicts_the_content_type( #[case] content_type: &'static str, #[case] body: Vec, + #[case] ends_early: bool, ) { let table = table_with_fetch_blobs_content_type(Some(content_type), body); let error = table.fetch_blobs("image", &[10]).await.unwrap_err(); - assert!( - matches!(error, Error::Arrow { .. }), - "expected an Arrow decode failure, got {error}" - ); + if ends_early { + assert!( + matches!(error, Error::ResponseInterrupted { batches: 0, .. }), + "expected an incomplete stream, got {error}" + ); + } else { + assert!( + matches!(error, Error::Arrow { .. }), + "expected an Arrow decode failure, got {error}" + ); + } } #[tokio::test] diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs new file mode 100644 index 000000000..af31a9b28 --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -0,0 +1,729 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Incremental decoding of response bodies that use Arrow IPC stream framing. + +use arrow_array::RecordBatch; +use arrow_buffer::Buffer; +use arrow_ipc::reader::StreamDecoder; +use bytes::Bytes; +use datafusion_common::DataFusionError; +use datafusion_physical_plan::SendableRecordBatchStream; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use futures::stream::BoxStream; +use futures::{Stream, StreamExt, TryStreamExt}; + +use crate::error::{BoxError, Error, Result}; + +/// Decode an Arrow IPC stream from a response body as its chunks arrive. +/// +/// Only the current chunk and the decoder's state are held, so memory is bounded +/// by the size of a batch rather than the size of the result. This waits for the +/// first batch, or for the end of an empty result, so a body that fails before +/// any data arrives fails the request itself. +/// +/// A complete body ends with the end-of-stream marker; the server aborts the body +/// without it when the query fails after sending headers. A body that ends early, +/// even between messages, is reported as [`Error::ResponseInterrupted`] and never +/// as a short result. +pub(super) async fn read_ipc_stream( + chunks: impl Stream> + Send + 'static, + request_id: String, + table_version: Option, +) -> Result +where + E: Into + 'static, +{ + let mut body = IpcStreamBody { + chunks: chunks.map_err(Into::into).boxed(), + chunk: Buffer::default(), + decoder: StreamDecoder::new(), + finished: false, + request_id, + table_version, + batches: 0, + rows: 0, + }; + let first = body.next_batch().await?; + // The schema is the first message, so only a body holding nothing but the + // end-of-stream marker can complete without one. + let schema = body.decoder.schema().ok_or_else(|| Error::Http { + source: "Arrow IPC stream ended without a schema".into(), + request_id: body.request_id.clone(), + status_code: None, + })?; + let rest = futures::stream::try_unfold(body, |mut body| async move { + Ok(body.next_batch().await?.map(|batch| (batch, body))) + }); + let batches = futures::stream::iter(first.map(Ok)) + .chain(rest) + .map_err(|error: Error| DataFusionError::External(Box::new(error))); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, batches))) +} + +struct IpcStreamBody { + chunks: BoxStream<'static, std::result::Result>, + /// The part of the current chunk that has not been decoded yet. + chunk: Buffer, + decoder: StreamDecoder, + /// Set once the body has ended with the end-of-stream marker. + finished: bool, + request_id: String, + table_version: Option, + batches: u64, + rows: u64, +} + +impl IpcStreamBody { + /// Decode until the next batch is complete. Returns `None` once the body + /// has ended with the end-of-stream marker. + async fn next_batch(&mut self) -> Result> { + while !self.finished { + if self.chunk.is_empty() { + match self.chunks.next().await { + Some(Ok(chunk)) => self.chunk = chunk.into(), + Some(Err(error)) => return Err(self.interrupted(error)), + None if read_end_of_stream(&mut self.decoder) => self.finished = true, + None => { + return Err(self.interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + )); + } + } + continue; + } + // Decoding stops after each batch, keeping the rest of the chunk. + if let Some(batch) = self.decoder.decode(&mut self.chunk)? { + self.batches += 1; + self.rows += batch.num_rows() as u64; + return Ok(Some(batch)); + } + } + Ok(None) + } + + fn interrupted(&self, source: BoxError) -> Error { + Error::ResponseInterrupted { + request_id: self.request_id.clone(), + batches: self.batches, + rows: self.rows, + table_version: self.table_version, + source: source.into(), + } + } +} + +/// Whether the decoder has read the end-of-stream marker. +/// +/// [`StreamDecoder::finish`] also accepts input that stops between messages, +/// because the Arrow format lets a writer end a stream by closing it. A decoder +/// that has read the marker rejects any further input, which is the only way +/// its API tells the two apart. +fn read_end_of_stream(decoder: &mut StreamDecoder) -> bool { + decoder.finish().is_ok() && decoder.decode(&mut Buffer::from_slice_ref([0u8])).is_err() +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use arrow_array::builder::StringDictionaryBuilder; + use arrow_array::types::Int8Type; + use arrow_array::{ArrayRef, Int32Array, StringArray}; + use arrow_ipc::CompressionType; + use arrow_ipc::writer::{DictionaryHandling, FileWriter, IpcWriteOptions, StreamWriter}; + use arrow_schema::{DataType, Field, Schema, SchemaRef}; + use lance::arrow::json::JsonSchema; + use rstest::rstest; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + use tokio::sync::mpsc; + + use super::*; + use crate::query::{ExecutableQuery, QueryExecutionOptions}; + use crate::remote::client::{ClientConfig, RetryConfig}; + use crate::remote::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE}; + use crate::{Table, connect}; + + /// Three batches of two rows under a schema with metadata. The second batch's + /// dictionary extends the first one's, which writers can send as a delta, and + /// the third replaces it. + fn batches() -> Vec { + let schema = Arc::new(Schema::new_with_metadata( + vec![ + Field::new("id", DataType::Int32, false), + Field::new_dictionary("label", DataType::Int8, DataType::Utf8, false), + ], + HashMap::from([("origin".to_string(), "test".to_string())]), + )); + let labels: [(&[&str], [&str; 2]); 3] = [ + (&["a", "b"], ["a", "b"]), + (&["a", "b", "c"], ["c", "a"]), + (&["d"], ["d", "d"]), + ]; + labels + .into_iter() + .enumerate() + .map(|(i, (dictionary, values))| { + let dictionary = StringArray::from(dictionary.to_vec()); + let mut label = + StringDictionaryBuilder::::new_with_dictionary(2, &dictionary) + .unwrap(); + values + .into_iter() + .for_each(|value| label.append_value(value)); + let id = Int32Array::from(vec![2 * i as i32, 2 * i as i32 + 1]); + RecordBatch::try_new( + schema.clone(), + vec![Arc::new(id) as ArrayRef, Arc::new(label.finish())], + ) + .unwrap() + }) + .collect() + } + + /// An IPC stream cut where the server cuts it: after the schema, after each + /// batch with its dictionaries, and after the end-of-stream marker. + fn messages( + schema: &Schema, + batches: &[RecordBatch], + options: IpcWriteOptions, + ) -> Vec> { + let mut writer = StreamWriter::try_new_with_options(Vec::new(), schema, options).unwrap(); + let mut messages = vec![std::mem::take(writer.get_mut())]; + for batch in batches { + writer.write(batch).unwrap(); + messages.push(std::mem::take(writer.get_mut())); + } + writer.finish().unwrap(); + messages.push(std::mem::take(writer.get_mut())); + messages + } + + fn chunks(body: &[u8], size: usize) -> Vec> { + body.chunks(size) + .map(|chunk| Ok(Bytes::copy_from_slice(chunk))) + .collect() + } + + /// The schema, the batches yielded, and the error that ended the stream. + async fn read( + chunks: Vec>, + ) -> (Option, Vec, Option) { + let stream = + match read_ipc_stream(futures::stream::iter(chunks), "request".into(), Some(7)).await { + Ok(stream) => stream, + Err(error) => return (None, vec![], Some(error)), + }; + let schema = stream.schema(); + let results = stream.collect::>().await; + let (batches, errors): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok()); + assert!(errors.len() <= 1, "the stream ends at its first error"); + let error = errors + .into_iter() + .next() + .map(|e| Error::from(e.unwrap_err())); + let batches = batches.into_iter().map(|r| r.unwrap()).collect(); + (Some(schema), batches, error) + } + + fn assert_interrupted(error: Option, expected_batches: u64, expected_rows: u64) { + match error { + Some(Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + .. + }) => { + assert_eq!(request_id, "request"); + assert_eq!((batches, rows), (expected_batches, expected_rows)); + assert_eq!(table_version, Some(7)); + } + other => panic!("expected an interrupted response, got {other:?}"), + } + } + + // One-byte chunks split every message; a single chunk holds them all. + #[rstest] + #[case(1)] + #[case(7)] + #[case(usize::MAX)] + #[tokio::test] + async fn decodes_any_chunking(#[case] chunk_size: usize) { + let input = batches(); + let body = messages(&input[0].schema(), &input, IpcWriteOptions::default()).concat(); + + let (schema, output, error) = read(chunks(&body, chunk_size)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(schema.unwrap(), input[0].schema()); + assert_eq!(output, input); + } + + #[rstest] + #[case(IpcWriteOptions::default().with_dictionary_handling(DictionaryHandling::Delta))] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::LZ4_FRAME)).unwrap())] + #[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::ZSTD)).unwrap())] + #[tokio::test] + async fn decodes_dictionary_deltas_and_compressed_batches(#[case] options: IpcWriteOptions) { + let input = batches(); + let body = messages(&input[0].schema(), &input, options).concat(); + + let (_, output, error) = read(chunks(&body, 5)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + /// The server answers an empty result with the schema and the end-of-stream marker. + #[tokio::test] + async fn empty_result_keeps_its_schema() { + let schema = batches()[0].schema(); + let body = messages(&schema, &[], IpcWriteOptions::default()).concat(); + + let (decoded, output, error) = read(chunks(&body, 3)).await; + + assert!(error.is_none(), "{error:?}"); + assert_eq!(decoded.unwrap(), schema); + assert!(output.is_empty()); + } + + #[tokio::test] + async fn body_ending_without_end_of_stream_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let complete = messages[..messages.len() - 1].concat(); + let after_first_batch = messages[..2].concat().len(); + // Where the body stops, and how many batches it holds by then. + for (end, delivered) in [ + (complete.len(), 3), // between messages, after the last batch + (complete.len() - 3, 2), // inside the last batch + (after_first_batch, 1), // between messages + (messages[0].len(), 0), // after the schema + (messages[0].len() / 2, 0), // inside the schema + (0, 0), // an empty body + ] { + let (_, output, error) = read(chunks(&complete[..end], 4)).await; + assert_eq!(output, input[..delivered], "body cut at {end}"); + assert_interrupted(error, delivered as u64, 2 * delivered as u64); + } + } + + #[tokio::test] + async fn body_error_is_interrupted() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + let mut body = chunks(&messages[..2].concat(), usize::MAX); + body.push(Err(std::io::Error::other("connection reset"))); + + let (_, output, error) = read(body).await; + + assert_eq!(output, input[..1]); + let message = error.as_ref().map(ToString::to_string).unwrap_or_default(); + assert!(message.contains("connection reset"), "{message}"); + assert_interrupted(error, 1, 2); + } + + #[tokio::test] + async fn malformed_body_is_an_arrow_error() { + let input = batches(); + let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default()); + // A message whose metadata is not a flatbuffer. + let garbage = [&[0xff; 4][..], &8u32.to_le_bytes(), &[0xab; 8]].concat(); + // Anything after the end-of-stream marker. + let trailing = [messages.concat(), vec![0]].concat(); + for body in [[messages[0].clone(), garbage].concat(), trailing] { + let (_, _, error) = read(chunks(&body, usize::MAX)).await; + assert!(matches!(error, Some(Error::Arrow { .. })), "{error:?}"); + } + } + + /// What the test server does next for a query request. + enum Reply { + /// A complete response with this status and an empty body. + Status(u16), + /// Headers of a chunked body with this content type. + Head(Option<&'static str>), + Chunk(Vec), + /// The last chunk, ending the body cleanly. + End, + /// Close the connection in the middle of the body. + Abort, + } + + struct Server { + table: Table, + replies: mpsc::UnboundedSender, + /// Headers of each query request received. + queries: Arc>>>, + } + + impl Server { + fn reply(&self, replies: impl IntoIterator) { + replies + .into_iter() + .for_each(|reply| self.replies.send(reply).unwrap()); + } + } + + /// Serve table `t` over HTTP. Query requests are answered, in order, by the + /// replies the test sends. + async fn serve() -> Server { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (replies, mut pending) = mpsc::unbounded_channel(); + let queries = Arc::new(Mutex::new(Vec::new())); + let received = queries.clone(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (path, headers) = read_request(&mut socket).await; + if path.ends_with("/describe/") { + let schema = Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new( + "vector", + DataType::new_fixed_size_list(DataType::Float32, 2, true), + false, + ), + ]); + let body = serde_json::json!({ + "version": 7, + "schema": JsonSchema::try_from(&schema).unwrap(), + }) + .to_string(); + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + socket.write_all(response.as_bytes()).await.unwrap(); + continue; + } + received.lock().unwrap().push(headers); + while let Some(reply) = pending.recv().await { + let last = !matches!(reply, Reply::Head(_) | Reply::Chunk(_)); + let bytes = match reply { + Reply::Status(status) => format!( + "HTTP/1.1 {status} Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .into_bytes(), + Reply::Head(content_type) => format!( + "HTTP/1.1 200 OK\r\n{}Transfer-Encoding: chunked\r\n\ + x-lancedb-version: 7\r\nConnection: close\r\n\r\n", + content_type + .map(|value| format!("Content-Type: {value}\r\n")) + .unwrap_or_default() + ) + .into_bytes(), + Reply::Chunk(chunk) => { + [format!("{:x}\r\n", chunk.len()).into_bytes(), chunk, b"\r\n".into()] + .concat() + } + Reply::End => b"0\r\n\r\n".to_vec(), + Reply::Abort => break, + }; + // The client may have stopped reading. + if socket.write_all(&bytes).await.is_err() || last { + break; + } + } + } + }); + let db = connect("db://test") + .api_key("key") + .region("us-east-1") + .host_override(&format!("http://{address}")) + .client_config(ClientConfig { + retry_config: RetryConfig { + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let table = db.open_table("t").execute().await.unwrap(); + Server { + table, + replies, + queries, + } + } + + async fn read_request(socket: &mut TcpStream) -> (String, HashMap) { + let mut request = Vec::new(); + let mut buf = [0; 4096]; + let head_end = loop { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request head"); + request.extend_from_slice(&buf[..n]); + if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") { + break end + 4; + } + }; + let head = String::from_utf8(request[..head_end].to_vec()).unwrap(); + let mut lines = head.lines(); + let path = lines.next().unwrap().split(' ').nth(1).unwrap().to_string(); + let headers: HashMap<_, _> = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string())) + .collect(); + let length: usize = headers + .get("content-length") + .map_or(0, |length| length.parse().unwrap()); + while request.len() < head_end + length { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request body"); + request.extend_from_slice(&buf[..n]); + } + (path, headers) + } + + /// The query batches as the server sends them: `id` only. + fn id_messages() -> Vec> { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batches: Vec<_> = (0..3) + .map(|i| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![i]))]) + .unwrap() + }) + .collect(); + messages(&schema, &batches, IpcWriteOptions::default()) + } + + fn ids(batch: &RecordBatch) -> Vec { + batch["id"] + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + } + + #[tokio::test] + async fn first_batch_arrives_before_the_rest_of_the_body() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + // The server sends the rest only after the first batch has been read. + let (results, first) = tokio::time::timeout(Duration::from_secs(10), async { + let mut results = server.table.query().execute().await.unwrap(); + let first = results.next().await.unwrap().unwrap(); + (results, first) + }) + .await + .expect("the first batch must not wait for the whole body"); + assert_eq!(ids(&first), [0]); + server.reply([Reply::Chunk(messages[2..].concat()), Reply::End]); + let rest = results.try_collect::>().await.unwrap(); + assert_eq!(rest.iter().flat_map(ids).collect::>(), [1, 2]); + + let queries = server.queries.lock().unwrap(); + assert_eq!(queries.len(), 1); + assert_eq!(queries[0]["accept"], super::super::QUERY_ACCEPT); + } + + /// A server abort, and a proxy that turns it into a clean end of the body, + /// both fail the query after the batches already read. Neither is retried. + #[rstest] + #[case::abort(Reply::Abort, true)] + #[case::clean_end(Reply::End, false)] + #[tokio::test] + async fn interrupted_body_is_typed_and_not_retried( + #[case] end: Reply, + #[case] transport_error: bool, + ) { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + end, + ]); + + let mut results = server.table.query().execute().await.unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = results.next().await.unwrap().unwrap_err(); + assert!(results.next().await.is_none()); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert_eq!(source.is::(), transport_error, "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 1); + } + + /// Vector queries run through a DataFusion plan, which must keep the error's type. + #[tokio::test] + async fn vector_query_keeps_the_interruption_type() { + let server = serve().await; + let messages = id_messages(); + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + assert!( + matches!(error, Error::ResponseInterrupted { batches: 1, .. }), + "{error:?}" + ); + } + + /// A server without multi-vector support gets a request per vector, and the + /// plan merging the responses shares an error between its partitions. + #[tokio::test] + async fn multi_vector_query_keeps_the_interruption() { + let server = serve().await; + let messages = id_messages(); + // Which vector gets which response does not matter. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages.concat()), + Reply::End, + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + Reply::Abort, + ]); + + let results = server + .table + .query() + .nearest_to(&[0.0f32, 0.0]) + .unwrap() + .add_query_vector(&[1.0f32, 1.0]) + .unwrap() + .execute() + .await + .unwrap(); + let error = results.try_collect::>().await.unwrap_err(); + + let Error::ResponseInterrupted { + request_id, + batches, + rows, + table_version, + source, + } = error + else { + panic!("expected an interrupted response, got {error:?}"); + }; + assert!(!request_id.is_empty()); + assert_eq!((batches, rows, table_version), (1, 1, Some(7))); + assert!(source.is::(), "{source}"); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn timeout_covers_reading_the_body() { + let server = serve().await; + let messages = id_messages(); + // The body stalls after the first batch. + server.reply([ + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(messages[..2].concat()), + ]); + + let options = QueryExecutionOptions { + timeout: Some(Duration::from_millis(500)), + ..Default::default() + }; + let mut results = server + .table + .query() + .execute_with_options(options) + .await + .unwrap(); + assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]); + let error = tokio::time::timeout(Duration::from_secs(10), results.next()) + .await + .expect("the timeout must end a stalled body") + .unwrap() + .unwrap_err(); + + assert!( + !matches!(error, Error::ResponseInterrupted { .. }), + "{error:?}" + ); + assert!( + error.to_string().contains("Query timeout after 500 ms"), + "{error}" + ); + assert_eq!( + server.queries.lock().unwrap()[0]["x-request-timeout-ms"], + "500" + ); + } + + /// Servers that do not stream query results answer with file framing, or + /// with no content type at all. + #[rstest] + #[case(Some(ARROW_FILE_CONTENT_TYPE))] + #[case(None)] + #[tokio::test] + async fn file_framing_is_still_read(#[case] content_type: Option<&'static str>) { + let server = serve().await; + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![4, 5]))]) + .unwrap(); + let mut writer = FileWriter::try_new(Vec::new(), &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + server.reply([ + Reply::Head(content_type), + Reply::Chunk(writer.into_inner().unwrap()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output, [batch]); + } + + #[tokio::test] + async fn failure_before_headers_is_retried() { + let server = serve().await; + server.reply([ + Reply::Status(503), + Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)), + Reply::Chunk(id_messages().concat()), + Reply::End, + ]); + + let results = server.table.query().execute().await.unwrap(); + let output = results.try_collect::>().await.unwrap(); + + assert_eq!(output.iter().flat_map(ids).collect::>(), [0, 1, 2]); + assert_eq!(server.queries.lock().unwrap().len(), 2); + } +} diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index 560fe858a..eedff924d 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -680,6 +680,22 @@ impl TimeoutStream { Box::pin(Self::new(inner, timeout)) } + /// Like [`Self::new`], but the stream expires at `deadline` rather than + /// `timeout` after its first poll. `timeout` is only used in the error. + pub fn with_deadline( + inner: SendableRecordBatchStream, + timeout: std::time::Duration, + deadline: tokio::time::Instant, + ) -> Self { + Self { + inner, + state: TimeoutState::Started { + deadline: Box::pin(tokio::time::sleep_until(deadline)), + timeout, + }, + } + } + fn timeout_error(timeout: &std::time::Duration) -> DataFusionError { DataFusionError::Execution(format!("Query timeout after {} ms", timeout.as_millis())) } From 0a5c36c1e2ead5baf87d62dfc36cada7ced0d581 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Mon, 9 Nov 2026 21:55:58 -0800 Subject: [PATCH 050/203] feat: plan computed columns against the session's DataFusion functions (#4924) A computed column's expression is planned with Lance's default planner, so a function the embedder registers with DataFusion can't be declared, and the declared field drops the return-field metadata a function attaches, such as a logical type. Every site that plans a declaration (declare, validate, refresh, schema changes, view and table creation) now uses the DataFusion session the table's lance session carries, when there is one. The declared field keeps the expression's return-field metadata, without schema declarations such as a primary key. --- rust/lancedb/src/database/namespace.rs | 3 + rust/lancedb/src/materialized_view.rs | 13 +- rust/lancedb/src/materialized_view/refresh.rs | 2 +- rust/lancedb/src/table.rs | 13 +- rust/lancedb/src/table/add_columns.rs | 24 ++ rust/lancedb/src/table/computed_columns.rs | 260 +++++++++++++++--- rust/lancedb/src/table/refresh.rs | 8 +- rust/lancedb/src/table/schema_evolution.rs | 17 +- 8 files changed, 291 insertions(+), 49 deletions(-) diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index d93f73c64..4e61710ff 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -336,6 +336,9 @@ impl Database for LanceNamespaceDatabase { // Refuse a bad declaration before the namespace records a table. crate::table::computed_columns::ensure_declarations_are_planned( &request.data.arrow_schema(), + self.session + .as_deref() + .and_then(lance::session::Session::datafusion_session), )?; let mut table_id = request.namespace_path.clone(); table_id.push(request.name.clone()); diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index c263dc001..bd7fbb942 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -958,7 +958,7 @@ fn is_declaration(key: &str) -> bool { || crate::table::computed_columns::is_declaration_key(key) } -fn without_declarations(field: &ArrowField) -> ArrowField { +pub(crate) fn without_declarations(field: &ArrowField) -> ArrowField { let metadata: HashMap = field .metadata() .iter() @@ -1123,6 +1123,10 @@ impl PreparedDeclaration { /// are validated over the assembled schema, and read only columns the /// view holds (see [`PreparedDeclaration::input_column`]). /// + /// `session` holds the DataFusion functions a declaration may call, as + /// for [`AddColumnsBuilder::computed`](crate::table::AddColumnsBuilder::computed); + /// `None` plans against Lance's built-in functions only. + /// /// ```no_run /// # #![recursion_limit = "256"] /// # use std::collections::HashMap; @@ -1148,7 +1152,7 @@ impl PreparedDeclaration { /// (INPUTS_META_KEY.into(), format!("[\"{text}\"]")), /// ])); /// let view = prepared - /// .with_computed_columns(vec![(1, length)], &[])? + /// .with_computed_columns(vec![(1, length)], &[], None)? /// .create("lengths") /// .await?; /// view.refresh().execute().await?; // rows land with `length` NULL @@ -1160,6 +1164,7 @@ impl PreparedDeclaration { mut self, columns: Vec<(usize, ArrowField)>, bindings: &[FunctionBinding], + session: Option<&datafusion::execution::context::SessionContext>, ) -> Result { let invalid = |message: String| Error::InvalidInput { message }; if columns.is_empty() { @@ -1223,7 +1228,7 @@ impl PreparedDeclaration { } rewrite_column_definitions(&mut metadata, self.schema.as_ref(), &fields)?; let schema = ArrowSchema::new_with_metadata(fields, metadata); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; self.schema = Arc::new(schema); Ok(self) } @@ -2685,7 +2690,7 @@ mod tests { (INPUTS_META_KEY.into(), "[\"x\"]".into()), ])); let view = prepared - .with_computed_columns(vec![(1, doubled)], &[]) + .with_computed_columns(vec![(1, doubled)], &[], None) .unwrap() .create("m") .await diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 1072b7684..8851d071e 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -133,7 +133,7 @@ pub(crate) async fn execute_refresh( })?; let physical = Arc::new(ArrowSchema::from(view_ds.schema())); - ensure_declarations_are_planned(&physical)?; + ensure_declarations_are_planned(&physical, view_ds.session().datafusion_session())?; if let Some(field) = physical .fields() .iter() diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index cc7b820f9..a58567b2e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -3407,7 +3407,11 @@ impl NativeTable { namespace_client: Option>, pushdown_operations: HashSet, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let session = params.as_ref().and_then(|p| p.session.as_deref()); + let batches = computed_columns::admit_create_source( + batches, + session.and_then(lance::session::Session::datafusion_session), + )?; // Default params uses format v1. let params = params.unwrap_or(WriteParams { ..Default::default() @@ -3508,7 +3512,12 @@ impl NativeTable { pushdown_operations: HashSet, session: Option>, ) -> Result { - let batches = computed_columns::admit_create_source(batches)?; + let batches = computed_columns::admit_create_source( + batches, + session + .as_deref() + .and_then(lance::session::Session::datafusion_session), + )?; // Build table_id from namespace + name for the storage options provider let mut table_id = namespace.clone(); table_id.push(name.to_string()); diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index be319a8be..1b827bb37 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -89,6 +89,30 @@ impl AddColumnsBuilder { /// # Ok(()) /// # } /// ``` + /// + /// In LanceDB Embedded, an expression can also call functions registered + /// on a DataFusion `SessionContext` attached to the connection's Lance + /// session. They are not stored with the table, so attach them on every + /// connection that opens it. + /// + /// ```no_run + /// # use std::sync::Arc; + /// # use datafusion::execution::context::SessionContext; + /// # use datafusion::logical_expr::ScalarUDF; + /// # async fn declare(my_udf: ScalarUDF) -> Result<(), Box> { + /// let functions = SessionContext::new(); + /// functions.register_udf(my_udf); + /// let session = lance::session::Session::default().with_datafusion_session(functions); + /// let db = lancedb::connect("data/db") + /// .session(Arc::new(session)) + /// .execute() + /// .await?; + /// let table = db.open_table("t").execute().await?; + /// table.add_columns().computed("y", "my_udf(x)").execute().await?; + /// table.refresh_column("y").await?; + /// # Ok(()) + /// # } + /// ``` pub fn computed(mut self, name: impl Into, expression: impl Into) -> Self { self.computed.push((name.into(), expression.into())); self diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 0e02e7ce2..e6d7d432c 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use arrow_schema::{DataType, Field as ArrowField, Fields, Schema as ArrowSchema, SchemaRef}; +use datafusion::execution::context::SessionContext; use datafusion_common::{ScalarValue, tree_node::TreeNode}; use datafusion_expr::Expr; use datafusion_physical_plan::PhysicalExpr; @@ -40,6 +41,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding}; +use crate::materialized_view::without_declarations; use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; @@ -1640,8 +1642,12 @@ pub(crate) fn plan_function_application( /// /// Paths are compared at their root: a declaration reading `metadata` is /// invalidated by a change to `metadata.age` just as surely. -pub(crate) fn ensure_not_an_input(schema: &SchemaRef, paths: &[&str]) -> Result<()> { - ensure_not_an_input_of(schema, paths, &[]) +pub(crate) fn ensure_not_an_input( + schema: &SchemaRef, + paths: &[&str], + session: Option<&SessionContext>, +) -> Result<()> { + ensure_not_an_input_of(schema, paths, &[], session) } /// [`ensure_not_an_input`] where `removed` names columns whose own @@ -1651,6 +1657,7 @@ pub(crate) fn ensure_not_an_input_of( schema: &SchemaRef, paths: &[&str], removed: &[&str], + session: Option<&SessionContext>, ) -> Result<()> { // By identity, not spelling: a quoted path names the same column, while // a path *into* one removes no declaration at all. @@ -1668,7 +1675,7 @@ pub(crate) fn ensure_not_an_input_of( // The expression, not stored inputs, is the source of truth; an // expression that no longer parses proves nothing, so refuse. let inputs = match &declaration.kind { - ComputedColumnKind::Sql { expression } => Planner::new(schema.clone()) + ComputedColumnKind::Sql { expression } => session_planner(schema.clone(), session) .parse_expr(expression) .map(|parsed| Planner::column_names_in_expr(&parsed)) .map_err(|e| Error::InvalidInput { @@ -1760,7 +1767,10 @@ pub(crate) fn ensure_batch_writes_no_computed_values( /// Function declaration satisfies the binding contract, and no SQL /// declaration reads another computed column. What passes here is what /// `refresh_column` can execute. -pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<()> { +pub(crate) fn ensure_declarations_are_planned( + schema: &ArrowSchema, + session: Option<&SessionContext>, +) -> Result<()> { let invalid = |message: String| Error::InvalidInput { message }; // A field with any declaration key is a declaration; a partial one is // not "no declaration", it is a broken one. @@ -1794,7 +1804,12 @@ pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<() .filter(|f| f.name() != &column.name) .map(|f| f.as_ref().clone()) .collect(); - let bound = bind(Arc::new(ArrowSchema::new(others)), &column.name, expression)?; + let bound = bind( + Arc::new(ArrowSchema::new(others)), + &column.name, + expression, + session, + )?; if let Some(input) = bound.roots.iter().find(|r| declared.contains(*r)) { return Err(invalid(format!( "computed column '{}' reads computed column '{input}'", @@ -1944,6 +1959,17 @@ pub(crate) struct BoundExpression { pub blob_paths: Vec, /// A directly projected Blob v2 field whose semantics the output inherits. projected_blob_field: Option, + /// Field metadata of the expression's return field, e.g. a function's + /// logical type. + return_metadata: HashMap, +} + +/// Plans against `session`'s functions when given, else Lance's defaults. +fn session_planner(schema: SchemaRef, session: Option<&SessionContext>) -> Planner { + match session { + Some(session) => Planner::new_with_session(schema, session.clone()), + None => Planner::new(schema), + } } fn is_direct_field_projection(expr: &Expr) -> bool { @@ -2089,7 +2115,12 @@ fn referenced_blob_paths(schema: &ArrowSchema, inputs: &[String]) -> Result 0`), /// and the guard protecting the stored SQL has to see every column the text /// names, not just the ones the simplified form still reads. -pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result { +pub(crate) fn bind( + schema: SchemaRef, + column: &str, + expression: &str, + session: Option<&SessionContext>, +) -> Result { let invalid = |message: String| Error::InvalidExpression { column: column.to_string(), message, @@ -2102,7 +2133,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .into_iter() .collect::>(); let parsing_schema = blob_runtime_schema(schema.as_ref(), &all_blob_paths); - let planner = Planner::new(parsing_schema); + let planner = session_planner(parsing_schema, session); let parsed = planner .parse_expr(expression) .map_err(|e| invalid(e.to_string()))?; @@ -2171,22 +2202,22 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .map(|field| field.name().clone()) .collect(); - let runtime_planner = Planner::new(runtime_schema); + let runtime_planner = session_planner(runtime_schema, session); let optimized = runtime_planner .optimize_expr(parsed) .map_err(|e| invalid(e.to_string()))?; - let physical = Planner::new(read_schema.clone()) + let physical = session_planner(read_schema.clone(), session) .create_physical_expr(&optimized) .map_err(|e| invalid(e.to_string()))?; - let data_type = physical - .data_type(read_schema.as_ref()) + let return_field = physical + .return_field(read_schema.as_ref()) .map_err(|e| invalid(e.to_string()))?; Ok(BoundExpression { inputs, roots, physical, - data_type, + data_type: return_field.data_type().clone(), blob_paths: blob_paths .iter() .map(|path| { @@ -2195,6 +2226,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< }) .collect(), projected_blob_field, + return_metadata: return_field.metadata().clone(), }) } @@ -2210,7 +2242,11 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< /// batch may declare `a` and then `b = a + 1` in one commit. Refresh order /// then matters, and refresh enforces it: `b` is refused while `a` still has /// unfilled rows. -fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result> { +fn plan_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { if columns.is_empty() { return Err(Error::InvalidInput { message: "at least one computed column is required".into(), @@ -2225,23 +2261,22 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< return Err(Error::ColumnAlreadyExists { name: name.clone() }); } - let bound = bind(schema.clone(), name, expression)?; + let bound = bind(schema.clone(), name, expression, session)?; // Declared columns start entirely null, so nullability is a property // of the declaration rather than of what the expression yields. let computed_metadata = computed_column_metadata(expression, &bound.inputs); - let field = match bound.projected_blob_field { - Some(source) => { - let mut metadata = source.metadata().clone(); - metadata.retain(|key, _| !is_declaration_key(key)); - metadata.extend(computed_metadata); - source - .with_name(name) - .with_nullable(true) - .with_metadata(metadata) + let projected = match bound.projected_blob_field { + Some(source) => source.with_name(name), + None => { + ArrowField::new(name, bound.data_type, true).with_metadata(bound.return_metadata) } - None => ArrowField::new(name, bound.data_type, true).with_metadata(computed_metadata), }; + // Keep the source's descriptive metadata, not its schema declarations. + let projected = without_declarations(&projected); + let mut metadata = projected.metadata().clone(); + metadata.extend(computed_metadata); + let field = projected.with_nullable(true).with_metadata(metadata); schema = Arc::new(ArrowSchema::new_with_metadata( schema .fields() @@ -2257,8 +2292,12 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< Ok(fields) } -pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result> { - plan_declarations(schema, columns) +pub(crate) fn plan( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result> { + plan_declarations(schema, columns, session) } /// Run the schema-level checks of @@ -2267,6 +2306,11 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result Result Result<()> { +pub fn validate_declarations( + schema: SchemaRef, + columns: &[(String, String)], + session: Option<&SessionContext>, +) -> Result<()> { ensure_not_function_bound( schema.as_ref(), "schema evolution", columns.iter().map(|(name, _)| name), )?; - plan(schema, columns).map(drop) + plan(schema, columns, session).map(drop) } /// Build the transform that declares `columns` against `schema`. @@ -2302,8 +2350,9 @@ pub fn validate_declarations(schema: SchemaRef, columns: &[(String, String)]) -> pub(crate) fn declare( schema: SchemaRef, columns: &[(String, String)], + session: Option<&SessionContext>, ) -> Result { - let fields = plan_declarations(schema, columns)?; + let fields = plan_declarations(schema, columns, session)?; Ok(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( fields, )))) @@ -2334,9 +2383,10 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st /// created. pub(crate) fn admit_create_source( batches: S, + session: Option<&SessionContext>, ) -> Result> { let schema = batches.arrow_schema(); - ensure_declarations_are_planned(&schema)?; + ensure_declarations_are_planned(&schema, session)?; let declared = computed_columns(&schema) .into_iter() .map(|c| c.name) @@ -2496,7 +2546,7 @@ mod tests { )]), )); let declarations = vec![("a".to_string(), "x + 1".to_string())]; - assert!(super::validate_declarations(schema, &declarations).is_err()); + assert!(super::validate_declarations(schema, &declarations, None).is_err()); } #[test] @@ -2588,7 +2638,7 @@ mod tests { } } - use arrow_array::record_batch; + use arrow_array::{RecordBatch, record_batch}; use arrow_schema::{DataType, TimeUnit}; use futures::TryStreamExt; use lance::dataset::ColumnAlteration; @@ -2618,6 +2668,137 @@ mod tests { computed_columns(table.schema().await.unwrap().as_ref()) } + /// Echoes an Int32 and tags its return field, like a function with a + /// logical type. + #[derive(Debug, PartialEq, Eq, Hash)] + struct Tagged(datafusion_expr::Signature); + + impl datafusion_expr::ScalarUDFImpl for Tagged { + fn name(&self) -> &str { + "tagged" + } + + fn signature(&self) -> &datafusion_expr::Signature { + &self.0 + } + + fn return_type(&self, _: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Int32) + } + + fn return_field_from_args( + &self, + _: datafusion_expr::ReturnFieldArgs, + ) -> datafusion_common::Result { + Ok(Arc::new( + ArrowField::new("tagged", DataType::Int32, true) + .with_metadata(HashMap::from([("tag".into(), "yes".into())])), + )) + } + + fn invoke_with_args( + &self, + args: datafusion_expr::ScalarFunctionArgs, + ) -> datafusion_common::Result { + Ok(args.args[0].clone()) + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_declarations_plan_against_the_session_functions() { + let functions = SessionContext::new(); + functions.register_udf(datafusion_expr::ScalarUDF::new_from_impl(Tagged( + datafusion_expr::Signature::exact( + vec![DataType::Int32], + datafusion_expr::Volatility::Immutable, + ), + ))); + let session = + Arc::new(lance::session::Session::default().with_datafusion_session(functions)); + let conn = connect("memory://") + .session(session) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2, 3]), ("y", Int32, [4, 5, 6])).unwrap(); + let table = conn + .create_table("session_functions", batch) + .execute() + .await + .unwrap(); + + add_computed(&table, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + assert_eq!( + schema.field_with_name("t").unwrap().metadata().get("tag"), + Some(&"yes".to_string()) + ); + table.refresh_column("t").await.unwrap(); + // Dropping a column re-plans every declaration on the table. + table.drop_columns(&["y"]).await.unwrap(); + + let batches = table + .query() + .select(Select::columns(&["t"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let expected = record_batch!(("t", Int32, [1, 2, 3])).unwrap(); + assert_eq!(batches[0].column(0).as_ref(), expected.column(0).as_ref()); + + let plain = table_with_ints("no_session").await; + let err = add_computed(&plain, &[("t".into(), "tagged(x)".into())]) + .await + .unwrap_err(); + assert!(err.to_string().contains("tagged"), "{err}"); + } + + /// A projection keeps its source's descriptive metadata, not its schema + /// declarations: a copy of the primary key is not a primary key. + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn test_projecting_the_primary_key_drops_its_declaration() { + let conn = connect("memory://").execute().await.unwrap(); + let ints = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); + let schema = ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, false) + .with_metadata(HashMap::from([("note".into(), "kept".into())])), + ]); + let batch = RecordBatch::try_new(Arc::new(schema), ints.columns().to_vec()).unwrap(); + let table = conn + .create_table("key_projection", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + + add_computed(&table, &[("copy".into(), "x".into())]) + .await + .unwrap(); + let schema = table.schema().await.unwrap(); + let copy = schema.field_with_name("copy").unwrap(); + assert!( + !copy + .metadata() + .keys() + .any(|key| key.starts_with("lance-schema:")), + "{copy:?}" + ); + assert_eq!(copy.metadata().get("note"), Some(&"kept".to_string())); + } + #[tokio::test] #[cfg_attr( not(feature = "experimental-functions"), @@ -2658,6 +2839,7 @@ mod tests { ("first".to_string(), "image".to_string()), ("second".to_string(), "first".to_string()), ], + None, ) .unwrap(); @@ -2680,6 +2862,7 @@ mod tests { let fields = plan( schema, &[("payload".to_string(), "coalesce(image, image)".to_string())], + None, ) .unwrap(); @@ -2914,7 +3097,8 @@ mod tests { assert!( validate_declarations( table.schema().await.unwrap(), - &[("e".into(), "random()".into())] + &[("e".into(), "random()".into())], + None, ) .is_err() ); @@ -4803,7 +4987,7 @@ mod tests { let schema = declare_plan(&schema, &downstream, "fb_downstream"); ensure_supported_function_metadata(&schema).unwrap(); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let bindings = function_bindings(&schema).unwrap(); assert!( computed_function_inputs(&schema, &bindings[0]) @@ -4868,7 +5052,7 @@ mod tests { let base = ArrowSchema::new(vec![ArrowField::new("x", DataType::Int32, true)]); let mut fields = base.fields().to_vec(); fields.extend( - plan(Arc::new(base), &[("doubled".into(), "x * 2".into())]) + plan(Arc::new(base), &[("doubled".into(), "x * 2".into())], None) .unwrap() .into_iter() .map(Arc::new), @@ -4887,7 +5071,7 @@ mod tests { .is_none_or(|metadata| !metadata.keys().any(|key| is_declaration_key(key))) ); let schema = Arc::new(declare_plan(&schema, &downstream, "fb_downstream")); - ensure_declarations_are_planned(&schema).unwrap(); + ensure_declarations_are_planned(&schema, None).unwrap(); let batch = RecordBatch::try_new( schema, vec![ diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index a8ae3c286..3c8ded1cf 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -308,6 +308,7 @@ async fn execute_refresh_column_with_source( schema.clone(), column, &expression, + dataset.session().datafusion_session(), )?); ensure_inputs_filled(&dataset, &schema, column, &bound).await?; let field = dataset @@ -490,7 +491,12 @@ async fn ensure_inputs_filled( ), }); }; - let input_bound = super::computed_columns::bind(schema.clone(), input, expression)?; + let input_bound = super::computed_columns::bind( + schema.clone(), + input, + expression, + dataset.session().datafusion_session(), + )?; let mut unfilled = 0u64; for fragment in dataset.get_fragments() { unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input) diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index db4d6b91f..ab872c7fc 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -166,7 +166,9 @@ pub(crate) async fn execute_declare( .into(), }); } - let transform = computed_columns::declare(table.schema().await?, columns)?; + let session = table.dataset.get().await?.session(); + let transform = + computed_columns::declare(table.schema().await?, columns, session.datafusion_session())?; let NewColumnTransform::AllNulls(schema) = transform else { unreachable!("declarations are all-null") }; @@ -307,7 +309,11 @@ pub(crate) async fn execute_alter_columns( .filter(|alteration| alteration.rename.is_some() || alteration.data_type.is_some()) .map(|alteration| alteration.path.as_str()) .collect::>(); - computed_columns::ensure_not_an_input(&schema, &rebinding)?; + computed_columns::ensure_not_an_input( + &schema, + &rebinding, + dataset.session().datafusion_session(), + )?; let retyped = alterations .iter() .filter(|alteration| alteration.data_type.is_some()) @@ -344,7 +350,12 @@ pub(crate) async fn execute_drop_columns( let dropped = names.iter().map(String::as_str).collect::>(); ensure_not_embedding_column(&schema, "drop", dropped.iter().copied())?; computed_columns::ensure_not_bound_by(&unbinding.retained, "schema evolution", &dropped)?; - computed_columns::ensure_not_an_input_of(&schema, &dropped, &dropped)?; + computed_columns::ensure_not_an_input_of( + &schema, + &dropped, + &dropped, + dataset.session().datafusion_session(), + )?; if !unbinding.is_noop() { // The retirement commits before the projection, so the whole From 13e4cf7e58f78779b07919862a593ccd3098c1de Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 10 Nov 2026 15:22:56 +0800 Subject: [PATCH 051/203] feat: expose Function publication intervals in refresh options (#4928) Python refresh APIs currently reject `publication_interval_rows`, so callers cannot request incremental Function output publication through the SDK. Add the optional typed parameter through the sync/async Python APIs, PyO3, and Rust `RefreshColumnOptions`, and serialize it as a top-level Enterprise refresh option. An omitted value preserves the existing wire request and whole-fragment default. Positive values set a publication threshold; zero and negative Python values fail before a request is sent. Embedded refreshes reject the Enterprise-only option. Documentation describes a threshold rather than an exact number of rows per publication. Validation on the designated development host: - A matching baseline build reproduced the missing public keyword argument in both sync and async submission tests. - The updated PyO3 build passed 54 focused Python tests; Rust payload, invalid-option, and default-wire tests each passed. Rust formatting and Python Ruff checks passed. - The single signed delivery commit differs from that tested implementation only in a Rustdoc correction describing Embedded rejection; formatting passed again. No dependency pins or lockfiles changed. The matching SDK is prepared for the separate server validation of failure/cancellation retention and missing-only refill. Those end-to-end results are still pending and are not implied by these SDK tests. Refs [ENT-3733](https://linear.app/lancedb/issue/ENT-3733). --- .../feature-engineering/refresh-column.mdx | 32 +++++++++++++++++ python/python/lancedb/_lancedb.pyi | 2 ++ python/python/lancedb/remote/table.py | 4 +++ python/python/lancedb/table.py | 34 +++++++++++++++++++ python/python/tests/test_remote_db.py | 4 +++ python/python/tests/test_table.py | 1 + python/src/table.rs | 12 +++++-- rust/lancedb/src/remote/table.rs | 6 ++++ rust/lancedb/src/table.rs | 14 ++++++-- rust/lancedb/src/table/refresh.rs | 24 +++++++++++++ 10 files changed, 128 insertions(+), 5 deletions(-) diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ac4ff93fe..0dfe3b33d 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -261,6 +261,38 @@ release. TypeScript does not expose GPU class discovery; pass `gpuClass` and `gpuCount` in the `refreshColumnAsync` options. +Completed Function outputs publish with their fragment by default. To opt into +a row-count publication threshold, set `publication_interval_rows` in Python or +`publication_interval_rows()` in Rust: + + +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + publication_interval_rows=60, +) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::table::RefreshColumnOptions; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().publication_interval_rows(60), + ) + .await?; +``` + + +The threshold is opt-in and must be greater than zero. The number of rows in an +individual publication can differ from this value depending on completed work +and Function batching; this is not an exact-N contract. Omit it to keep +whole-fragment publication. + +The TypeScript SDK does not expose the publication threshold option yet. + The job APIs also take the row filter and failure handling of the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed to new rows (see [what a filter recomputes](#partial)) and told to skip rows diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 2ac4dde58..f2d5285fa 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -619,6 +619,7 @@ class Table: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, @@ -636,6 +637,7 @@ class Table: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 8f1f741fb..a963ab55e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1143,6 +1143,7 @@ class RemoteTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1159,6 +1160,7 @@ class RemoteTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -1178,6 +1180,7 @@ class RemoteTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1195,6 +1198,7 @@ class RemoteTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 75975a2c3..06bace5b8 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3178,6 +3178,7 @@ class Table(ABC): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3216,6 +3217,12 @@ class Table(ABC): Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -3263,6 +3270,7 @@ class Table(ABC): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3300,6 +3308,12 @@ class Table(ABC): greater than zero. None uses the server default. Lower this for slow Functions to stay within the executor's per-call deadline. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -5442,6 +5456,7 @@ class LanceTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5461,6 +5476,7 @@ class LanceTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -5480,6 +5496,7 @@ class LanceTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5501,6 +5518,7 @@ class LanceTable(Table): column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -7865,6 +7883,7 @@ class AsyncTable: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -7903,6 +7922,12 @@ class AsyncTable: Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -7945,6 +7970,7 @@ class AsyncTable: column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None @@ -8054,6 +8080,7 @@ class AsyncTable: *, where: Optional[str] = None, batch_size: Optional[int] = None, + publication_interval_rows: Optional[int] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -8091,6 +8118,12 @@ class AsyncTable: greater than zero. None uses the server default. Lower this for slow Functions to stay within the executor's per-call deadline. Has no effect on local expression-backed columns. + publication_interval_rows: int, optional + Opt-in publication threshold for completed Function outputs. Must + be greater than zero. None keeps whole-fragment publication. The + actual publication boundary can be larger than this threshold + because it also depends on completed work and Function batching. + LanceDB Enterprise only; local refreshes reject this option. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -8150,6 +8183,7 @@ class AsyncTable: column, where=where, batch_size=batch_size, + publication_interval_rows=publication_interval_rows, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 685bc809d..671d0ff23 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1863,6 +1863,7 @@ def test_remote_create_index_async_returns_job(): {"batch_size": None}, {"batch_size": 1}, {"batch_size": 8}, + {"publication_interval_rows": 60}, {"gpu_class": "a10g", "gpu_count": 2}, { "retry_policy": {"transient": True, "max_attempts": 3}, @@ -1911,6 +1912,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result( expected["error_policy"] = refresh_kwargs["error_policy"] for key in ( "where", + "publication_interval_rows", "max_failed_fraction", "max_failed_rows", "row_timeout_seconds", @@ -2088,6 +2090,8 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"max_failed_rows": -1}, "max_failed_rows"), ({"row_timeout_seconds": 0}, "row_timeout_seconds"), ({"init_timeout_seconds": -5}, "init_timeout_seconds"), + ({"publication_interval_rows": 0}, "publication_interval_rows"), + ({"publication_interval_rows": -1}, "publication_interval_rows"), ({"num_workers": 0}, "num_workers"), ( {"max_executor_processes_per_worker": -2}, diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 2a502fe62..157870bb5 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5995,6 +5995,7 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) ({"max_failed_rows": 10}, "max_failed_rows"), ({"row_timeout_seconds": 30}, "row_timeout_seconds"), ({"init_timeout_seconds": 60}, "init_timeout_seconds"), + ({"publication_interval_rows": 60}, "publication_interval_rows"), ({"num_workers": 2}, "num_workers"), ({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"), ], diff --git a/python/src/table.rs b/python/src/table.rs index 92a6ef835..23c5b69d7 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -46,6 +46,7 @@ mod scannable; struct RefreshColumnArgs { where_clause: Option, batch_size: Option, + publication_interval_rows: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -73,6 +74,7 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult, column: String, r#where: Option, batch_size: Option, + publication_interval_rows: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2227,6 +2232,7 @@ impl Table { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, + publication_interval_rows, gpu_class, gpu_count, retry_policy, @@ -2248,13 +2254,14 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async( self_: PyRef<'_, Self>, column: String, r#where: Option, batch_size: Option, + publication_interval_rows: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2269,6 +2276,7 @@ impl Table { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, + publication_interval_rows, gpu_class, gpu_count, retry_policy, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 6956905c4..a69611306 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11072,6 +11072,7 @@ mod tests { serde_json::json!({ "column": "quality", "where": "id % 2 = 0", + "publication_interval_rows": 60, "error_policy": "skip", "max_failed_fraction": 0.01, "max_failed_rows": 50, @@ -11088,6 +11089,7 @@ mod tests { }); let options = RefreshColumnOptions::default() .where_clause("id % 2 = 0") + .publication_interval_rows(60) .error_policy(FunctionErrorPolicy::Skip) .max_failed_fraction(0.01) .max_failed_rows(50) @@ -11135,6 +11137,10 @@ mod tests { RefreshColumnOptions::default().max_executor_processes_per_worker(0), "max_executor_processes_per_worker", ), + ( + RefreshColumnOptions::default().publication_interval_rows(0), + "publication_interval_rows", + ), ] { let error = table .refresh_column_async_with_options("quality", options) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index a58567b2e..80b6bd7ad 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2141,10 +2141,14 @@ impl Table { /// /// [`RefreshColumnOptions::batch_size()`] caps rows per Function call in /// LanceDB Enterprise and must be greater than zero when set. + /// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in + /// row-count publication threshold for completed Function outputs; unset + /// keeps whole-fragment publication. /// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and /// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget. - /// These options have no effect on expression-backed columns in LanceDB - /// Embedded. Remote refreshes require + /// Batch-size and GPU options have no effect on expression-backed columns + /// in LanceDB Embedded; a publication threshold is rejected there. + /// Remote refreshes require /// [`Table::refresh_column_async_with_options`]. /// /// ``` @@ -2201,12 +2205,16 @@ impl Table { /// Set [`RefreshColumnOptions::batch_size()`] to cap the rows each remote /// Function call receives, for example to keep slow Functions within the /// executor's per-call deadline. Set + /// [`RefreshColumnOptions::publication_interval_rows()`] to publish + /// completed Function outputs at a row-count threshold; unset keeps + /// whole-fragment publication. Set /// [`RefreshColumnOptions::gpu_class()`] and /// [`RefreshColumnOptions::gpu_count()`] to override the registered GPU /// class or set an aggregate GPU budget for Function workers. Unset values /// use the Function and server defaults; zero counts and malformed class /// names are rejected before submitting a job. Embedded expression - /// refreshes ignore all three options. + /// refreshes ignore the batch-size and GPU options, and reject publication + /// thresholds and other Enterprise-only options. /// /// ``` /// # use lancedb::{Table, table::RefreshColumnOptions}; diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 3c8ded1cf..a8be34b17 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -100,6 +100,14 @@ pub struct RefreshColumnOptions { /// effect on expression-backed columns in LanceDB Embedded. #[serde(skip_serializing_if = "Option::is_none")] pub batch_size: Option, + /// Opt-in row-count threshold for publishing completed Function outputs. + /// + /// Must be greater than zero. `None` keeps whole-fragment publication. + /// Actual publication boundaries can be larger than this threshold because + /// they also depend on completed work and Function batching. LanceDB Embedded + /// rejects this option. + #[serde(skip_serializing_if = "Option::is_none")] + pub publication_interval_rows: Option, /// GPU class for Function workers in LanceDB Enterprise. /// /// `None` keeps the Function's registered class, or the deployment default @@ -174,6 +182,13 @@ impl RefreshColumnOptions { self } + /// Use `rows` as the opt-in publication threshold for completed Function + /// outputs. The actual publication boundary can be larger than this value. + pub fn publication_interval_rows(mut self, rows: u64) -> Self { + self.publication_interval_rows = Some(rows); + self + } + /// Request Function workers from `gpu_class`. pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { self.gpu_class = Some(gpu_class.into()); @@ -201,6 +216,10 @@ impl RefreshColumnOptions { "max_executor_processes_per_worker", self.max_executor_processes_per_worker.is_some(), ), + ( + "publication_interval_rows", + self.publication_interval_rows.is_some(), + ), ] .into_iter() .find_map(|(name, set)| set.then_some(name)) @@ -253,6 +272,11 @@ impl RefreshColumnOptions { message: "batch_size must be greater than zero".into(), }); } + if self.publication_interval_rows == Some(0) { + return Err(Error::InvalidInput { + message: "publication_interval_rows must be greater than zero".into(), + }); + } if let Some(gpu_class) = &self.gpu_class { validate_gpu_class_name(gpu_class)?; } From e928e374d0ba8b7a813f709796ee7ae69365de54 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 10 Nov 2026 00:25:41 -0800 Subject: [PATCH 052/203] chore: update lance dependency to v15.0.0-beta.16 (#4935) Update the Rust workspace, Java lance-core, and Python test dependency to [Lance v15.0.0-beta.16](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.16). Synchronize `python/uv.lock` with the published beta.16 wheels for Linux, macOS, and Windows. Run the native Linux x64 wheel build on an eight-core runner, matching the existing ARM build allocation, after its optimized build repeatedly exceeded the job deadline on the standard runner. The dependency update passed Clippy, formatting, and CI-script checks; the Python lockfile refresh/check passes. Fresh CI is running for the runner adjustment. Java dependency-resolution failures caused solely by publication lag are accepted for this upgrade. --------- Co-authored-by: Jack Ye --- .github/workflows/pypi-publish.yml | 2 +- Cargo.lock | 96 +++++++++++++++--------------- Cargo.toml | 30 +++++----- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 14 ++--- 6 files changed, 73 insertions(+), 73 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index b2db765d0..5aea2ca30 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -44,7 +44,7 @@ jobs: - platform: x86_64 manylinux: "2_28" extra_args: "--features fp16kernels" - runner: ubuntu-22.04 + runner: ubuntu-2404-8x-x64 package_name: "lancedb" rustflags: "" # For successful fat LTO builds, we need a large runner to avoid OOM errors. diff --git a/Cargo.lock b/Cargo.lock index 893fb21d6..ad42d60b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5671,8 +5671,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5695,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5741,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5759,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5775,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5790,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5845,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5860,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5902,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce" +version = "15.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index ab8e86f97..e77e0ffd6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 88b66b3ad..4d1dccdb4 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.15 + 15.0.0-beta.16 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 153d138b4..036acf075 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b15", + "pylance==15.0.0b16", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 2cd4ac496..a5ae1caf8 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b15" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b15" +version = "15.0.0b16" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,11 +4312,11 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_29HO58/pylance-15.0.0b15-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:46c870c3d650f911eccb7406ec77f72fa448f80b2f827ff35dd86bbc0b9e08ca" }, - { url = "https://pypi.fury.io/lance-format/-/ver_OBkXR/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f418584cdee98d27aac538ebe5203051a0b78a98668aff22bc29aebe3dd3c9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_TMbLm/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3656d52ba65d297b41f1973d1a3efbb888f761cf7c934ff15e0c1aecc560b2d5" }, - { url = "https://pypi.fury.io/lance-format/-/ver_mmYmR/pylance-15.0.0b15-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a50d06e3a86d68acf8edf5a83736890a648a16a1cb8c8ccde9ef5b6c82ebef76" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1aYiTc/pylance-15.0.0b15-cp310-abi3-win_amd64.whl", hash = "sha256:6451499f0612d0326d54168bedcc6df29c1e0700c4f92902f5f00a6ecdf17745" }, + { url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" }, + { url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" }, + { url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" }, ] [[package]] From 3851938b6e21c9ac6de534e78dadd12d9bed4013 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 10 Nov 2026 08:26:43 +0000 Subject: [PATCH 053/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.9=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index bbf036dc8..992d126d0 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.9" +current_version = "0.42.0-beta.10" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index ad42d60b0..56642301c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5930,7 +5930,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "ahash", "anyhow", @@ -6041,7 +6041,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "anyhow", "arrow-array", @@ -6084,7 +6084,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "arrow-array", "arrow-buffer", @@ -6109,7 +6109,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 6b0ac9492..3d3a3f8e1 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.42.0-beta.9 + 0.42.0-beta.10 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index f915a6a64..758e41acd 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.9 + 0.42.0-beta.10 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 4d1dccdb4..2f72f98a7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.9 + 0.42.0-beta.10 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index d8f16adb1..47fc92237 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.9" +version = "0.42.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 f04147d46..3761d6f4f 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.42.0-beta.9", + "version": "0.42.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 af781ae92..5b7a167d0 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.42.0-beta.9", + "version": "0.42.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 c08a81137..e902929bf 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.42.0-beta.9", + "version": "0.42.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 624b22de3..a54f47de3 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.42.0-beta.9", + "version": "0.42.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 d200c24c3..cc1894e70 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.42.0-beta.9", + "version": "0.42.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 a0b3cfd48..d5e0309d0 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.42.0-beta.9", + "version": "0.42.0-beta.10", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0544af0c7..5e9698e7f 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.42.0-beta.9", + "version": "0.42.0-beta.10", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index c2424cd55..5579e1c55 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.9", + "version": "0.42.0-beta.10", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 2c577766b..102b0f67b 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.9" +version = "0.42.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 6f5d45232..783216243 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 601d0f58b..051db741a 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.9" +version = "0.42.0-beta.10" edition = "2021" license.workspace = true repository.workspace = true From c0bd83ef295704bb1879fdf3f4c21ccb776dee02 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 10 Nov 2026 19:47:30 +0800 Subject: [PATCH 054/203] feat(sql): expose durable job ids on query handles (#4941) Expose the durable SQL registry id separately from the connection-scoped query UUID. Rust and Python query handles and descriptions expose optional `job_id`; result readers preserve it in schema metadata under `x-lancedb-sql-job-id`, without adding business columns. Clients can reopen that id with `open_job`. Poll success and failure metadata update the same handle. A failure before the first successful poll retains its job id and original structured error. The cancellation documentation distinguishes the Flight waiter from `cancel_job(job_id)`. Validation on the designated EC2: the two focused error interoperability tests and Ruff passed on `a8798e81`; delivery has the identical tree. The preceding 51 Rust SQL tests and earlier 31 native Python SQL tests are reused for unchanged coverage. Matching-runtime independent acceptance remains pending. Companion server change: https://github.com/lancedb/sophon/pull/10049. Refs ENT-3562. --- python/python/lancedb/_lancedb.pyi | 4 + python/python/lancedb/db.py | 13 +- python/python/lancedb/sql.py | 32 +++- python/python/tests/test_sql.py | 10 + python/src/sql.rs | 11 +- rust/lancedb/src/remote/sql.rs | 266 ++++++++++++++++++++------ rust/lancedb/src/remote/sql/stream.rs | 44 ++++- rust/lancedb/src/remote/sql_test.rs | 187 +++++++++++++++++- rust/lancedb/src/sql.rs | 30 ++- 9 files changed, 516 insertions(+), 81 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index f2d5285fa..801035391 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -501,6 +501,8 @@ class JobDescription: class SqlQuery: @property def id(self) -> UUID: ... + @property + def job_id(self) -> Optional[str]: ... async def describe(self) -> QueryDescription: ... async def reader(self) -> RecordBatchStream: ... async def cancel(self) -> None: ... @@ -509,6 +511,8 @@ class QueryDescription: @property def id(self) -> UUID: ... @property + def job_id(self) -> Optional[str]: ... + @property def status(self) -> str: ... @property def progress(self) -> Optional[float]: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index e73a44aec..a5d7aeb41 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1515,7 +1515,10 @@ class DBConnection(EnforceOverrides): This submits through :meth:`execute_query_async` and waits until the initial result stream is readable. It does not wait for the full query - to finish. + to finish. A statement that ran as a server-side SQL job exposes the + durable Job Registry id in the reader schema metadata under + ``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the + query handle itself is needed. """ return self.execute_query_async( query, @@ -1554,6 +1557,9 @@ class DBConnection(EnforceOverrides): 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. + Once a server-side SQL job exists, ``describe().job_id`` exposes its + durable Job Registry id while the query is still running. This is + separate from the connection-scoped query ``id``. LanceDB Embedded connections do not support SQL. """ @@ -4128,7 +4134,10 @@ class AsyncConnection(object): This submits through :meth:`execute_query_async` and waits until the initial result stream is readable. It does not wait for the full query - to finish. + to finish. A statement that ran as a server-side SQL job exposes the + durable Job Registry id in the reader schema metadata under + ``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the + query handle itself is needed. """ submitted = await self.execute_query_async( query, diff --git a/python/python/lancedb/sql.py b/python/python/lancedb/sql.py index 7498cddcc..5da4d35dd 100644 --- a/python/python/lancedb/sql.py +++ b/python/python/lancedb/sql.py @@ -104,6 +104,15 @@ class AsyncQuery: """The stable identifier scoped to the connection that submitted it.""" return self._inner.id + @property + def job_id(self) -> Optional[str]: + """The durable Job Registry id once the server reports this query as a job. + + A running query reports it after :meth:`describe` observes the latest + server status. This is separate from the connection-scoped ``id``. + """ + return self._inner.job_id + async def describe(self) -> QueryDescription: """Get a point-in-time description of the query.""" return await self._inner.describe() @@ -118,7 +127,12 @@ class AsyncQuery: return AsyncRecordBatchReader(await self._inner.reader()) async def cancel(self) -> None: - """Request cancellation of the query.""" + """Request cancellation of this query's Flight execution. + + A durable server-side job may reject this operation because its Flight + waiter cannot cancel the registry job. Use ``connection.cancel_job()`` + with ``job_id`` to cancel that job. + """ await self._inner.cancel() @@ -133,6 +147,15 @@ class Query: """The stable identifier scoped to the connection that submitted it.""" return self._inner.id + @property + def job_id(self) -> Optional[str]: + """The durable Job Registry id once the server reports this query as a job. + + A running query reports it after :meth:`describe` observes the latest + server status. This is separate from the connection-scoped ``id``. + """ + return self._inner.job_id + def describe(self) -> QueryDescription: """Get a point-in-time description of the query.""" return LOOP.run(self._inner.describe()) @@ -159,7 +182,12 @@ class Query: return pa.RecordBatchReader.from_batches(reader.schema, batches()) def cancel(self) -> None: - """Request cancellation of the query.""" + """Request cancellation of this query's Flight execution. + + A durable server-side job may reject this operation because its Flight + waiter cannot cancel the registry job. Use ``connection.cancel_job()`` + with ``job_id`` to cancel that job. + """ LOOP.run(self._inner.cancel()) diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index 0ed382d93..b4c555635 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -20,6 +20,7 @@ NIL_QUERY_ID = UUID(int=0) class FakeNativeQuery: id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef") + job_id = None async def reader(self): return pa.table({"value": [1, 2]}) @@ -68,6 +69,15 @@ def test_query_id_is_uuid(): assert Query(query).id == query.id +def test_query_job_id_is_optional_and_separate_from_query_id(): + native = FakeNativeQuery() + native.job_id = "j1-durable" + query = AsyncQuery(native) + assert query.id != query.job_id + assert query.job_id == "j1-durable" + assert Query(query).job_id == "j1-durable" + + def test_connection_serializes_sql_host_override(): endpoint = "grpc+tls://sql.example.com:10026" restored = lancedb.deserialize_conn( diff --git a/python/src/sql.rs b/python/src/sql.rs index 612521207..166cf0df5 100644 --- a/python/src/sql.rs +++ b/python/src/sql.rs @@ -31,6 +31,11 @@ impl Query { self.inner.id() } + #[getter] + pub fn job_id(&self) -> Option { + self.inner.job_id() + } + pub fn describe(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -63,6 +68,7 @@ impl Query { #[derive(Clone)] pub struct QueryDescription { id: Uuid, + job_id: Option, status: String, progress: Option, expires_at: Option>, @@ -72,8 +78,8 @@ pub struct QueryDescription { impl QueryDescription { fn __repr__(&self) -> String { format!( - "QueryDescription(id={:?}, status={:?}, progress={:?}, expires_at={:?})", - self.id, self.status, self.progress, self.expires_at + "QueryDescription(id={:?}, job_id={:?}, status={:?}, progress={:?}, expires_at={:?})", + self.id, self.job_id, self.status, self.progress, self.expires_at ) } } @@ -82,6 +88,7 @@ impl From for QueryDescription { fn from(description: lancedb::sql::QueryDescription) -> Self { Self { id: description.id, + job_id: description.job_id, status: description.status.to_string(), progress: description.progress, expires_at: description.expires_at, diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 724c813b3..0b87ff5a5 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -19,11 +19,12 @@ use arrow_flight::{ FlightDescriptor, FlightEndpoint, FlightInfo, PollInfo, }; use arrow_schema::{Schema, SchemaRef}; -use futures::TryStreamExt; +use futures::{StreamExt, TryStreamExt}; use http::header::{HeaderMap, HeaderName, HeaderValue}; use prost::Message; use serde::{Serialize, de::DeserializeOwned}; use tokio::sync::{Mutex, Notify, OnceCell, mpsc}; +use tonic::Request; use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}; use uuid::Uuid; @@ -87,6 +88,12 @@ struct ResultEndpointStream { stream: FlightRecordBatchStream, request_id: String, read_timeout: Duration, + job_id: Option, +} + +struct PollResult { + info: PollInfo, + job_id: Option, } struct PreparedSqlResult { @@ -233,10 +240,19 @@ impl SqlClient { materialized_view_job_handle, ) .await?; - let query = match opened.submission { + let stream::OpenedSubmission { + submission, + materialized_view_job_handle_supported, + job_id, + } = opened; + let query = match submission { Submission::Stream(response) => { - let query = - Arc::new(StreamingQuery::new(query_id, self.inner.clone(), response)); + let query = Arc::new(StreamingQuery::new( + query_id, + self.inner.clone(), + response, + job_id.clone(), + )); self.queries .insert(query_id, RegisteredQuery::Streamed(query.clone())); Query::new(Arc::new(StreamingQueryHandle::new(query))) @@ -247,6 +263,7 @@ impl SqlClient { self.inner.clone(), request.default_namespace_path, poll_info, + job_id, )?); self.queries .insert(query_id, RegisteredQuery::Polled(query.clone())); @@ -255,8 +272,7 @@ impl SqlClient { }; Ok(SubmittedQuery { query, - materialized_view_job_handle_supported: opened - .materialized_view_job_handle_supported, + materialized_view_job_handle_supported, }) }) .await @@ -283,6 +299,7 @@ impl SqlClient { self.inner.clone(), default_namespace_path.to_vec(), poll_info, + None, )?); self.queries .insert(query_id, RegisteredQuery::Polled(query.clone())); @@ -383,16 +400,29 @@ impl SqlClientInner { &self, descriptor: FlightDescriptor, default_namespace_path: &[String], - ) -> Result> { + ) -> Result> { let request_id = uuid::Uuid::new_v4().to_string(); - let mut client = self - .client_with_headers(default_namespace_path, &request_id) - .await - .map_err(|err| sql_error(&request_id, err))?; - match tokio::time::timeout(STATUS_POLL_TIMEOUT, client.poll_flight_info(descriptor)).await { - Ok(result) => result - .map(Some) - .map_err(|err| sql_flight_error(&request_id, &err)), + let connection = self.connection(&request_id).await?; + let headers = self.headers(default_namespace_path, &request_id).await?; + let metadata = client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + let mut request = Request::new(descriptor); + *request.metadata_mut() = metadata; + match tokio::time::timeout( + STATUS_POLL_TIMEOUT, + connection.client.clone().poll_flight_info(request), + ) + .await + { + Ok(Ok(response)) => { + let job_id = sql_job_id_from_metadata(response.metadata()); + Ok(Some(PollResult { + info: response.into_inner(), + job_id, + })) + } + Ok(Err(status)) => Err(sql_status_error(&request_id, &status)), Err(_) => Ok(None), } } @@ -401,7 +431,7 @@ impl SqlClientInner { &self, descriptor: FlightDescriptor, default_namespace_path: &[String], - ) -> Result { + ) -> Result { let read_timeout = resolve_timeout( self.client_config.timeout_config.read_timeout, "LANCE_CLIENT_READ_TIMEOUT", @@ -413,12 +443,18 @@ impl SqlClientInner { loop { let started = Instant::now(); let request_id = uuid::Uuid::new_v4().to_string(); - let mut client = self - .client_with_headers(default_namespace_path, &request_id) - .await?; - let result = - tokio::time::timeout(read_timeout, client.poll_flight_info(descriptor.clone())) - .await; + let connection = self.connection(&request_id).await?; + let headers = self.headers(default_namespace_path, &request_id).await?; + let metadata = client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + let mut request = Request::new(descriptor.clone()); + *request.metadata_mut() = metadata; + let result = tokio::time::timeout( + read_timeout, + connection.client.clone().poll_flight_info(request), + ) + .await; let poll_info = match result { Err(_) if retry_count < retry_config.read_retries => { retry_count += 1; @@ -426,7 +462,7 @@ impl SqlClientInner { continue; } Err(_) => return Err(sql_error(&request_id, "SQL query poll timed out")), - Ok(Err(FlightError::Tonic(status))) + Ok(Err(status)) if matches!( status.code(), tonic::Code::DeadlineExceeded | tonic::Code::Unavailable @@ -436,8 +472,14 @@ impl SqlClientInner { tokio::time::sleep(poll_retry_delay(&retry_config, retry_count)).await; continue; } - Ok(Err(error)) => return Err(sql_flight_error(&request_id, &error)), - Ok(Ok(poll_info)) => poll_info, + Ok(Err(status)) => return Err(sql_status_error(&request_id, &status)), + Ok(Ok(response)) => { + let job_id = sql_job_id_from_metadata(response.metadata()); + PollResult { + info: response.into_inner(), + job_id, + } + } }; if let Some(delay) = MIN_POLL_INTERVAL.checked_sub(started.elapsed()) { tokio::time::sleep(delay).await; @@ -461,17 +503,27 @@ impl SqlClientInner { let ticket = endpoint.ticket.ok_or_else(|| { sql_error(&request_id, "SQL result endpoint did not include a ticket") })?; - let mut endpoint_client = self - .client_with_headers(default_namespace_path, &request_id) - .await?; - let stream = tokio::time::timeout(read_timeout, endpoint_client.do_get(ticket)) - .await - .map_err(|_| sql_error(&request_id, "SQL result fetch timed out"))? - .map_err(|err| sql_flight_error(&request_id, &err))?; + let connection = self.connection(&request_id).await?; + let headers = self.headers(default_namespace_path, &request_id).await?; + let metadata = client_with_headers(connection.client.clone(), &headers)? + .metadata() + .clone(); + let mut request = Request::new(ticket); + *request.metadata_mut() = metadata; + let response = + tokio::time::timeout(read_timeout, connection.client.clone().do_get(request)) + .await + .map_err(|_| sql_error(&request_id, "SQL result fetch timed out"))? + .map_err(|status| sql_status_error(&request_id, &status))?; + let job_id = sql_job_id_from_metadata(response.metadata()); + let stream = response + .into_inner() + .map_err(|status| FlightError::Tonic(Box::new(status))); Ok(ResultEndpointStream { - stream, + stream: FlightRecordBatchStream::new_from_flight_data(stream), request_id, read_timeout, + job_id, }) } @@ -547,6 +599,7 @@ impl SqlClientInner { Ok(CancelOutcome::Status(status)) } + #[cfg(test)] async fn client_with_headers( &self, default_namespace_path: &[String], @@ -684,6 +737,7 @@ impl QueryRegistry { struct RemoteQuery { id: Uuid, + job_id: StdMutex>, client: Arc, default_namespace_path: Vec, state: Mutex, @@ -713,6 +767,7 @@ impl RemoteQuery { client: Arc, default_namespace_path: Vec, poll_info: PollInfo, + job_id: Option, ) -> Result { let expires_at = query_expiration(&poll_info)?; let terminal_at = OnceLock::new(); @@ -724,6 +779,7 @@ impl RemoteQuery { }; Ok(Self { id, + job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())), client, default_namespace_path, state: Mutex::new(poll_info), @@ -850,6 +906,44 @@ impl RemoteQuery { *self.last_accessed.lock().unwrap() = Instant::now(); } + fn job_id(&self) -> Option { + self.job_id.lock().unwrap().clone() + } + + fn observe_job_id(&self, job_id: Option<&str>) -> Result<()> { + let Some(job_id) = job_id.filter(|job_id| !job_id.is_empty()) else { + return Ok(()); + }; + let mut current = self.job_id.lock().unwrap(); + match current.as_deref() { + None => *current = Some(job_id.to_string()), + Some(existing) if existing == job_id => {} + Some(existing) => { + return Err(Error::Runtime { + message: format!( + "SQL query changed durable job identity from {existing} to {job_id}" + ), + }); + } + } + Ok(()) + } + + fn observe_error_job_id(&self, error: &Error) -> Result<()> { + self.observe_job_id( + error + .remote_error_metadata() + .and_then(|metadata| metadata.job_id.as_deref()), + ) + } + + fn record_error_job_id(&self, result: Result) -> Result { + if let Err(error) = &result { + self.observe_error_job_id(error)?; + } + result + } + async fn poll_next_state(&self, descriptor: FlightDescriptor) -> Result { self.touch(); if self.is_cancellation_requested() { @@ -874,10 +968,11 @@ impl RemoteQuery { Err(_) if self.is_cancellation_requested() => { return Err(self.cancelled_error()); } - result => result?, + result => self.record_error_job_id(result)?, }, }; - self.update_state(&descriptor, updated).await + self.observe_job_id(updated.job_id.as_deref())?; + self.update_state(&descriptor, updated.info).await } async fn prepare_result(self: &Arc) -> Result { @@ -894,8 +989,9 @@ impl RemoteQuery { result = self.client.open_result_endpoint( endpoint, &self.default_namespace_path, - ) => result?, + ) => self.record_error_job_id(result)?, }; + self.observe_job_id(endpoint_stream.job_id.as_deref())?; let buffered_batch = tokio::select! { biased; _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), @@ -908,6 +1004,7 @@ impl RemoteQuery { .ok_or_else(|| Error::Runtime { message: "SQL result endpoint did not include a schema".to_string(), })?; + self.observe_job_id(sql_job_id_from_schema(&schema).as_deref())?; return Ok(PreparedSqlResult { schema, next_endpoint: 1, @@ -925,6 +1022,7 @@ impl RemoteQuery { .map_err(|err| sql_error(&request_id, err))?, ) }; + self.observe_job_id(sql_job_id_from_schema(&schema).as_deref())?; return Ok(PreparedSqlResult { schema, next_endpoint: 0, @@ -1001,7 +1099,7 @@ impl RemoteQuery { result = self.client.open_result_endpoint( endpoint, &self.default_namespace_path, - ) => result?, + ) => self.record_error_job_id(result)?, }); continue; } @@ -1067,24 +1165,22 @@ impl RemoteQuery { self.touch(); if self.is_cancellation_requested() { let state = self.state.lock().await.clone(); - return query_description(self.id, &state, self.lifecycle()); + return query_description(self.id, self.job_id(), &state, self.lifecycle()); } let state = self.state.lock().await.clone(); let state = if let Some(descriptor) = state.flight_descriptor.clone() { let poll_guard = tokio::select! { biased; - _ = self.wait_for_cancellation() => return query_description( - self.id, - &state, - self.lifecycle(), - ), + _ = self.wait_for_cancellation() => { + return query_description(self.id, self.job_id(), &state, self.lifecycle()) + } poll_guard = tokio::time::timeout( STATUS_POLL_TIMEOUT, self.poll_gate.lock(), ) => poll_guard, }; let Ok(_poll_guard) = poll_guard else { - return query_description(self.id, &state, self.lifecycle()); + return query_description(self.id, self.job_id(), &state, self.lifecycle()); }; let latest = self.state.lock().await.clone(); if latest.flight_descriptor.as_ref() != Some(&descriptor) { @@ -1092,25 +1188,28 @@ impl RemoteQuery { } else { let updated = tokio::select! { biased; - _ = self.wait_for_cancellation() => return query_description( - self.id, - &latest, - self.lifecycle(), - ), + _ = self.wait_for_cancellation() => { + return query_description(self.id, self.job_id(), &latest, self.lifecycle()) + } result = self.client.poll_status( descriptor.clone(), &self.default_namespace_path, ) => match result { - Err(_) if self.is_cancellation_requested() => return query_description( - self.id, - &latest, - self.lifecycle(), - ), - result => result?, + Err(error) if self.is_cancellation_requested() => { + self.observe_error_job_id(&error)?; + return query_description( + self.id, + self.job_id(), + &latest, + self.lifecycle(), + ); + } + result => self.record_error_job_id(result)?, }, }; if let Some(updated) = updated { - self.update_state(&descriptor, updated).await? + self.observe_job_id(updated.job_id.as_deref())?; + self.update_state(&descriptor, updated.info).await? } else { latest } @@ -1118,7 +1217,7 @@ impl RemoteQuery { } else { state }; - query_description(self.id, &state, self.lifecycle()) + query_description(self.id, self.job_id(), &state, self.lifecycle()) } async fn cancel(&self) -> Result<()> { @@ -1214,11 +1313,15 @@ impl RemoteQuery { if self.state.lock().await.flight_descriptor.as_ref() != Some(&descriptor) { continue; } - let updated = self.client.poll_continuation( + let updated = self.record_error_job_id( + self.client.poll_continuation( descriptor.clone(), &self.default_namespace_path, - ).await?; - self.update_state(&descriptor, updated).await?; + ) + .await, + )?; + self.observe_job_id(updated.job_id.as_deref())?; + self.update_state(&descriptor, updated.info).await?; } _ = notified => {} } @@ -1247,6 +1350,10 @@ impl QueryHandle for RemoteQueryHandle { self.query.id } + fn job_id(&self) -> Option { + self.query.job_id() + } + async fn describe(&self) -> Result { self.query.describe().await } @@ -1286,7 +1393,12 @@ impl QueryHandle for RemoteQueryHandle { receiver.recv().await.map(|item| (item, receiver)) }); result_start.commit(); - Ok(Box::pin(SimpleRecordBatchStream::new(stream, schema))) + let stream: SendableRecordBatchStream = + Box::pin(SimpleRecordBatchStream::new(stream, schema)); + Ok(match self.job_id() { + Some(job_id) => attach_sql_job_id(stream, &job_id), + None => stream, + }) } async fn cancel(&self) -> Result<()> { @@ -1296,12 +1408,14 @@ impl QueryHandle for RemoteQueryHandle { fn query_description( id: Uuid, + job_id: Option, poll_info: &PollInfo, lifecycle: QueryLifecycle, ) -> Result { let expires_at = query_expiration(poll_info)?; Ok(QueryDescription { id, + job_id, status: match lifecycle { QueryLifecycle::Cancelling => QueryStatus::Cancelling, QueryLifecycle::Cancelled => QueryStatus::Cancelled, @@ -1317,6 +1431,36 @@ fn query_description( }) } +fn sql_job_id_from_metadata(metadata: &tonic::metadata::MetadataMap) -> Option { + metadata + .get(SQL_JOB_ID_METADATA_KEY) + .and_then(|value| value.to_str().ok()) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +fn sql_job_id_from_schema(schema: &Schema) -> Option { + schema + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .filter(|value| !value.is_empty()) + .cloned() +} + +pub(super) fn attach_sql_job_id( + stream: SendableRecordBatchStream, + job_id: &str, +) -> SendableRecordBatchStream { + let mut metadata = stream.schema().metadata().clone(); + metadata.insert(SQL_JOB_ID_METADATA_KEY.to_string(), job_id.to_string()); + let schema = Arc::new(stream.schema().as_ref().clone().with_metadata(metadata)); + let batch_schema = schema.clone(); + let stream = stream.map(move |batch| { + batch.and_then(|batch| batch.with_schema(batch_schema.clone()).map_err(Error::from)) + }); + Box::pin(SimpleRecordBatchStream::new(stream, schema)) +} + fn query_expiration(poll_info: &PollInfo) -> Result>> { poll_info .expiration_time diff --git a/rust/lancedb/src/remote/sql/stream.rs b/rust/lancedb/src/remote/sql/stream.rs index 420eecd15..16155bf7c 100644 --- a/rust/lancedb/src/remote/sql/stream.rs +++ b/rust/lancedb/src/remote/sql/stream.rs @@ -55,6 +55,7 @@ pub(super) struct StreamingQuery { cancelled: Notify, terminal_at: OnceLock, last_accessed: StdMutex, + job_id: StdMutex>, } struct PreparedStream { @@ -125,6 +126,7 @@ pub(super) enum Submission { pub(super) struct OpenedSubmission { pub(super) submission: Submission, pub(super) materialized_view_job_handle_supported: bool, + pub(super) job_id: Option, } impl StreamingQuery { @@ -190,6 +192,7 @@ impl StreamingQuery { } .map_err(|_| sql_error(&request_id, "SQL query submission timed out"))? .map_err(|error| sql_status_error(&request_id, &error))?; + let response_job_id = super::sql_job_id_from_metadata(response.metadata()); let negotiated = response .metadata() .get(PROTOCOL_HEADER) @@ -233,6 +236,7 @@ impl StreamingQuery { return Ok(OpenedSubmission { submission: Submission::Deferred(info), materialized_view_job_handle_supported, + job_id: response_job_id, }); } } @@ -245,8 +249,10 @@ impl StreamingQuery { stream, request_id, read_timeout, + job_id: None, }), materialized_view_job_handle_supported: false, + job_id: response_job_id, }) } @@ -254,6 +260,7 @@ impl StreamingQuery { id: Uuid, client: Arc, response: ResultEndpointStream, + job_id: Option, ) -> Self { Self { id, @@ -263,6 +270,7 @@ impl StreamingQuery { cancelled: Notify::new(), terminal_at: OnceLock::new(), last_accessed: StdMutex::new(Instant::now()), + job_id: StdMutex::new(job_id.filter(|job_id| !job_id.is_empty())), } } @@ -291,6 +299,7 @@ impl StreamingQuery { }; Ok(QueryDescription { id: self.id, + job_id: self.job_id(), status, progress: (status == QueryStatus::Finished).then_some(1.0), expires_at: None, @@ -326,6 +335,29 @@ impl StreamingQuery { *self.lifecycle.lock().unwrap() == Lifecycle::Cancelled } + fn job_id(&self) -> Option { + self.job_id.lock().unwrap().clone() + } + + fn observe_job_id(&self, job_id: Option<&str>) -> Result<()> { + let Some(job_id) = job_id.filter(|job_id| !job_id.is_empty()) else { + return Ok(()); + }; + let mut current = self.job_id.lock().unwrap(); + match current.as_deref() { + None => *current = Some(job_id.to_string()), + Some(existing) if existing == job_id => {} + Some(existing) => { + return Err(Error::Runtime { + message: format!( + "SQL query changed durable job identity from {existing} to {job_id}" + ), + }); + } + } + Ok(()) + } + fn cancelled_error(&self) -> Error { Error::JobCancelled { job_id: Some(self.id.to_string()), @@ -373,6 +405,7 @@ impl StreamingQuery { .ok_or_else(|| Error::Runtime { message: "SQL result stream did not include a schema".to_string(), })?; + self.observe_job_id(super::sql_job_id_from_schema(&schema).as_deref())?; if first.is_none() { self.settle(Lifecycle::Finished); } @@ -476,6 +509,10 @@ impl QueryHandle for StreamingQueryHandle { self.query.id } + fn job_id(&self) -> Option { + self.query.job_id() + } + async fn describe(&self) -> Result { self.query.describe() } @@ -526,7 +563,12 @@ impl QueryHandle for StreamingQueryHandle { receiver.recv().await.map(|item| (item, receiver)) }); result_start.commit(); - Ok(Box::pin(SimpleRecordBatchStream::new(stream, schema))) + let stream: SendableRecordBatchStream = + Box::pin(SimpleRecordBatchStream::new(stream, schema)); + Ok(match self.job_id() { + Some(job_id) => super::attach_sql_job_id(stream, &job_id), + None => stream, + }) } async fn cancel(&self) -> Result<()> { diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 65d08c984..8ac08f10c 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -160,8 +160,17 @@ impl TestSqlService { return Response::new(rows); } let poll_info = self.defer.then(|| { - let mut info = FlightInfo::new() - .with_endpoint(FlightEndpoint::new().with_ticket(Ticket::new(query.to_string()))); + let mut info = FlightInfo::new(); + if !query.starts_with("SELECT durable job") { + info = info.with_endpoint( + FlightEndpoint::new().with_ticket(Ticket::new(query.to_string())), + ); + } + if query.starts_with("SELECT durable job") { + info = info + .try_with_schema(&self.result_for_query(query).schema()) + .unwrap(); + } if self.materialized_view_job_handle_supported { info.app_metadata = b"early-v1".to_vec().into(); } @@ -198,6 +207,13 @@ impl TestSqlService { response .metadata_mut() .insert(PROTOCOL_HEADER, PROTOCOL_VERSION.parse().unwrap()); + if query.starts_with("SELECT direct durable job") { + let job_id = query.rsplit(' ').next().unwrap(); + response.metadata_mut().insert( + SQL_JOB_ID_METADATA_KEY, + format!("job-{job_id}").parse().unwrap(), + ); + } response } } @@ -351,7 +367,14 @@ impl FlightService for TestSqlService { .insert("x-lancedb-sql-job-id", "job-1".parse().unwrap()); return Err(status); } - let complete = if query == "SELECT no info" { + if query == "SELECT durable job failure" && stage == 1 { + let mut status = Status::internal("durable SQL job failed"); + status + .metadata_mut() + .insert("x-lancedb-sql-job-id", "job-1".parse().unwrap()); + return Err(status); + } + let complete = if query == "SELECT no info" || query.starts_with("SELECT durable job") { stage >= 2 } else { stage >= 1 @@ -362,11 +385,14 @@ impl FlightService for TestSqlService { } else { query.clone() }; - let mut info = FlightInfo::new().with_endpoint( - FlightEndpoint::new() - .with_ticket(Ticket::new(first_ticket)) - .with_location("grpc://127.0.0.1:1"), - ); + let mut info = FlightInfo::new(); + if !(query.starts_with("SELECT durable job") && !complete) { + info = info.with_endpoint( + FlightEndpoint::new() + .with_ticket(Ticket::new(first_ticket)) + .with_location("grpc://127.0.0.1:1"), + ); + } if query == "SELECT incremental" && stage > 0 { info = info.with_endpoint( FlightEndpoint::new() @@ -378,13 +404,21 @@ impl FlightService for TestSqlService { let schema = self.result_for_query(&query).schema(); info = info.try_with_schema(&schema).unwrap(); } - Ok(Response::new(PollInfo { + let mut response = Response::new(PollInfo { info: (query != "SELECT no info" || stage > 0).then_some(info), flight_descriptor: (!complete) .then(|| FlightDescriptor::new_cmd(format!("poll:{}:{query}", stage + 1))), progress: Some(if complete { 1.0 } else { 0.25 }), expiration_time: None, - })) + }); + if query.starts_with("SELECT durable job") && stage > 0 { + let job_id = query.rsplit(' ').next().unwrap(); + response.metadata_mut().insert( + SQL_JOB_ID_METADATA_KEY, + format!("job-{job_id}").parse().unwrap(), + ); + } + Ok(response) } async fn get_schema( @@ -730,6 +764,106 @@ async fn parameters_travel_on_one_exchange() { assert_eq!(headers[0].api_key, "test-key"); } +#[tokio::test] +async fn running_job_backed_queries_expose_their_own_durable_job_id() { + let service = TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }; + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + + let first = client + .execute(ExecuteQueryRequest::new("SELECT durable job first")) + .await + .unwrap(); + let second = client + .execute(ExecuteQueryRequest::new("SELECT durable job second")) + .await + .unwrap(); + assert_eq!(first.job_id(), None); + assert_eq!(second.job_id(), None); + + let first_description = first.describe().await.unwrap(); + let second_description = second.describe().await.unwrap(); + assert_eq!(first_description.status, QueryStatus::Running); + assert_eq!(first_description.job_id.as_deref(), Some("job-first")); + assert_eq!(second_description.status, QueryStatus::Running); + assert_eq!(second_description.job_id.as_deref(), Some("job-second")); + assert_ne!(first.id(), second.id()); + assert_ne!(first_description.job_id, second_description.job_id); + + let reader = first.reader().await.unwrap(); + assert_eq!( + reader + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-first") + ); + assert_eq!(first.job_id().as_deref(), Some("job-first")); + assert_eq!(second.job_id().as_deref(), Some("job-second")); + + let reader_only = client + .execute(ExecuteQueryRequest::new("SELECT durable job reader-only")) + .await + .unwrap(); + let reader_only_result = reader_only.reader().await.unwrap(); + assert_eq!( + reader_only_result + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-reader-only") + ); + + let ordinary = client + .execute(ExecuteQueryRequest::new("SELECT ordinary")) + .await + .unwrap(); + assert_eq!(ordinary.describe().await.unwrap().job_id, None); +} + +#[tokio::test] +async fn direct_job_backed_queries_expose_the_initial_response_job_id() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let (client, _shutdown) = start_sql_service(service, ClientConfig::default()).await; + let query = client + .execute(ExecuteQueryRequest::new("SELECT direct durable job direct")) + .await + .unwrap(); + + assert_eq!(query.job_id().as_deref(), Some("job-direct")); + assert_eq!( + query.describe().await.unwrap().job_id.as_deref(), + Some("job-direct") + ); + let reader = query.reader().await.unwrap(); + assert_eq!( + reader + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-direct") + ); + let batches = reader.try_collect::>().await.unwrap(); + assert_eq!(batches.len(), 1); + assert_eq!( + batches[0] + .schema() + .metadata() + .get(SQL_JOB_ID_METADATA_KEY) + .map(String::as_str), + Some("job-direct") + ); +} + /// The server plans before it answers, so a refusal is the submission's. #[tokio::test] async fn a_refused_statement_fails_its_submission() { @@ -1213,6 +1347,35 @@ async fn function_failure_preserves_the_isolated_sql_job_id() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn fast_durable_job_failure_exposes_the_same_job_id_on_the_query_handle() { + let (client, shutdown) = start_sql_service( + TestSqlService { + adaptive: true, + defer: true, + ..Default::default() + }, + ClientConfig::default(), + ) + .await; + let query = client + .execute(ExecuteQueryRequest { + query: "SELECT durable job failure".into(), + default_namespace_path: vec![], + parameters: None, + }) + .await + .unwrap(); + assert_eq!(query.job_id(), None); + + let Err(Error::JobFailed { job_id, .. }) = collect_result(&query).await else { + panic!("a failed durable query must remain a structured JobFailed error"); + }; + assert_eq!(job_id.as_deref(), Some("job-1")); + assert_eq!(query.job_id().as_deref(), Some("job-1")); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn rejected_job_cancellation_does_not_abort_sql_completion() { let service = TestSqlService { @@ -1843,6 +2006,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { flight_descriptor: Some(FlightDescriptor::new_cmd("restored")), ..Default::default() }, + None, ) .unwrap(), ); @@ -1975,6 +2139,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { flight_descriptor: Some(FlightDescriptor::new_cmd(descriptor)), ..Default::default() }, + None, ) .unwrap(), ); @@ -1996,6 +2161,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { expiration_time: Some(Default::default()), ..Default::default() }, + None, ) .unwrap(), ); @@ -2012,6 +2178,7 @@ async fn submits_polls_fetches_cancels_and_reuses_client() { flight_descriptor: Some(FlightDescriptor::new_cmd("stale")), ..Default::default() }, + None, ) .unwrap(), ); diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs index 5c01fe898..bda5df085 100644 --- a/rust/lancedb/src/sql.rs +++ b/rust/lancedb/src/sql.rs @@ -44,6 +44,10 @@ impl fmt::Display for QueryStatus { pub struct QueryDescription { /// The stable, connection-scoped identifier assigned when the query was submitted. pub id: Uuid, + /// The durable Job Registry identifier for a server-side SQL job, when the + /// submitted statement ran as one. This identifier can be passed to + /// `open_job`; `id` remains connection-scoped. + pub job_id: Option, /// The server-visible lifecycle state. pub status: QueryStatus, /// Server-reported completion progress, when known. Values are in `[0.0, 1.0]`, @@ -56,6 +60,9 @@ pub struct QueryDescription { #[async_trait] pub(crate) trait QueryHandle: Send + Sync { fn id(&self) -> Uuid; + fn job_id(&self) -> Option { + None + } async fn describe(&self) -> Result; async fn reader(&self) -> Result; async fn cancel(&self) -> Result<()>; @@ -68,8 +75,9 @@ pub(crate) trait QueryHandle: Send + Sync { /// 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. +/// [`Self::id`] is scoped to the connection that submitted the query. When the +/// server runs the statement as a SQL job, [`Self::job_id`] exposes the durable +/// Job Registry identifier accepted by `open_job`. pub struct Query { handle: Arc, } @@ -79,6 +87,7 @@ impl std::fmt::Debug for Query { formatter .debug_struct("Query") .field("id", &self.id()) + .field("job_id", &self.job_id()) .finish() } } @@ -94,6 +103,16 @@ impl Query { self.handle.id() } + /// Return the durable Job Registry identifier when the server has reported + /// one for this query. + /// + /// A running query may report it after [`Self::describe`] observes the + /// server's latest status. The connection-scoped [`Self::id`] remains a + /// separate identifier. + pub fn job_id(&self) -> Option { + self.handle.job_id() + } + /// Get a point-in-time description of the query. /// /// Directly streamed queries stay [`QueryStatus::Running`] until the result @@ -115,7 +134,12 @@ impl Query { self.handle.reader().await } - /// Request cancellation of the query. + /// Request cancellation of this query's Flight execution. + /// + /// For a durable server-side SQL job, the operation may return + /// [`Error::NotSupported`] because the Flight waiter cannot cancel the + /// registry job. Use [`Connection::cancel_job`](crate::Connection::cancel_job) + /// with [`Self::job_id`] to cancel that job. pub async fn cancel(&self) -> Result<()> { self.handle.cancel().await } From f7648d4a22c7128aeb391f556331ee981dd0d332 Mon Sep 17 00:00:00 2001 From: BHAWESHBHASKAR <90614484+BHAWESHBHASKAR@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:28:39 +0530 Subject: [PATCH 055/203] feat(python): expose the ZoneMap scalar index (#4816) --- python/python/lancedb/_lancedb.pyi | 3 +++ python/python/lancedb/index.py | 17 +++++++++++++++++ python/python/lancedb/table.py | 12 +++++++++--- python/python/tests/test_index.py | 24 ++++++++++++++++++++++++ python/src/index.rs | 4 +++- 5 files changed, 56 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 801035391..aec0f7fb1 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -25,6 +25,7 @@ from .index import ( LabelList, Fm, NGram, + ZoneMap, HnswPq, HnswSq, HnswFlat, @@ -553,6 +554,7 @@ class Table: LabelList, Fm, NGram, + ZoneMap, FTS, ], replace: Optional[bool], @@ -576,6 +578,7 @@ class Table: LabelList, Fm, NGram, + ZoneMap, FTS, ], replace: Optional[bool], diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index 9f53f203b..f1626c540 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -130,6 +130,23 @@ class NGram: pass +@dataclass +class ZoneMap: + """Describe a ZoneMap index configuration. + + A `ZoneMap` index stores compact min and max summaries for contiguous + ranges (zones) of rows. During a scan it skips any zone whose summary + cannot satisfy the predicate, so it accelerates range and equality + filters such as `col > 10`, `col BETWEEN a AND b`, and `col = x`, + without changing the results. + + It suits large numeric or temporal columns whose values are correlated + with row order (for example `timestamp`, `price`, `id`). + """ + + pass + + @dataclass class FTS: """Describe a FTS index configuration. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 06bace5b8..bf13cc7bd 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -75,6 +75,7 @@ from .index import ( LabelList, Fm, NGram, + ZoneMap, HnswPq, HnswSq, HnswFlat, @@ -300,6 +301,7 @@ IndexConfigType = Union[ LabelList, Fm, NGram, + ZoneMap, FTS, ] @@ -1907,7 +1909,7 @@ class Table(ABC): 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, NGram, FTS. + BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. wait_timeout : timedelta, optional @@ -4285,7 +4287,7 @@ class LanceTable(Table): 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, NGram, FTS. + BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. wait_timeout : timedelta, optional @@ -6662,6 +6664,7 @@ class AsyncTable: LabelList, Fm, NGram, + ZoneMap, FTS, ] ] = None, @@ -6738,12 +6741,13 @@ class AsyncTable: LabelList, Fm, NGram, + ZoneMap, FTS, ), ): raise TypeError( "config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq," - " BTree, Bitmap, LabelList, Fm, NGram, or FTS, but got " + " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, or FTS, but got " + str(type(config)) ) try: @@ -6782,6 +6786,7 @@ class AsyncTable: LabelList, Fm, NGram, + ZoneMap, FTS, ] ] = None, @@ -8741,6 +8746,7 @@ class IndexStatistics: "BITMAP", "LABEL_LIST", "NGRAM", + "ZONEMAP", ] distance_type: Optional[Literal["l2", "cosine", "dot"]] = None num_indices: Optional[int] = None diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 1b252f993..738a791ad 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -22,6 +22,7 @@ from lancedb.index import ( LabelList, Fm, NGram, + ZoneMap, HnswPq, HnswSq, HnswFlat, @@ -279,6 +280,28 @@ async def test_create_ngram_index(db_async): assert "ScalarIndexQuery" in plan +@pytest.mark.asyncio +async def test_create_zonemap_index(db_async): + # ZoneMap indexes accelerate range and equality filters on ordered columns. + data = pa.table( + { + "id": list(range(100)), + "value": list(range(100)), + } + ) + table = await db_async.create_table("zonemap_table", data) + await table.create_index("value", config=ZoneMap()) + + indices = await table.list_indices() + assert len(indices) == 1 + assert indices[0].index_type == "ZoneMap" + assert indices[0].columns == ["value"] + + # The index narrows a range scan without changing its results. + result = await table.query().where("value >= 90").to_arrow() + assert sorted(result["id"].to_pylist()) == list(range(90, 100)) + + @pytest.mark.asyncio async def test_create_bitmap_index(some_table: AsyncTable): await some_table.create_index("id", config=Bitmap()) @@ -591,6 +614,7 @@ def test_index_statistics_index_type_lists_all_supported_values(): "BITMAP", "LABEL_LIST", "NGRAM", + "ZONEMAP", } assert ( diff --git a/python/src/index.rs b/python/src/index.rs index 3ec03b6fd..039440211 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -10,6 +10,7 @@ use lancedb::index::{ Index as LanceDbIndex, scalar::{ BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder, + ZoneMapIndexBuilder, }, }; use pyo3::IntoPyObject; @@ -117,6 +118,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult Ok(LanceDbIndex::LabelList(Default::default())), "Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())), "NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())), + "ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())), "FTS" => { let params = source.extract::()?; let code_options = CodeAnalyzerOptions { @@ -291,7 +293,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult Err(PyValueError::new_err(format!( - "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", + "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", not_supported ))), } From faa5987b3308021f37d083084cf79455740f49f7 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 10 Nov 2026 08:22:52 -0800 Subject: [PATCH 056/203] fix(python): name unsupported Function globals in capture errors (#4938) Function source packaging rejected unsupported global values without identifying the variable or explaining the supported captures. Include the global name even for a nested tuple failure, describe the supported literal values and remedy, and document the capture boundary. Adds function/class regression cases for Arrow types, nested tuples, dictionaries and non-finite floats, plus a supported nested literal control. New serialization support remains separate. Formatting applied; no local builds or tests were run. CI will execute the regression coverage. --- python/python/lancedb/functions.py | 17 +++--- .../python/tests/test_function_packaging.py | 54 +++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index fe5a1a45a..eed4050a8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1428,19 +1428,21 @@ def _is_function_decorator(node: ast.expr) -> bool: ) -def _literal_source(value: Any) -> str: +def _literal_source(value: Any, name: str) -> str: if value is None or type(value) in (bool, int, str, bytes): return repr(value) if type(value) is float and math.isfinite(value): return repr(value) if type(value) is tuple: - children = ", ".join(_literal_source(child) for child in value) + children = ", ".join(_literal_source(child, name) for child in value) if len(value) == 1: children += "," return f"({children})" raise TypeError( "Function source references an unsupported global value of type " - f"{type(value).__name__}" + f"{type(value).__name__} in {name!r}. Only None, bool, int, str, bytes, " + "finite float, and tuples of these literals can be captured. " + "Define this value inside the function or class body instead." ) @@ -1875,7 +1877,7 @@ class _SourcePackager: if imported is value: self._require_importable(module_name) return f"from {module_name} import {qualname} as {name}" - return f"{name} = {_literal_source(value)}" + return f"{name} = {_literal_source(value, name)}" def _require_importable(self, module_name: str) -> None: """Warn about an import the Function's environment may not be able to @@ -2486,8 +2488,8 @@ def function( - modules, and classes and functions importable from an installed package, become imports; the package must be declared in ``pip`` or ``conda``; - - literals (``None``, booleans, numbers, strings, bytes, tuples of them) - are inlined; + - literals (``None``, ``bool``, ``int``, ``str``, ``bytes``, finite + ``float``, and tuples containing only these literals) are inlined; - functions and classes defined in ``__main__``, such as notebook cells, are packaged by source, together with what they reference; - modules and packages listed in ``code`` are shipped as Python source and @@ -2505,6 +2507,9 @@ def function( image. Warnings follow normal Python warning filters and may be promoted to errors. Declare every third-party import in ``pip`` or ``conda`` even when it happens to be installed on the registration host. + Other global values, including Arrow types and schemas, lists, dictionaries, + sets, and NumPy arrays, cannot be captured as literals. Define them inside + the function or class body instead. Closures, lambdas, nested definitions, mutable module-level objects, code that reaches the module namespace another way (``globals()``/``eval``, ``sys.modules``, ``builtins``), and a diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 050aeb3ea..83dfdaeb3 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -127,6 +127,60 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.parametrize("kind", ["function", "class"]) +@pytest.mark.parametrize( + ("global_value", "value_type"), + [ + ("pa.struct([('label', pa.string())])", "StructType"), + ("(1, (pa.int64(),))", "DataType"), + ("{'label': 1}", "dict"), + ("float('inf')", "float"), + ], +) +def test_unsupported_global_names_value_and_remedy( + helper_package, kind, global_value, value_type +): + definition = ( + "class uses_global:\n" + " def __call__(self, value: int) -> int:\n" + " return value if CAPTURED_VALUE else 0\n" + if kind == "class" + else "def uses_global(value: int) -> int:\n" + " return value if CAPTURED_VALUE else 0\n" + ) + module = helper_package( + "fx_unsupported_global", + { + "__init__.py": f"import pyarrow as pa\nCAPTURED_VALUE = {global_value}\n" + + definition + }, + ) + with pytest.raises(TypeError) as error: + function(module.uses_global) + message = str(error.value) + assert "CAPTURED_VALUE" in message + assert value_type in message + assert "finite float" in message + assert "inside the function or class body" in message + + +def test_supported_nested_literal_global_still_packages(helper_package): + module = helper_package( + "fx_literal_global", + { + "__init__.py": "CAPTURED_VALUE = (None, True, 1, 'label', " + "b'bytes', (1.5,))\n" + "def uses_global(value: int) -> int:\n" + " return value + CAPTURED_VALUE[2]\n" + }, + ) + definition = function(module.uses_global) + namespace = {} + exec(compile(artifact(definition), "user_function.py", "exec"), namespace) + assert namespace["uses_global"](3) == 4 + assert namespace["CAPTURED_VALUE"] == module.CAPTURED_VALUE + + @pytest.mark.parametrize("annotation", ["Array", "RecordBatch"]) @pytest.mark.parametrize("kind", ["function", "class"]) def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package): From 3bfa02337596bab28fc2aa6e2d2a19ef76cb0de1 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 10 Nov 2026 08:23:13 -0800 Subject: [PATCH 057/203] fix(python): bound Job and AsyncJob payload previews (#4939) Printing a Job or a bound status method could dump hundreds of lines of serialized Function initialization. Bound nested payload previews in both sync and async handles while preserving cached identity, state, failure and result information. Full spec/result values remain available through their properties, with no additional backend calls. Adds regression coverage for large payloads, bound method display, unobserved handles and completed local jobs. The broader method/property API design remains separate. Formatting applied; no local builds or tests were run. CI will execute the regression coverage. --- python/python/lancedb/job.py | 36 ++++++++++++--------- python/python/tests/test_job.py | 45 +++++++++++++++++++++++++++ python/python/tests/test_remote_db.py | 11 ++----- 3 files changed, 68 insertions(+), 24 deletions(-) diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 92b545ce7..86a1295cc 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -4,7 +4,7 @@ """Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio -import json +import reprlib import time from datetime import timedelta from typing import Any, Callable, Generic, Optional, TypeVar, cast @@ -461,43 +461,49 @@ class AsyncJob(Generic[T]): _REPR_INDENT = " " * 4 +_REPR_MAX_FIELD_LENGTH = 240 +_PAYLOAD_REPR = reprlib.Repr() +_PAYLOAD_REPR.maxlevel = 2 +_PAYLOAD_REPR.maxdict = 4 +_PAYLOAD_REPR.maxlist = 4 +_PAYLOAD_REPR.maxtuple = 4 +_PAYLOAD_REPR.maxstring = 120 +_PAYLOAD_REPR.maxother = 120 def _repr_payload(value: Any) -> str: - """Render a job payload as indented JSON, aligned under its field.""" - try: - rendered = json.dumps(value, indent=4) - except TypeError: - return repr(value) - return rendered.replace("\n", "\n" + _REPR_INDENT) + """Bound nested payload previews without changing the stored values.""" + rendered = _PAYLOAD_REPR.repr(value).replace("\n", "\\n") + if len(rendered) > _REPR_MAX_FIELD_LENGTH: + return rendered[: _REPR_MAX_FIELD_LENGTH - 3] + "..." + return rendered def _job_repr(kind: str, job: Any) -> str: - """Render every field the handle currently knows, omitting the rest. + """Show cached job identity and bounded previews without backend calls. - One field per line, with the JSON payloads indented, because a refresh - job's spec and result are the point of printing it. + The complete payloads remain available through ``spec`` and ``result``. """ state = job.state if state is None: # Nothing has been fetched yet, so there is nothing to lay out. - known = f"id={job.id!r}, " if job.id is not None else "" + known = f"id={_repr_payload(job.id)}, " if job.id is not None else "" return f"{kind}({known}not refreshed)" fields = [] if job.id is not None: - fields.append(f"id={job.id!r}") - fields.append(f"state={state!r}") + fields.append(f"id={_repr_payload(job.id)}") + fields.append(f"state={_repr_payload(state)}") for name in ("job_type", "creation_ms"): value = getattr(job, name) if value is not None: - fields.append(f"{name}={value!r}") + fields.append(f"{name}={_repr_payload(value)}") for name in ("spec", "result"): value = getattr(job, name) if value is not None: fields.append(f"{name}={_repr_payload(value)}") if job.failure is not None: - fields.append(f"failure={job.failure!r}") + fields.append(f"failure={_repr_payload(job.failure)}") body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields) return f"{kind}({body}\n)" diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index c3189cbad..07b8a8c5e 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -4,6 +4,7 @@ import asyncio import time from datetime import timedelta +from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock import pytest @@ -13,6 +14,50 @@ from lancedb.job import AsyncJob, Job, _progress_eta from lancedb.remote.errors import HttpError, RetryError +@pytest.mark.parametrize("sync", [False, True]) +def test_job_repr_bounds_large_payloads_without_fetching(sync): + spec = {"initialization": list(range(100000)), "source": "x" * 100000} + result = {"rows_computed": 7, "details": [{"data": b"x" * 10000}] * 1000} + inner = SimpleNamespace( + id="job-repr", + _state="failed", + job_type="function_refresh", + _description=SimpleNamespace( + creation_ms=2000, + spec=spec, + result=result, + failure="worker failed " + "x" * 10000, + ), + ) + job = AsyncJob(inner) + if sync: + job = Job(job) + rendered = repr(job) + assert len(rendered) < 1600 + assert len(rendered.splitlines()) <= 10 + assert "id='job-repr'" in rendered + assert "state='failed'" in rendered + assert "job_type='function_refresh'" in rendered + assert "rows_computed" in rendered + assert "worker failed" in rendered + assert "..." in rendered + assert len(repr(job.status)) < 1700 + assert job.spec is spec + assert job.result is result + assert len(job.spec["initialization"]) == 100000 + + +@pytest.mark.parametrize("sync", [False, True]) +def test_job_repr_handles_unobserved_and_local_jobs(sync): + unobserved = AsyncJob(SimpleNamespace(id="job-pending", _state=None)) + local = AsyncJob(None) + if sync: + unobserved, local = Job(unobserved), Job(local) + assert "id='job-pending', not refreshed" in repr(unobserved) + assert "state='finished'" in repr(local) + assert "failure=" not in repr(local) + + @pytest.fixture(params=["async", "sync"]) def wait_job(request): async def wait(inner, timeout=None, result_decoder=None): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 671d0ff23..789df1726 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5539,9 +5539,6 @@ def test_remote_job_handle_reports_its_own_detail(): assert json.loads(job._spec_json) == {"column": "vec"} assert json.loads(job._result_json) == {"rows_assigned": 1000000} - # print() shows everything the handle knows and nothing it does not. - # print() lays every known field out on its own line, with the JSON - # payloads indented rather than crammed onto one line. assert repr(job) == "\n".join( [ "Job(", @@ -5549,12 +5546,8 @@ def test_remote_job_handle_reports_its_own_detail(): " state='finished',", " job_type='refresh_column',", " creation_ms=2000,", - " spec={", - ' "column": "vec"', - " },", - " result={", - ' "rows_assigned": 1000000', - " },", + " spec={'column': 'vec'},", + " result={'rows_assigned': 1000000},", ")", ] ) From 481e82293e7894c41ee7eb8f870078f04656670e Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 10 Nov 2026 08:24:32 -0800 Subject: [PATCH 058/203] fix(python): explain explicit blob reads and subset copies (#4940) Unsupported remote blob materialization errors now point to row-ID selection, fetch_blobs and fetch_blob_files. Document descriptor structs, fetched bytes and Function BlobReader inputs, and show a bounded subset-copy recipe that keeps the source unchanged between selection and fetching. Adds guidance assertions and copy coverage preserving payloads, empty blobs and nulls. No new blob materialization API is introduced. Formatting applied; no local builds or tests were run. CI will execute the regression coverage. --- docs/web/management/table.mdx | 45 +++++++++++++++++++++++++++ python/python/lancedb/query.py | 10 ++++-- python/python/lancedb/table.py | 6 ++++ python/python/tests/test_blob.py | 34 +++++++++++++++++++- python/python/tests/test_remote_db.py | 6 +++- 5 files changed, 97 insertions(+), 4 deletions(-) diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index c229e13f0..99c92f4e2 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -477,6 +477,51 @@ 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`. +###### Copy a subset of blob rows {#multimodal-copy-subset} + +Blob query results describe the stored payload; they are not the bytes to +insert into another table. These APIs return different values: + +| Read path | Value | +| --- | --- | +| SQL or an Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | +| `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | +| A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | + +For an Enterprise source table, select the rows and fetch their bytes explicitly. +The following example copies up to 100 rows from an existing `images` table with +an integer `id` and a blob `image` column. Keep the source unchanged during this +operation: selection and fetching are separate requests. + +```python +import lancedb +import pyarrow as pa + +source = db.open_table("images") +hits = ( + source.search() + .where("id < 100") + .select(["id"]) + .with_row_id(True) + .limit(100) + .to_arrow() +) +payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist() +subset = db.create_table( + "image_subset", + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), +) +if hits.num_rows: + subset.add([ + {"id": image_id, "image": payload} + for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True) + ]) +``` + +Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches +for larger subsets; `fetch_blobs` materializes all requested bytes in memory. +For incremental decoding, use `fetch_blob_files` instead. + `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 diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 4a3fea2e2..ac15f013c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -206,7 +206,10 @@ def _blob_bytes_without_snapshot_error() -> NotImplementedError: "blob_mode='bytes' cannot safely materialize blob columns without a " "stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown " "run the query on a server, so the blob fetch could read another table " - "version. Use blob_mode='descriptions'." + "version. Use blob_mode='descriptions' to inspect descriptors. To read " + "payloads, select row IDs with with_row_id(True), then call " + "table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, " + "row_ids). Keep the source unchanged between selection and fetching." ) @@ -453,7 +456,10 @@ def _finish_remote_pandas( raise NotImplementedError( f"remote to_pandas(blob_mode={blob_mode!r}) cannot safely materialize " "blob columns without a stable table snapshot; " - "use blob_mode='descriptions'" + "use blob_mode='descriptions' to inspect descriptors. To read payloads, " + "select row IDs with with_row_id(True), then call " + "table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, " + "row_ids). Keep the source unchanged between selection and fetching." ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index bf13cc7bd..8f9a78e99 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2626,6 +2626,12 @@ class Table(ABC): 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`. + + The returned Arrow ``large_binary`` array contains payload bytes, not + SQL/query descriptor dictionaries. Use ``.to_pylist()`` to obtain + Python ``bytes`` or ``None`` values for copying into a blob column. + Select row IDs with ``search().with_row_id(True)`` first. Selection and + fetching are separate requests: keep the source unchanged between them. """ @abstractmethod diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index ceb43522e..ebafdfbe9 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1070,8 +1070,10 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path): ) table.add([{"id": 1, "image": b"one"}]) - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises(NotImplementedError, match="stable table snapshot") as exc: table.to_arrow(blob_mode="bytes") + assert "fetch_blobs(column, row_ids)" in str(exc.value) + assert "with_row_id(True)" in str(exc.value) with pytest.raises(NotImplementedError, match="stable table snapshot"): table.search().to_list(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): @@ -1103,6 +1105,36 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path) await table.query().to_batches(blob_mode="bytes") +def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + rows = [ + {"id": 1, "image": b"one"}, + {"id": 2, "image": b""}, + {"id": 3, "image": None}, + {"id": 4, "image": b"excluded"}, + ] + source = db.create_table("source", data=rows, schema=schema) + hits = ( + source.search() + .where("id < 4") + .select(["id"]) + .with_row_id(True) + .limit(100) + .to_arrow() + ) + payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist() + subset = db.create_table("subset", schema=schema) + subset.add( + [ + {"id": image_id, "image": payload} + for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True) + ] + ) + copied = subset.search().to_list(blob_mode="bytes") + assert sorted(copied, key=lambda row: row["id"]) == rows[:3] + + def test_fetch_blobs_round_trip(): table = _blob_table( "round_trip", diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 789df1726..3a1d7f5db 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -4958,8 +4958,12 @@ def test_sync_remote_blob_pandas_avoids_storage_access( assert "_rowid" not in df.columns assert df["image"][0]["size"] == 5 else: - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises( + NotImplementedError, match="stable table snapshot" + ) as exc: query.to_pandas(blob_mode=blob_mode) + assert "fetch_blobs(column, row_ids)" in str(exc.value) + assert "with_row_id(True)" in str(exc.value) @pytest.mark.asyncio From d44f7689202be259879d91cad3d8d0b0acb208a8 Mon Sep 17 00:00:00 2001 From: Lucia Cerchie Date: Tue, 10 Nov 2026 15:07:59 -0800 Subject: [PATCH 059/203] docs: add generated agent prompt catalog section (UAX-192) (#4945) Add an automated prompt catalog section to the agentic skills page. The combined docs build fills its insertion marker from the evaluation source, avoiding a manually maintained prompt list. Keep the evaluation context and fixture guidance in this page so docs reviewers can edit it independently of the generator. Existing workflow examples remain in place. Part of UAX-192. Depends on https://github.com/lancedb/docs/pull/434; merge that docs pipeline change first. Validation: combined assembly and Mintlify validation pass. --- docs/web/basics/agentic-skills.mdx | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/web/basics/agentic-skills.mdx b/docs/web/basics/agentic-skills.mdx index d88b5dddf..638e39bdd 100644 --- a/docs/web/basics/agentic-skills.mdx +++ b/docs/web/basics/agentic-skills.mdx @@ -78,6 +78,24 @@ Not every agent supports project scope; `npx plugins targets` lists what it found and what each target supports. +## Automated prompt catalog {#automated-prompts} + +Explore the prompts covered by automated agent evaluations. Each prompt uses +example data and may require existing tables, +indexes, metadata, branches, version history, or running jobs. Replace the test +fixtures and connection details with your own before using a prompt. + +The evaluations run against a LanceDB Enterprise test database, with and +without the agent plugin. Evaluation coverage does not guarantee success for +every agent or model. + +Prompts are reproduced verbatim, including the answer formats used by automated +grading. Table names, local files, and placeholders in these prompts refer to +test fixtures. Supply your own data, database connection, and timestamps when +adapting them. + +{/* agent-eval-catalog */} + ## Example prompts {#example-prompts} These prompts show the kind of work the plugin helps an agent get right on From 4d22c0ce2b6825c880c818e737b079db494b4053 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 10:05:52 +0800 Subject: [PATCH 060/203] feat: expose Function refresh resource budgets in SDKs (#4951) ## Summary - Add the canonical Rust `FunctionWorkerResourceBudget` and `RefreshColumnOptions::resource_budget()` for explicit Enterprise Function refreshes. - Forward the nested budget through Python sync/async, PyO3, Rust remote requests, Node NAPI, and TypeScript. - Require positive CPU and memory values; normalize an omitted nested GPU count to numeric zero; reject the nested budget when combined with the top-level `gpu_count` shorthand. - Reject `resource_budget` on LanceDB Embedded refresh paths instead of silently ignoring it. - Document the Rust, Python, and TypeScript APIs, including that SQL servers currently require all three budget fields. The Rust, Python, and TypeScript additions use `cpu_millis` / `cpuMillis`, `memory_bytes` / `memoryBytes`, and `gpu_count` / `gpuCount`. The top-level GPU shorthand keeps its existing behavior and remains mutually exclusive with the complete nested budget. ## Scope and compatibility This change configures only the explicit refresh call. It does not configure `add_columns` automatic refresh and does not introduce a fleet-wide call-cap interface. A LanceDB Enterprise server must expose the nested `resource_budget` backfill contract. LanceDB Embedded continues to support its existing expression refresh defaults and rejects the new complete budget explicitly. ## Validation Validated against the final signed product source: - Rust: resource-budget remote serialization test `2 passed`; validation test `1 passed`. - Python: actual PyO3 build; remote-request matrix `22 passed`; invalid-option matrix `20 passed`; local rejection `22 passed`; Ruff check and format clean. - Repository-standard Pyright entry point: `0 errors`, within the repository's configured include set. - Node: native build and Biome lint passed; the existing remote-request test `1 passed`, including fractional, negative, overflow, NaN, and infinity nested GPU cases; the existing local-rejection test `1 passed`. - TypeDoc generation and generated-document cleanliness passed. - The native-tested product source differs from this head only in two semantically equivalent Node range checks required by Clippy. Current CI compiles and lints the final blobs. No dependency or lockfile changes are included. --- docs/src/js/classes/Table.md | 21 +++-- docs/src/js/globals.md | 1 + .../FunctionWorkerResourceBudget.md | 39 ++++++++ .../src/js/interfaces/RefreshColumnOptions.md | 14 ++- .../feature-engineering/refresh-column.mdx | 64 ++++++++++++- nodejs/__test__/remote.test.ts | 83 +++++++++++++++++ nodejs/__test__/table.test.ts | 5 ++ nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 21 +++-- nodejs/src/table.rs | 55 +++++++++++- python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/remote/table.py | 4 + python/python/lancedb/table.py | 78 ++++++++++++---- python/python/tests/test_remote_db.py | 47 ++++++++++ python/python/tests/test_table.py | 4 + python/src/table.rs | 90 ++++++++++++++++--- rust/lancedb/src/remote/table.rs | 60 ++++++++++++- rust/lancedb/src/table.rs | 26 +++--- rust/lancedb/src/table/refresh.rs | 63 +++++++++++++ 19 files changed, 623 insertions(+), 55 deletions(-) create mode 100644 docs/src/js/interfaces/FunctionWorkerResourceBudget.md diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 1fad723fe..5ab1751d4 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1141,11 +1141,18 @@ LanceDB Enterprise it is the server's backfill job. Refresh options, mirroring the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` - and `initTimeoutSeconds` govern failing rows, and `batchSize`, - `gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker` - size the workers. All are LanceDB Enterprise only; a LanceDB Embedded - refresh rejects every option other than `batchSize`, `gpuClass` and - `gpuCount`. + and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, + `resourceBudget` and `maxExecutorProcessesPerWorker` size registered + Function refreshes. A `resourceBudget` requires `cpuMillis` and + `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. + The budget applies only to this explicit refresh and does not configure + a later automatic refresh. + `gpuCount` at the top level is the shorthand that preserves the + deployment defaults for CPU and memory, and cannot be combined with + `resourceBudget`. `numWorkers` applies only to expression columns; use + `resourceBudget` for registered Functions. All are LanceDB Enterprise + only; a LanceDB Embedded refresh rejects every option other than + `batchSize`, `gpuClass` and `gpuCount`. #### Returns @@ -1156,6 +1163,10 @@ LanceDB Enterprise it is the server's backfill job. ```ts const job = await table.refreshColumnAsync("embedding", { where: "published_at > '2026-01-01'", + resourceBudget: { + cpuMillis: 8000, + memoryBytes: 16 * 1024 ** 3, + }, errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index dab1c61bc..50f55f937 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -99,6 +99,7 @@ - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md) - [FunctionErrors](interfaces/FunctionErrors.md) - [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md) +- [FunctionWorkerResourceBudget](interfaces/FunctionWorkerResourceBudget.md) - [HnswPqOptions](interfaces/HnswPqOptions.md) - [HnswSqOptions](interfaces/HnswSqOptions.md) - [IndexConfig](interfaces/IndexConfig.md) diff --git a/docs/src/js/interfaces/FunctionWorkerResourceBudget.md b/docs/src/js/interfaces/FunctionWorkerResourceBudget.md new file mode 100644 index 000000000..0352bc833 --- /dev/null +++ b/docs/src/js/interfaces/FunctionWorkerResourceBudget.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionWorkerResourceBudget + +# Interface: FunctionWorkerResourceBudget + +Aggregate worker resources for one Enterprise Function refresh. + +## Properties + +### cpuMillis + +```ts +cpuMillis: number; +``` + +Aggregate CPU budget in millicores; 1000 is one CPU. + +*** + +### gpuCount? + +```ts +optional gpuCount: number; +``` + +Aggregate GPU budget. Omitted means zero, a CPU-only refresh. + +*** + +### memoryBytes + +```ts +memoryBytes: number; +``` + +Aggregate memory budget in bytes. diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 840012040..151cbb72f 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -8,7 +8,8 @@ Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores -`batchSize`, `gpuClass` and `gpuCount` and rejects the rest. +`batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including +`resourceBudget`. ## Properties @@ -105,6 +106,17 @@ Worker count for an expression column; Function columns reject it. *** +### resourceBudget? + +```ts +optional resourceBudget: FunctionWorkerResourceBudget; +``` + +Complete aggregate CPU and memory budget for a registered Function +refresh. `gpuCount` inside the budget defaults to zero. + +*** + ### rowTimeoutSeconds? ```ts diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 0dfe3b33d..043c712cb 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -166,8 +166,62 @@ The resource values cap the Function workers together: this example allows up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not per-worker allocations or a guaranteed worker count. `num_workers` is only accepted for SQL-expression columns; registered Function columns reject it. -When setting CPU or memory, supply all three budget fields, using -`gpu_count = 0` for a CPU-only Function. + +The SDKs accept the same nested budget. CPU and memory are required; the GPU +count inside the budget defaults to zero, so a CPU-only Function can omit it: + + +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + resource_budget={ + "cpu_millis": 8000, + "memory_bytes": 16 * 1024**3, + }, +) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::table::{ + FunctionWorkerResourceBudget, + RefreshColumnOptions, +}; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().resource_budget( + FunctionWorkerResourceBudget::new(8000, 17_179_869_184), + ), + ) + .await?; +``` + +```typescript TypeScript icon="typescript" +const job = await table.refreshColumnAsync("embedding", { + resourceBudget: { + cpuMillis: 8000, + memoryBytes: 16 * 1024 ** 3, + }, +}); +await job.wait(); +``` + + +On current SQL servers, the equivalent `REFRESH COLUMN ... WITH (...)` form +still takes all three fields when CPU or memory is set; use `gpu_count = 0` +for a CPU-only Function. The SDK normalizes an omitted nested GPU count to a +numeric zero before sending the request. + +The existing top-level `gpu_count` / `gpuCount` option remains the shorthand +for changing only the aggregate GPU budget. It cannot be combined with the +complete resource budget. Omitting both preserves the server's existing +defaults. + +These examples configure only the explicit refresh shown. They do not set the +budget for an automatic refresh scheduled after `add_columns`; that remains a +separate declaration and scheduler capability. `batch_size` caps rows in one Function call; LanceDB adapts actual call and work sizes. For Function columns, the refresh defaults to @@ -248,7 +302,8 @@ async fn refresh( `gpu_count` is the aggregate GPU budget for the refresh's Function workers, -not a request for that many GPUs per worker. It must be positive. +not a request for that many GPUs per worker. It must be positive and preserves +the deployment's CPU and memory defaults. `gpu_class` must name a class returned by `list_gpu_classes()`; class names are lowercase DNS labels. Omit either option to use the Function's registered class or the server's configured budget. `list_gpu_classes()` requires System @@ -341,7 +396,8 @@ The SDK rejects a blank `where`, a `max_failed_fraction` outside 0 to 1, a timeout that is not a positive number and a zero worker or process count before sending the request; the server validates everything else. A LanceDB Embedded refresh rejects every option other than `batch_size`, `gpu_class` -and `gpu_count`. +and `gpu_count`; in particular, it rejects `resource_budget` rather than +silently ignoring it. ## When a refresh fails {#failures} diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 242be6101..e26adc58d 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -693,6 +693,12 @@ describe("remote connection", () => { }); expect(job.id).toBe("j-9"); await table.refreshColumnAsync("embedding"); + await table.refreshColumnAsync("embedding", { + resourceBudget: { + cpuMillis: 8_000, + memoryBytes: 16 * 1024 ** 3, + }, + }); // Invalid options reject before any request is sent. for (const [options, message] of [ [{ maxFailedRows: -1 }, "maxFailedRows"], @@ -702,6 +708,75 @@ describe("remote connection", () => { [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], [{ numWorkers: 0 }, "num_workers"], [{ gpuCount: 0 }, "gpu_count"], + [ + { + resourceBudget: { + cpuMillis: 1_000, + memoryBytes: 1_024, + }, + gpuCount: 1, + }, + "gpu_count cannot be combined with resource_budget", + ], + [ + { + resourceBudget: { + cpuMillis: 0, + memoryBytes: 1_024, + }, + }, + "resourceBudget.cpuMillis", + ], + [ + { + resourceBudget: { + cpuMillis: 1_000, + memoryBytes: 1_024, + gpuCount: 1.5, + }, + }, + "resourceBudget.gpuCount", + ], + [ + { + resourceBudget: { + cpuMillis: 1_000, + memoryBytes: 1_024, + gpuCount: -1, + }, + }, + "resourceBudget.gpuCount", + ], + [ + { + resourceBudget: { + cpuMillis: 1_000, + memoryBytes: 1_024, + gpuCount: 2 ** 32, + }, + }, + "resourceBudget.gpuCount", + ], + [ + { + resourceBudget: { + cpuMillis: 1_000, + memoryBytes: 1_024, + gpuCount: Number.NaN, + }, + }, + "resourceBudget.gpuCount", + ], + [ + { + resourceBudget: { + cpuMillis: 1_000, + memoryBytes: 1_024, + gpuCount: Number.POSITIVE_INFINITY, + }, + }, + "resourceBudget.gpuCount", + ], ] as const) { await expect( table.refreshColumnAsync("embedding", options), @@ -718,6 +793,14 @@ describe("remote connection", () => { "max_executor_processes_per_worker": 2}`, ), { column: "embedding" }, + JSON.parse( + `{"column": "embedding", + "resource_budget": { + "cpu_millis": 8000, + "memory_bytes": 17179869184, + "gpu_count": 0 + }}`, + ), ]); }); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index c3888d6c0..84f831a7a 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5686,6 +5686,11 @@ describe("computed columns", () => { await expect( table.refreshColumnAsync("x", { errorPolicy: "skip" }), ).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh"); + await expect( + table.refreshColumnAsync("x", { + resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 }, + }), + ).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh"); }); it("records Function errors only on remote tables", async () => { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 9644b0060..6bd46c9c8 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -57,6 +57,7 @@ export { AddResult, AddColumnsResult, RefreshColumnOptions, + FunctionWorkerResourceBudget, RefreshColumnResult, FunctionErrors, FunctionErrorsOptions, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 5ef298c8c..d7aac1fa0 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -722,15 +722,26 @@ export abstract class Table { * @param {RefreshColumnOptions} options Refresh options, mirroring the SQL * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` - * and `initTimeoutSeconds` govern failing rows, and `batchSize`, - * `gpuClass`, `gpuCount`, `numWorkers` and `maxExecutorProcessesPerWorker` - * size the workers. All are LanceDB Enterprise only; a LanceDB Embedded - * refresh rejects every option other than `batchSize`, `gpuClass` and - * `gpuCount`. + * and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, + * `resourceBudget` and `maxExecutorProcessesPerWorker` size registered + * Function refreshes. A `resourceBudget` requires `cpuMillis` and + * `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. + * The budget applies only to this explicit refresh and does not configure + * a later automatic refresh. + * `gpuCount` at the top level is the shorthand that preserves the + * deployment defaults for CPU and memory, and cannot be combined with + * `resourceBudget`. `numWorkers` applies only to expression columns; use + * `resourceBudget` for registered Functions. All are LanceDB Enterprise + * only; a LanceDB Embedded refresh rejects every option other than + * `batchSize`, `gpuClass` and `gpuCount`. * @example * ```ts * const job = await table.refreshColumnAsync("embedding", { * where: "published_at > '2026-01-01'", + * resourceBudget: { + * cpuMillis: 8000, + * memoryBytes: 16 * 1024 ** 3, + * }, * errorPolicy: "skip", * maxFailedFraction: 0.01, * rowTimeoutSeconds: 30, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index ebbc4a060..a008c606b 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -9,7 +9,8 @@ use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; use lancedb::table::{ AddDataMode, ColumnAlteration as LanceColumnAlteration, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, - NewColumnTransform, Ref, Table as LanceDbTable, + FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref, + Table as LanceDbTable, }; use napi::Env; use napi::bindgen_prelude::*; @@ -1586,9 +1587,44 @@ pub struct FunctionErrorsOptions { pub limit: Option, } +/// Aggregate worker resources for one Enterprise Function refresh. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionWorkerResourceBudget { + /// Aggregate CPU budget in millicores; 1000 is one CPU. + pub cpu_millis: f64, + /// Aggregate memory budget in bytes. + pub memory_bytes: f64, + /// Aggregate GPU budget. Omitted means zero, a CPU-only refresh. + pub gpu_count: Option, +} + +fn resource_budget_integer(value: f64, name: &str) -> napi::Result { + const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) { + return Err(napi::Error::from_reason(format!( + "{name} must be a positive safe integer" + ))); + } + Ok(value as u64) +} + +fn resource_budget_gpu_count(value: Option) -> napi::Result { + let Some(value) = value else { + return Ok(0); + }; + if !value.is_finite() || value.fract() != 0.0 || !(0.0..=u32::MAX as f64).contains(&value) { + return Err(napi::Error::from_reason( + "resourceBudget.gpuCount must be an integer between 0 and 4294967295", + )); + } + Ok(value as u32) +} + /// Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every /// option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores -/// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest. +/// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including +/// `resourceBudget`. #[napi(object)] #[derive(Clone, Debug, Default)] pub struct RefreshColumnOptions { @@ -1599,6 +1635,9 @@ pub struct RefreshColumnOptions { pub batch_size: Option, /// GPU class for Function workers. pub gpu_class: Option, + /// Complete aggregate CPU and memory budget for a registered Function + /// refresh. `gpuCount` inside the budget defaults to zero. + pub resource_budget: Option, /// Positive aggregate GPU budget for Function workers. pub gpu_count: Option, /// `"fail"` (default) stops on a row error; `"skip"` writes null and @@ -1628,6 +1667,18 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { options.where_clause = value.where_clause; options.batch_size = value.batch_size.map(|size| size as usize); options.gpu_class = value.gpu_class; + options.resource_budget = value + .resource_budget + .map(|budget| { + Ok::<_, napi::Error>( + LanceFunctionWorkerResourceBudget::new( + resource_budget_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, + resource_budget_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?, + ) + .with_gpu_count(resource_budget_gpu_count(budget.gpu_count)?), + ) + }) + .transpose()?; options.gpu_count = value.gpu_count; options.error_policy = match value.error_policy.as_deref() { None => None, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index aec0f7fb1..81615ae73 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -627,6 +627,7 @@ class Table: where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, @@ -645,6 +646,7 @@ class Table: where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index a963ab55e..f389f313f 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1144,6 +1144,7 @@ class RemoteTable(Table): where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1161,6 +1162,7 @@ class RemoteTable(Table): where=where, batch_size=batch_size, publication_interval_rows=publication_interval_rows, + resource_budget=resource_budget, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -1181,6 +1183,7 @@ class RemoteTable(Table): where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1199,6 +1202,7 @@ class RemoteTable(Table): where=where, batch_size=batch_size, publication_interval_rows=publication_interval_rows, + resource_budget=resource_budget, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 8f9a78e99..59a7384fd 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3187,6 +3187,7 @@ class Table(ABC): where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3231,15 +3232,23 @@ class Table(ABC): actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. + resource_budget: dict[str, int], optional + Aggregate resources for one registered Function refresh. The + ``cpu_millis`` and ``memory_bytes`` keys are required; + ``gpu_count`` is optional and defaults to zero, which requests a + CPU-only budget. This budget cannot be combined with the top-level + ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. gpu_count: int, optional - Positive aggregate GPU budget for Function workers. None leaves - the server's configured budget unchanged. LanceDB Enterprise - only. + Positive aggregate GPU budget for Function workers without changing + the deployment's CPU and memory defaults. None leaves the server's + configured budget unchanged. For a complete CPU and memory budget, + use ``resource_budget`` instead. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -3259,7 +3268,8 @@ class Table(ABC): Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it. LanceDB Enterprise only. + columns reject it and use ``resource_budget`` instead. LanceDB + Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -3279,6 +3289,7 @@ class Table(ABC): where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3322,15 +3333,23 @@ class Table(ABC): actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. + resource_budget: dict[str, int], optional + Aggregate resources for one registered Function refresh. The + ``cpu_millis`` and ``memory_bytes`` keys are required; + ``gpu_count`` is optional and defaults to zero, which requests a + CPU-only budget. This budget cannot be combined with the top-level + ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. gpu_count: int, optional - Positive aggregate GPU budget for Function workers. None leaves - the server's configured budget unchanged. LanceDB Enterprise - only. + Positive aggregate GPU budget for Function workers without changing + the deployment's CPU and memory defaults. None leaves the server's + configured budget unchanged. For a complete CPU and memory budget, + use ``resource_budget`` instead. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -3350,7 +3369,8 @@ class Table(ABC): Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it. LanceDB Enterprise only. + columns reject it and use ``resource_budget`` instead. LanceDB + Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -5465,6 +5485,7 @@ class LanceTable(Table): where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5485,6 +5506,7 @@ class LanceTable(Table): where=where, batch_size=batch_size, publication_interval_rows=publication_interval_rows, + resource_budget=resource_budget, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -5505,6 +5527,7 @@ class LanceTable(Table): where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5527,6 +5550,7 @@ class LanceTable(Table): where=where, batch_size=batch_size, publication_interval_rows=publication_interval_rows, + resource_budget=resource_budget, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -7895,6 +7919,7 @@ class AsyncTable: where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -7939,15 +7964,23 @@ class AsyncTable: actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. + resource_budget: dict[str, int], optional + Aggregate resources for one registered Function refresh. The + ``cpu_millis`` and ``memory_bytes`` keys are required; + ``gpu_count`` is optional and defaults to zero, which requests a + CPU-only budget. This budget cannot be combined with the top-level + ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. gpu_count: int, optional - Positive aggregate GPU budget for Function workers. None leaves - the server's configured budget unchanged. LanceDB Enterprise - only. + Positive aggregate GPU budget for Function workers without changing + the deployment's CPU and memory defaults. None leaves the server's + configured budget unchanged. For a complete CPU and memory budget, + use ``resource_budget`` instead. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -7967,7 +8000,8 @@ class AsyncTable: Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it. LanceDB Enterprise only. + columns reject it and use ``resource_budget`` instead. LanceDB + Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -7982,6 +8016,7 @@ class AsyncTable: where=where, batch_size=batch_size, publication_interval_rows=publication_interval_rows, + resource_budget=resource_budget, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None @@ -8092,6 +8127,7 @@ class AsyncTable: where: Optional[str] = None, batch_size: Optional[int] = None, publication_interval_rows: Optional[int] = None, + resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -8135,15 +8171,23 @@ class AsyncTable: actual publication boundary can be larger than this threshold because it also depends on completed work and Function batching. LanceDB Enterprise only; local refreshes reject this option. + resource_budget: dict[str, int], optional + Aggregate resources for one registered Function refresh. The + ``cpu_millis`` and ``memory_bytes`` keys are required; + ``gpu_count`` is optional and defaults to zero, which requests a + CPU-only budget. This budget cannot be combined with the top-level + ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. None keeps the Function's registered class or the deployment default. LanceDB Enterprise only. gpu_count: int, optional - Positive aggregate GPU budget for Function workers. None leaves - the server's configured budget unchanged. LanceDB Enterprise - only. + Positive aggregate GPU budget for Function workers without changing + the deployment's CPU and memory defaults. None leaves the server's + configured budget unchanged. For a complete CPU and memory budget, + use ``resource_budget`` instead. LanceDB Enterprise only. retry_policy: FunctionRetryPolicy, optional Override retries of failed user-code calls. Only use when repeating partial work is safe. Set max_attempts=1 to disable retries. @@ -8163,7 +8207,8 @@ class AsyncTable: Deadline for Function initialization. LanceDB Enterprise only. num_workers: int, optional Worker count for an expression column; registered Function - columns reject it. LanceDB Enterprise only. + columns reject it and use ``resource_budget`` instead. LanceDB + Enterprise only. max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. @@ -8195,6 +8240,7 @@ class AsyncTable: where=where, batch_size=batch_size, publication_interval_rows=publication_interval_rows, + resource_budget=resource_budget, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 3a1d7f5db..109dbfbdb 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1864,6 +1864,14 @@ def test_remote_create_index_async_returns_job(): {"batch_size": 1}, {"batch_size": 8}, {"publication_interval_rows": 60}, + {"resource_budget": {"cpu_millis": 2000, "memory_bytes": 4 * 1024**3}}, + { + "resource_budget": { + "cpu_millis": 8000, + "memory_bytes": 16 * 1024**3, + "gpu_count": 2, + } + }, {"gpu_class": "a10g", "gpu_count": 2}, { "retry_policy": {"transient": True, "max_attempts": 3}, @@ -1904,6 +1912,12 @@ async def test_remote_refresh_async_returns_typed_terminal_result( expected["gpu_class"] = refresh_kwargs["gpu_class"] if refresh_kwargs.get("gpu_count") is not None: expected["gpu_count"] = refresh_kwargs["gpu_count"] + if refresh_kwargs.get("resource_budget") is not None: + budget = refresh_kwargs["resource_budget"] + expected["resource_budget"] = { + **budget, + "gpu_count": budget.get("gpu_count", 0), + } if refresh_kwargs.get("retry_policy") is not None: expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate( refresh_kwargs["retry_policy"] @@ -2093,6 +2107,39 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"publication_interval_rows": 0}, "publication_interval_rows"), ({"publication_interval_rows": -1}, "publication_interval_rows"), ({"num_workers": 0}, "num_workers"), + ( + {"resource_budget": {"cpu_millis": 1000}}, + "resource_budget.memory_bytes", + ), + ( + { + "resource_budget": { + "cpu_millis": 0, + "memory_bytes": 1, + } + }, + "resource_budget.cpu_millis", + ), + ( + { + "resource_budget": { + "cpu_millis": 1000, + "memory_bytes": 1, + }, + "gpu_count": 1, + }, + "gpu_count cannot be combined with resource_budget", + ), + ( + { + "resource_budget": { + "cpu_millis": 1000, + "memory_bytes": 1, + "unknown": 1, + } + }, + "unsupported key 'unknown'", + ), ( {"max_executor_processes_per_worker": -2}, "max_executor_processes_per_worker", diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 157870bb5..2422437c2 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5996,6 +5996,10 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) ({"row_timeout_seconds": 30}, "row_timeout_seconds"), ({"init_timeout_seconds": 60}, "init_timeout_seconds"), ({"publication_interval_rows": 60}, "publication_interval_rows"), + ( + {"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}}, + "resource_budget", + ), ({"num_workers": 2}, "num_workers"), ({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"), ], diff --git a/python/src/table.rs b/python/src/table.rs index 23c5b69d7..56fc3bf5c 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -29,15 +29,17 @@ use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, - FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, Ref, - RefreshColumnOptions, Table as LanceDbTable, + FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionWorkerResourceBudget, IndexRemapMode, + NewColumnTransform, Ref, RefreshColumnOptions, Table as LanceDbTable, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, exceptions::{PyRuntimeError, PyValueError}, pyclass, pyfunction, pymethods, - types::{IntoPyDict, PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods}, + types::{ + IntoPyDict, PyAnyMethods, PyBool, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods, + }, }; mod scannable; @@ -47,6 +49,7 @@ struct RefreshColumnArgs { where_clause: Option, batch_size: Option, publication_interval_rows: Option, + resource_budget: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -70,11 +73,71 @@ fn positive_count>(value: Option, name: &str) -> PyResult, + name: &str, + allow_zero: bool, +) -> PyResult { + if value.is_none() || value.is_instance_of::() { + return Err(PyValueError::new_err(format!( + "resource_budget.{name} must be an integer" + ))); + } + let parsed = value + .extract::() + .map_err(|_| PyValueError::new_err(format!("resource_budget.{name} must be an integer")))?; + if !allow_zero && parsed == 0 { + return Err(PyValueError::new_err(format!( + "resource_budget.{name} must be greater than zero" + ))); + } + Ok(parsed) +} + +fn parse_resource_budget( + budget: Option<&Bound<'_, PyDict>>, +) -> PyResult> { + let Some(budget) = budget else { + return Ok(None); + }; + for key in budget.keys() { + let key = key + .extract::() + .map_err(|_| PyValueError::new_err("resource_budget keys must be strings"))?; + if !matches!(key.as_str(), "cpu_millis" | "memory_bytes" | "gpu_count") { + return Err(PyValueError::new_err(format!( + "resource_budget contains unsupported key '{key}'" + ))); + } + } + let cpu_millis = budget + .get_item("cpu_millis")? + .ok_or_else(|| PyValueError::new_err("resource_budget.cpu_millis is required"))?; + let cpu_millis = resource_budget_integer(&cpu_millis, "cpu_millis", false)?; + let memory_bytes = budget + .get_item("memory_bytes")? + .ok_or_else(|| PyValueError::new_err("resource_budget.memory_bytes is required"))?; + let memory_bytes = resource_budget_integer(&memory_bytes, "memory_bytes", false)?; + let gpu_count = match budget.get_item("gpu_count")? { + None => 0, + Some(value) if value.is_none() => 0, + Some(value) => { + u32::try_from(resource_budget_integer(&value, "gpu_count", true)?).map_err(|_| { + PyValueError::new_err("resource_budget.gpu_count must be no greater than u32::MAX") + })? + } + }; + Ok(Some( + FunctionWorkerResourceBudget::new(cpu_millis, memory_bytes).with_gpu_count(gpu_count), + )) +} + fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { let RefreshColumnArgs { where_clause, batch_size, publication_interval_rows, + resource_budget, gpu_class, gpu_count, retry_policy, @@ -118,6 +181,7 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult, + pub fn refresh_column<'py>( + self_: PyRef<'py, Self>, column: String, r#where: Option, batch_size: Option, publication_interval_rows: Option, + resource_budget: Option>, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2228,11 +2293,12 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, - ) -> PyResult> { + ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, publication_interval_rows, + resource_budget: parse_resource_budget(resource_budget.as_ref())?, gpu_class, gpu_count, retry_policy, @@ -2254,14 +2320,15 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] #[allow(clippy::too_many_arguments)] - pub fn refresh_column_async( - self_: PyRef<'_, Self>, + pub fn refresh_column_async<'py>( + self_: PyRef<'py, Self>, column: String, r#where: Option, batch_size: Option, publication_interval_rows: Option, + resource_budget: Option>, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2272,11 +2339,12 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, - ) -> PyResult> { + ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, publication_interval_rows, + resource_budget: parse_resource_budget(resource_budget.as_ref())?, gpu_class, gpu_count, retry_policy, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index a69611306..4f428809c 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11028,6 +11028,48 @@ mod tests { assert_eq!(job.id(), Some("j-gpu")); } + #[rstest] + #[case(None, 0)] + #[case(Some(2), 2)] + #[tokio::test] + async fn test_refresh_column_async_resource_budget( + #[case] gpu_count: Option, + #[case] expected_gpu_count: u32, + ) { + use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions}; + + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "resource_budget": { + "cpu_millis": 8_000, + "memory_bytes": 17_179_869_184_u64, + "gpu_count": expected_gpu_count, + }, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-budget"}"#) + .unwrap() + }); + let mut budget = FunctionWorkerResourceBudget::new(8_000, 17_179_869_184); + if let Some(gpu_count) = gpu_count { + budget = budget.with_gpu_count(gpu_count); + } + let job = table + .refresh_column_async_with_options( + "quality", + RefreshColumnOptions::default().resource_budget(budget), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-budget")); + } + #[tokio::test] async fn test_refresh_column_async_retry_policy() { use crate::function::{FunctionErrorPolicy, FunctionRetryPolicy}; @@ -11155,7 +11197,7 @@ mod tests { #[tokio::test] async fn test_refresh_column_rejects_invalid_gpu_options_before_request() { - use crate::table::RefreshColumnOptions; + use crate::table::{FunctionWorkerResourceBudget, RefreshColumnOptions}; let table = Table::new_with_handler("my_table", |_| -> http::Response { panic!("invalid GPU options must not send a request") @@ -11170,6 +11212,22 @@ mod tests { "gpu_class", ), (RefreshColumnOptions::default().gpu_count(0), "gpu_count"), + ( + RefreshColumnOptions::default() + .resource_budget(FunctionWorkerResourceBudget::new(0, 1)), + "resource_budget.cpu_millis", + ), + ( + RefreshColumnOptions::default() + .resource_budget(FunctionWorkerResourceBudget::new(1, 0)), + "resource_budget.memory_bytes", + ), + ( + RefreshColumnOptions::default() + .resource_budget(FunctionWorkerResourceBudget::new(1, 1)) + .gpu_count(1), + "gpu_count cannot be combined with resource_budget", + ), ] { let error = table .refresh_column_async_with_options("quality", options) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 80b6bd7ad..bd9220754 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -114,7 +114,7 @@ pub use optimize::{ CompactionMode, CompactionOptions, CompactionOverrides, IndexRemapMode, OptimizeAction, OptimizeStats, }; -pub use refresh::{RefreshColumnOptions, RefreshColumnResult}; +pub use refresh::{FunctionWorkerResourceBudget, RefreshColumnOptions, RefreshColumnResult}; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; pub use schema_evolution::{ AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate, @@ -2144,10 +2144,14 @@ impl Table { /// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in /// row-count publication threshold for completed Function outputs; unset /// keeps whole-fragment publication. + /// [`RefreshColumnOptions::resource_budget()`] sets the aggregate CPU, + /// memory, and GPU budget for a Function refresh. /// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and - /// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget. + /// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget + /// without changing the deployment's CPU and memory defaults. /// Batch-size and GPU options have no effect on expression-backed columns - /// in LanceDB Embedded; a publication threshold is rejected there. + /// in LanceDB Embedded; a resource budget and publication threshold are + /// rejected there. /// Remote refreshes require /// [`Table::refresh_column_async_with_options`]. /// @@ -2208,13 +2212,15 @@ impl Table { /// [`RefreshColumnOptions::publication_interval_rows()`] to publish /// completed Function outputs at a row-count threshold; unset keeps /// whole-fragment publication. Set - /// [`RefreshColumnOptions::gpu_class()`] and - /// [`RefreshColumnOptions::gpu_count()`] to override the registered GPU - /// class or set an aggregate GPU budget for Function workers. Unset values - /// use the Function and server defaults; zero counts and malformed class - /// names are rejected before submitting a job. Embedded expression - /// refreshes ignore the batch-size and GPU options, and reject publication - /// thresholds and other Enterprise-only options. + /// [`RefreshColumnOptions::resource_budget()`] to pass a complete aggregate + /// CPU, memory, and GPU budget for a Function refresh. The standalone + /// [`RefreshColumnOptions::gpu_count()`] shorthand and + /// [`RefreshColumnOptions::gpu_class()`] placement remain available; a + /// resource budget cannot be combined with the gpu-count shorthand. Unset + /// values use the Function and server defaults; invalid counts and malformed + /// class names are rejected before submitting a job. Embedded expression + /// refreshes ignore the batch-size and GPU options, and reject resource + /// budgets, publication thresholds, and other Enterprise-only options. /// /// ``` /// # use lancedb::{Table, table::RefreshColumnOptions}; diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index a8be34b17..742d60f18 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -55,6 +55,38 @@ use crate::function::validate_gpu_class_name; use crate::job::Job; use crate::{Error, Result}; +/// Aggregate worker resources for one Enterprise Function refresh. +/// +/// CPU is in millicores (1000 = one core) and memory is in bytes. These +/// values cap the Function workers together; they are not per-worker +/// allocations. The default GPU budget is zero, which describes a CPU-only +/// Function. This option is rejected by LanceDB Embedded refreshes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[non_exhaustive] +pub struct FunctionWorkerResourceBudget { + pub cpu_millis: u64, + pub memory_bytes: u64, + /// Aggregate GPU budget across the refresh. Zero is CPU-only. + pub gpu_count: u32, +} + +impl FunctionWorkerResourceBudget { + /// Create a CPU-only aggregate budget. + pub fn new(cpu_millis: u64, memory_bytes: u64) -> Self { + Self { + cpu_millis, + memory_bytes, + gpu_count: 0, + } + } + + /// Set the aggregate GPU budget. + pub fn with_gpu_count(mut self, gpu_count: u32) -> Self { + self.gpu_count = gpu_count; + self + } +} + /// Options for refreshing a computed column. /// /// Serializes to the Enterprise backfill request body, one key per set @@ -108,6 +140,10 @@ pub struct RefreshColumnOptions { /// rejects this option. #[serde(skip_serializing_if = "Option::is_none")] pub publication_interval_rows: Option, + /// Complete aggregate CPU, memory, and GPU budget for a registered + /// Function refresh. Cannot be combined with `gpu_count`. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_budget: Option, /// GPU class for Function workers in LanceDB Enterprise. /// /// `None` keeps the Function's registered class, or the deployment default @@ -189,6 +225,15 @@ impl RefreshColumnOptions { self } + /// Set the aggregate worker resource budget for a Function refresh. + /// + /// Use [`FunctionWorkerResourceBudget::new`] for a CPU-only budget, or + /// [`FunctionWorkerResourceBudget::with_gpu_count`] to include GPUs. + pub fn resource_budget(mut self, budget: FunctionWorkerResourceBudget) -> Self { + self.resource_budget = Some(budget); + self + } + /// Request Function workers from `gpu_class`. pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { self.gpu_class = Some(gpu_class.into()); @@ -220,6 +265,7 @@ impl RefreshColumnOptions { "publication_interval_rows", self.publication_interval_rows.is_some(), ), + ("resource_budget", self.resource_budget.is_some()), ] .into_iter() .find_map(|(name, set)| set.then_some(name)) @@ -277,6 +323,23 @@ impl RefreshColumnOptions { message: "publication_interval_rows must be greater than zero".into(), }); } + if self.resource_budget.is_some() && self.gpu_count.is_some() { + return Err(Error::InvalidInput { + message: "gpu_count cannot be combined with resource_budget".into(), + }); + } + if let Some(budget) = &self.resource_budget { + if budget.cpu_millis == 0 { + return Err(Error::InvalidInput { + message: "resource_budget.cpu_millis must be greater than zero".into(), + }); + } + if budget.memory_bytes == 0 { + return Err(Error::InvalidInput { + message: "resource_budget.memory_bytes must be greater than zero".into(), + }); + } + } if let Some(gpu_class) = &self.gpu_class { validate_gpu_class_name(gpu_class)?; } From 1e5b6deee3b45d9246825f9d1cf908c0a0142c43 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 10:08:13 +0800 Subject: [PATCH 061/203] fix(python): support legacy blob query bytes (#4947) ## Summary - Let local plain queries over row-addressable legacy v1 and v2 blob columns use `blob_mode="bytes"` without importing `pylance` through pandas, batch, or Arrow conversion. - Preserve aliases, filters, ordering, limits, null and empty payloads, empty result schemas, and the caller's `_rowid` choice. - Build the hidden row-id query separately so reusing an async builder for lazy reads or non-blob projections cannot retain an automatic `_rowid`. - Keep byte reads closed for blobs inside lists, remote or namespace pushdown, and query shapes whose result rows cannot be matched back to the source. Blob v2 lazy auto-row-id behavior is unchanged. Fixes #4645 ## Validation - 26 focused Python tests passed with the test subprocess blocking all `lance` imports. The persisted fixture writes and reopens a storage-v2.1 table, then covers sync and async pandas, batches, and Arrow conversion plus async builder reuse. - The existing unsupported vector and hybrid reranker regressions now assert the current eligibility diagnostic, and the legacy table-level Arrow regression now asserts successful bytes, schema, values, and hidden row IDs. Both focused tests passed. - The runtime receipt records no installed `pylance` distribution and no importable `lance` module. The Python-only change was verified with an existing compatible 0.42.0b9 extension; the relevant query and fetch APIs are unchanged between that source and this 0.42.0b10 base. - Ruff format and lint pass for every changed Python file. --- docs/web/basics/lance.mdx | 7 +- docs/web/management/table.mdx | 36 +-- docs/web/quickstart.mdx | 5 +- python/python/lancedb/_blob.py | 36 ++- python/python/lancedb/query.py | 254 ++++++++++++------ python/python/lancedb/schema.py | 9 + python/python/lancedb/table.py | 21 +- python/python/tests/test_blob.py | 33 ++- .../tests/test_blob_query_without_pylance.py | 201 +++++++++++++- python/python/tests/test_query.py | 20 +- 10 files changed, 493 insertions(+), 129 deletions(-) diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 0341ee333..84996ffe9 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -49,9 +49,10 @@ tbl = db.open_table("frames") # opens /data/frames.lance; version=N pins a vers Use `lancedb` for search, retrieval, data curation, multimodal blob access and application code. Install `pylance` (`import lance`) only when building query engines or connectors, calling format-level fragment APIs directly, or -converting plain-scan lazy or legacy blob columns with `to_pandas()` (see -[Multimodal data and blobs](/management/table#multimodal) for `pylance`-free -conversions). +converting plain-scan lazy blob handles with `to_pandas()`. Legacy plain-scan +byte conversions use LanceDB's native path without `pylance` (see +[Multimodal data and blobs](/management/table#multimodal) for conversion +boundaries). | `pylance` (`import lance`) | `lancedb` (`import lancedb`) | | --- | --- | diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 99c92f4e2..2a05b4a0f 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -465,9 +465,11 @@ methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a 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. +pylance. Eligible local plain scans also convert row-addressable legacy blob +bytes without pylance. Pandas conversions that need the Lance scanner, +including plain-scan `"lazy"` handles and scanner-only options, still require +pylance. `to_arrow()`, `to_list()`, `to_batches()`, and the fetch methods do +not require pylance for supported local queries. `blob_mode="bytes"` requires a LanceDB Embedded table snapshot, so Enterprise and in-memory tables raise `NotImplementedError`. On an Enterprise table, @@ -531,10 +533,11 @@ 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. +`to_batches(blob_mode="bytes")` fetches row-addressable blob v2 payloads and +eligible local plain-scan legacy v1 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 @@ -542,17 +545,18 @@ and iterate with `for`. For async queries, call 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. +The default `"lazy"` mode returns blob v2 descriptors and keeps their 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, 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 -`ValueError`. +including no blobs inside lists, Enterprise tables, namespace `QueryTable` +pushdown, or query shapes that cannot preserve their row results. Legacy v1 +bytes are limited to eligible local plain scans. 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} diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 5bd9a3efe..ef462cbf7 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -59,8 +59,9 @@ uv add --prerelease allow --index https://pypi.fury.io/lancedb/ lancedb Most applications only need `lancedb`. Install the optional `pylance` extra and include the Lance preview index only when building query engines or connectors, -calling format-level `lance` APIs directly, or converting plain-scan lazy or -legacy blob columns with `to_pandas()`: +calling format-level `lance` APIs directly, or converting plain-scan lazy blob +handles with `to_pandas()`. Legacy plain-scan byte conversions use LanceDB's +native path and do not require `pylance`: ```bash Python (pip) icon="terminal" diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 010c92009..2c545a17e 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Blob fetch API and v2 projection helpers.""" +"""Blob fetch API and projection helpers.""" from __future__ import annotations @@ -13,7 +13,11 @@ from typing import TYPE_CHECKING, Optional, Union import pyarrow as pa from .expr import Expr -from .schema import blob_column_paths, row_addressable_blob_v2_paths +from .schema import ( + blob_column_paths, + row_addressable_blob_paths, + row_addressable_blob_v2_paths, +) from .types import BlobMode, QueryProjection, QueryProjectionSpec if TYPE_CHECKING: @@ -165,6 +169,25 @@ def blob_v2_projection_sources( return _project_blob_paths(row_addressable_blob_v2_paths(schema), projection) +def blob_projection_sources( + schema: pa.Schema, + projection: QueryProjection, + *, + include_legacy: bool = False, +) -> dict[str, str]: + """Map projected blob outputs to row-addressable source columns. + + Legacy v1 columns are included only when the caller can safely fetch them + through the same row-id path as v2. + """ + paths = ( + row_addressable_blob_paths(schema) + if include_legacy + else row_addressable_blob_v2_paths(schema) + ) + return _project_blob_paths(paths, projection) + + def reject_unfetchable_blob_columns( schema: pa.Schema, projection: QueryProjection, blob_sources: dict[str, str] ) -> None: @@ -177,8 +200,9 @@ def reject_unfetchable_blob_columns( if unfetchable: raise ValueError( f"blob_mode='bytes' cannot fetch blob columns {unfetchable}. Bytes are " - "fetched by row id, which covers blob v2 columns with one blob per " - "row but not legacy blob columns or blobs inside lists. Use " + "fetched by row id for legacy and v2 columns in local plain scans, " + "but not for blobs inside lists or query shapes whose result columns " + "cannot be matched back to the source. Use " "blob_mode='descriptions' or remove these columns from the projection." ) @@ -269,7 +293,7 @@ def finalize_blob_query_table( return stash_auto_row_ids(tbl, blob_paths) -async def replace_v2_blob_columns_with_bytes( +async def replace_blob_columns_with_bytes( tbl: pa.Table, blob_sources: dict[str, str], fetch_blobs: FetchBlobsAsync, @@ -289,7 +313,7 @@ async def replace_v2_blob_columns_with_bytes( return tbl -def replace_v2_blob_columns_with_bytes_sync( +def replace_blob_columns_with_bytes_sync( tbl: pa.Table, blob_sources: dict[str, str], fetch_blobs: FetchBlobsSync, diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index ac15f013c..bab40be95 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -48,12 +48,13 @@ from ._blob import ( FetchBlobsAsync, FetchBlobsSync, blob_auto_row_id_for_scan, + blob_projection_sources, blob_v2_projection_sources, finalize_blob_query_table, reject_unfetchable_blob_columns, reject_unmatched_blob_outputs, - replace_v2_blob_columns_with_bytes, - replace_v2_blob_columns_with_bytes_sync, + replace_blob_columns_with_bytes, + replace_blob_columns_with_bytes_sync, strip_auto_row_ids, validate_blob_mode, ) @@ -245,6 +246,17 @@ def _query_is_plain_scan(query: Query) -> bool: ) +def _query_is_plain_blob_scan(query: Query) -> bool: + """Whether native batch conversion can preserve this query's row result.""" + return ( + query.vector is None + and query.full_text_query is None + and query.take_offsets is None + and query.take_row_ids is None + and not query.postfilter + ) + + def _filter_to_sql(filter: Optional[Union[str, Expr]]) -> Optional[str]: if filter is None: return None @@ -421,7 +433,7 @@ def _finish_plain_scan_pandas( ) -> pd.DataFrame: if blob_sources: tbl = _scanner_to_table(scanner) - tbl = replace_v2_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs) + tbl = replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs) if strip_auto_row_id and "_rowid" in tbl.column_names: tbl = tbl.drop_columns(["_rowid"]) if flatten is not None: @@ -475,7 +487,7 @@ async def _finish_plain_scan_pandas_async( ) -> pd.DataFrame: if blob_sources: tbl = _scanner_to_table(scanner) - tbl = await replace_v2_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs) + tbl = await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs) if strip_auto_row_id and "_rowid" in tbl.column_names: tbl = tbl.drop_columns(["_rowid"]) if flatten is not None: @@ -1281,10 +1293,10 @@ class LanceQueryBuilder(ABC): blob_mode: str, default "lazy" 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`. + plain scans also support ``"bytes"`` for row-addressable legacy blob + columns without pylance. Other local blob v2 queries return + descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads + in ``"bytes"`` mode, through :meth:`to_arrow`. LanceDB Enterprise blob queries support only ``"descriptions"`` until a stable table snapshot can bind the query and blob fetches. @@ -1352,8 +1364,8 @@ class LanceQueryBuilder(ABC): blob_mode: str, default "lazy" ``"lazy"`` returns blob v2 descriptors that carry the row id ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. - ``"bytes"`` returns payload bytes and raises for legacy blob columns - and blobs inside lists. + ``"bytes"`` returns payload bytes for supported row-addressable blob + columns and raises for blobs inside lists. """ raise NotImplementedError @@ -1370,7 +1382,7 @@ class LanceQueryBuilder(ABC): 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, the default ``blob_mode="lazy"`` keeps the + For blob v2 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. @@ -1390,10 +1402,11 @@ class LanceQueryBuilder(ABC): The timeout also covers reading the batches, so consuming them slowly can exceed it. 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`. + ``"lazy"`` keeps blob v2 descriptors and auto row ids for manual + fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches + supported row-addressable blob payloads one batch at a time, without + requiring pylance. Bytes mode has the same restrictions as + :meth:`to_arrow`. Examples -------- @@ -1599,20 +1612,41 @@ class LanceQueryBuilder(ABC): def _scan_needs_row_id(self) -> bool: return self._user_requested_row_id() or self._blob_auto_row_id_enabled() - def _query_for_scan(self) -> Query: + def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query: query = self.to_query_object() - if self._scan_needs_row_id(): + if self._scan_needs_row_id() or blob_sources: query.with_row_id = True return query + def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: + if blob_mode != "bytes": + return False + try: + query = self.to_query_object() + except NotImplementedError: + return False + return ( + _query_is_plain_blob_scan(query) + and getattr(self, "_reranker", None) is None + and not _query_needs_lance_scanner(self) + and _supports_local_blob_fetch( + self._table._table, + getattr(self._table, "_pushdown_operations", ()), + ) + ) + def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]: - """Map projected blob v2 outputs to their source columns. + """Map projected blob outputs to their source columns. Bytes mode is checked here, before the query runs. """ validate_blob_mode(blob_mode) schema = self._table.schema - blob_sources = blob_v2_projection_sources(schema, self._columns) + blob_sources = blob_projection_sources( + schema, + self._columns, + include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode), + ) if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, self._columns, blob_sources) @@ -1633,7 +1667,7 @@ class LanceQueryBuilder(ABC): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return replace_v2_blob_columns_with_bytes_sync( + return replace_blob_columns_with_bytes_sync( tbl, blob_sources, self._table.fetch_blobs ) @@ -1645,18 +1679,23 @@ class LanceQueryBuilder(ABC): blob_sources: dict[str, str], ) -> pa.Table: blob_auto_row_id = self._blob_auto_row_id_enabled() - finalized = finalize_blob_query_table( - tbl, - user_requested_row_id=self._user_requested_row_id(), - blob_auto_row_id=blob_auto_row_id, - blob_paths=blob_sources.keys() if blob_auto_row_id else (), - ) + if blob_mode == "bytes" and blob_sources: + # Bytes conversion reads _rowid directly, including when the + # projection mixes legacy and v2 columns. + finalized = tbl + else: + finalized = finalize_blob_query_table( + tbl, + user_requested_row_id=self._user_requested_row_id(), + blob_auto_row_id=blob_auto_row_id, + blob_paths=blob_sources.keys() if blob_auto_row_id else (), + ) finalized = self._apply_arrow_blob_mode(finalized, blob_mode, blob_sources) # with_row_id(False) does not reach the scan, which adds _rowid anyway. # Lazy keeps it because fetch_blobs(hits) reads it there. if ( blob_mode != "lazy" - and self._with_row_id is False + and not self._user_requested_row_id() and "_rowid" in finalized.column_names ): finalized = finalized.drop_columns(["_rowid"]) @@ -1896,18 +1935,29 @@ class LanceQueryBuilder(ABC): query = self.to_query_object() if not _query_is_plain_scan(query): return None + blob_sources = ( + blob_projection_sources( + self._table.schema, + query.columns, + include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode), + ) + if blob_mode == "bytes" + else {} + ) # Remote and in-memory tables have no Lance dataset to scan. if not self._table._table._inner._is_native() or ( get_uri_scheme(self._table._dataset_path) == "memory" ): return None - # 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) + # Bytes conversions use LanceDB's fetch path for both blob versions. + # Descriptions for v2 do too; lazy handles still need the scanner. + if not _query_needs_lance_scanner(self) and ( + (blob_mode == "bytes" and blob_sources) + or ( + blob_mode == "descriptions" + and blob_v2_projection_sources(self._table.schema, query.columns) + ) ): return None try: @@ -1915,12 +1965,7 @@ class LanceQueryBuilder(ABC): 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) - if blob_mode == "bytes" - else {} - ) - if blob_sources: + if blob_mode == "bytes": reject_unfetchable_blob_columns( self._table.schema, query.columns, blob_sources ) @@ -2254,8 +2299,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): blob_mode: str, default "lazy" ``"lazy"`` returns blob v2 descriptors that carry the row id ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. - ``"bytes"`` returns payload bytes and raises for legacy blob columns - and blobs inside lists. + ``"bytes"`` returns payload bytes for supported row-addressable blob + columns and raises for blobs inside lists. """ blob_sources = self._validated_blob_sources(blob_mode) return self._finalize_blob_query_table( @@ -2333,7 +2378,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): 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] - query = self._query_for_scan() + query = self._query_for_scan(blob_sources) result_set = self._table._execute_query( query, batch_size=batch_size, timeout=timeout ) @@ -2551,7 +2596,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): blob_sources = self._validated_blob_sources(blob_mode) self._table._ensure_no_legacy_fts_index() - query = self._query_for_scan() + query = self._query_for_scan(blob_sources) results = self._table._execute_query(query, timeout=timeout).read_all() if self._reranker is not None: results = self._reranker.rerank_fts(self._query, results) @@ -2597,6 +2642,8 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): blob_mode: BlobMode = "lazy", ) -> pa.Table: blob_sources = self._validated_blob_sources(blob_mode) + if blob_mode == "bytes" and blob_sources: + return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all() return self._finalize_blob_query_table( self.to_batches(timeout=timeout).read_all(), blob_mode=blob_mode, @@ -2630,7 +2677,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): blob_mode: BlobMode = "lazy", ) -> pa.RecordBatchReader: blob_sources = self._validated_blob_sources(blob_mode) - query = self._query_for_scan() + query = self._query_for_scan(blob_sources) reader = self._table._execute_query( query, batch_size=batch_size, timeout=timeout ) @@ -3501,6 +3548,22 @@ class AsyncQueryBase(object): self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) self._inner.with_row_id() + async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: + if blob_mode != "bytes" or self._table is None: + return False + try: + query = self.to_query_object() + except NotImplementedError: + return False + return ( + _query_is_plain_blob_scan(query) + and getattr(self, "_reranker", None) is None + and not _query_needs_lance_scanner(self) + and _supports_local_blob_fetch( + self._table, self._table._pushdown_operations + ) + ) + def select(self, columns: Union[List[str], dict[str, str]]) -> Self: """ Return only the specified columns. @@ -3608,10 +3671,11 @@ class AsyncQueryBase(object): The timeout also covers reading the batches, so consuming them slowly can exceed it. 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`. + ``"lazy"`` keeps blob v2 descriptors and auto row ids for manual + fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches + supported row-addressable blob payloads one batch at a time, without + requiring pylance. Bytes mode has the same restrictions as + :meth:`to_arrow`. Examples -------- @@ -3620,13 +3684,16 @@ class AsyncQueryBase(object): """ blob_sources = await self._validated_blob_sources(blob_mode) reader = await self._execute_batches( - max_batch_length=max_batch_length, timeout=timeout + max_batch_length=max_batch_length, + timeout=timeout, + blob_sources=blob_sources, ) if blob_mode == "lazy": return reader async def convert(tbl: pa.Table) -> pa.Table: - tbl = self._finalize_blob_query_table(tbl) + if not (blob_mode == "bytes" and blob_sources): + 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"]) @@ -3647,7 +3714,24 @@ class AsyncQueryBase(object): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: + if ( + blob_sources + and not self._user_requested_row_id() + and await self._can_fetch_plain_legacy_blobs("bytes") + ): + # Build a separate query so the hidden row id needed for byte + # conversion cannot leak into later executions of this builder. + query = self.to_query_object() + query.with_row_id = True + if self._table is None: + raise RuntimeError("blob query is not bound to a table") + row_id_query = self._table._sync_query_to_async(query) + return await row_id_query._execute_batches( + max_batch_length=max_batch_length, + timeout=timeout, + ) await self._maybe_add_blob_row_id() return AsyncRecordBatchReader( await self._inner.execute( @@ -3664,7 +3748,7 @@ class AsyncQueryBase(object): return await self._inner.output_schema() async def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]: - """Map projected blob v2 outputs to their source columns. + """Map projected blob outputs to their source columns. Bytes mode is checked here, before the query runs. """ @@ -3674,7 +3758,11 @@ class AsyncQueryBase(object): return {} schema = await self._table.schema() projection = _query_request_projection(self._inner.to_query_request()) - blob_sources = blob_v2_projection_sources(schema, projection) + blob_sources = blob_projection_sources( + schema, + projection, + include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode), + ) if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, projection, blob_sources) @@ -3695,7 +3783,7 @@ class AsyncQueryBase(object): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return await replace_v2_blob_columns_with_bytes( + return await replace_blob_columns_with_bytes( tbl, blob_sources, self._table.fetch_blobs ) @@ -3721,11 +3809,14 @@ class AsyncQueryBase(object): blob_mode: str, default "lazy" ``"lazy"`` returns blob v2 descriptors that carry the row id ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. - ``"bytes"`` returns payload bytes and raises for legacy blob columns - and blobs inside lists. + ``"bytes"`` returns payload bytes for supported row-addressable blob + columns and raises for blobs inside lists. LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``. """ blob_sources = await self._validated_blob_sources(blob_mode) + if blob_mode == "bytes" and blob_sources: + reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode) + return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) batch_iter = await self.to_batches(timeout=timeout) tbl = self._finalize_blob_query_table( pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema) @@ -3798,10 +3889,10 @@ class AsyncQueryBase(object): blob_mode: str, default "lazy" 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`. + plain scans also support ``"bytes"`` for row-addressable legacy blob + columns without pylance. Other local blob v2 queries return + descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads + in ``"bytes"`` mode, through :meth:`to_arrow`. LanceDB Enterprise blob queries support only ``"descriptions"`` until a stable table snapshot can bind the query and blob fetches. @@ -3879,21 +3970,27 @@ class AsyncQueryBase(object): with_row_id=self._with_row_id, ) blob_sources = ( - blob_v2_projection_sources(schema, query.columns) + blob_projection_sources( + schema, + query.columns, + include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode), + ) if blob_mode == "bytes" else {} ) - if blob_sources: + if blob_mode == "bytes": reject_unfetchable_blob_columns(schema, query.columns, blob_sources) # Remote and in-memory tables have no Lance dataset to scan. if not self._table._inner._is_native() or ( get_uri_scheme(await self._table.uri()) == "memory" ): return None - if ( - blob_mode != "lazy" - and not _query_needs_lance_scanner(self) - and blob_v2_projection_sources(schema, query.columns) + if not _query_needs_lance_scanner(self) and ( + (blob_mode == "bytes" and blob_sources) + or ( + blob_mode == "descriptions" + and blob_v2_projection_sources(schema, query.columns) + ) ): return None try: @@ -4404,8 +4501,11 @@ class AsyncFTSQuery(AsyncStandardQuery): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: - reader = await super()._execute_batches(timeout=timeout) + reader = await super()._execute_batches( + timeout=timeout, blob_sources=blob_sources + ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: results = self._reranker.rerank_fts(self.get_query(), results) @@ -4728,8 +4828,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: - reader = await super()._execute_batches(timeout=timeout) + reader = await super()._execute_batches( + timeout=timeout, blob_sources=blob_sources + ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: results = self._reranker.rerank_vector(self._query_string, results) @@ -4857,11 +4960,14 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: # WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s. return await _wal_hybrid.with_pk_fallback_async( lambda: self._run_hybrid( - max_batch_length=max_batch_length, timeout=timeout + max_batch_length=max_batch_length, + timeout=timeout, + blob_sources=blob_sources, ), self._table, fused=lambda: self._pk_fusion is not None, @@ -4873,19 +4979,18 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, + blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: fts_query, vec_query, limit, offset = await self._create_child_queries() req = fts_query._inner.to_query_request() - blob_auto_row_id = False + blob_auto_row_id = bool(blob_sources) blob_paths: tuple[str, ...] = () if self._table is not None: schema = await self._table.schema() projection = _query_request_projection(req) - blob_auto_row_id = blob_auto_row_id_for_scan( - schema, - projection, - with_row_id=self._with_row_id, + blob_auto_row_id = blob_auto_row_id or blob_auto_row_id_for_scan( + schema, projection, with_row_id=self._with_row_id ) if blob_auto_row_id: blob_paths = tuple( @@ -5182,8 +5287,7 @@ class BaseQueryBuilder(object): blob_mode: str, default "lazy" ``"lazy"`` returns blob v2 descriptors that carry the row id ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. - ``"bytes"`` returns payload bytes and raises for legacy blob columns - and blobs inside lists. + ``"bytes"`` is not supported for remote or pushdown blob queries. """ return LOOP.run(self._inner.to_arrow(timeout, blob_mode=blob_mode)) diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py index d92f7f692..5e36ffc86 100644 --- a/python/python/lancedb/schema.py +++ b/python/python/lancedb/schema.py @@ -122,6 +122,15 @@ def blob_v2_column_paths(schema: pa.Schema) -> list[str]: return [path for path, _ in _collect_blob_paths(schema, is_blob_v2_field)] +def row_addressable_blob_paths(schema: pa.Schema) -> list[str]: + """Blob v1 and v2 paths with one blob addressable by table row id.""" + return [ + path + for path, has_list_ancestor in _collect_blob_paths(schema, is_blob_like_field) + if not has_list_ancestor + ] + + def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]: """Blob v2 paths with one blob addressable by table row id. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 59a7384fd..f113baa05 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1589,8 +1589,8 @@ class Table(ABC): blob_mode: str, default "lazy" ``"lazy"`` returns blob v2 descriptors that carry the row id ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. - ``"bytes"`` returns payload bytes and raises for legacy blob columns - and blobs inside lists. + ``"bytes"`` returns payload bytes for supported row-addressable blob + columns and raises for blobs inside lists. Returns ------- @@ -4160,7 +4160,7 @@ class LanceTable(Table): ): return self.to_arrow().to_pandas(**kwargs) - if blob_mode == "bytes" and blob_v2_column_paths(self.schema): + if blob_mode == "bytes" and schema_has_blob_field(self.schema): return self.search().to_pandas(blob_mode=blob_mode, **kwargs) return self.to_lance().to_pandas(blob_mode=blob_mode, **kwargs) @@ -4173,8 +4173,8 @@ class LanceTable(Table): blob_mode: str, default "lazy" ``"lazy"`` returns blob v2 descriptors that carry the row id ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. - ``"bytes"`` returns payload bytes and raises for legacy blob columns - and blobs inside lists. + ``"bytes"`` returns payload bytes for supported row-addressable blob + columns and raises for blobs inside lists. Returns ------- @@ -6640,7 +6640,7 @@ class AsyncTable: if blob_mode == "lazy" and get_uri_scheme(await self.uri()) == "memory": return (await self.to_arrow()).to_pandas(**kwargs) - if blob_mode == "bytes" and blob_v2_column_paths(schema): + if blob_mode == "bytes" and schema_has_blob_field(schema): return await self.query().to_pandas(blob_mode=blob_mode, **kwargs) return (await self.to_lance()).to_pandas(blob_mode=blob_mode, **kwargs) @@ -6652,8 +6652,8 @@ class AsyncTable: blob_mode: str, default "lazy" ``"lazy"`` returns blob v2 descriptors that carry the row id ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. - ``"bytes"`` returns payload bytes and raises for legacy blob columns - and blobs inside lists. + ``"bytes"`` returns payload bytes for supported row-addressable blob + columns and raises for blobs inside lists. Returns ------- @@ -7460,7 +7460,10 @@ class AsyncTable: if query.offset is not None: async_query = async_query.offset(query.offset) if query.columns: - async_query = async_query.select(query.columns) + columns = query.columns + if isinstance(columns, list) and columns and isinstance(columns[0], tuple): + columns = dict(columns) + async_query = async_query.select(columns) if query.filter is not None: async_query = async_query.where(query.filter) if query.fast_search: diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index ebafdfbe9..bb946c37c 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1651,16 +1651,41 @@ def test_bytes_mode_rejects_blobs_inside_lists(): def test_row_addressable_paths_exclude_list_children(): - from lancedb.schema import row_addressable_blob_v2_paths + from lancedb.schema import ( + row_addressable_blob_paths, + row_addressable_blob_v2_paths, + ) schema = pa.schema( [ pa.field("id", pa.int64()), - pa.field("info", pa.struct([lancedb.blob("blob")])), + pa.field( + "info", + pa.struct( + [ + lancedb.blob("blob"), + pa.field( + "legacy", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, + ), + ] + ), + ), + pa.field( + "legacy", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, + ), pa.field("images", pa.list_(lancedb.blob("image"))), ] ) assert blob_v2_column_paths(schema) == ["info.blob", "images.image"] + assert row_addressable_blob_paths(schema) == [ + "info.blob", + "info.legacy", + "legacy", + ] assert row_addressable_blob_v2_paths(schema) == ["info.blob"] @@ -2325,6 +2350,8 @@ async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch): if blob_mode != "lazy": assert "_rowid" not in reader.schema.names assert "_lance_row_id" not in str(reader.schema) + else: + assert "_rowid" in reader.schema.names class _KeepAllScoresReranker(Reranker): @@ -2368,7 +2395,7 @@ def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path): .rerank(_KeepAllScoresReranker()) ) - with pytest.raises(ValueError, match=r"\['blob'\].*legacy blob columns"): + with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"): query.to_arrow(blob_mode="bytes") diff --git a/python/python/tests/test_blob_query_without_pylance.py b/python/python/tests/test_blob_query_without_pylance.py index a5ce6db44..7c503d1ff 100644 --- a/python/python/tests/test_blob_query_without_pylance.py +++ b/python/python/tests/test_blob_query_without_pylance.py @@ -8,12 +8,7 @@ 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): - if result == "pandas": - pytest.importorskip("pandas") - script = """\ +_WITHOUT_LANCE = """\ import importlib.abc import sys @@ -23,7 +18,15 @@ class MissingLance(importlib.abc.MetaPathFinder): raise ModuleNotFoundError(fullname, name="lance") sys.meta_path.insert(0, MissingLance()) -""" + textwrap.dedent( +""" + + +@pytest.mark.parametrize("api", ["sync", "async"]) +@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"]) +def test_blob_query_without_pylance(tmp_path, api, result): + if result == "pandas": + pytest.importorskip("pandas") + script = _WITHOUT_LANCE + textwrap.dedent( """\ import asyncio import lancedb @@ -94,3 +97,187 @@ sys.meta_path.insert(0, MissingLance()) text=True, ) assert completed.returncode == 0, completed.stderr + + +@pytest.mark.parametrize("api", ["sync", "async"]) +@pytest.mark.parametrize("result", ["pandas", "batches", "arrow"]) +def test_plain_legacy_blob_query_without_pylance(tmp_path, api, result): + if result == "pandas": + pytest.importorskip("pandas") + script = _WITHOUT_LANCE + textwrap.dedent( + """\ + import asyncio + import lancedb + import pyarrow as pa + from lancedb.query import ColumnOrdering + + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("filename", pa.string()), + pa.field( + "video_blob", + pa.large_binary(), + metadata={"lance-encoding:blob": "true"}, + ), + ] + ) + rows = [ + {"id": 1, "filename": "file-1.mp4", "video_blob": b"outside"}, + {"id": 2, "filename": "file-2.mp4", "video_blob": b""}, + {"id": 3, "filename": "file-3.mp4", "video_blob": None}, + {"id": 4, "filename": "file-4.mp4", "video_blob": b"four"}, + ] + expected = [ + {"filename": "file-2.mp4", "payload": b""}, + {"filename": "file-3.mp4", "payload": None}, + {"filename": "file-4.mp4", "payload": b"four"}, + ] + + def configure(query): + return ( + query.select({"filename": "filename", "payload": "video_blob"}) + .where("id >= 2") + .order_by( + [ColumnOrdering(column_name="id", ascending=True)] + ) + .limit(3) + ) + + async def main(): + storage_options = {"new_table_data_storage_version": "2.1"} + if sys.argv[2] == "async": + db = await lancedb.connect_async( + sys.argv[1], storage_options=storage_options + ) + table = await db.create_table("legacy", schema=schema) + await table.add(rows) + table = await db.open_table("legacy") + def query(): + return configure(table.query()) + def original_query(): + return table.query().select( + {"filename": "filename", "payload": "video_blob"} + ).limit(1) + def empty_query(): + return query().where("id < 0") + def batches(): + return query().to_batches( + max_batch_length=1, blob_mode="bytes" + ) + else: + db = lancedb.connect( + sys.argv[1], storage_options=storage_options + ) + table = db.create_table("legacy", schema=schema) + table.add(rows) + table = db.open_table("legacy") + def query(): + return configure(table.search()) + def original_query(): + return table.search().select( + {"filename": "filename", "payload": "video_blob"} + ).limit(1) + def empty_query(): + return query().where("id < 0") + def batches(): + return query().to_batches( + batch_size=1, blob_mode="bytes" + ) + + if sys.argv[2] == "async": + reused = table.query().select( + {"filename": "filename", "payload": "video_blob"} + ).limit(3) + byte_reader = await reused.to_batches(blob_mode="bytes") + await byte_reader.read_all() + lazy_reader = await reused.to_batches(blob_mode="lazy") + assert "_rowid" not in lazy_reader.schema.names + await lazy_reader.read_all() + reused.select(["filename"]) + nonblob_reader = await reused.to_batches(blob_mode="lazy") + assert nonblob_reader.schema.names == ["filename"] + await nonblob_reader.read_all() + + if sys.argv[3] == "pandas": + frame = query().to_pandas(blob_mode="bytes") + if sys.argv[2] == "async": + frame = await frame + assert frame.to_dict("records") == expected + original = original_query().to_pandas(blob_mode="bytes") + if sys.argv[2] == "async": + original = await original + assert original.to_dict("records") == [ + {"filename": "file-1.mp4", "payload": b"outside"} + ] + direct = table.to_pandas(blob_mode="bytes") + if sys.argv[2] == "async": + direct = await direct + assert direct.to_dict("records") == rows + empty = empty_query().to_pandas(blob_mode="bytes") + if sys.argv[2] == "async": + empty = await empty + assert empty.to_dict("records") == [] + elif sys.argv[3] == "batches": + reader = batches() + if sys.argv[2] == "async": + reader = await reader + rows_out = [batch async for batch in reader] + else: + rows_out = list(reader) + assert reader.schema.field("payload").type == pa.large_binary() + assert "_rowid" not in reader.schema.names + assert all(batch.num_rows == 1 for batch in rows_out) + assert all(batch.schema == reader.schema for batch in rows_out) + actual = [row for batch in rows_out for row in batch.to_pylist()] + assert actual == expected + original_reader = original_query().to_batches(blob_mode="bytes") + if sys.argv[2] == "async": + original_reader = await original_reader + original_rows = [batch async for batch in original_reader] + else: + original_rows = list(original_reader) + assert [ + row for batch in original_rows for row in batch.to_pylist() + ] == [{"filename": "file-1.mp4", "payload": b"outside"}] + empty_reader = empty_query().to_batches(blob_mode="bytes") + if sys.argv[2] == "async": + empty_reader = await empty_reader + empty_batches = [batch async for batch in empty_reader] + else: + empty_batches = list(empty_reader) + assert empty_batches == [] + assert empty_reader.schema.field("payload").type == pa.large_binary() + else: + table_out = query().to_arrow(blob_mode="bytes") + if sys.argv[2] == "async": + table_out = await table_out + assert table_out.schema.field("payload").type == pa.large_binary() + assert "_rowid" not in table_out.column_names + assert table_out.to_pylist() == expected + original = original_query().to_arrow(blob_mode="bytes") + if sys.argv[2] == "async": + original = await original + assert original.to_pylist() == [ + {"filename": "file-1.mp4", "payload": b"outside"} + ] + direct = table.to_arrow(blob_mode="bytes") + if sys.argv[2] == "async": + direct = await direct + assert direct.to_pylist() == rows + empty_table = empty_query().to_arrow(blob_mode="bytes") + if sys.argv[2] == "async": + empty_table = await empty_table + assert empty_table.num_rows == 0 + assert empty_table.schema.field("payload").type == pa.large_binary() + 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 95148dcf9..aee67d32a 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -348,7 +348,7 @@ def test_plain_scan_query_to_pandas_blob_bytes_projection(tmp_db, blob_schema): @pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"]) -def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow( +def test_plain_scan_query_to_pandas_blob_mode_uses_native_path( tmp_db, monkeypatch, blob_mode ): pytest.importorskip("lance") @@ -362,7 +362,8 @@ def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow( def fail_to_arrow(*args, **kwargs): raise AssertionError("to_arrow should not be called before native pandas") - monkeypatch.setattr(query, "to_arrow", fail_to_arrow) + if blob_mode == "descriptions": + monkeypatch.setattr(query, "to_arrow", fail_to_arrow) df = query.to_pandas(blob_mode=blob_mode) @@ -488,7 +489,7 @@ async def test_async_plain_scan_query_to_pandas_blob_bytes_projection( @pytest.mark.asyncio @pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"]) -async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow( +async def test_async_plain_scan_query_to_pandas_blob_mode_uses_native_path( tmp_db_async, monkeypatch, blob_mode ): pytest.importorskip("lance") @@ -502,7 +503,8 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow async def fail_to_arrow(*args, **kwargs): raise AssertionError("to_arrow should not be called before native pandas") - monkeypatch.setattr(query, "to_arrow", fail_to_arrow) + if blob_mode == "descriptions": + monkeypatch.setattr(query, "to_arrow", fail_to_arrow) df = await query.to_pandas(blob_mode=blob_mode) @@ -541,12 +543,14 @@ def test_vector_query_to_pandas_legacy_blob_descriptions_and_bytes(tmp_db): df = query.to_pandas(blob_mode="descriptions") assert df["blob"].tolist() == [{"position": 0, "size": 3}] - with pytest.raises(ValueError, match="legacy blob columns"): + with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"): query.to_pandas(blob_mode="bytes") - with pytest.raises(ValueError, match="legacy blob columns"): + with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"): query.to_arrow(blob_mode="bytes") - with pytest.raises(ValueError, match="legacy blob columns"): - table.to_arrow(blob_mode="bytes") + table_arrow = table.to_arrow(blob_mode="bytes") + assert table_arrow.schema.field("blob").type == pa.large_binary() + assert "_rowid" not in table_arrow.column_names + assert table_arrow["blob"].to_pylist() == [b"one", b"two", b"three", b"four"] assert table.to_pandas(blob_mode="bytes")["blob"].tolist() == [ b"one", b"two", From c9d176ae7e37efa9ed45dabb0cd5734250ed20f5 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 10:39:03 +0800 Subject: [PATCH 062/203] feat: resolve latest Function versions (#4949) ## Problem Function catalog lookup required an exact version string even though callers commonly need the latest currently visible immutable revision. On the current SDK, resolving that version required an out-of-band catalog query before calling `get_function`. ## Change - Make Python `get_function(name)` default to latest while accepting `int` or `str` for exact lookup. - Normalize integer versions to their decimal string form and reject `bool` explicitly. Existing string validation and errors remain unchanged. - Thread `None` through the rebuilt PyO3 binding and route it to the new Rust `Connection::get_function_latest`. - Resolve latest through the existing catalog `DESCRIBE FUNCTION` path without `WITH (version = ...)`. The returned value is one exact immutable version, not a mutable alias. - Preserve the existing Rust exact-version API. ## Validation On the designated EC2 host with the rebuilt extension: - `test_local_function_catalog_operations_are_not_supported`: **1 passed**. This crosses the Python connection, rebuilt PyO3, and embedded Rust `NotSupported` boundary with the omitted-version call. - Async and sync catalog-path tests: **2 passed**, 117 deselected. - Remote SQL Function creation/description integration test: **1 passed**. - An earlier Rust invocation with the wrong module path matched **0 tests**; it is retained as harness evidence and is not counted as a pass. ## Scope This is the Function lookup SDK slice. It does not include the separate atomic rebind/publication server work tracked under ENT-3418. --- docs/web/management/function.mdx | 14 +++++--- docs/web/sql/ddl/function.mdx | 5 ++- python/python/lancedb/_lancedb.pyi | 5 ++- python/python/lancedb/db.py | 34 ++++++++++++++++--- python/python/lancedb/remote/db.py | 5 +-- .../tests/test_first_class_function_slice2.py | 32 ++++++++++++++--- python/src/connection.rs | 16 ++++----- rust/lancedb/src/connection.rs | 23 +++++++++++-- rust/lancedb/src/database.rs | 8 +++++ rust/lancedb/src/remote/db.rs | 15 +++++++- rust/lancedb/src/remote/sql/function.rs | 11 +++--- rust/lancedb/src/remote/sql_test.rs | 8 +++++ .../tests/first_class_function_slice2.rs | 6 +++- 13 files changed, 147 insertions(+), 35 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index c8fa0626c..bebbe1169 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -107,7 +107,9 @@ single `id` is the SQL query UUID. Repeated waits reuse the completed result. `create_function` is the blocking equivalent. A registered version is fetched -with `db.get_function(name, version=...)`. +with `db.get_function(name, version=...)`. The version may be an integer or +its string form. Omit `version` to resolve and return the latest currently +visible revision. The SQL command submits an internal `create_function` image-build job and @@ -118,9 +120,10 @@ have no registry history and cannot be reopened with `open_job()`. ## List and describe {#list-describe} `list_functions` pages through every published version in a namespace, -ordered by name then version; `get_function` opens one exact version by -name and `version`. Both take `namespace_path`, defaulting to the root -namespace, the same as `create_function`. +ordered by name then version. `get_function` accepts an integer or string +version, or resolves the latest visible revision when `version` is omitted. +Both take `namespace_path`, defaulting to the root namespace, the same as +`create_function`. ```python Python icon="python" @@ -128,6 +131,7 @@ for version in db.list_functions(): print(version.name, version.version, version.created_at_millis) version = db.get_function("double", version="1") +latest = db.get_function("double") ``` ```rust @@ -140,6 +144,7 @@ while let Some(version) = versions.try_next().await? { } let version = connection.get_function("double", "1", &[]).await?; +let latest = connection.get_function_latest("double", &[]).await?; # Ok(()) # } ``` @@ -151,6 +156,7 @@ SHOW FUNCTIONS SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100) DESCRIBE FUNCTION double WITH (version = '1') +DESCRIBE FUNCTION double ``` diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 8cd45f8bc..95c2d4d6e 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -94,9 +94,12 @@ registration handle has type `query` and uses the SQL query UUID as its single ```sql DESCRIBE FUNCTION embed WITH (version = '1', include_source = true) +DESCRIBE FUNCTION embed ``` -DESCRIBE returns one `definition` JSON column for the exact version. +DESCRIBE returns one `definition` JSON column for the exact version. When +`version` is omitted, it resolves and returns the latest currently visible +immutable revision. `include_source` defaults to false; source-inclusive reads report an omission when the stored artifact exceeds the inline source limit. diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 81615ae73..4f676de8c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -190,7 +190,10 @@ class Connection(object): self, request_json: str, namespace_path: Optional[List[str]] = None ) -> Job: ... async def get_function( - self, name: str, version: str, namespace_path: Optional[List[str]] = None + self, + name: str, + version: Optional[str] = None, + namespace_path: Optional[List[str]] = None, ) -> str: ... def list_functions( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index a5d7aeb41..73c8305ff 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -140,6 +140,18 @@ def _view_description( ) +def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[str]: + if version is None: + return None + if isinstance(version, bool): + raise TypeError("version must be an int, str, or None") + if isinstance(version, int): + return str(version) + if isinstance(version, str): + return version + raise TypeError("version must be an int, str, or None") + + class DBConnection(EnforceOverrides): """An active LanceDB connection interface. @@ -1027,10 +1039,15 @@ class DBConnection(EnforceOverrides): self, name: str, *, - version: str, + version: Optional[Union[int, str]] = None, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: - """Open one exact immutable Function version from the remote catalog.""" + """Open an immutable Function version from the remote catalog. + + ``version`` may be an integer or string. When omitted, the server + resolves the latest currently visible revision and returns that exact + immutable version. + """ raise NotImplementedError( _append_doc_url( "Function catalog operations are not supported " @@ -2310,9 +2327,10 @@ class LanceDBConnection(DBConnection): self, name: str, *, - version: str, + version: Optional[Union[int, str]] = None, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: + version = _normalize_function_version(version) return LOOP.run( self._conn.get_function( name, version=version, namespace_path=namespace_path @@ -3610,10 +3628,16 @@ class AsyncConnection(object): self, name: str, *, - version: str, + version: Optional[Union[int, str]] = None, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: - """Open one exact immutable Function version from the remote catalog.""" + """Open an immutable Function version from the remote catalog. + + ``version`` may be an integer or string. When omitted, the server + resolves the latest currently visible revision and returns that exact + immutable version. + """ + version = _normalize_function_version(version) return FunctionVersion.from_json( await self._inner.get_function(name, version, namespace_path) ) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 2cc6bf056..ebceba16b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -37,7 +37,7 @@ import pyarrow as pa from ..common import DATA from lancedb.listing import Listing, NamespaceListing, TableListing -from ..db import DBConnection, LOOP +from ..db import DBConnection, LOOP, _normalize_function_version from ..functions import FunctionVersion, FunctionDefinition from ..graph import EdgeTable, NodeTable, PropertyGraph from ..job import AsyncJob, Job @@ -985,9 +985,10 @@ class RemoteDBConnection(DBConnection): self, name: str, *, - version: str, + version: Optional[Union[int, str]] = None, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: + version = _normalize_function_version(version) return LOOP.run( self._conn.get_function( name, version=version, namespace_path=namespace_path diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 53b0189f5..6f6c93f3f 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1894,6 +1894,8 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path): db.create_function_async(normalize_score) with pytest.raises(NotImplementedError, match=message): db.get_function("normalize_score", version=FUNCTION_VERSION) + with pytest.raises(NotImplementedError, match=message): + db.get_function("normalize_score") with pytest.raises(NotImplementedError, match=message): list(db.list_functions()) with pytest.raises(NotImplementedError, match=message): @@ -1903,8 +1905,10 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path): class _RawFunctionCatalog: def __init__(self, definition, *, encode=False): self.definition = json.dumps(definition) if encode else definition + self.requested_versions = [] - async def get_function(self, _name, version, namespace_path): + async def get_function(self, _name, version=None, namespace_path=None): + self.requested_versions.append(version) return self.definition def list_functions(self, *, namespace_path=None, page_token=None, page_limit=None): @@ -1944,13 +1948,22 @@ async def test_async_catalog_path_preserves_execution_controls(): row_timeout_seconds=8.0, result_stability="input_and_context", ) - connection = AsyncConnection(_RawFunctionCatalog(definition, encode=True)) + catalog = _RawFunctionCatalog(definition, encode=True) + connection = AsyncConnection(catalog) + latest = await connection.get_function("embed") + integer = await connection.get_function("embed", version=1) exact = await connection.get_function("embed", version="1") + await connection.get_function("embed", version="001") listed = [item async for item in connection.list_functions(page_limit=32)] assert len(listed) == 1 - for version in [exact, *listed]: + for version in [latest, integer, exact, *listed]: assert _assert_execution_control_encoding(version) == definition + assert catalog.requested_versions == [None, "1", "1", "001"] + with pytest.raises(TypeError, match="int, str, or None"): + await connection.get_function("embed", version=True) + with pytest.raises(TypeError, match="int, str, or None"): + await connection.get_function("embed", version=1.5) def test_sync_catalog_path_preserves_execution_controls(): @@ -1963,13 +1976,22 @@ def test_sync_catalog_path_preserves_execution_controls(): result_stability="input_and_context", ) connection = object.__new__(RemoteDBConnection) - connection._conn = _RawFunctionCatalog(FunctionVersion(**definition)) + catalog = _RawFunctionCatalog(FunctionVersion(**definition)) + connection._conn = catalog + latest = connection.get_function("embed") + integer = connection.get_function("embed", version=1) exact = connection.get_function("embed", version="1") + connection.get_function("embed", version="001") listed = list(connection.list_functions(page_limit=32)) assert len(listed) == 1 - for version in [exact, *listed]: + for version in [latest, integer, exact, *listed]: assert _assert_execution_control_encoding(version) == definition + assert catalog.requested_versions == [None, "1", "1", "001"] + with pytest.raises(TypeError, match="int, str, or None"): + connection.get_function("embed", version=True) + with pytest.raises(TypeError, match="int, str, or None"): + connection.get_function("embed", version=1.5) def test_sync_drop_function_emits_server_warnings_without_changing_bool_api(): diff --git a/python/src/connection.rs b/python/src/connection.rs index bffa167d8..0be933cf2 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -877,22 +877,22 @@ impl Connection { }) } - #[pyo3(signature = (name, version, namespace_path=None))] + #[pyo3(signature = (name, version=None, namespace_path=None))] pub fn get_function( self_: PyRef<'_, Self>, name: String, - version: String, + version: Option, namespace_path: Option>, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { - inner - .get_function(name, version, &namespace_path) - .await - .infer_error()? - .to_canonical_json() - .infer_error() + let function = match version { + Some(version) => inner.get_function(name, version, &namespace_path).await, + None => inner.get_function_latest(name, &namespace_path).await, + } + .infer_error()?; + function.to_canonical_json().infer_error() }) } diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index dec5e1359..a360818b5 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -668,9 +668,10 @@ impl Connection { /// Look up one exact immutable Function version in the remote catalog. /// - /// Both the logical name and server-assigned version id are required; - /// mutable aliases and latest-version lookup are intentionally absent. - /// LanceDB Embedded databases return [`Error::NotSupported`]. + /// Both the logical name and server-assigned version id are required. + /// Use [`Self::get_function_latest`] when the caller wants the latest + /// currently visible revision. LanceDB Embedded databases return + /// [`Error::NotSupported`]. pub async fn get_function( &self, name: impl AsRef, @@ -682,6 +683,22 @@ impl Connection { .await } + /// Look up the latest currently visible immutable Function version. + /// + /// The server resolves and returns one exact version document. This is a + /// resolution point, not a mutable alias: later registrations do not + /// change the returned object. LanceDB Embedded databases return + /// [`Error::NotSupported`]. + pub async fn get_function_latest( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result { + self.internal + .get_function_latest(name.as_ref(), namespace_path) + .await + } + /// List every published immutable Function version in `namespace_path` of /// the remote catalog. Functions in child namespaces are not included. /// diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 44d038521..bcdfd94b8 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -552,6 +552,14 @@ pub trait Database: ) -> Result { function_catalog_not_supported() } + /// Look up the latest currently visible immutable Function version. + async fn get_function_latest( + &self, + _name: &str, + _namespace_path: &[String], + ) -> Result { + function_catalog_not_supported() + } /// Fetch one page of published immutable Function versions in one namespace. async fn list_functions( &self, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index c33c7267d..a4952593b 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -887,7 +887,20 @@ impl Database for RemoteDatabase { validate_function_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .describe_function(name, version, namespace_path) + .describe_function(name, Some(version), namespace_path) + .await + .map_err(direct_catalog_resource_error) + } + + async fn get_function_latest( + &self, + name: &str, + namespace_path: &[String], + ) -> Result { + validate_function_name(name)?; + validate_namespace(namespace_path)?; + self.sql_client()? + .describe_function(name, None, namespace_path) .await .map_err(direct_catalog_resource_error) } diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index e90792a8a..c2b5aba06 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -51,17 +51,20 @@ impl SqlClient { pub(in crate::remote) async fn describe_function( &self, name: &str, - version: &str, + version: Option<&str>, namespace: &[String], ) -> Result { validate_function_name(name)?; validate_namespace(namespace)?; + let version_clause = match version { + Some(version) => format!(" WITH (version = {})", literal(version)), + None => String::new(), + }; self.object_job( ExecuteQueryRequest { query: format!( - "DESCRIBE FUNCTION {} WITH (version = {})", - quote_identifier(name), - literal(version) + "DESCRIBE FUNCTION {}{version_clause}", + quote_identifier(name) ), default_namespace_path: namespace.to_vec(), parameters: None, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 8ac08f10c..3d728aa3e 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3049,6 +3049,13 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(described_json["batch_size"], 12); assert_eq!(described_json["row_timeout_seconds"], 8.0); assert_eq!(described_json["result_stability"], "input_and_context"); + let latest = db + .get_function_latest("embed", &["team".into()]) + .await + .unwrap(); + assert_eq!(latest.name(), "embed"); + assert_eq!(latest.version(), "1"); + assert_eq!(latest.batch_size(), Some(12)); let listed = db .list_functions(&["team".into()], Default::default()) .await @@ -3068,6 +3075,7 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(listed_json["result_stability"], "input_and_context"); let seen = statements.lock().unwrap(); assert_eq!(seen[1], "DESCRIBE FUNCTION \"embed\" WITH (version = '1')"); + assert_eq!(seen[2], "DESCRIBE FUNCTION \"embed\""); shutdown.send(()).unwrap(); } } diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index fe8fc27c5..77432702a 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -156,11 +156,15 @@ async fn local_function_catalog_operations_return_stable_not_supported() { .get_function("normalize_score", "1", &[]) .await .unwrap_err(); + let latest_lookup_error = connection + .get_function_latest("normalize_score", &[]) + .await + .unwrap_err(); let drop_error = connection .drop_function("normalize_score", "1", &[]) .await .unwrap_err(); - for error in [create_error, lookup_error, drop_error] { + for error in [create_error, lookup_error, latest_lookup_error, drop_error] { assert!(matches!( error, Error::NotSupported { message } From 8029428c7152e6b018dcab31f5240e3144caab68 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 11:23:17 +0800 Subject: [PATCH 063/203] feat: persist automatic Function refresh resource budgets (#4953) ## Depends on merged #4951 Phase 1 merged as `4d22c0ce2b6825c880c818e737b079db494b4053`, so this PR now targets `main`. It reuses the canonical `FunctionWorkerResourceBudget` introduced there rather than copying the type. For Function `add_columns` declarations, Python and Rust now persist `auto_refresh_resource_budget` in computed-column metadata and send it as `auto_refresh_resource_budget` in the remote request. CPU milliseconds and memory bytes are required positive integers. Omitting `gpu_count` is accepted as zero and the canonical outgoing JSON still contains `"gpu_count": 0`. Unknown fields, missing CPU or memory, wrong types, zero CPU or memory, negative values, and overflow are rejected. The same budget is applied to every public output binding of a multi-output Function declaration. Existing metadata is retained, and SQL-expression declarations or local execution reject the budget instead of silently ignoring it. Node is unchanged because its current `addColumns` surface only accepts SQL computed expressions and has no Function declaration path. This change does not implement fleet call concurrency limits or enforce the budget in the runtime. The Enterprise server must support the nested Function worker resource-budget contract before these values can act as execution limits. ## Validation - Python extension build passed. - Remote Function declaration and local unsupported-path rejection each passed. - Canonical metadata round-trip passed, including omitted GPU decoding to zero and explicit `gpu_count: 0` on encode. - Function multi-output remote wire test passed with `--features remote`. - Repository-scoped Python type check passed with 0 errors. - All runtime source blobs match the native-tested source. The post-native deltas are one documentation example line and an existing routing-test stub update for the new optional argument; the affected parameterized test passed 3/3 against the existing extension build. No private test runners are part of this PR. --- .../add-computed-column.mdx | 46 ++++- .../feature-engineering/refresh-column.mdx | 8 +- python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/remote/table.py | 2 + python/python/lancedb/table.py | 19 +++ .../tests/test_first_class_function_slice1.py | 6 +- python/python/tests/test_remote_db.py | 87 ++++++++++ python/python/tests/test_table.py | 15 ++ python/src/table.rs | 24 ++- rust/lancedb/src/remote/table.rs | 17 ++ rust/lancedb/src/table/add_columns.rs | 43 ++++- rust/lancedb/src/table/computed_columns.rs | 159 +++++++++++++++++- rust/lancedb/src/table/refresh.rs | 30 ++-- 13 files changed, 427 insertions(+), 31 deletions(-) diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 2c9e9be4c..851b37d9b 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -60,9 +60,49 @@ columns through `col(...)`, keyed by the output column name. It commits a new, empty table version the same way a SQL expression does, so the usual [versioning](/management/table#versioning) applies. -Both a Function application and a SQL expression accept the same -`auto_refresh_enabled` and `auto_refresh_interval_seconds` options, and both -refresh and toggle the same way; see [Auto Refresh](/enterprise/auto-refresh). +Both a Function application and a SQL expression accept +`auto_refresh_enabled` and `auto_refresh_interval_seconds`, and both refresh +and toggle the same way; see [Auto Refresh](/enterprise/auto-refresh). + +Python and Rust Function declarations can also set +`auto_refresh_resource_budget` to give their automatic refreshes an aggregate +CPU, memory, and optional GPU budget. CPU and memory are required. The nested +`gpu_count` defaults to zero, so omitting it requests CPU-only workers: + + +```python Python icon="python" +table.add_columns( + {"caption": version(jpeg=col("jpeg"))}, + auto_refresh_resource_budget={ + "cpu_millis": 8000, + "memory_bytes": 16 * 1024**3, + }, +) +``` + +```rust Rust icon="rust" +table + .add_columns() + .function(function_application) + .computed_options(ComputedColumnOptions { + auto_refresh_enabled: true, + auto_refresh_interval_seconds: None, + auto_refresh_resource_budget: Some( + FunctionWorkerResourceBudget::new(8000, 17_179_869_184), + ), + }) + .execute() + .await?; +``` + + +This setting applies to every output in the Function binding. SQL-expression +columns do not use Function workers, so they reject +`auto_refresh_resource_budget` instead of accepting an option that has no +effect. The separate `resource_budget` refresh option configures one explicit +refresh and does not change this automatic-refresh declaration. The Node.js +SDK does not currently expose a Function declaration through `addColumns`, so +this option is not added to an unsupported surface. ## Fill a column with a SQL expression {#expressions} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 043c712cb..62328d790 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -219,9 +219,11 @@ for changing only the aggregate GPU budget. It cannot be combined with the complete resource budget. Omitting both preserves the server's existing defaults. -These examples configure only the explicit refresh shown. They do not set the -budget for an automatic refresh scheduled after `add_columns`; that remains a -separate declaration and scheduler capability. +These examples configure only the explicit refresh shown. A registered +Function declaration can separately set `auto_refresh_resource_budget` on +`add_columns`; that declaration controls the budget for its automatic +refreshes. SQL-expression columns reject the automatic resource-budget option +because they do not use Function workers. `batch_size` caps rows in one Function call; LanceDB adapts actual call and work sizes. For Function columns, the refresh defaults to diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4f676de8c..fafa21cbf 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -615,6 +615,7 @@ class Table: columns: list[tuple[str, str]], auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[int] = None, + auto_refresh_resource_budget: Optional[dict[str, int]] = None, ) -> AddColumnsResult: ... async def add_function_columns( self, @@ -622,6 +623,7 @@ class Table: output_name: Optional[str], auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[int] = None, + auto_refresh_resource_budget: Optional[dict[str, int]] = None, ) -> AddColumnsResult: ... async def refresh_column( self, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index f389f313f..4aca6bcc5 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1127,6 +1127,7 @@ class RemoteTable(Table): computed: Dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, + auto_refresh_resource_budget: Optional[Dict[str, int]] = None, ) -> AddColumnsResult: return LOOP.run( self._table.add_columns( @@ -1134,6 +1135,7 @@ class RemoteTable(Table): computed=computed, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + auto_refresh_resource_budget=auto_refresh_resource_budget, ) ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index f113baa05..a4d40c901 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3085,6 +3085,7 @@ class Table(ABC): computed: Dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, + auto_refresh_resource_budget: Optional[Dict[str, int]] = None, ): """ Add new columns with defined values. @@ -3153,6 +3154,12 @@ class Table(ABC): When omitted, the server determines when to refresh. Applies to every computed output in this call. Scheduling options require computed or Function columns. + auto_refresh_resource_budget: dict[str, int], optional + Aggregate CPU, memory, and GPU budget for automatic refreshes of a + registered Function declaration. ``cpu_millis`` and + ``memory_bytes`` are required; ``gpu_count`` defaults to zero. + This option cannot be used with SQL-expression columns. LanceDB + Enterprise only. Returns ------- @@ -5468,6 +5475,7 @@ class LanceTable(Table): computed: Dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, + auto_refresh_resource_budget: Optional[Dict[str, int]] = None, ) -> AddColumnsResult: return LOOP.run( self._table.add_columns( @@ -5475,6 +5483,7 @@ class LanceTable(Table): computed=computed, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + auto_refresh_resource_budget=auto_refresh_resource_budget, ) ) @@ -7758,6 +7767,7 @@ class AsyncTable: computed: dict[str, str] | None = None, auto_refresh_enabled: bool | None = None, auto_refresh_interval_seconds: int | None = None, + auto_refresh_resource_budget: Optional[Dict[str, int]] = None, ) -> AddColumnsResult: """ Add new columns with defined values. @@ -7824,6 +7834,12 @@ class AsyncTable: not force recomputation. Applies to every declared computed output. These options cannot be used with one-time transforms or ordinary all-null columns. + auto_refresh_resource_budget: dict[str, int], optional + Aggregate CPU, memory, and GPU budget for automatic refreshes of + registered Function outputs. ``cpu_millis`` and ``memory_bytes`` + are required; ``gpu_count`` defaults to zero. SQL-expression + columns do not use Function workers and reject this option. + LanceDB Enterprise only. Examples -------- @@ -7852,6 +7868,7 @@ class AsyncTable: options_supplied = ( auto_refresh_enabled is not None or auto_refresh_interval_seconds is not None + or auto_refresh_resource_budget is not None ) function_application = None function_output_name = None @@ -7880,6 +7897,7 @@ class AsyncTable: function_output_name, auto_refresh_enabled, auto_refresh_interval_seconds, + auto_refresh_resource_budget, ) if isinstance(transforms, pa.Field): @@ -7900,6 +7918,7 @@ class AsyncTable: list(computed.items()), auto_refresh_enabled, auto_refresh_interval_seconds, + auto_refresh_resource_budget, ) if options_supplied: raise ValueError( diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 27a9a9376..c392fdc7f 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -459,6 +459,7 @@ class _FunctionDeclarationInner: output_name, auto_refresh_enabled, auto_refresh_interval_seconds, + auto_refresh_resource_budget, ): self.calls.append( ( @@ -466,6 +467,7 @@ class _FunctionDeclarationInner: output_name, auto_refresh_enabled, auto_refresh_interval_seconds, + auto_refresh_resource_budget, ) ) return "declared" @@ -491,7 +493,7 @@ 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) + assert inner.calls[-1][2:] == (None, None, None) bare = application._copy(update={"columns": {}}).rename( columns={"normalized_text": "search_text"} @@ -502,7 +504,7 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica 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) + assert inner.calls[-1][2:] == (False, 300, None) @pytest.mark.asyncio diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 109dbfbdb..2547cf807 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -36,6 +36,7 @@ from lancedb.graph import ( PropertyGraph, PropertyGraphDescription, ) +from lancedb.functions import FunctionApplication from lancedb.query import ( AsyncQuery, ColumnOrdering, @@ -5831,6 +5832,92 @@ def test_remote_add_columns_reader_not_supported(): assert all("/add_columns/" not in path for path in requests) +@pytest.mark.asyncio +async def test_remote_add_function_columns_forwards_auto_refresh_resource_budget(): + bodies = [] + application = FunctionApplication.from_json( + json.dumps( + { + "function": { + "name": "embed", + "version": "1", + "object_id": "fixture", + "location": "memory:///fixture", + "manifest_digest": ( + "sha256:7e22f815b6648e14f093a3979a8e5a2082" + "fa773ebe1ec84b135cae7e84d6f8e6" + ), + }, + "inputs": [ + { + "parameter": "text", + "kind": "column", + "value": {"path": "text"}, + } + ], + "output": { + "kind": "scalar", + "arrow_type": "float32", + "nullable": False, + }, + } + ) + ) + + def handler(request): + if request.path == "/v1/table/test/describe/": + response = { + "version": 1, + "schema": { + "fields": [ + { + "name": "text", + "type": {"type": "string"}, + "nullable": True, + } + ] + }, + } + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + elif request.path == "/v1/table/test/add_columns/": + content_len = int(request.headers.get("Content-Length", 0)) + bodies.append(json.loads(request.rfile.read(content_len))) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b'{"version": 2}') + else: + request.send_response(404) + request.end_headers() + + budget = {"cpu_millis": 2_000, "memory_bytes": 4 * 1024**3} + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + table.add_columns( + {"embedding": application}, + auto_refresh_resource_budget=budget, + ) + + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + await table.add_columns( + {"embedding": application}, + auto_refresh_resource_budget=budget, + ) + + assert len(bodies) == 2 + for body in bodies: + assert body["auto_refresh_enabled"] is True + assert body["auto_refresh_resource_budget"] == { + **budget, + "gpu_count": 0, + } + assert body["new_columns"] == [{"name": "embedding", "all_null": True}] + + @pytest.mark.asyncio async def test_async_property_graph_handles(): calls = [] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 2422437c2..6c9485ced 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6255,6 +6255,21 @@ def test_auto_refresh_options_require_computed_columns(tmp_path): table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True) +def test_auto_refresh_resource_budget_requires_a_function(tmp_path): + table = lancedb.connect(tmp_path).create_table("invalid_budget", [{"x": 1}]) + before = table.version + with pytest.raises(ValueError, match="registered Function"): + table.add_columns( + computed={"doubled": "x * 2"}, + auto_refresh_resource_budget={ + "cpu_millis": 1_000, + "memory_bytes": 1_024, + }, + ) + assert table.version == before + assert table.schema.names == ["x"] + + @pytest.mark.experimental_functions @pytest.mark.asyncio async def test_async_computed_auto_refresh_uses_server_interval(tmp_path): diff --git a/python/src/table.rs b/python/src/table.rs index 56fc3bf5c..07dc49979 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2217,17 +2217,21 @@ impl Table { }) } - #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] - pub fn add_computed_columns( - self_: PyRef<'_, Self>, + #[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))] + pub fn add_computed_columns<'py>( + self_: PyRef<'py, Self>, columns: Vec<(String, String)>, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - ) -> PyResult> { + auto_refresh_resource_budget: Option>, + ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let options = ComputedColumnOptions { auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true), auto_refresh_interval_seconds, + auto_refresh_resource_budget: parse_resource_budget( + auto_refresh_resource_budget.as_ref(), + )?, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { @@ -2244,20 +2248,24 @@ impl Table { }) } - #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] - pub fn add_function_columns( - self_: PyRef<'_, Self>, + #[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))] + pub fn add_function_columns<'py>( + self_: PyRef<'py, Self>, application_json: String, output_name: Option, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, - ) -> PyResult> { + auto_refresh_resource_budget: 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, + auto_refresh_resource_budget: parse_resource_budget( + auto_refresh_resource_budget.as_ref(), + )?, }; options.validate().infer_error()?; future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 4f428809c..ee9b3827b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3951,6 +3951,9 @@ impl BaseTable for RemoteTable { if let Some(interval) = options.auto_refresh_interval_seconds { body["auto_refresh_interval_seconds"] = serde_json::json!(interval); } + if let Some(budget) = options.auto_refresh_resource_budget { + body["auto_refresh_resource_budget"] = serde_json::json!(budget); + } self.apply_branch_body(&mut body); let request = self .client @@ -10361,6 +10364,7 @@ mod tests { .computed_options(crate::table::computed_columns::ComputedColumnOptions { auto_refresh_enabled: false, auto_refresh_interval_seconds: interval, + auto_refresh_resource_budget: None, }) .execute() .await @@ -10797,6 +10801,11 @@ mod tests { )) .unwrap(); expected["auto_refresh_enabled"] = serde_json::json!(true); + expected["auto_refresh_resource_budget"] = serde_json::json!({ + "cpu_millis": 8_000, + "memory_bytes": 17_179_869_184_u64, + "gpu_count": 2, + }); assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -10824,6 +10833,14 @@ mod tests { let result = table .add_columns() .function(application) + .computed_options(crate::table::computed_columns::ComputedColumnOptions { + auto_refresh_enabled: true, + auto_refresh_interval_seconds: None, + auto_refresh_resource_budget: Some( + crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) + .with_gpu_count(2), + ), + }) .execute() .await .unwrap(); diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 1b827bb37..a76c0d043 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -171,7 +171,9 @@ impl AddColumnsBuilder { /// Configure automatic refresh for every output declared in this call. /// Settings are stored with the declaration. They require computed or - /// Function columns; LanceDB Embedded persists them without starting a scheduler. + /// Function columns. LanceDB Embedded persists enabled and interval settings + /// without starting a scheduler; an automatic resource budget requires an + /// Enterprise registered Function and rejects SQL-expression columns. /// /// ``` /// # use lancedb::{Table, table::computed_columns::ComputedColumnOptions}; @@ -180,6 +182,7 @@ impl AddColumnsBuilder { /// .computed_options(ComputedColumnOptions { /// auto_refresh_enabled: true, /// auto_refresh_interval_seconds: Some(300), + /// auto_refresh_resource_budget: None, /// }).execute().await?; /// # Ok(()) /// # } @@ -207,6 +210,13 @@ impl AddColumnsBuilder { .into(), }); } + if options.auto_refresh_resource_budget.is_some() && function.is_none() { + return Err(Error::InvalidInput { + message: + "auto_refresh_resource_budget requires a registered Function declaration" + .into(), + }); + } } let options = options.unwrap_or_default(); @@ -289,6 +299,7 @@ mod tests { let options = ComputedColumnOptions { auto_refresh_enabled: false, auto_refresh_interval_seconds: Some(300), + auto_refresh_resource_budget: None, }; let result = table .add_columns() @@ -373,6 +384,36 @@ mod tests { ); } + #[tokio::test] + async fn auto_refresh_resource_budget_requires_a_function() { + let table = table_with_two_columns("budget_expression").await; + let err = table + .add_columns() + .computed("doubled", "x * 2") + .computed_options(ComputedColumnOptions { + auto_refresh_enabled: true, + auto_refresh_interval_seconds: None, + auto_refresh_resource_budget: Some( + crate::table::FunctionWorkerResourceBudget::new(1_000, 1_024), + ), + }) + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("registered Function")), + "{err:?}" + ); + assert!( + table + .schema() + .await + .unwrap() + .field_with_name("doubled") + .is_err() + ); + } + #[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 e6d7d432c..8fce7a260 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -42,6 +42,7 @@ use serde_json::Value; use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding}; use crate::materialized_view::without_declarations; +use crate::table::FunctionWorkerResourceBudget; use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; @@ -61,6 +62,9 @@ pub const INPUTS_META_KEY: &str = "computed_column.inputs"; 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"; +/// Aggregate worker-resource budget for automatic Function refreshes. +pub const AUTO_REFRESH_RESOURCE_BUDGET_META_KEY: &str = + "computed_column.auto_refresh_resource_budget"; /// Scheduling settings persisted on each computed output. LanceDB Embedded /// stores these settings; automatic scheduling requires LanceDB Enterprise. @@ -73,6 +77,10 @@ pub struct ComputedColumnOptions { /// When omitted, the server determines when to refresh. #[serde(skip_serializing_if = "Option::is_none")] pub auto_refresh_interval_seconds: Option, + /// Aggregate worker-resource budget for automatic Function refreshes. + /// This option requires a registered Function output. + #[serde(skip_serializing_if = "Option::is_none")] + pub auto_refresh_resource_budget: Option, } impl Default for ComputedColumnOptions { @@ -80,6 +88,7 @@ impl Default for ComputedColumnOptions { Self { auto_refresh_enabled: true, auto_refresh_interval_seconds: None, + auto_refresh_resource_budget: None, } } } @@ -95,6 +104,9 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer no greater than u64::MAX / 1000".into(), }); } + if let Some(budget) = &self.auto_refresh_resource_budget { + budget.validate()?; + } Ok(()) } @@ -112,6 +124,15 @@ impl ComputedColumnOptions { message: "auto_refresh_interval_seconds must be a positive integer".into(), })?); } + if let Some(value) = metadata.get(AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) { + options.auto_refresh_resource_budget = Some(serde_json::from_str(value).map_err( + |error| Error::InvalidInput { + message: format!( + "auto_refresh_resource_budget must be a valid resource budget: {error}" + ), + }, + )?); + } options.validate()?; Ok(options) } @@ -119,6 +140,7 @@ impl ComputedColumnOptions { /// Attach validated settings to newly declared computed output fields. pub fn apply_to_schema(&self, schema: &ArrowSchema) -> Result { self.validate()?; + let option_metadata = self.metadata()?; let fields = schema .fields() .iter() @@ -134,7 +156,7 @@ impl ComputedColumnOptions { return field.clone(); } let mut metadata = field.metadata().clone(); - metadata.extend(self.metadata()); + metadata.extend(option_metadata.clone()); Arc::new(field.as_ref().clone().with_metadata(metadata)) }) .collect::>(); @@ -145,7 +167,7 @@ impl ComputedColumnOptions { } /// Field metadata values shared by native and server declaration paths. - pub fn metadata(&self) -> HashMap { + pub fn metadata(&self) -> Result> { let mut metadata = HashMap::from([( AUTO_REFRESH_ENABLED_META_KEY.into(), self.auto_refresh_enabled.to_string(), @@ -153,7 +175,15 @@ impl ComputedColumnOptions { if let Some(interval) = self.auto_refresh_interval_seconds { metadata.insert(AUTO_REFRESH_INTERVAL_META_KEY.into(), interval.to_string()); } - metadata + if let Some(budget) = &self.auto_refresh_resource_budget { + metadata.insert( + AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), + serde_json::to_string(budget).map_err(|error| Error::InvalidInput { + message: format!("failed to encode auto_refresh_resource_budget: {error}"), + })?, + ); + } + Ok(metadata) } } @@ -2533,6 +2563,129 @@ pub(crate) mod test_support { #[cfg(test)] mod tests { + #[test] + fn computed_auto_refresh_resource_budget_metadata_round_trips() { + let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) + .with_gpu_count(2); + let options = super::ComputedColumnOptions { + auto_refresh_enabled: true, + auto_refresh_interval_seconds: Some(300), + auto_refresh_resource_budget: Some(budget), + }; + assert_eq!( + super::ComputedColumnOptions::from_metadata(&HashMap::new()).unwrap(), + super::ComputedColumnOptions::default() + ); + let metadata = options.metadata().unwrap(); + assert_eq!( + metadata + .get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) + .map(String::as_str), + Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2}"#) + ); + assert_eq!( + super::ComputedColumnOptions::from_metadata(&metadata).unwrap(), + options + ); + + let mut omitted_gpu = metadata.clone(); + omitted_gpu.insert( + super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), + r#"{"cpu_millis":8000,"memory_bytes":17179869184}"#.into(), + ); + let decoded = super::ComputedColumnOptions::from_metadata(&omitted_gpu).unwrap(); + assert_eq!(decoded.auto_refresh_resource_budget.unwrap().gpu_count, 0); + assert_eq!( + decoded + .metadata() + .unwrap() + .get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) + .map(String::as_str), + Some(r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":0}"#) + ); + + for invalid in [ + r#"{"memory_bytes":17179869184,"gpu_count":2}"#, + r#"{"cpu_millis":8000,"gpu_count":2}"#, + r#"{"cpu_millis":"8000","memory_bytes":17179869184,"gpu_count":2}"#, + r#"{"cpu_millis":-1,"memory_bytes":17179869184,"gpu_count":2}"#, + r#"{"cpu_millis":18446744073709551616,"memory_bytes":17179869184,"gpu_count":2}"#, + r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":-1}"#, + r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":4294967296}"#, + r#"{"cpu_millis":8000,"memory_bytes":17179869184,"gpu_count":2,"unknown":1}"#, + r#"{"cpu_millis":0,"memory_bytes":17179869184,"gpu_count":2}"#, + r#"{"cpu_millis":8000,"memory_bytes":0,"gpu_count":2}"#, + ] { + let mut malformed = metadata.clone(); + malformed.insert( + super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY.into(), + invalid.into(), + ); + assert!( + super::ComputedColumnOptions::from_metadata(&malformed).is_err(), + "accepted invalid budget: {invalid}" + ); + } + } + + #[test] + fn computed_auto_refresh_resource_budget_applies_to_function_outputs() { + let function_field = |name: &str, ordinal: u32| { + ArrowField::new(name, DataType::Int32, true).with_metadata(HashMap::from([ + ( + super::COMPUTED_COLUMN_META_KEY.to_string(), + "true".to_string(), + ), + ( + super::KIND_META_KEY.to_string(), + super::FUNCTION_KIND.to_string(), + ), + ( + super::FUNCTION_BINDING_ID_META_KEY.to_string(), + "binding-1".to_string(), + ), + ( + super::FUNCTION_OUTPUT_ORDINAL_META_KEY.to_string(), + ordinal.to_string(), + ), + ("custom".to_string(), "preserved".to_string()), + ])) + }; + let schema = ArrowSchema::new(vec![ + ArrowField::new("input", DataType::Int32, true), + function_field("first", 0), + function_field("second", 1), + function_field("assignment", super::FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL), + ]); + let budget = crate::table::FunctionWorkerResourceBudget::new(8_000, 17_179_869_184) + .with_gpu_count(2); + let updated = super::ComputedColumnOptions { + auto_refresh_resource_budget: Some(budget), + ..Default::default() + } + .apply_to_schema(&schema) + .unwrap(); + + for name in ["first", "second"] { + let metadata = updated.field_with_name(name).unwrap().metadata(); + assert_eq!( + metadata.get(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY), + Some(&serde_json::to_string(&budget).unwrap()) + ); + assert_eq!( + metadata.get("custom").map(String::as_str), + Some("preserved") + ); + } + assert!( + !updated + .field_with_name("assignment") + .unwrap() + .metadata() + .contains_key(super::AUTO_REFRESH_RESOURCE_BUDGET_META_KEY) + ); + } + /// The gate's reproducer: the validator applies the same schema-level /// guard declaring does, so a staging caller is refused before it commits /// anything else. diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 742d60f18..31c165be6 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -61,12 +61,14 @@ use crate::{Error, Result}; /// values cap the Function workers together; they are not per-worker /// allocations. The default GPU budget is zero, which describes a CPU-only /// Function. This option is rejected by LanceDB Embedded refreshes. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] #[non_exhaustive] pub struct FunctionWorkerResourceBudget { pub cpu_millis: u64, pub memory_bytes: u64, /// Aggregate GPU budget across the refresh. Zero is CPU-only. + #[serde(default)] pub gpu_count: u32, } @@ -85,6 +87,21 @@ impl FunctionWorkerResourceBudget { self.gpu_count = gpu_count; self } + + /// Require every per-tier resource limit to request at least one unit. + pub fn validate(&self) -> Result<()> { + if self.cpu_millis == 0 { + return Err(Error::InvalidInput { + message: "resource_budget.cpu_millis must be greater than zero".into(), + }); + } + if self.memory_bytes == 0 { + return Err(Error::InvalidInput { + message: "resource_budget.memory_bytes must be greater than zero".into(), + }); + } + Ok(()) + } } /// Options for refreshing a computed column. @@ -329,16 +346,7 @@ impl RefreshColumnOptions { }); } if let Some(budget) = &self.resource_budget { - if budget.cpu_millis == 0 { - return Err(Error::InvalidInput { - message: "resource_budget.cpu_millis must be greater than zero".into(), - }); - } - if budget.memory_bytes == 0 { - return Err(Error::InvalidInput { - message: "resource_budget.memory_bytes must be greater than zero".into(), - }); - } + budget.validate()?; } if let Some(gpu_class) = &self.gpu_class { validate_gpu_class_name(gpu_class)?; From cf8e6d0fd459250c20ff1e36a409632212113b59 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 14:32:26 +0800 Subject: [PATCH 064/203] feat: expose Function call concurrency limits (#4956) ## Summary Adds an optional `max_concurrency` setting to Function registration and explicit refresh: - A registered Function version can define the default maximum number of user-code calls in flight for one logical execution. - A refresh can override that default for that execution only. - The value must be a positive `u32` and is independent from `resource_budget`; it is not an account-wide quota. - Omitting the option preserves the previous request payload. Local embedded refreshes reject this Enterprise-only option. Rust, Python sync/async, PyO3, and the existing Node refresh surface forward the option. Node has no Function registration surface today, so no registration API is added there. The generated TypeDoc pages are included for the new public option. ## Validation The native-tested source covers Function version decoding, registration validation and serialization, the Flight SQL registration ticket and returned version, remote refresh forwarding, local rejection, and Node's numeric boundary before conversion. Exact stage results are Rust `1+3` plus four remote cases at `1` each; Python `14/1/49/24`; Node `57` remote and `1` local rejection. Ruff, standard repository Pyright, and Biome passed. The tested Python extension was `21aa256a970f4a16ea8253d68401d0fc573d946412e8752155dfcad63f30654d`; the tested Node addon and generated native declaration were `f6089f861981f96f8ce0f6dbef43de0907b9eeb4b63e84cdd5da14e00d6cbd30` and `4c4ceb205824075d706897c726c215dcf839880c757f0d0582d24cec5f938416`. The final 24-file diff preserves the 22 tested product/test/fixture/source-doc blobs and adds only two generated TypeDoc pages. --- docs/src/js/classes/Table.md | 8 ++- .../src/js/interfaces/RefreshColumnOptions.md | 11 ++++ docs/web/curation/create-function.mdx | 16 +++--- .../feature-engineering/refresh-column.mdx | 33 ++++++++++++ nodejs/__test__/remote.test.ts | 15 +++++- nodejs/__test__/table.test.ts | 3 ++ nodejs/lancedb/table.ts | 8 ++- nodejs/src/table.rs | 20 ++++++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/functions.py | 39 +++++++++++++-- python/python/lancedb/remote/table.py | 4 ++ python/python/lancedb/table.py | 34 +++++++++++++ .../tests/test_first_class_function_slice1.py | 6 +++ .../tests/test_first_class_function_slice2.py | 6 +++ python/python/tests/test_remote_db.py | 49 +++++++++++++++++- python/python/tests/test_table.py | 1 + python/src/table.rs | 36 ++++++++++++- rust/lancedb/src/function.rs | 50 +++++++++++++++++++ rust/lancedb/src/remote/sql_test.rs | 15 ++++++ rust/lancedb/src/remote/table.rs | 6 +++ rust/lancedb/src/table/refresh.rs | 19 +++++++ .../tests/first_class_function_slice2.rs | 10 ++++ ...rolled_registration_request.canonical.json | 2 +- ...ction_controlled_registration_request.json | 1 + 24 files changed, 376 insertions(+), 18 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 5ab1751d4..27acc9847 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1142,8 +1142,11 @@ LanceDB Enterprise it is the server's backfill job. `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, - `resourceBudget` and `maxExecutorProcessesPerWorker` size registered - Function refreshes. A `resourceBudget` requires `cpuMillis` and + `maxConcurrency`, `resourceBudget` and + `maxExecutorProcessesPerWorker` size registered Function refreshes. + `maxConcurrency` overrides the registered default for this logical + execution only and is a positive integer; it is not an account-wide + quota. A `resourceBudget` requires `cpuMillis` and `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. The budget applies only to this explicit refresh and does not configure a later automatic refresh. @@ -1167,6 +1170,7 @@ const job = await table.refreshColumnAsync("embedding", { cpuMillis: 8000, memoryBytes: 16 * 1024 ** 3, }, + maxConcurrency: 4, errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 151cbb72f..6cc8f7f8f 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -64,6 +64,17 @@ Deadline for Function initialization, in seconds. *** +### maxConcurrency? + +```ts +optional maxConcurrency: number; +``` + +Override the registered Function's maximum concurrent user-code calls +for this logical execution. + +*** + ### maxExecutorProcessesPerWorker? ```ts diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 9f6370347..111eaf13f 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -60,6 +60,7 @@ from lancedb import function @function( pip=["numpy==2.2.0"], batch_size=32, + max_concurrency=4, row_timeout_seconds=90, ) def score_batch(value: pa.Array) -> pa.Array: @@ -72,12 +73,15 @@ once a function also does something with real fixed cost per call -- loading a model, opening a connection, making a network round trip. `batch_size` caps the number of input rows in each execution batch; actual -batches may be smaller. `row_timeout_seconds` bounds each Python call: one -row for scalar Functions or the entire batch for vectorized Functions. It -does not include the instance's `__init__`. Both settings are fixed into the -registered version and apply to direct calls, computed columns, and -materialized-view refreshes alike. Omit them to use adaptive batching and the -service's default per-call deadline. +batches may be smaller. `max_concurrency` limits user-code calls in flight for +one Function within one logical execution; it does not limit calls across +different jobs and is not an account-wide quota. `row_timeout_seconds` bounds +each Python call: one row for scalar Functions or the entire batch for +vectorized Functions. It does not include the instance's `__init__`. These +settings are fixed into the registered version and apply to direct calls, +computed columns, and materialized-view refreshes alike. A refresh can +override `max_concurrency` for that execution. Omit it to preserve the +existing behavior. ## Stateful Functions: load once, call many times {#stateful} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 62328d790..b3fcdc937 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -225,6 +225,39 @@ Function declaration can separately set `auto_refresh_resource_budget` on refreshes. SQL-expression columns reject the automatic resource-budget option because they do not use Function workers. +To override the registered Function's call concurrency for this logical +execution only: + + +```python Python icon="python" +job = table.refresh_column_async("embedding", max_concurrency=4) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::table::RefreshColumnOptions; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().max_concurrency(4), + ) + .await?; +``` + +```typescript TypeScript icon="typescript" +const job = await table.refreshColumnAsync("embedding", { + maxConcurrency: 4, +}); +await job.wait(); +``` + + +`max_concurrency` caps user-code calls in flight for one Function within one +logical execution. It is not an account-wide quota and does not resize or +rewrite `resource_budget`. Omitting it uses the registration default; a +refresh value overrides that default for this execution only. + `batch_size` caps rows in one Function call; LanceDB adapts actual call and work sizes. For Function columns, the refresh defaults to `error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index e26adc58d..280905897 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -682,6 +682,7 @@ describe("remote connection", () => { const job = await table.refreshColumnAsync("embedding", { where: "id % 2 = 0", batchSize: 16, + maxConcurrency: 3, gpuClass: "a10g", gpuCount: 2, errorPolicy: "skip", @@ -699,6 +700,11 @@ describe("remote connection", () => { memoryBytes: 16 * 1024 ** 3, }, }); + await expect( + table.refreshColumnAsync("embedding", { + maxConcurrency: true as unknown as number, + }), + ).rejects.toThrow(); // Invalid options reject before any request is sent. for (const [options, message] of [ [{ maxFailedRows: -1 }, "maxFailedRows"], @@ -706,6 +712,12 @@ describe("remote connection", () => { [{ where: " " }, "where"], [{ maxFailedFraction: 2 }, "max_failed_fraction"], [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], + [{ maxConcurrency: 1.5 }, "maxConcurrency"], + [{ maxConcurrency: 0 }, "maxConcurrency"], + [{ maxConcurrency: -1 }, "maxConcurrency"], + [{ maxConcurrency: 2 ** 32 }, "maxConcurrency"], + [{ maxConcurrency: Number.NaN }, "maxConcurrency"], + [{ maxConcurrency: Number.POSITIVE_INFINITY }, "maxConcurrency"], [{ numWorkers: 0 }, "num_workers"], [{ gpuCount: 0 }, "gpu_count"], [ @@ -787,7 +799,8 @@ describe("remote connection", () => { expect(bodies).toEqual([ JSON.parse( `{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16, - "gpu_class": "a10g", "gpu_count": 2, "error_policy": "skip", + "max_concurrency": 3, "gpu_class": "a10g", "gpu_count": 2, + "error_policy": "skip", "max_failed_fraction": 0.01, "max_failed_rows": 50, "row_timeout_seconds": 30, "init_timeout_seconds": 120, "max_executor_processes_per_worker": 2}`, diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 84f831a7a..80d8296e2 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5686,6 +5686,9 @@ describe("computed columns", () => { await expect( table.refreshColumnAsync("x", { errorPolicy: "skip" }), ).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh"); + await expect( + table.refreshColumnAsync("x", { maxConcurrency: 4 }), + ).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh"); await expect( table.refreshColumnAsync("x", { resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 }, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index d7aac1fa0..d56f66cde 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -723,8 +723,11 @@ export abstract class Table { * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` * and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, - * `resourceBudget` and `maxExecutorProcessesPerWorker` size registered - * Function refreshes. A `resourceBudget` requires `cpuMillis` and + * `maxConcurrency`, `resourceBudget` and + * `maxExecutorProcessesPerWorker` size registered Function refreshes. + * `maxConcurrency` overrides the registered default for this logical + * execution only and is a positive integer; it is not an account-wide + * quota. A `resourceBudget` requires `cpuMillis` and * `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. * The budget applies only to this explicit refresh and does not configure * a later automatic refresh. @@ -742,6 +745,7 @@ export abstract class Table { * cpuMillis: 8000, * memoryBytes: 16 * 1024 ** 3, * }, + * maxConcurrency: 4, * errorPolicy: "skip", * maxFailedFraction: 0.01, * rowTimeoutSeconds: 30, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index a008c606b..5b52c0d16 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1621,6 +1621,22 @@ fn resource_budget_gpu_count(value: Option) -> napi::Result { Ok(value as u32) } +fn positive_u32(value: Option, name: &str) -> napi::Result> { + value + .map(|value| { + if !value.is_finite() + || value.fract() != 0.0 + || !(1.0..=u32::MAX as f64).contains(&value) + { + return Err(napi::Error::from_reason(format!( + "{name} must be an integer between 1 and 4294967295" + ))); + } + Ok(value as u32) + }) + .transpose() +} + /// Options for `Table.refreshColumn` and `Table.refreshColumnAsync`. Every /// option is LanceDB Enterprise only; a LanceDB Embedded refresh ignores /// `batchSize`, `gpuClass` and `gpuCount` and rejects the rest, including @@ -1633,6 +1649,9 @@ pub struct RefreshColumnOptions { pub where_clause: Option, /// Maximum rows per Function call; must be greater than zero. pub batch_size: Option, + /// Override the registered Function's maximum concurrent user-code calls + /// for this logical execution. + pub max_concurrency: Option, /// GPU class for Function workers. pub gpu_class: Option, /// Complete aggregate CPU and memory budget for a registered Function @@ -1666,6 +1685,7 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { let mut options = Self::default(); options.where_clause = value.where_clause; options.batch_size = value.batch_size.map(|size| size as usize); + options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?; options.gpu_class = value.gpu_class; options.resource_budget = value .resource_budget diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index fafa21cbf..dfb887461 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -631,6 +631,7 @@ class Table: *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -650,6 +651,7 @@ class Table: *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[dict[str, int]] = None, gpu_class: Optional[str] = None, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index eed4050a8..6d0c2ff52 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -97,6 +97,16 @@ def _validate_batch_size(value: Any) -> Optional[int]: return value +def _validate_max_concurrency(value: Any) -> Optional[int]: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError("max_concurrency must be an integer") + if not 1 <= value <= 2**32 - 1: + raise ValueError("max_concurrency must be between 1 and 4294967295") + return value + + def _validate_row_timeout(value: Any) -> Optional[float]: if value is None: return None @@ -529,9 +539,10 @@ class FunctionVersion(_RemoteValue): ``gpu_class`` is the operator-defined GPU pool fixed into this Function version, or ``None`` when registration used the deployment default. - ``batch_size``, ``row_timeout_seconds``, and ``result_stability`` retain - the execution controls reported by the catalog. They are ``None`` for - versions registered before the corresponding declaration. + ``batch_size``, ``max_concurrency``, ``row_timeout_seconds``, and + ``result_stability`` retain the execution controls reported by the + catalog. They are ``None`` for versions registered before the + corresponding declaration. """ name: str @@ -548,6 +559,7 @@ class FunctionVersion(_RemoteValue): disabled: bool gpu_class: Optional[str] = None batch_size: Optional[int] = None + max_concurrency: Optional[int] = None row_timeout_seconds: Optional[float] = None result_stability: Optional[str] = None @@ -556,6 +568,11 @@ class FunctionVersion(_RemoteValue): def _validate_batch_size(cls, value): return _validate_batch_size(value) + @field_validator("max_concurrency", mode="before") + @classmethod + def _validate_max_concurrency(cls, value): + return _validate_max_concurrency(value) + @field_validator("row_timeout_seconds", mode="before") @classmethod def _validate_row_timeout(cls, value): @@ -691,6 +708,7 @@ class FunctionRegistrationRequest(_RemoteValue): signature: FunctionSignature runtime: PythonRuntimeSpec batch_size: Optional[int] = None + max_concurrency: Optional[int] = None row_timeout_seconds: Optional[float] = None retry_policy: Optional[FunctionRetryPolicy] = None secret_bindings: tuple[SecretBinding, ...] = () @@ -701,6 +719,11 @@ class FunctionRegistrationRequest(_RemoteValue): def _validate_batch_size(cls, value): return _validate_batch_size(value) + @field_validator("max_concurrency", mode="before") + @classmethod + def _validate_max_concurrency(cls, value): + return _validate_max_concurrency(value) + @field_validator("row_timeout_seconds", mode="before") @classmethod def _validate_row_timeout(cls, value): @@ -2163,6 +2186,7 @@ class FunctionDefinition: env: Mapping[str, str], python_version: Optional[str], batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, row_timeout_seconds: Optional[float] = None, retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, @@ -2310,6 +2334,7 @@ class FunctionDefinition: signature=signature, runtime=runtime, batch_size=batch_size, + max_concurrency=max_concurrency, row_timeout_seconds=row_timeout_seconds, retry_policy=retry_policy, models=models, @@ -2408,6 +2433,7 @@ def function( env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, row_timeout_seconds: Optional[float] = None, retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, @@ -2431,6 +2457,7 @@ def function( env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, row_timeout_seconds: Optional[float] = None, retry_policy: Optional[FunctionRetryPolicy] = None, gpu: bool = False, @@ -2564,6 +2591,11 @@ def function( Maximum number of input rows supplied in one execution batch. Must be between 1 and 4294967295. Remote execution may use smaller batches. When omitted, the service chooses the batch size adaptively. + max_concurrency : int, optional + Maximum user-code calls in flight for one Function within one logical + execution. Must be between 1 and 4294967295. A refresh can override + this default for that execution only. Omitting it preserves the + existing behavior. This is not an account-wide quota. row_timeout_seconds : float, optional Positive, finite deadline in seconds for each Python call: one row for scalar Functions and one batch for vectorized Functions. This does not @@ -2700,6 +2732,7 @@ def function( env={} if env is None else env, python_version=python_version, batch_size=batch_size, + max_concurrency=max_concurrency, row_timeout_seconds=row_timeout_seconds, retry_policy=retry_policy, gpu=gpu, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 4aca6bcc5..af648c45c 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1145,6 +1145,7 @@ class RemoteTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -1163,6 +1164,7 @@ class RemoteTable(Table): column, where=where, batch_size=batch_size, + max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, gpu_class=gpu_class, @@ -1184,6 +1186,7 @@ class RemoteTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -1203,6 +1206,7 @@ class RemoteTable(Table): column, where=where, batch_size=batch_size, + max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, gpu_class=gpu_class, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index a4d40c901..609e116ba 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3193,6 +3193,7 @@ class Table(ABC): *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -3233,6 +3234,12 @@ class Table(ABC): Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on local expression-backed columns. + max_concurrency: int, optional + Override the registered Function's maximum concurrent user-code + calls for this logical execution. Must be between 1 and + 4294967295. None uses the registration default. This is not an + account-wide quota. LanceDB Enterprise only; local refreshes + reject this option. publication_interval_rows: int, optional Opt-in publication threshold for completed Function outputs. Must be greater than zero. None keeps whole-fragment publication. The @@ -3295,6 +3302,7 @@ class Table(ABC): *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -3334,6 +3342,12 @@ class Table(ABC): greater than zero. None uses the server default. Lower this for slow Functions to stay within the executor's per-call deadline. Has no effect on local expression-backed columns. + max_concurrency: int, optional + Override the registered Function's maximum concurrent user-code + calls for this logical execution. Must be between 1 and + 4294967295. None uses the registration default. This is not an + account-wide quota. LanceDB Enterprise only; local refreshes + reject this option. publication_interval_rows: int, optional Opt-in publication threshold for completed Function outputs. Must be greater than zero. None keeps whole-fragment publication. The @@ -5493,6 +5507,7 @@ class LanceTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -5514,6 +5529,7 @@ class LanceTable(Table): column, where=where, batch_size=batch_size, + max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, gpu_class=gpu_class, @@ -5535,6 +5551,7 @@ class LanceTable(Table): *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -5558,6 +5575,7 @@ class LanceTable(Table): column, where=where, batch_size=batch_size, + max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, gpu_class=gpu_class, @@ -7940,6 +7958,7 @@ class AsyncTable: *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -7980,6 +7999,12 @@ class AsyncTable: Maximum rows per Function call on the remote server. Must be greater than zero. None uses the server default. Has no effect on local expression-backed columns. + max_concurrency: int, optional + Override the registered Function's maximum concurrent user-code + calls for this logical execution. Must be between 1 and + 4294967295. None uses the registration default. This is not an + account-wide quota. LanceDB Enterprise only; local refreshes + reject this option. publication_interval_rows: int, optional Opt-in publication threshold for completed Function outputs. Must be greater than zero. None keeps whole-fragment publication. The @@ -8037,6 +8062,7 @@ class AsyncTable: column, where=where, batch_size=batch_size, + max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, gpu_class=gpu_class, @@ -8148,6 +8174,7 @@ class AsyncTable: *, where: Optional[str] = None, batch_size: Optional[int] = None, + max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, gpu_class: Optional[str] = None, @@ -8187,6 +8214,12 @@ class AsyncTable: greater than zero. None uses the server default. Lower this for slow Functions to stay within the executor's per-call deadline. Has no effect on local expression-backed columns. + max_concurrency: int, optional + Override the registered Function's maximum concurrent user-code + calls for this logical execution. Must be between 1 and + 4294967295. None uses the registration default. This is not an + account-wide quota. LanceDB Enterprise only; local refreshes + reject this option. publication_interval_rows: int, optional Opt-in publication threshold for completed Function outputs. Must be greater than zero. None keeps whole-fragment publication. The @@ -8261,6 +8294,7 @@ class AsyncTable: column, where=where, batch_size=batch_size, + max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, gpu_class=gpu_class, diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index c392fdc7f..f8e225183 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -184,6 +184,7 @@ def test_function_version_preserves_execution_controls(): value = job_result("remote_function_job.json") value.update( batch_size=12, + max_concurrency=4, row_timeout_seconds=8.0, result_stability="input_and_context", ) @@ -192,9 +193,14 @@ def test_function_version_preserves_execution_controls(): assert encoded == value assert type(encoded["batch_size"]) is int + assert type(encoded["max_concurrency"]) is int assert type(encoded["row_timeout_seconds"]) is float assert type(encoded["result_stability"]) is str + for invalid in [True, 1.5, 0, -1, 2**32]: + with pytest.raises(ValueError, match="max_concurrency"): + FunctionVersion(**{**value, "max_concurrency": invalid}) + def test_function_version_binds_named_columns_as_one_immutable_application(): version = FunctionVersion.from_json( diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 6f6c93f3f..2cc731892 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -134,6 +134,7 @@ def test_function_execution_controls_match_shared_registration_golden(): env={"MODE": "test"}, python_version="3.12", batch_size=2, + max_concurrency=4, row_timeout_seconds=0.75, )(normalize_score.__wrapped__) assert ( @@ -193,6 +194,11 @@ def test_function_retry_policy_rejects_invalid_options(options): ({"batch_size": 0}, "batch_size"), ({"batch_size": 2**32}, "batch_size"), ({"batch_size": True}, "batch_size"), + ({"max_concurrency": 0}, "max_concurrency"), + ({"max_concurrency": -1}, "max_concurrency"), + ({"max_concurrency": 2**32}, "max_concurrency"), + ({"max_concurrency": True}, "max_concurrency"), + ({"max_concurrency": 1.5}, "max_concurrency"), ({"row_timeout_seconds": 0}, "row_timeout_seconds"), ({"row_timeout_seconds": -0.25}, "row_timeout_seconds"), ({"row_timeout_seconds": float("inf")}, "row_timeout_seconds"), diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 2547cf807..5224e5482 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -10,6 +10,7 @@ import io import inspect import json import multiprocessing as mp +from pathlib import Path import pickle import re import socket @@ -36,7 +37,7 @@ from lancedb.graph import ( PropertyGraph, PropertyGraphDescription, ) -from lancedb.functions import FunctionApplication +from lancedb.functions import FunctionApplication, function from lancedb.query import ( AsyncQuery, ColumnOrdering, @@ -1864,6 +1865,7 @@ def test_remote_create_index_async_returns_job(): {"batch_size": None}, {"batch_size": 1}, {"batch_size": 8}, + {"max_concurrency": 3}, {"publication_interval_rows": 60}, {"resource_budget": {"cpu_millis": 2000, "memory_bytes": 4 * 1024**3}}, { @@ -1927,6 +1929,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result( expected["error_policy"] = refresh_kwargs["error_policy"] for key in ( "where", + "max_concurrency", "publication_interval_rows", "max_failed_fraction", "max_failed_rows", @@ -2107,6 +2110,11 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): ({"init_timeout_seconds": -5}, "init_timeout_seconds"), ({"publication_interval_rows": 0}, "publication_interval_rows"), ({"publication_interval_rows": -1}, "publication_interval_rows"), + ({"max_concurrency": True}, "max_concurrency"), + ({"max_concurrency": 1.5}, "max_concurrency"), + ({"max_concurrency": 0}, "max_concurrency"), + ({"max_concurrency": -1}, "max_concurrency"), + ({"max_concurrency": 2**32}, "max_concurrency"), ({"num_workers": 0}, "num_workers"), ( {"resource_budget": {"cpu_millis": 1000}}, @@ -6093,6 +6101,45 @@ def _mock_remote_table_with_sql(flight_server): yield lancedb.connect(**kwargs).create_table("test", [{"id": 1}]) +def test_remote_function_registration_transports_max_concurrency(): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust" + / "lancedb" + / "tests" + / "fixtures" + / "first_class_functions" + / "v1" + / "remote_function_version.canonical.json" + ) + definition = json.loads(fixture.read_text()) + definition["max_concurrency"] = 4 + + @function(name="normalize_score", max_concurrency=4) + def registered(value: float) -> float: + return value + + class RegistrationServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table({"definition": [json.dumps(definition)]}) + ) + + server = RegistrationServer() + with _mock_remote_sql_connection(server) as kwargs: + version = lancedb.connect(**kwargs).create_function(registered) + + assert len(server.tickets) == 1 + assert b'"max_concurrency":4' in server.tickets[0] + assert version.max_concurrency == 4 + + @pytest.mark.asyncio @pytest.mark.parametrize("asynchronous", [False, True]) @pytest.mark.parametrize( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 6c9485ced..7146ed86b 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5995,6 +5995,7 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) ({"max_failed_rows": 10}, "max_failed_rows"), ({"row_timeout_seconds": 30}, "row_timeout_seconds"), ({"init_timeout_seconds": 60}, "init_timeout_seconds"), + ({"max_concurrency": 4}, "max_concurrency"), ({"publication_interval_rows": 60}, "publication_interval_rows"), ( {"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}}, diff --git a/python/src/table.rs b/python/src/table.rs index 07dc49979..24cc9ae5c 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -48,6 +48,7 @@ mod scannable; struct RefreshColumnArgs { where_clause: Option, batch_size: Option, + max_concurrency: Option, publication_interval_rows: Option, resource_budget: Option, gpu_class: Option, @@ -73,6 +74,31 @@ fn positive_count>(value: Option, name: &str) -> PyResult>, name: &str) -> PyResult> { + let Some(value) = value else { + return Ok(None); + }; + if value.is_none() || value.is_instance_of::() { + return Err(PyValueError::new_err(format!( + "{name} must be an integer between 1 and 4294967295" + ))); + } + let parsed = value.extract::().map_err(|_| { + PyValueError::new_err(format!( + "{name} must be an integer between 1 and 4294967295" + )) + })?; + u32::try_from(parsed) + .ok() + .filter(|parsed| *parsed > 0) + .map(Some) + .ok_or_else(|| { + PyValueError::new_err(format!( + "{name} must be an integer between 1 and 4294967295" + )) + }) +} + fn resource_budget_integer( value: &Bound<'_, PyAny>, name: &str, @@ -136,6 +162,7 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult( self_: PyRef<'py, Self>, column: String, r#where: Option, batch_size: Option, + max_concurrency: Option>, publication_interval_rows: Option, resource_budget: Option>, gpu_class: Option, @@ -2305,6 +2334,7 @@ impl Table { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, + max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, resource_budget: parse_resource_budget(resource_budget.as_ref())?, gpu_class, @@ -2328,13 +2358,14 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, column: String, r#where: Option, batch_size: Option, + max_concurrency: Option>, publication_interval_rows: Option, resource_budget: Option>, gpu_class: Option, @@ -2351,6 +2382,7 @@ impl Table { let options = refresh_column_options(RefreshColumnArgs { where_clause: r#where, batch_size, + max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, resource_budget: parse_resource_budget(resource_budget.as_ref())?, gpu_class, diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 41a683c54..3566fc938 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -611,6 +611,13 @@ pub struct FunctionVersion { deserialize_with = "deserialize_batch_size" )] batch_size: Option, + /// Default maximum concurrent user-code calls per logical execution. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_max_concurrency" + )] + max_concurrency: Option, /// Per-call deadline in seconds. #[serde(default, skip_serializing_if = "Option::is_none")] row_timeout_seconds: Option, @@ -681,6 +688,11 @@ impl FunctionVersion { self.batch_size } + /// Default maximum concurrent user-code calls, when declared. + pub fn max_concurrency(&self) -> Option { + self.max_concurrency + } + /// Per-call deadline in seconds, when declared. pub fn row_timeout_seconds(&self) -> Option { self.row_timeout_seconds.map(RowTimeoutSeconds::get) @@ -769,6 +781,18 @@ where Ok(value) } +fn deserialize_max_concurrency<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer) + .map_err(|error| de::Error::custom(format!("max_concurrency: {error}")))?; + validate_max_concurrency_value(value).map_err(de::Error::custom)?; + Ok(value) +} + fn validate_batch_size_value(value: Option) -> std::result::Result<(), &'static str> { if value == Some(0) { return Err("batch_size must be between 1 and u32::MAX"); @@ -776,6 +800,13 @@ fn validate_batch_size_value(value: Option) -> std::result::Result<(), &'st Ok(()) } +fn validate_max_concurrency_value(value: Option) -> std::result::Result<(), &'static str> { + if value == Some(0) { + return Err("max_concurrency must be between 1 and u32::MAX"); + } + Ok(()) +} + fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'static str> { if value.is_some_and(|seconds| !seconds.is_finite() || seconds <= 0.0) { return Err("row_timeout_seconds must be positive and finite"); @@ -804,6 +835,15 @@ pub struct FunctionRegistrationRequest { deserialize_with = "deserialize_batch_size" )] pub batch_size: Option, + /// Default maximum concurrent user-code calls for each logical execution + /// of this Function version. Omission leaves the current behavior + /// unchanged. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_max_concurrency" + )] + pub max_concurrency: Option, /// Deadline for each Python call, in seconds: one row for scalar Functions /// and one batch for vectorized Functions. It does not govern Function /// initialization. @@ -841,6 +881,7 @@ impl FunctionRegistrationRequest { message: message.to_string(), }; validate_batch_size_value(self.batch_size).map_err(invalid_input)?; + validate_max_concurrency_value(self.max_concurrency).map_err(invalid_input)?; validate_row_timeout_value(self.row_timeout_seconds).map_err(invalid_input)?; if let Some(policy) = &self.retry_policy { policy.validate()?; @@ -1318,6 +1359,15 @@ mod tests { assert_eq!(version.gpu_class(), Some("a10g")); let encoded: Value = serde_json::from_str(&version.to_canonical_json().unwrap()).unwrap(); assert_eq!(encoded["gpu_class"], "a10g"); + + document["max_concurrency"] = serde_json::json!(4); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.max_concurrency(), Some(4)); + let encoded: Value = serde_json::from_str(&version.to_canonical_json().unwrap()).unwrap(); + assert_eq!(encoded["max_concurrency"], 4); + + document["max_concurrency"] = serde_json::json!(0); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); } #[test] diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 3d728aa3e..efc2ba6a4 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -2959,6 +2959,7 @@ async fn function_creation_and_description_use_sql_query_handles() { for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] { let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); request_json["batch_size"] = serde_json::json!(2); + request_json["max_concurrency"] = serde_json::json!(4); request_json["row_timeout_seconds"] = serde_json::json!(0.75); request_json["secret_bindings"] = serde_json::json!([{ "kind": "env", @@ -2967,6 +2968,7 @@ async fn function_creation_and_description_use_sql_query_handles() { }]); let mut version_json: serde_json::Value = serde_json::from_str(VERSION).unwrap(); version_json["batch_size"] = serde_json::json!(12); + version_json["max_concurrency"] = serde_json::json!(4); version_json["row_timeout_seconds"] = serde_json::json!(8.0); version_json["result_stability"] = serde_json::json!("input_and_context"); if with_models { @@ -3010,6 +3012,7 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created.name(), "embed"); assert_eq!(created.version(), "1"); assert_eq!(created.batch_size(), Some(12)); + assert_eq!(created.max_concurrency(), Some(4)); assert_eq!(created.row_timeout_seconds(), Some(8.0)); assert_eq!(created.result_stability(), Some("input_and_context")); // Assert the actual SQL body, after the same native JSON decode used @@ -3029,6 +3032,7 @@ async fn function_creation_and_description_use_sql_query_handles() { serde_json::from_str(&created.to_canonical_json().unwrap()).unwrap(); assert_eq!(created_json["image"].get("models"), expected_models); assert_eq!(created_json["batch_size"], 12); + assert_eq!(created_json["max_concurrency"], 4); assert_eq!(created_json["row_timeout_seconds"], 8.0); assert_eq!(created_json["result_stability"], "input_and_context"); assert_eq!( @@ -3041,12 +3045,14 @@ async fn function_creation_and_description_use_sql_query_handles() { .unwrap(); assert_eq!(described.name(), "embed"); assert_eq!(described.batch_size(), Some(12)); + assert_eq!(described.max_concurrency(), Some(4)); assert_eq!(described.row_timeout_seconds(), Some(8.0)); assert_eq!(described.result_stability(), Some("input_and_context")); let described_json: serde_json::Value = serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap(); assert_eq!(described_json["image"].get("models"), expected_models); assert_eq!(described_json["batch_size"], 12); + assert_eq!(described_json["max_concurrency"], 4); assert_eq!(described_json["row_timeout_seconds"], 8.0); assert_eq!(described_json["result_stability"], "input_and_context"); let latest = db @@ -3062,6 +3068,7 @@ async fn function_creation_and_description_use_sql_query_handles() { .unwrap(); assert_eq!(listed.items.len(), 1); assert_eq!(listed.items[0].batch_size(), Some(12)); + assert_eq!(listed.items[0].max_concurrency(), Some(4)); assert_eq!(listed.items[0].row_timeout_seconds(), Some(8.0)); assert_eq!( listed.items[0].result_stability(), @@ -3071,6 +3078,7 @@ async fn function_creation_and_description_use_sql_query_handles() { serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap(); assert_eq!(listed_json["image"].get("models"), expected_models); assert_eq!(listed_json["batch_size"], 12); + assert_eq!(listed_json["max_concurrency"], 4); assert_eq!(listed_json["row_timeout_seconds"], 8.0); assert_eq!(listed_json["result_stability"], "input_and_context"); let seen = statements.lock().unwrap(); @@ -3106,6 +3114,13 @@ async fn function_creation_rejects_invalid_execution_controls_before_sql() { request.batch_size = Some(0); let error = db.create_function_async(request, &[]).await.unwrap_err(); assert!(matches!(error, Error::InvalidInput { message } if message.contains("batch_size"))); + + let mut request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap(); + request.max_concurrency = Some(0); + let error = db.create_function_async(request, &[]).await.unwrap_err(); + assert!( + matches!(error, Error::InvalidInput { message } if message.contains("max_concurrency")) + ); assert!(statements.lock().unwrap().is_empty()); shutdown.send(()).unwrap(); } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index ee9b3827b..247b1925c 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11131,6 +11131,7 @@ mod tests { serde_json::json!({ "column": "quality", "where": "id % 2 = 0", + "max_concurrency": 3, "publication_interval_rows": 60, "error_policy": "skip", "max_failed_fraction": 0.01, @@ -11148,6 +11149,7 @@ mod tests { }); let options = RefreshColumnOptions::default() .where_clause("id % 2 = 0") + .max_concurrency(3) .publication_interval_rows(60) .error_policy(FunctionErrorPolicy::Skip) .max_failed_fraction(0.01) @@ -11192,6 +11194,10 @@ mod tests { RefreshColumnOptions::default().num_workers(0), "num_workers", ), + ( + RefreshColumnOptions::default().max_concurrency(0), + "max_concurrency", + ), ( RefreshColumnOptions::default().max_executor_processes_per_worker(0), "max_executor_processes_per_worker", diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 31c165be6..ff73e6366 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -149,6 +149,12 @@ pub struct RefreshColumnOptions { /// effect on expression-backed columns in LanceDB Embedded. #[serde(skip_serializing_if = "Option::is_none")] pub batch_size: Option, + /// Override the registered Function's maximum concurrent user-code calls + /// for this logical execution. Must be greater than zero. `None` uses the + /// registration default, or disabled when the Function declares none. + /// This is not an account quota and does not change `resource_budget`. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_concurrency: Option, /// Opt-in row-count threshold for publishing completed Function outputs. /// /// Must be greater than zero. `None` keeps whole-fragment publication. @@ -235,6 +241,13 @@ impl RefreshColumnOptions { self } + /// Override the registered Function's maximum concurrent user-code calls + /// for this logical execution. + pub fn max_concurrency(mut self, max_concurrency: u32) -> Self { + self.max_concurrency = Some(max_concurrency); + self + } + /// Use `rows` as the opt-in publication threshold for completed Function /// outputs. The actual publication boundary can be larger than this value. pub fn publication_interval_rows(mut self, rows: u64) -> Self { @@ -278,6 +291,7 @@ impl RefreshColumnOptions { "max_executor_processes_per_worker", self.max_executor_processes_per_worker.is_some(), ), + ("max_concurrency", self.max_concurrency.is_some()), ( "publication_interval_rows", self.publication_interval_rows.is_some(), @@ -335,6 +349,11 @@ impl RefreshColumnOptions { message: "batch_size must be greater than zero".into(), }); } + if self.max_concurrency == Some(0) { + return Err(Error::InvalidInput { + message: "max_concurrency must be greater than zero".into(), + }); + } if self.publication_interval_rows == Some(0) { return Err(Error::InvalidInput { message: "publication_interval_rows must be greater than zero".into(), diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 77432702a..829486015 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -71,6 +71,7 @@ fn execution_controls_match_shared_canonical_golden() { let value: Value = serde_json::from_str(&request.to_canonical_json().unwrap()).unwrap(); assert_eq!(value["batch_size"], 2); + assert_eq!(value["max_concurrency"], 4); assert_eq!(value["row_timeout_seconds"], 0.75); } @@ -80,6 +81,10 @@ fn execution_controls_require_their_positive_ranges() { for (field, value) in [ ("batch_size", Value::from(0)), ("batch_size", Value::from(4_294_967_296_u64)), + ("max_concurrency", Value::from(0)), + ("max_concurrency", Value::from(4_294_967_296_u64)), + ("max_concurrency", Value::from(-1)), + ("max_concurrency", Value::from(1.5)), ("row_timeout_seconds", Value::from(0)), ("row_timeout_seconds", Value::from(-0.25)), ] { @@ -107,6 +112,11 @@ fn execution_controls_are_validated_before_canonical_serialization() { request.batch_size = Some(0); let error = request.to_canonical_json().unwrap_err(); assert!(error.to_string().contains("batch_size"), "{error}"); + + let mut request = FunctionRegistrationRequest::from_json(&source).unwrap(); + request.max_concurrency = Some(0); + let error = request.to_canonical_json().unwrap_err(); + assert!(error.to_string().contains("max_concurrency"), "{error}"); } /// The same shared golden as the Python suite builds from `@function(secrets=...)` diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json index 9ce9a289f..b5bdff2a8 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.canonical.json @@ -1 +1 @@ -{"artifact":{"adapter":{"kind":"scalar_to_arrow_batch","version":1},"content":{"data":"ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK","encoding":"base64"},"digest":"sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f","entrypoint":"normalize_score","kind":"python_callable"},"batch_size":2,"name":"normalize_score","row_timeout_seconds":0.75,"runtime":{"env":{"MODE":"test"},"environment":{"kind":"pip","packages":["numpy>=2"]},"kind":"python","python_version":"3.12"},"signature":{"inputs":[{"arrow_type":"float64","name":"value","nullable":false}],"output":{"arrow_type":"float64","kind":"scalar","nullable":false}}} +{"artifact":{"adapter":{"kind":"scalar_to_arrow_batch","version":1},"content":{"data":"ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK","encoding":"base64"},"digest":"sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f","entrypoint":"normalize_score","kind":"python_callable"},"batch_size":2,"max_concurrency":4,"name":"normalize_score","row_timeout_seconds":0.75,"runtime":{"env":{"MODE":"test"},"environment":{"kind":"pip","packages":["numpy>=2"]},"kind":"python","python_version":"3.12"},"signature":{"inputs":[{"arrow_type":"float64","name":"value","nullable":false}],"output":{"arrow_type":"float64","kind":"scalar","nullable":false}}} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json index cb0961eba..ce21edb51 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_controlled_registration_request.json @@ -1,6 +1,7 @@ { "name": "normalize_score", "batch_size": 2, + "max_concurrency": 4, "row_timeout_seconds": 0.75, "artifact": { "kind": "python_callable", From 34e8b8087b6d904f3381d0cdd3541b1e08477cc8 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 11 Nov 2026 16:11:47 +0800 Subject: [PATCH 065/203] fix: preserve function freshness across input-preserving writes (#4948) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updating an unrelated column or merging rows with unchanged Function inputs rewrites fragment files, causing already computed outputs to be treated as stale. Preserve their freshness from the successful write transaction when the inputs and outputs are provably unchanged; keep changed or uncertain inputs eligible for recomputation. Mixed update/insert writes keep a separate pending-fill proof so retained outputs can be reused while inserted NULL outputs still need computation. Partial refreshes under a new Function definition discard the previous definition’s completed and pending proofs. Preservation uses a version-fenced metadata commit, and an optional preservation failure does not turn a successful data write into an error. Validation: 67 freshness tests pass, including the new partial-definition regression (confirmed failing before its fix), unrelated updates, identical/mixed merges, NULL/nested/blob inputs, dirty-state preservation, concurrency fences and sidecar retention. `cargo fmt --all` and `cargo clippy --quiet --locked --features remote --tests --examples` pass. Compatibility: `StalenessPlan` adds a public `pending_fill` field, so direct Rust struct literals must be updated. Refresh consumers must handle pending-fill admission and publication before adopting this behavior; a dependency bump alone does not complete consumer integration. End-to-end consumer validation and deployment remain separate. No latency claim is made for this SDK-only change. --- rust/lancedb/src/table/computed_columns.rs | 5 + rust/lancedb/src/table/freshness.rs | 1077 +++++++++++++++++++- rust/lancedb/src/table/merge.rs | 17 +- rust/lancedb/src/table/update.rs | 21 +- 4 files changed, 1106 insertions(+), 14 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 8fce7a260..d09a790a3 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -211,6 +211,11 @@ pub const FUNCTION_BINDINGS_VERSION: u32 = 1; /// declared before signatures existed. pub const SOURCE_SIGNATURE_META_KEY: &str = "computed_refresh.source_signature"; +/// Signatures of input-preserving rewrites whose retained Function outputs +/// are current but whose inserted rows still need their first computation. +/// A sidecar reference keeps this separate from completed freshness stamps. +pub const PENDING_FILL_SIGNATURE_META_KEY: &str = "computed_refresh.pending_fill_signature"; + /// Field metadata key holding the definition digest a column was last /// computed under. A change to it makes every row stale. pub const DEFINITION_VERSION_META_KEY: &str = "computed_refresh.definition_version"; diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 021abe5a9..50434143e 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -25,10 +25,11 @@ use std::io::{Cursor, Read}; use std::ops::Range; use arrow_array::{Array, UInt64Array}; +use arrow_schema::{DataType, Schema as ArrowSchema}; use futures::TryStreamExt; use lance::Dataset; use lance::dataset::refs::Ref; -use lance::dataset::transaction::Operation; +use lance::dataset::transaction::{Operation, UpdateMode}; use lance_core::ROW_ADDR; use lance_core::datatypes::{Field as LanceField, Schema as LanceSchema}; use lance_io::object_store::{ObjectStore, uri_to_url}; @@ -40,7 +41,8 @@ use sha2::{Digest, Sha256}; use uuid::Uuid; use crate::table::computed_columns::{ - DEFINITION_VERSION_META_KEY, RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, + DEFINITION_VERSION_META_KEY, FUNCTION_BINDINGS_META_KEY, PENDING_FILL_SIGNATURE_META_KEY, + RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, field_root, function_bindings, }; use crate::{Error, Result}; @@ -738,12 +740,14 @@ async fn referenced_digests(dataset: &Dataset, into: &mut HashSet) -> Re for version in dataset.versions().await? { let at = dataset.checkout_version(version.version).await?; for field in at.schema().fields_pre_order() { - if let Some(digest) = field - .metadata - .get(SOURCE_SIGNATURE_META_KEY) - .and_then(|value| value.strip_prefix(SIDECAR_REF)) - { - into.insert(digest.to_string()); + for key in [SOURCE_SIGNATURE_META_KEY, PENDING_FILL_SIGNATURE_META_KEY] { + if let Some(digest) = field + .metadata + .get(key) + .and_then(|value| value.strip_prefix(SIDECAR_REF)) + { + into.insert(digest.to_string()); + } } } } @@ -820,6 +824,10 @@ pub struct StalenessPlan { pub dirty: HashSet, /// Current-signature fragments with only some rows dirty. pub row_dirty: RowStateMap, + /// Retained values are current, but unassigned inserted rows need filling. + /// These signatures become completed stamps only after a full null-fill. + #[serde(default)] + pub pending_fill: SignatureMap, /// Fragments a compaction produced from fresh ones, at their current /// signature: not dirty, and for the seal to record. pub inherited: SignatureMap, @@ -1174,13 +1182,29 @@ pub async fn staleness_against( let mut inherited = carried.inherited; let mut dirty = carried.dirty_products; let mut row_dirty = RowStateMap::new(); + let pending = match field_meta(dataset, column, PENDING_FILL_SIGNATURE_META_KEY) { + Some(reference) if unrecorded => { + let state = match reference.strip_prefix(SIDECAR_REF) { + Some(digest) => read_sidecar(dataset, digest).await.ok(), + None => None, + }; + state + .filter(|state| state.row_state.is_empty() && state.basis.is_empty()) + .map(|state| state.signatures) + .unwrap_or_default() + } + _ => SignatureMap::new(), + }; + let mut pending_fill = SignatureMap::new(); let mut live = HashSet::new(); let bases = Bases::of(dataset)?; for fragment in dataset.get_fragments() { let id = fragment.id() as u32; live.insert(id); let current = fragment_input_signature(&bases, fragment.metadata(), inputs)?; - if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { + if !stored.contains_key(&id) && !dirty.contains(&id) && pending.get(&id) == Some(¤t) { + pending_fill.insert(id, current); + } else if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { dirty.insert(id); } else if let Some(rows) = row_state.get(&id) { row_dirty.insert(id, rows.clone()); @@ -1192,6 +1216,7 @@ pub async fn staleness_against( recompute_all: false, dirty, row_dirty, + pending_fill, inherited, }) } @@ -1263,18 +1288,302 @@ pub async fn record_freshness( }) } +/// The source of a just-committed write whose retained Function values may +/// still be fresh. The fields must describe the actual write, including its +/// join keys; they must not be inferred from a later table snapshot. +pub enum FunctionWrite<'a> { + /// Assignments executed by Lance's update builder. + Update { columns: &'a [String] }, + /// The source schema and join columns executed by Lance's merge builder. + Merge { + source_schema: &'a ArrowSchema, + on: &'a [String], + /// The insertion count from the same committed merge result. + num_inserted_rows: u64, + }, +} + +impl FunctionWrite<'_> { + fn writes_root(&self, root: &str) -> Result { + match self { + Self::Update { columns } => columns.iter().try_fold(false, |found, column| { + Ok(found || field_root(column)? == root) + }), + Self::Merge { source_schema, .. } => Ok(source_schema.field_with_name(root).is_ok()), + } + } + + fn preserves_input(&self, path: &str, schema: &ArrowSchema) -> Result { + let parts = lance_core::datatypes::parse_field_path(path)?; + let root = field_root(path)?; + if !self.writes_root(&root)? { + return Ok(true); + } + let Self::Merge { + source_schema, on, .. + } = self + else { + return Ok(false); + }; + if parts.len() != 1 || !on.contains(&root) { + return Ok(false); + } + let target = schema.field_with_name(&root)?; + let source = source_schema.field_with_name(&root)?; + // Join equality must preserve the Function's exact input. In particular, + // floating-point joins can equate different signed zeros or NaN payloads. + // Extension types can also define equality over a decoded representation. + Ok(source.data_type() == target.data_type() + && !source + .metadata() + .contains_key(lance_arrow::ARROW_EXT_NAME_KEY) + && !target + .metadata() + .contains_key(lance_arrow::ARROW_EXT_NAME_KEY) + && matches!( + target.data_type(), + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Binary + | DataType::LargeBinary + | DataType::FixedSizeBinary(_) + )) + } +} + +/// Preserve Function freshness after an input-preserving update or merge. +/// +/// Call this on the exact dataset returned by the write, before any subsequent +/// operation. `write` must describe that write's real assignments or source. +/// The successful transaction's read version supplies the source freshness, +/// including when the write retried. Only fresh source fragments are carried; +/// partial repairs and unknown input equality remain stale. Inserted rows keep +/// NULL outputs and carry a pending-fill signature instead of a completed stamp. +/// +/// All siblings are stamped in one version-fenced metadata commit. Failure is +/// an optimization miss: callers must retain the successful data-write result, +/// rather than report a failed write that a client might repeat. +/// +/// ``` +/// use lance::Dataset; +/// use lancedb::table::freshness::{FunctionWrite, preserve_function_freshness}; +/// # async fn after_label_update(dataset: &mut Dataset) { +/// let columns = vec!["label".to_string()]; +/// if let Err(error) = preserve_function_freshness( +/// dataset, FunctionWrite::Update { columns: &columns }, +/// ).await { +/// log::warn!("freshness preservation skipped: {error}"); +/// } +/// # } +/// ``` +pub async fn preserve_function_freshness( + dataset: &mut Dataset, + write: FunctionWrite<'_>, +) -> Result<()> { + let schema = ArrowSchema::from(dataset.schema()); + let bindings = function_bindings(&schema)?; + if bindings.is_empty() { + return Ok(()); + } + let committed_version = dataset.version().version; + let Some(transaction) = dataset + .read_transaction_by_version(committed_version) + .await? + else { + return Ok(()); + }; + let Operation::Update { + removed_fragment_ids, + updated_fragments, + new_fragments, + update_mode: Some(UpdateMode::RewriteRows), + .. + } = &transaction.operation + else { + return Ok(()); + }; + if new_fragments.is_empty() { + return Ok(()); + } + let before = dataset.checkout_version(transaction.read_version).await?; + if before.schema().metadata.get(FUNCTION_BINDINGS_META_KEY) + != dataset.schema().metadata.get(FUNCTION_BINDINGS_META_KEY) + { + return Ok(()); + } + let before_schema = ArrowSchema::from(before.schema()); + let sources = removed_fragment_ids + .iter() + .copied() + .chain(updated_fragments.iter().map(|fragment| fragment.id)) + .collect::>(); + // Commit assigns fragment IDs. Match only this transaction's files, not + // unrelated appends that may have committed while it was being written. + let live_fragments = dataset.get_fragments(); + let produced = new_fragments + .iter() + .map(|fragment| { + live_fragments + .iter() + .find(|live| live.metadata().files == fragment.files) + .map(|live| live.id() as u32) + .ok_or_else(|| { + invalid("written Function fragment is missing from its commit".into()) + }) + }) + .collect::>>()?; + let live = live_fragments + .iter() + .map(|fragment| fragment.id() as u32) + .collect::>(); + let mut pending = Vec::new(); + for binding in bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let mut preserved = true; + for path in &paths { + preserved &= write.preserves_input(path, &before_schema)?; + } + // Even a join-key output can supply a non-NULL value to an insert. + // Those values were not computed under this binding. + for name in binding + .outputs() + .iter() + .map(|output| output.output_name.as_str()) + .chain( + binding + .assignment() + .map(|assignment| assignment.output_name.as_str()), + ) + { + preserved &= !write.writes_root(name)?; + } + if !preserved { + continue; + } + let old_inputs = fields_for_paths(before.schema(), &paths)?; + let new_inputs = fields_for_paths(dataset.schema(), &paths)?; + for output in binding.outputs() { + let column = &output.output_name; + let (Some(old_field), Some(new_field)) = ( + before.schema().field(column), + dataset.schema().field(column), + ) else { + continue; + }; + if old_field.metadata != new_field.metadata { + continue; + } + let StoredFreshnessState::Present { mut state, .. } = + stored_freshness_state(&before, column).await + else { + continue; + }; + let stale = + staleness_against(&before, column, binding.binding_id(), &old_inputs).await?; + if stale.recompute_all + || sources.iter().any(|id| { + before.get_fragment(*id as usize).is_none() || stale.needs_recompute(*id as u32) + }) + { + continue; + } + // Advancing recorded_at must also carry unrelated compactions + // already proven fresh at the write's source version. + for (id, signature) in stale.inherited { + if signature_of(dataset, id, &new_inputs)?.as_ref() == Some(&signature) { + state.signatures.insert(id, signature); + } + } + let needs_fill = matches!(write, FunctionWrite::Merge { num_inserted_rows, .. } if num_inserted_rows > 0) + || sources + .iter() + .any(|id| stale.pending_fill.contains_key(&(*id as u32))); + let mut pending_fill = stale.pending_fill; + let produced_signatures = signatures_for(dataset, &produced, &new_inputs)?; + if needs_fill { + pending_fill.extend(produced_signatures); + } else { + state.signatures.extend(produced_signatures); + } + pending_fill.retain(|id, _| live.contains(id)); + state.signatures.retain(|id, _| live.contains(id)); + state.row_state.retain(|id, _| live.contains(id)); + state.basis.clear(); + let reference = write_sidecar(dataset, &state.normalize()?).await?; + let fill_reference = if pending_fill.is_empty() { + None + } else { + Some( + write_sidecar( + dataset, + &FreshnessState { + signatures: pending_fill, + ..Default::default() + }, + ) + .await?, + ) + }; + pending.push(( + column.clone(), + binding.binding_id().to_string(), + reference, + fill_reference, + )); + } + } + if pending.is_empty() { + return Ok(()); + } + let mut metadata = dataset.update_field_metadata(); + for (column, definition, reference, fill_reference) in pending { + metadata = metadata.update( + &column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), Some(reference)), + (PENDING_FILL_SIGNATURE_META_KEY.to_string(), fill_reference), + (DEFINITION_VERSION_META_KEY.to_string(), Some(definition)), + ( + RECORDED_AT_VERSION_META_KEY.to_string(), + Some(committed_version.to_string()), + ), + ], + )?; + } + metadata + .with_expected_latest_version(committed_version) + .await?; + Ok(()) +} + /// Merge `entries` into the column's stored map and stamp the definition and /// the version the map now describes. Merges rather than replaces: the /// entries cover only the fragments this refresh wrote, and every fragment it /// skipped keeps the entry an earlier one left. Entries for fragments no /// longer in the manifest are dropped, so compaction cannot grow the map -/// without bound. Returns the version the stamp landed at. +/// without bound. When the definition changes, only the newly computed entries +/// are trusted. Returns the version the stamp landed at. pub async fn write_signatures( dataset: &mut Dataset, column: &str, definition_version: &str, entries: SignatureMap, ) -> Result { + let definition_changed = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) + .is_some_and(|version| version != definition_version); let live: HashSet = dataset .get_fragments() .iter() @@ -1291,6 +1600,9 @@ pub async fn write_signatures( FreshnessState::default() } }; + if definition_changed { + state = FreshnessState::default(); + } let recomputed: HashSet = entries.keys().copied().collect(); let signatures_changed = entries .iter() @@ -1359,7 +1671,7 @@ async fn write_freshness_state( (reference, Some(digest)) }; let describes = dataset.version().version; - let updates = vec![ + let mut updates = vec![ (SOURCE_SIGNATURE_META_KEY.to_string(), Some(signature_ref)), ( DEFINITION_VERSION_META_KEY.to_string(), @@ -1370,6 +1682,13 @@ async fn write_freshness_state( Some(describes.to_string()), ), ]; + // Pending-fill proofs vouch for retained outputs under the old definition. + // A partial publication must not make them valid under its new stamp. + if field_meta(dataset, column, DEFINITION_VERSION_META_KEY) + .is_some_and(|version| version != definition_version) + { + updates.push((PENDING_FILL_SIGNATURE_META_KEY.to_string(), None)); + } let builder = dataset.update_field_metadata().update(column, updates)?; match expected_latest_version { Some(expected) => builder.with_expected_latest_version(expected).await?, @@ -1741,6 +2060,742 @@ mod tests { const COLUMN: &str = "doubled"; const EXPRESSION: &str = "value * 2"; + async fn fresh_function_table() -> crate::Table { + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, [Some("x"), None, Some("z"), Some("w")]), + ("search_text", Utf8, ["a x", "b", "c z", "d w"]), + ("search_token_count", Int64, [2, 1, 2, 2]), + ("spare", Int32, [0, 0, 0, 0]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("fresh_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let binding = text_features_binding(""); + stamp_bindings(&table, std::slice::from_ref(&binding)).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + native.dataset.update(dataset); + table + } + + async fn function_plan(dataset: &Dataset, column: &str) -> StalenessPlan { + staleness_against( + dataset, + column, + "fb_01K3TEXT", + &fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(), + ) + .await + .unwrap() + } + + #[rstest::rstest] + #[case::nullable_text("text")] + #[case::nested_text("nested")] + #[case::blob("blob")] + #[tokio::test] + async fn function_write_preserves_complex_omitted_inputs( + #[case] kind: &str, + #[values(false, true)] merge: bool, + ) { + use arrow_array::{ + ArrayRef, Int32Array, Int64Array, RecordBatch, StringArray, StructArray, + }; + + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + + let texts = Arc::new(StringArray::from(vec![ + Some("alpha"), + None, + Some(""), + Some("delta"), + ])); + let (body_field, body): (ArrowField, ArrayRef) = match kind { + "text" => (ArrowField::new("body", DataType::Utf8, true), texts), + "nested" => { + let fields = vec![ArrowField::new("text", DataType::Utf8, true)].into(); + let body = StructArray::new( + fields, + vec![texts], + Some(arrow_buffer::NullBuffer::from(vec![ + true, false, true, true, + ])), + ); + ( + ArrowField::new("body", body.data_type().clone(), true), + Arc::new(body), + ) + } + "blob" => { + let mut builder = lance::blob::BlobArrayBuilder::new(4); + builder.push_bytes(b"alpha").unwrap(); + builder.push_null().unwrap(); + builder.push_bytes(b"").unwrap(); + builder.push_bytes(b"delta").unwrap(); + ( + lance::blob::blob_field("body", true), + builder.finish().unwrap(), + ) + } + _ => unreachable!(), + }; + let batch = RecordBatch::try_new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("title", DataType::Utf8, false), + body_field.clone(), + ArrowField::new("search_text", DataType::Utf8, true), + ArrowField::new("search_token_count", DataType::Int64, true), + ArrowField::new("spare", DataType::Int32, false), + ])), + vec![ + Arc::new(StringArray::from(vec!["a", "b", "c", "d"])), + body, + Arc::new(StringArray::from(vec!["alpha", "null", "empty", "delta"])), + Arc::new(Int64Array::from(vec![5, 0, 0, 5])), + Arc::new(Int32Array::from(vec![0; 4])), + ], + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("complex_function_inputs", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + data_storage_version: Some(lance_file::version::LanceFileVersion::V2_2), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut raw = serde_json::to_value(text_features_binding("")).unwrap(); + let json_field = + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![body_field])) + .unwrap() + .fields + .remove(0); + raw["input_schema"]["fields"][1] = serde_json::to_value(&json_field).unwrap(); + raw["inputs"][1]["arrow_type"] = serde_json::Value::String(match kind { + "text" => "utf8".into(), + "blob" => crate::function::FUNCTION_BLOB_V2_TYPE.into(), + _ => serde_json::to_string(&json_field.r#type).unwrap(), + }); + let binding = serde_json::from_value(raw).unwrap(); + stamp_bindings(&table, std::slice::from_ref(&binding)).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + native.dataset.update(dataset); + if merge { + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("spare", Int32, [1, 1, 1, 1]) + ) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + } else { + table.update().column("spare", "1").execute().await.unwrap(); + } + let dataset = native.dataset.get().await.unwrap(); + for column in ["search_text", "search_token_count"] { + let plan = function_plan(&dataset, column).await; + assert!( + !plan.recompute_all && plan.dirty.is_empty() && plan.pending_fill.is_empty(), + "{plan:?}" + ); + } + let mut scan = dataset.scan(); + scan.with_row_address(); + scan.project(&["title", "search_text", "search_token_count", "body"]) + .unwrap(); + let mut actual = BTreeMap::new(); + for batch in scan + .try_into_stream() + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + { + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let text = batch + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + let lengths = batch + .column(2) + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + assert!(!text.is_null(row) && !lengths.is_null(row)); + let body = batch.column_by_name("body").unwrap(); + let input = if kind == "blob" { + let addresses = batch + .column_by_name(ROW_ADDR) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + match dataset + .take_blobs_by_addresses(&[addresses.value(row)], "body") + .await + .unwrap() + .pop() + .unwrap() + { + Some(file) => Some(file.read().await.unwrap().to_vec()), + None => None, + } + } else { + let leaf = if kind == "nested" { + body.as_any() + .downcast_ref::() + .unwrap() + .column(0) + } else { + body + }; + let leaf = leaf.as_any().downcast_ref::().unwrap(); + (!body.is_null(row) && !leaf.is_null(row)) + .then(|| leaf.value(row).as_bytes().to_vec()) + }; + let expected_input = match titles.value(row) { + "a" => Some(b"alpha".to_vec()), + "b" => None, + "c" => Some(vec![]), + "d" => Some(b"delta".to_vec()), + _ => unreachable!(), + }; + assert_eq!(input, expected_input); + actual.insert( + titles.value(row).to_string(), + (text.value(row).to_string(), lengths.value(row)), + ); + } + } + assert_eq!( + actual, + BTreeMap::from([ + ("a".into(), ("alpha".into(), 5)), + ("b".into(), ("null".into(), 0)), + ("c".into(), ("empty".into(), 0)), + ("d".into(), ("delta".into(), 5)), + ]) + ); + } + + #[rstest::rstest] + #[case::label_update(false, 1, false)] + #[case::label_merge(true, 1, false)] + #[case::identical_merge(true, 0, false)] + #[case::mixed_update_insert(true, 1, true)] + #[tokio::test] + async fn function_write_preserves_unchanged_inputs( + #[case] merge: bool, + #[case] spare: i32, + #[case] insert: bool, + ) { + use crate::query::ExecutableQuery; + + let table = fresh_function_table().await; + let version = if merge { + let titles = if insert { + vec!["a", "c", "e"] + } else { + vec!["a", "c"] + }; + let batch = arrow_array::record_batch!( + ("title", Utf8, titles.clone()), + ("spare", Int32, vec![spare; titles.len()]) + ) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + if insert { + merge.when_not_matched_insert_all(); + } + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap() + .version + } else { + table + .update() + .only_if("title IN ('a', 'c')") + .column("spare", spare.to_string()) + .execute() + .await + .unwrap() + .version + }; + assert_eq!(version, table.version().await.unwrap()); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for column in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, column).await; + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + assert_eq!(stale.pending_fill.is_empty(), !insert, "{stale:?}"); + } + let batches = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut values = BTreeMap::new(); + for batch in batches { + let titles = batch + .column_by_name("title") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let outputs = batch + .column_by_name("search_text") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..batch.num_rows() { + values.insert( + titles.value(i).to_string(), + (!outputs.is_null(i)).then(|| outputs.value(i).to_string()), + ); + } + } + for (title, output) in [("a", "a x"), ("b", "b"), ("c", "c z"), ("d", "d w")] { + assert_eq!(values[title].as_deref(), Some(output)); + } + assert_eq!(values.len(), if insert { 5 } else { 4 }); + if insert { + assert_eq!(values["e"], None, "new rows still need Function evaluation"); + prune_sidecars(&dataset, true).await.unwrap(); + assert!( + !function_plan(&dataset, "search_text") + .await + .pending_fill + .is_empty() + ); + } + } + + #[rstest::rstest] + #[case::same_definition(false)] + #[case::changed_definition(true)] + #[tokio::test] + async fn partial_refresh_preserves_only_current_definition(#[case] changed: bool) { + let table = fresh_function_table().await; + let batch = + arrow_array::record_batch!(("title", Utf8, ["a", "e"]), ("spare", Int32, [1, 1])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge.when_not_matched_insert_all(); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap(); + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let before = function_plan(&dataset, "search_text").await; + assert!(!before.pending_fill.is_empty()); + assert!(before.dirty.is_empty()); + // Refresh only the untouched fragment. Retained values elsewhere + // still belong to the old definition, even though their inputs match. + let definition = if changed { + "new-function-version" + } else { + "fb_01K3TEXT" + }; + let pinned = dataset.clone(); + let stale = staleness_against(&pinned, "search_text", definition, &inputs) + .await + .unwrap(); + let computed = signatures_for(&dataset, &[1], &inputs).unwrap(); + assert_eq!(computed.len(), 1); + record_freshness( + &mut dataset, + Some((&pinned, &stale)), + "search_text", + definition, + &inputs, + computed, + ) + .await + .unwrap(); + let after = staleness_against(&dataset, "search_text", definition, &inputs) + .await + .unwrap(); + assert!(!after.is_dirty(1), "{after:?}"); + if changed { + for fragment in dataset.get_fragments().iter().filter(|f| f.id() != 1) { + assert!(after.is_dirty(fragment.id() as u32), "{after:?}"); + } + assert!(after.pending_fill.is_empty(), "{after:?}"); + } else { + assert_eq!(after.pending_fill, before.pending_fill); + assert!(after.dirty.is_empty(), "{after:?}"); + } + } + + #[tokio::test] + async fn function_write_retains_pending_fill_across_another_update() { + let table = fresh_function_table().await; + let batch = + arrow_array::record_batch!(("title", Utf8, ["e"]), ("spare", Int32, [1])).unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_not_matched_insert_all(); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap(); + table + .update() + .only_if("title = 'e'") + .column("spare", "2") + .execute() + .await + .unwrap(); + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let stale = function_plan(&dataset, "search_text").await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!( + stale.pending_fill.keys().copied().collect::>(), + vec![3] + ); + + write_signatures( + &mut dataset, + "search_text", + "fb_01K3TEXT", + stale.pending_fill, + ) + .await + .unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .pending_fill + .is_empty() + ); + // An older pending-fill reference must not override a later completed + // stamp or make a genuinely changed input fresh. + let changed = lance::dataset::UpdateBuilder::new(Arc::new(dataset)) + .update_where("title = 'e'") + .unwrap() + .set("body", "'changed'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + assert!( + function_plan(&changed.new_dataset, "search_text") + .await + .is_dirty(4) + ); + } + + #[rstest::rstest] + #[case::dirty_source("a", true)] + #[case::unrelated_dirty_fragment("c", false)] + #[tokio::test] + async fn function_write_preserves_pending_repairs( + #[case] title: &str, + #[case] dirty_product: bool, + ) { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signature = signatures_for(&dataset, &[0], &inputs).unwrap()[&0].clone(); + begin_row_repair( + &mut dataset, + "search_text", + "fb_01K3TEXT", + &inputs, + "pending-refresh", + &BTreeMap::from([( + 0, + RowRepair { + signature, + rows: RoaringBitmap::from_iter([0]), + }, + )]), + ) + .await + .unwrap(); + let prior = stored_row_states(&dataset, "search_text").await; + native.dataset.update(dataset); + table + .update() + .only_if(format!("title = '{title}'")) + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert_eq!(stale.is_dirty(2), dirty_product, "{stale:?}"); + assert_eq!(stored_row_states(&dataset, "search_text").await, prior); + } + + #[rstest::rstest] + #[case::input("body", "'changed'")] + #[case::output("search_text", "'uncomputed'")] + #[tokio::test] + async fn function_write_does_not_certify_changed_values( + #[case] column: &str, + #[case] value: &str, + ) { + let table = fresh_function_table().await; + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let result = lance::dataset::UpdateBuilder::new(dataset) + .update_where("title = 'a'") + .unwrap() + .set(column, value) + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut after = result.new_dataset.as_ref().clone(); + let version = after.version().version; + preserve_function_freshness( + &mut after, + FunctionWrite::Update { + columns: &[column.into()], + }, + ) + .await + .unwrap(); + assert_eq!(after.version().version, version); + assert!(function_plan(&after, "search_text").await.is_dirty(2)); + } + + #[rstest::rstest] + #[case::input_same_rows("body", "a", true)] + #[case::input_other_rows("body", "c", false)] + #[case::output_same_rows("search_text", "a", true)] + #[case::output_other_rows("search_text", "c", false)] + #[tokio::test] + async fn function_write_preserves_prior_invalidation( + #[case] changed_column: &str, + #[case] title: &str, + #[case] dirty_product: bool, + ) { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let result = lance::dataset::UpdateBuilder::new(native.dataset.get().await.unwrap()) + .update_where("title = 'a'") + .unwrap() + .set(changed_column, "'changed'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + assert!( + function_plan(&result.new_dataset, "search_text") + .await + .is_dirty(2) + ); + native.dataset.update(result.new_dataset.as_ref().clone()); + + table + .update() + .only_if(format!("title = '{title}'")) + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert_eq!(stale.is_dirty(3), dirty_product, "{stale:?}"); + if !dirty_product { + assert!( + stale.is_dirty(2), + "the earlier invalidation was lost: {stale:?}" + ); + } + } + + #[tokio::test] + async fn function_write_keeps_a_changed_definition_stale() { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .update_field_metadata() + .update( + "search_text", + [(DEFINITION_VERSION_META_KEY, Some("old-function-version"))], + ) + .unwrap() + .await + .unwrap(); + native.dataset.update(dataset); + table.update().column("spare", "1").execute().await.unwrap(); + assert!( + function_plan(native.dataset.get().await.unwrap().as_ref(), "search_text") + .await + .recompute_all + ); + } + + #[rstest::rstest] + #[case::delete(false)] + #[case::restore(true)] + #[tokio::test] + async fn function_write_cannot_stamp_over_a_concurrent_commit(#[case] restore: bool) { + let table = fresh_function_table().await; + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let before_version = dataset.version().version; + let result = lance::dataset::UpdateBuilder::new(dataset) + .update_where("title = 'a'") + .unwrap() + .set("spare", "1") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut staged = result.new_dataset.as_ref().clone(); + let mut concurrent = staged.clone(); + if restore { + concurrent = concurrent.checkout_version(before_version).await.unwrap(); + concurrent.restore().await.unwrap(); + } else { + concurrent.delete("title = 'd'").await.unwrap(); + } + let current_version = concurrent.version().version; + let before = field_meta(&concurrent, "search_text", SOURCE_SIGNATURE_META_KEY); + assert!( + preserve_function_freshness( + &mut staged, + FunctionWrite::Update { + columns: &["spare".into()] + } + ) + .await + .is_err() + ); + concurrent.checkout_latest().await.unwrap(); + assert_eq!(concurrent.version().version, current_version); + assert_eq!( + field_meta(&concurrent, "search_text", SOURCE_SIGNATURE_META_KEY), + before + ); + } + + #[tokio::test] + async fn function_write_retains_inherited_compaction_freshness() { + let table = fresh_function_table().await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + compact(&mut dataset).await; + assert!( + !function_plan(&dataset, "search_text") + .await + .inherited + .is_empty() + ); + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("spare", "1") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + let stale = function_plan(&dataset, "search_text").await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!(dataset.get_fragments().len(), 2); + } + /// Two fragments of 50 rows, `id` and `value`, with `doubled` declared /// all-null against `value`, tracked from birth. async fn table(uri: &str) -> Dataset { diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 1f0b80829..3f37c540d 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -385,6 +385,8 @@ pub(crate) async fn execute_merge_insert( } let dataset = table.dataset.get().await?; + let source_schema = source.schema(); + let on = params.on.clone(); let mut builder = LanceMergeInsertBuilder::try_new(dataset.clone(), params.on)?; match ( params.when_matched_update_all, @@ -432,8 +434,21 @@ pub(crate) async fn execute_merge_insert( Either::Right(job.execute(source).map_err(|e| e.into())) }; let (new_dataset, stats) = future.await?; + let mut new_dataset = new_dataset.as_ref().clone(); + if let Err(error) = super::freshness::preserve_function_freshness( + &mut new_dataset, + super::freshness::FunctionWrite::Merge { + source_schema: &source_schema, + on: &on, + num_inserted_rows: stats.num_inserted_rows, + }, + ) + .await + { + log::warn!("merge committed but Function freshness could not be preserved: {error}"); + } let version = new_dataset.manifest().version; - table.dataset.update(new_dataset.as_ref().clone()); + table.dataset.update(new_dataset); Ok(MergeResult { version, num_updated_rows: stats.num_updated_rows, diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index aa325cd7c..d9828fff1 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -113,6 +113,11 @@ pub(crate) async fn execute_update( } // 4. Apply the columns (SET clause) + let written_columns = update + .columns + .iter() + .map(|(column, _)| column.clone()) + .collect::>(); for (column, value) in update.columns { builder = builder.set(column, &value)?; } @@ -120,13 +125,25 @@ pub(crate) async fn execute_update( // 5. Execute the operation (Write new files) let operation = builder.build()?; let res = operation.execute().await?; + let mut new_dataset = res.new_dataset.as_ref().clone(); + if let Err(error) = super::freshness::preserve_function_freshness( + &mut new_dataset, + super::freshness::FunctionWrite::Update { + columns: &written_columns, + }, + ) + .await + { + log::warn!("update committed but Function freshness could not be preserved: {error}"); + } // 6. Update the table's view of the latest version - table.dataset.update(res.new_dataset.as_ref().clone()); + let version = new_dataset.version().version; + table.dataset.update(new_dataset); Ok(UpdateResult { rows_updated: res.rows_updated, - version: res.new_dataset.version().version, + version, }) } From 7cc3904a7e98b18062a28f7841fa613002e13061 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 19:12:06 +0800 Subject: [PATCH 066/203] feat: expose exact Function column freshness (#4958) ## Problem Function-backed columns need an exact `fresh`, `stale`, `never_computed`, and `failed` partition for the table version a caller is reading. The existing error listing is capped, and composing it with job and schema listings cannot prove which rows currently failed. ## Behavior - Adds a strict freshness reader beside the existing permissive planner. It distinguishes an absent certificate from legacy evidence that omits failures, and from a current certificate carrying failure coverage. - Extends the immutable freshness sidecar with per-fragment known and failed row bitmaps. Partial or `WHERE` publications cover only observed rows; untouched rows stay unknown. Deleted rows do not block classification. - Adds failure-aware whole-fragment and row-repair writers. A rejected older attempt cannot overwrite failure evidence already recorded for a newer input signature. - Adds `column_status`, `column_statuses`, and `wait_fresh` to Python and the corresponding Node methods. The client calls the server's exact status endpoint, validates the four-way partition and one-version guarantee, and preserves the complete Function version, last-job, and automatic-refresh metadata. - Adds an MDX-commented draft usage section to the Enterprise computed-column refresh guide, covering Python, Rust, and TypeScript and remaining hidden until the server integration ships. - Sends `column`, `branch`, and exact `version` selectors to the status route. A pinned handle rejects a nonempty response from any other table version; latest handles keep the existing read-freshness headers. - Retries `wait_fresh` only for HTTP 503 with `function_column_status_finalization_pending`. Existing failed rows remain visible and do not keep the wait pending; other errors propagate. - Models the shared scheduler projection, including `up_to_date`, real `blocked` states, their reason, failure streak, and effective cooldown. ## Validation This is the SDK side of ENT-3563. Sophon's failure-coverage publication and status endpoint are a separate integration; deployed end-to-end and whole-ticket acceptance remain pending. - Rust: 9 exact freshness/status tests passed, plus 1 exact latest-handle freshness-header test. The pinned transport test was extended with a wrong-version response and rerun at `ebd6649a` (1 passed). Coverage includes untouched partial rows, selected-row failure clearing, cross-generation evidence, typed and non-retried errors, `up_to_date`, blocked scheduler fields, and exact-version requests. - Python: 2 native PyO3 remote-transport tests passed together, including typed retry; one local facade test reaches the existing unsupported boundary. - Node: the NAPI addon built successfully, TypeScript and Biome passed, and the selected native remote-transport test passed 1/0, including exact-version selection and blocked scheduler metadata. - `cargo fmt`, `git diff --check`, Ruff format/lint, Python compile, Biome, and TypeScript checks passed. Validation is mapped by the relevant unchanged source rather than treated as one final-head run: the nine Rust tests ran at `e4d51fc8`, the latest-header and Python remote tests at `31e68b7d`, the local Python test and Node build at `6f213584`, and the final TypeScript/Jest delta at `4f2d5c27`. The final product tree excludes those five private EC2 runner files and adds six generated TypeDoc files plus one hidden draft usage section in the computed-column refresh guide. The Node delta corrected a private TypeScript command and reused the unchanged native addon. --- docs/src/js/classes/Table.md | 64 ++ docs/src/js/globals.md | 4 + .../FunctionColumnAutoRefreshStatus.md | 95 ++ .../FunctionColumnLastRefreshJob.md | 41 + .../src/js/interfaces/FunctionColumnStatus.md | 97 ++ .../interfaces/FunctionColumnVersionStatus.md | 57 + docs/src/python/python.md | 8 + .../feature-engineering/refresh-column.mdx | 51 + nodejs/__test__/remote.test.ts | 63 ++ nodejs/lancedb/index.ts | 4 + nodejs/lancedb/table.ts | 111 ++ nodejs/src/table.rs | 151 +++ python/python/lancedb/__init__.py | 14 + python/python/lancedb/_lancedb.pyi | 45 + python/python/lancedb/remote/table.py | 14 + python/python/lancedb/table.py | 71 +- python/python/tests/test_remote_db.py | 131 +++ python/python/tests/test_table.py | 10 + python/src/lib.rs | 11 +- python/src/table.rs | 175 ++++ rust/lancedb/src/error.rs | 19 + rust/lancedb/src/remote/table.rs | 495 ++++++++- rust/lancedb/src/table.rs | 85 ++ rust/lancedb/src/table/freshness.rs | 977 +++++++++++++++++- .../src/table/function_column_status.rs | 303 ++++++ 25 files changed, 3055 insertions(+), 41 deletions(-) create mode 100644 docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md create mode 100644 docs/src/js/interfaces/FunctionColumnLastRefreshJob.md create mode 100644 docs/src/js/interfaces/FunctionColumnStatus.md create mode 100644 docs/src/js/interfaces/FunctionColumnVersionStatus.md create mode 100644 rust/lancedb/src/table/function_column_status.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 27acc9847..aba747a7c 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -704,6 +704,47 @@ so this is safe to call repeatedly. *** +### functionColumnStatus() + +```ts +abstract functionColumnStatus(column): Promise +``` + +Return exact freshness status for one Function-backed output column. + +#### Parameters + +* **column**: `string` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)> + +*** + +### functionColumnStatuses() + +```ts +abstract functionColumnStatuses(column?): Promise +``` + +Return exact freshness status for Function-backed output columns. + +All results describe one server table version. Omit `column` for every +Function output. Rows already failed remain visible and do not prevent +`waitFresh` from completing. A handle pinned to an exact version requests +that version; a latest handle retains normal read-freshness behavior. + +#### Parameters + +* **column?**: `string` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)[]> + +*** + ### functionErrors() ```ts @@ -1598,3 +1639,26 @@ Waits for asynchronous indexing to complete on the table. #### Returns `Promise`<`void`> + +*** + +### waitFresh() + +```ts +abstract waitFresh(column, timeoutSeconds?): Promise +``` + +Poll until no stale or never-computed rows remain. + +Only HTTP 503 with the exact finalization-pending error code is retried; +every other error propagates. Failed rows do not block completion. + +#### Parameters + +* **column**: `string` + +* **timeoutSeconds?**: `number` + +#### Returns + +`Promise`<[`FunctionColumnStatus`](../interfaces/FunctionColumnStatus.md)> diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 50f55f937..19d7ceb97 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -95,6 +95,10 @@ - [FtsToken](interfaces/FtsToken.md) - [FullTextQuery](interfaces/FullTextQuery.md) - [FullTextSearchOptions](interfaces/FullTextSearchOptions.md) +- [FunctionColumnAutoRefreshStatus](interfaces/FunctionColumnAutoRefreshStatus.md) +- [FunctionColumnLastRefreshJob](interfaces/FunctionColumnLastRefreshJob.md) +- [FunctionColumnStatus](interfaces/FunctionColumnStatus.md) +- [FunctionColumnVersionStatus](interfaces/FunctionColumnVersionStatus.md) - [FunctionErrorFragment](interfaces/FunctionErrorFragment.md) - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md) - [FunctionErrors](interfaces/FunctionErrors.md) diff --git a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md new file mode 100644 index 000000000..bc8f7daab --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md @@ -0,0 +1,95 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnAutoRefreshStatus + +# Interface: FunctionColumnAutoRefreshStatus + +Automatic-refresh projection for a Function output. + +## Properties + +### activeJobId? + +```ts +optional activeJobId: string; +``` + +*** + +### blockedReason? + +```ts +optional blockedReason: + | "table_has_mem_wal" + | "inputs_not_settled" + | "dependency_in_flight" + | "table_capacity" + | "cancelled" + | "preparation_backoff"; +``` + +*** + +### effectiveCooldownMillis? + +```ts +optional effectiveCooldownMillis: bigint; +``` + +*** + +### enabled + +```ts +enabled: boolean; +``` + +*** + +### failureStreak + +```ts +failureStreak: number; +``` + +*** + +### intervalSeconds? + +```ts +optional intervalSeconds: bigint; +``` + +*** + +### nextRunAtMillis + +```ts +nextRunAtMillis: null | bigint; +``` + +*** + +### nextRunAtReason? + +```ts +optional nextRunAtReason: string; +``` + +*** + +### state + +```ts +state: + | "running" + | "disabled" + | "ready" + | "up_to_date" + | "waiting_interval" + | "waiting_backoff" + | "blocked" + | "unobservable"; +``` diff --git a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md new file mode 100644 index 000000000..1d7d3b300 --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md @@ -0,0 +1,41 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnLastRefreshJob + +# Interface: FunctionColumnLastRefreshJob + +Latest matching refresh Job projected for a Function output. + +## Properties + +### automatic? + +```ts +optional automatic: boolean; +``` + +*** + +### completedAtMillis? + +```ts +optional completedAtMillis: bigint; +``` + +*** + +### jobId + +```ts +jobId: string; +``` + +*** + +### state + +```ts +state: string; +``` diff --git a/docs/src/js/interfaces/FunctionColumnStatus.md b/docs/src/js/interfaces/FunctionColumnStatus.md new file mode 100644 index 000000000..755a8af81 --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnStatus.md @@ -0,0 +1,97 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnStatus + +# Interface: FunctionColumnStatus + +Exact four-way status of one Function output at one table version. + +## Properties + +### autoRefresh + +```ts +autoRefresh: FunctionColumnAutoRefreshStatus; +``` + +*** + +### bindingId + +```ts +bindingId: string; +``` + +*** + +### column + +```ts +column: string; +``` + +*** + +### failed + +```ts +failed: bigint; +``` + +*** + +### fresh + +```ts +fresh: bigint; +``` + +*** + +### function + +```ts +function: FunctionColumnVersionStatus; +``` + +*** + +### lastRefreshJob? + +```ts +optional lastRefreshJob: FunctionColumnLastRefreshJob; +``` + +*** + +### neverComputed + +```ts +neverComputed: bigint; +``` + +*** + +### rows + +```ts +rows: bigint; +``` + +*** + +### stale + +```ts +stale: bigint; +``` + +*** + +### tableVersion + +```ts +tableVersion: bigint; +``` diff --git a/docs/src/js/interfaces/FunctionColumnVersionStatus.md b/docs/src/js/interfaces/FunctionColumnVersionStatus.md new file mode 100644 index 000000000..fa02139d2 --- /dev/null +++ b/docs/src/js/interfaces/FunctionColumnVersionStatus.md @@ -0,0 +1,57 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionColumnVersionStatus + +# Interface: FunctionColumnVersionStatus + +Exact immutable Function revision attached to a table output. + +## Properties + +### location + +```ts +location: string; +``` + +*** + +### manifestDigest + +```ts +manifestDigest: string; +``` + +*** + +### name + +```ts +name: string; +``` + +*** + +### namespacePath + +```ts +namespacePath: string[]; +``` + +*** + +### objectId + +```ts +objectId: string; +``` + +*** + +### version + +```ts +version: string; +``` diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 7f28d8804..eccaae6ce 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -523,6 +523,14 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.FunctionErrorFragment +::: lancedb.FunctionColumnStatus + +::: lancedb.FunctionColumnVersionStatus + +::: lancedb.FunctionColumnLastRefreshJob + +::: lancedb.FunctionColumnAutoRefreshStatus + ::: lancedb.job.Job ::: lancedb.job.AsyncJob diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index b3fcdc937..e1a9c43f3 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -150,6 +150,57 @@ does not raise, which is what makes it safe in a loop; `wait()` raises A long backfill can therefore be started, left, and checked on from a different process. +{/* +Draft for the Function freshness release. Keep this section hidden until the +Enterprise status endpoint and its integration acceptance are deployed. + +### Check Function column freshness {#freshness} + +For a Function-backed column, the SDK can report how many live rows are +`fresh`, `stale`, `never_computed`, or `failed` at the table version it +reads. `wait_fresh`, `waitFresh`, and `wait_for_function_column` poll until no +stale or never-computed rows remain. Rows that already failed stay in the +returned status and do not keep the wait pending, so inspect `failed` after a +successful wait: + + +```python Python icon="python" +status = table.column_status("embedding") +print(status.fresh, status.stale, status.never_computed, status.failed) + +final_status = table.wait_fresh("embedding") +print(final_status.failed) +``` + +```typescript TypeScript icon="typescript" +const status = await table.functionColumnStatus("embedding"); +console.log( + status.fresh, + status.stale, + status.neverComputed, + status.failed, +); + +const finalStatus = await table.waitFresh("embedding"); +console.log(finalStatus.failed); +``` + +```rust Rust icon="rust" +let status = table.function_column_status("embedding").await?; +println!( + "{} {} {} {}", + status.fresh, status.stale, status.never_computed, status.failed +); + +let final_status = table.wait_for_function_column("embedding", None).await?; +println!("{}", final_status.failed); +``` + + +The wait helpers do not submit or cancel a refresh. They retry only the typed +finalization-pending response and propagate other errors. +*/} + ### Configure workers and resources {#resources} SQL exposes the worker budget directly, which is the lever when a backfill is diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 280905897..6c160ed03 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -647,6 +647,69 @@ describe("remote connection", () => { ]); }); + it("passes a pinned version and decodes Function scheduler status", async () => { + const queries: Record[] = []; + await withMockDatabase( + (req, res) => { + const url = new URL(req.url ?? "/", "http://localhost"); + if (url.pathname.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 42, + schema: { fields: [] }, + }), + ); + return; + } + if (url.pathname === "/v1/table/docs/function_columns/status") { + queries.push(Object.fromEntries(url.searchParams.entries())); + res.writeHead(200, { "Content-Type": "application/json" }).end( + `[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":2, + "stale":2, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":3, + "effective_cooldown_millis":8000, + "blocked_reason":"preparation_backoff", + "next_run_at_millis":null + } + }]`, + ); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + await table.checkout(42); + const status = await table.functionColumnStatus("embedding"); + expect(status.tableVersion).toBe(42n); + expect(status.autoRefresh.state).toBe("blocked"); + expect(status.autoRefresh.failureStreak).toBe(3); + expect(status.autoRefresh.effectiveCooldownMillis).toBe(8000n); + expect(status.autoRefresh.blockedReason).toBe("preparation_backoff"); + }, + ); + expect(queries).toEqual([{ column: "embedding", version: "42" }]); + }); + it("forwards refresh options to the backfill request", async () => { const bodies: unknown[] = []; await withMockDatabase( diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 6bd46c9c8..35697dc8c 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -154,6 +154,10 @@ export { export { Table, + FunctionColumnAutoRefreshStatus, + FunctionColumnLastRefreshJob, + FunctionColumnStatus, + FunctionColumnVersionStatus, Branches, BranchColumnSummary, BranchColumnChange, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index d56f66cde..99eb0d1f9 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -258,6 +258,66 @@ export interface RTEWriteSpec { writerConfigDefaults?: Record; } +/** Exact immutable Function revision attached to a table output. */ +export interface FunctionColumnVersionStatus { + name: string; + namespacePath: string[]; + objectId: string; + location: string; + version: string; + manifestDigest: string; +} + +/** Latest matching refresh Job projected for a Function output. */ +export interface FunctionColumnLastRefreshJob { + jobId: string; + state: string; + automatic?: boolean; + completedAtMillis?: bigint; +} + +/** Automatic-refresh projection for a Function output. */ +export interface FunctionColumnAutoRefreshStatus { + enabled: boolean; + intervalSeconds?: bigint; + activeJobId?: string; + state: + | "disabled" + | "running" + | "ready" + | "up_to_date" + | "waiting_interval" + | "waiting_backoff" + | "blocked" + | "unobservable"; + failureStreak: number; + effectiveCooldownMillis?: bigint; + blockedReason?: + | "table_has_mem_wal" + | "inputs_not_settled" + | "dependency_in_flight" + | "table_capacity" + | "cancelled" + | "preparation_backoff"; + nextRunAtMillis: bigint | null; + nextRunAtReason?: string; +} + +/** Exact four-way status of one Function output at one table version. */ +export interface FunctionColumnStatus { + column: string; + bindingId: string; + function: FunctionColumnVersionStatus; + tableVersion: bigint; + rows: bigint; + fresh: bigint; + stale: bigint; + neverComputed: bigint; + failed: bigint; + lastRefreshJob?: FunctionColumnLastRefreshJob; + autoRefresh: FunctionColumnAutoRefreshStatus; +} + /** * A Table is a collection of Records in a LanceDB Database. * @@ -780,6 +840,32 @@ export abstract class Table { options?: FunctionErrorsOptions, ): Promise; + /** + * Return exact freshness status for Function-backed output columns. + * + * All results describe one server table version. Omit `column` for every + * Function output. Rows already failed remain visible and do not prevent + * `waitFresh` from completing. A handle pinned to an exact version requests + * that version; a latest handle retains normal read-freshness behavior. + */ + abstract functionColumnStatuses( + column?: string, + ): Promise; + + /** Return exact freshness status for one Function-backed output column. */ + abstract functionColumnStatus(column: string): Promise; + + /** + * Poll until no stale or never-computed rows remain. + * + * Only HTTP 503 with the exact finalization-pending error code is retried; + * every other error propagates. Failed rows do not block completion. + */ + abstract waitFresh( + column: string, + timeoutSeconds?: number, + ): Promise; + /** * Recompute this table's contents from its materialized-view definition. * @@ -1557,6 +1643,31 @@ export class LocalTable extends Table { return await this.inner.functionErrors(options); } + async functionColumnStatuses( + column?: string, + ): Promise { + return (await this.inner.functionColumnStatuses( + column, + )) as FunctionColumnStatus[]; + } + + async functionColumnStatus(column: string): Promise { + return (await this.inner.functionColumnStatus( + column, + )) as FunctionColumnStatus; + } + + async waitFresh( + column: string, + timeoutSeconds?: number, + ): Promise { + validateNonNegativeInteger(timeoutSeconds, "timeoutSeconds"); + return (await this.inner.waitForFunctionColumn( + column, + timeoutSeconds, + )) as FunctionColumnStatus; + } + async refreshMaterializedView( sourceVersion?: number, full?: boolean, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 5b52c0d16..f6d3e538e 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -534,6 +534,55 @@ impl Table { Ok(errors.into()) } + #[napi(catch_unwind)] + pub async fn function_column_statuses( + &self, + column: Option, + ) -> napi::Result> { + let statuses = self + .inner_ref()? + .function_column_statuses(column.as_deref()) + .await + .default_error()?; + Ok(statuses.into_iter().map(Into::into).collect()) + } + + #[napi(catch_unwind)] + pub async fn function_column_status( + &self, + column: String, + ) -> napi::Result { + let status = self + .inner_ref()? + .function_column_status(&column) + .await + .default_error()?; + Ok(status.into()) + } + + #[napi(catch_unwind)] + pub async fn wait_for_function_column( + &self, + column: String, + timeout_seconds: Option, + ) -> napi::Result { + let timeout = timeout_seconds + .map(|seconds| { + u64::try_from(seconds) + .map(std::time::Duration::from_secs) + .map_err(|_| { + napi::Error::from_reason("timeoutSeconds must be a non-negative integer") + }) + }) + .transpose()?; + let status = self + .inner_ref()? + .wait_for_function_column(&column, timeout) + .await + .default_error()?; + Ok(status.into()) + } + #[napi(catch_unwind)] pub async fn refresh_materialized_view( &self, @@ -1799,6 +1848,108 @@ pub struct FunctionErrors { pub truncated: bool, } +/// One exact immutable Function revision attached to a table output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnVersionStatus { + pub name: String, + pub namespace_path: Vec, + pub object_id: String, + pub location: String, + pub version: String, + pub manifest_digest: String, +} + +/// Latest matching refresh Job projected for a Function output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + pub automatic: Option, + pub completed_at_millis: Option, +} + +/// Automatic-refresh projection for a Function output. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + pub interval_seconds: Option, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +/// Exact four-way status of one Function output at one table version. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: BigInt, + pub rows: BigInt, + pub fresh: BigInt, + pub stale: BigInt, + pub never_computed: BigInt, + pub failed: BigInt, + pub last_refresh_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +impl From for FunctionColumnStatus { + fn from(status: lancedb::table::FunctionColumnStatus) -> Self { + Self { + column: status.column, + binding_id: status.binding_id, + function: FunctionColumnVersionStatus { + name: status.function.name, + namespace_path: status.function.namespace_path, + object_id: status.function.object_id, + location: status.function.location, + version: status.function.version, + manifest_digest: status.function.manifest_digest, + }, + table_version: BigInt::from(status.table_version), + rows: BigInt::from(status.rows), + fresh: BigInt::from(status.fresh), + stale: BigInt::from(status.stale), + never_computed: BigInt::from(status.never_computed), + failed: BigInt::from(status.failed), + last_refresh_job: status + .last_refresh_job + .map(|job| FunctionColumnLastRefreshJob { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis.map(BigInt::from), + }), + auto_refresh: FunctionColumnAutoRefreshStatus { + enabled: status.auto_refresh.enabled, + interval_seconds: status.auto_refresh.interval_seconds.map(BigInt::from), + active_job_id: status.auto_refresh.active_job_id, + state: status.auto_refresh.state.as_str().to_string(), + failure_streak: status.auto_refresh.failure_streak, + effective_cooldown_millis: status + .auto_refresh + .effective_cooldown_millis + .map(BigInt::from), + blocked_reason: status + .auto_refresh + .blocked_reason + .map(|reason| reason.as_str().to_string()), + next_run_at_millis: status.auto_refresh.next_run_at_millis.map(BigInt::from), + next_run_at_reason: status.auto_refresh.next_run_at_reason, + }, + } + } +} + impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { Self { diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 2208fd612..31285d100 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -17,6 +17,16 @@ __version__ = str(_Version(_native_version)) from ._lancedb import connect as lancedb_connect from ._lancedb import FtsToken +from ._lancedb import ( + FunctionColumnAutoRefreshStatus as FunctionColumnAutoRefreshStatus, +) +from ._lancedb import ( + FunctionColumnLastRefreshJob as FunctionColumnLastRefreshJob, +) +from ._lancedb import FunctionColumnStatus as FunctionColumnStatus +from ._lancedb import ( + FunctionColumnVersionStatus as FunctionColumnVersionStatus, +) from ._lancedb import FunctionErrorFragment as FunctionErrorFragment from ._lancedb import FunctionErrorRecord as FunctionErrorRecord from ._lancedb import FunctionErrors as FunctionErrors @@ -660,6 +670,10 @@ __all__ = [ "AsyncTable", "CompactionOptions", "FtsToken", + "FunctionColumnAutoRefreshStatus", + "FunctionColumnLastRefreshJob", + "FunctionColumnStatus", + "FunctionColumnVersionStatus", "col", "Expr", "func", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index dfb887461..07306c1d9 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -671,6 +671,13 @@ class Table: column: Optional[str] = None, limit: Optional[int] = None, ) -> FunctionErrors: ... + async def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: ... + async def column_status(self, column: str) -> FunctionColumnStatus: ... + async def wait_column_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: ... async def refresh_materialized_view( self, source_version: Optional[int] = None, @@ -1088,6 +1095,44 @@ class FunctionErrors: fragments: list[FunctionErrorFragment] truncated: bool +class FunctionColumnVersionStatus: + name: str + namespace_path: list[str] + object_id: str + location: str + version: str + manifest_digest: str + +class FunctionColumnLastRefreshJob: + job_id: str + state: str + automatic: Optional[bool] + completed_at_millis: Optional[int] + +class FunctionColumnAutoRefreshStatus: + enabled: bool + interval_seconds: Optional[int] + active_job_id: Optional[str] + state: str + failure_streak: int + effective_cooldown_millis: Optional[int] + blocked_reason: Optional[str] + next_run_at_millis: Optional[int] + next_run_at_reason: Optional[str] + +class FunctionColumnStatus: + column: str + binding_id: str + function: FunctionColumnVersionStatus + table_version: int + rows: int + fresh: int + stale: int + never_computed: int + failed: int + last_refresh_job: Optional[FunctionColumnLastRefreshJob] + auto_refresh: FunctionColumnAutoRefreshStatus + class RefreshMaterializedViewResult: @staticmethod def from_json(value: str) -> RefreshMaterializedViewResult: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index af648c45c..3f6bff45e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -34,6 +34,7 @@ from lancedb._lancedb import ( DeleteResult, DropColumnsResult, FtsToken, + FunctionColumnStatus, IndexConfig, RTEWriteSpec, MergeResult, @@ -1233,6 +1234,19 @@ class RemoteTable(Table): self._table.function_errors(job_id=job_id, column=column, limit=limit) ) + def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + return LOOP.run(self._table.column_statuses(column=column)) + + def column_status(self, column: str) -> FunctionColumnStatus: + return LOOP.run(self._table.column_status(column)) + + def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + return LOOP.run(self._table.wait_fresh(column, timeout)) + def alter_columns( self, *alterations: Iterable[Dict[str, str]] ) -> AlterColumnsResult: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 609e116ba..762f826c2 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -35,7 +35,7 @@ from urllib.parse import urlparse from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable from . import __version__ -from ._lancedb import _parse_field_path +from ._lancedb import FunctionColumnStatus, _parse_field_path from ._blob import ( BlobFile, _normalize_blob_descriptor, @@ -3504,6 +3504,36 @@ class Table(ABC): ... print("listing stopped at the limit") """ + @abstractmethod + def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + """Return exact status for Function-backed output columns. + + All statuses describe one server table version. ``column=None`` returns + every Function output. This operation is available on LanceDB + Enterprise tables. A table handle pinned to an exact version requests + that version; a latest handle retains the normal read-freshness + behavior. + """ + + @abstractmethod + def column_status(self, column: str) -> FunctionColumnStatus: + """Return exact status for one Function-backed output column.""" + + @abstractmethod + def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + """Poll until the column has no stale or never-computed rows. + + Rows already failed remain visible in the returned status and do not + keep this method waiting. The method never submits or cancels work. + Transport errors and unrecoverable status-evidence errors propagate. + A typed finalization-pending response is retried; arbitrary failure + responses are not. + """ + @abstractmethod def alter_columns(self, *alterations: Iterable[Dict[str, str]]): """ @@ -5604,6 +5634,19 @@ class LanceTable(Table): self._table.function_errors(job_id=job_id, column=column, limit=limit) ) + def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + return LOOP.run(self._table.column_statuses(column=column)) + + def column_status(self, column: str) -> FunctionColumnStatus: + return LOOP.run(self._table.column_status(column)) + + def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + return LOOP.run(self._table.wait_fresh(column, timeout)) + def alter_columns( self, *alterations: Iterable[Dict[str, str]] ) -> AlterColumnsResult: @@ -8168,6 +8211,32 @@ class AsyncTable: job_id=job_id, column=column, limit=limit ) + async def column_statuses( + self, column: Optional[str] = None + ) -> list[FunctionColumnStatus]: + """Return exact status for Function-backed output columns. + + All results describe one server table version. ``column=None`` returns + every Function output. A handle pinned to an exact version requests + that version. + """ + return await self._inner.column_statuses(column=column) + + async def column_status(self, column: str) -> FunctionColumnStatus: + """Return exact status for one Function-backed output column.""" + return await self._inner.column_status(column) + + async def wait_fresh( + self, column: str, timeout: Optional[timedelta] = None + ) -> FunctionColumnStatus: + """Poll until no stale or never-computed rows remain. + + Failed rows do not block completion. Server and transport errors are + not retried. Only the typed finalization-pending response is retried + with bounded backoff; arbitrary 500 responses surface immediately. + """ + return await self._inner.wait_column_fresh(column, timeout) + async def refresh_column_async( self, column: str, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 5224e5482..fd933b43c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2288,6 +2288,137 @@ def test_remote_function_errors_lists_the_rows_a_refresh_skipped(attempts): assert everything.truncated is True +def test_remote_function_column_status_passes_pinned_version(): + queries = [] + status = { + "column": "embedding", + "binding_id": "fb_01", + "function": { + "name": "embed", + "object_id": "embed", + "location": "objects/embed", + "version": "7", + "manifest_digest": "sha256:abc", + }, + "table_version": 42, + "rows": 4, + "fresh": 2, + "stale": 2, + "never_computed": 0, + "failed": 0, + "auto_refresh": { + "enabled": True, + "interval_seconds": 60, + "active_job_id": None, + "state": "blocked", + "failure_streak": 3, + "effective_cooldown_millis": 8000, + "blocked_reason": "preparation_backoff", + "next_run_at_millis": None, + }, + } + + def handler(request): + parsed = urlparse(request.path) + if parsed.path == "/v1/table/test/describe/": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps({"version": 42, "schema": {"fields": []}}).encode() + ) + elif parsed.path == "/v1/table/test/function_columns/status": + queries.append(parse_qs(parsed.query)) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps([status]).encode()) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + table.checkout(42) + result = table.column_status("embedding") + + assert queries == [{"column": ["embedding"], "version": ["42"]}] + assert result.table_version == 42 + assert (result.fresh, result.stale, result.never_computed, result.failed) == ( + 2, + 2, + 0, + 0, + ) + assert result.auto_refresh.state == "blocked" + assert result.auto_refresh.failure_streak == 3 + assert result.auto_refresh.effective_cooldown_millis == 8000 + assert result.auto_refresh.blocked_reason == "preparation_backoff" + + +def test_remote_wait_fresh_retries_only_typed_finalization_pending(): + calls = 0 + status = { + "column": "embedding", + "binding_id": "fb_01", + "function": { + "name": "embed", + "object_id": "embed", + "location": "objects/embed", + "version": "7", + "manifest_digest": "sha256:abc", + }, + "table_version": 42, + "rows": 1, + "fresh": 1, + "stale": 0, + "never_computed": 0, + "failed": 0, + "auto_refresh": { + "enabled": False, + "state": "disabled", + "failure_streak": 0, + "next_run_at_millis": None, + }, + } + + def handler(request): + nonlocal calls + parsed = urlparse(request.path) + if parsed.path == "/v1/table/test/describe/": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps({"version": 42, "schema": {"fields": []}}).encode() + ) + elif parsed.path == "/v1/table/test/function_columns/status": + calls += 1 + if calls == 1: + request.send_response(503) + request.send_header( + "x-lancedb-error-code", + "function_column_status_finalization_pending", + ) + request.end_headers() + request.wfile.write(b"finalization pending") + else: + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps([status]).encode()) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + result = table.wait_fresh("embedding", timeout=timedelta(seconds=2)) + + assert calls == 2 + assert result.fresh == result.rows == 1 + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) @pytest.mark.parametrize("failure", ["send", "read"]) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 7146ed86b..e3b69ced1 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6036,6 +6036,16 @@ def test_function_errors_are_remote_only(tmp_path): table.function_errors() +def test_function_column_status_is_remote_only(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("t", [{"x": 1}]) + with pytest.raises( + NotImplementedError, + match="exact Function column status is supported only in LanceDB Enterprise", + ): + table.wait_fresh("x") + + @pytest.mark.experimental_functions @pytest.mark.parametrize("batch_size", [None, 8]) def test_refresh_column_async_returns_job(tmp_path, batch_size): diff --git a/python/src/lib.rs b/python/src/lib.rs index 27ff4cb01..f78c4e7bb 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -16,9 +16,10 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery}; use session::Session; use table::{ AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken, - FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MergeResult, PyBlobFile, - RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, Table, - UpdateFieldMetadataResult, UpdateResult, + FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, + FunctionColumnVersionStatus, FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, + MergeResult, PyBlobFile, RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, + Table, UpdateFieldMetadataResult, UpdateResult, }; pub mod arrow; @@ -117,6 +118,10 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/python/src/table.rs b/python/src/table.rs index 24cc9ae5c..cf627961c 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -892,6 +892,136 @@ impl From for FunctionErrors { } } +/// Exact immutable Function revision attached to a table output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnVersionStatus { + pub name: String, + pub namespace_path: Vec, + pub object_id: String, + pub location: String, + pub version: String, + pub manifest_digest: String, +} + +impl From for FunctionColumnVersionStatus { + fn from(function: lancedb::function::FunctionVersionRef) -> Self { + Self { + name: function.name, + namespace_path: function.namespace_path, + object_id: function.object_id, + location: function.location, + version: function.version, + manifest_digest: function.manifest_digest, + } + } +} + +/// Latest matching refresh Job projected for a Function output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + pub automatic: Option, + pub completed_at_millis: Option, +} + +impl From for FunctionColumnLastRefreshJob { + fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self { + Self { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis, + } + } +} + +/// Automatic-refresh projection for a Function output. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + pub interval_seconds: Option, + pub active_job_id: Option, + pub state: String, + pub failure_streak: u32, + pub effective_cooldown_millis: Option, + pub blocked_reason: Option, + pub next_run_at_millis: Option, + pub next_run_at_reason: Option, +} + +impl From for FunctionColumnAutoRefreshStatus { + fn from(status: lancedb::table::FunctionColumnAutoRefreshStatus) -> Self { + Self { + enabled: status.enabled, + interval_seconds: status.interval_seconds, + active_job_id: status.active_job_id, + state: status.state.as_str().to_string(), + failure_streak: status.failure_streak, + effective_cooldown_millis: status.effective_cooldown_millis, + blocked_reason: status + .blocked_reason + .map(|reason| reason.as_str().to_string()), + next_run_at_millis: status.next_run_at_millis, + next_run_at_reason: status.next_run_at_reason, + } + } +} + +/// Exact four-way status of one Function output at one table version. +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: u64, + pub rows: u64, + pub fresh: u64, + pub stale: u64, + pub never_computed: u64, + pub failed: u64, + pub last_refresh_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +#[pymethods] +impl FunctionColumnStatus { + pub fn __repr__(&self) -> String { + format!( + "FunctionColumnStatus(column={:?}, table_version={}, rows={}, fresh={}, stale={}, never_computed={}, failed={})", + self.column, + self.table_version, + self.rows, + self.fresh, + self.stale, + self.never_computed, + self.failed + ) + } +} + +impl From for FunctionColumnStatus { + fn from(status: lancedb::table::FunctionColumnStatus) -> Self { + Self { + column: status.column, + binding_id: status.binding_id, + function: status.function.into(), + table_version: status.table_version, + rows: status.rows, + fresh: status.fresh, + stale: status.stale, + never_computed: status.never_computed, + failed: status.failed, + last_refresh_job: status.last_refresh_job.map(Into::into), + auto_refresh: status.auto_refresh.into(), + } + } +} + #[pyclass(get_all, from_py_object)] #[derive(Clone, Debug)] pub struct RefreshMaterializedViewResult { @@ -2425,6 +2555,51 @@ impl Table { }) } + #[pyo3(signature = (column=None))] + pub fn column_statuses( + self_: PyRef<'_, Self>, + column: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let statuses = inner + .function_column_statuses(column.as_deref()) + .await + .infer_error()?; + Ok(statuses + .into_iter() + .map(FunctionColumnStatus::from) + .collect::>()) + }) + } + + pub fn column_status(self_: PyRef<'_, Self>, column: String) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let status = inner.function_column_status(&column).await.infer_error()?; + Ok(FunctionColumnStatus::from(status)) + }) + } + + #[pyo3(signature = (column, timeout=None))] + pub fn wait_column_fresh<'py>( + self_: PyRef<'py, Self>, + column: String, + timeout: Option>, + ) -> PyResult> { + let timeout = timeout + .map(|timeout| timeout.extract::()) + .transpose()?; + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let status = inner + .wait_for_function_column(&column, timeout) + .await + .infer_error()?; + Ok(FunctionColumnStatus::from(status)) + }) + } + #[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_materialized_view( diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 7499641fc..853ca831f 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -543,6 +543,25 @@ fn has_unsupported_local_filesystem_source(error: &(dyn std::error::Error + 'sta } impl Error { + /// HTTP status associated with a remote request error. + /// + /// Retry wrappers preserve the underlying status. Other error variants do + /// not represent an HTTP response and return `None`. + #[cfg(feature = "remote")] + pub fn status_code(&self) -> Option { + match self { + Self::Http { status_code, .. } => *status_code, + Self::Retry { status_code, .. } => *status_code, + Self::TableNotFound { source, .. } => { + source.downcast_ref::().and_then(Self::status_code) + } + Self::JobFailed { failure, .. } => { + failure.source.as_deref().and_then(Self::status_code) + } + _ => None, + } + } + /// Structured resource details reported by a remote HTTP error. /// /// Older servers do not include these fields, in which case this returns diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 247b1925c..222ff527b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -42,7 +42,8 @@ use crate::table::query::create_multi_vector_plan; use crate::table::rte_stats::GetRTEStatsResponse; use crate::table::write_progress::FinishOnDrop; use crate::table::{ - AlterColumnsResult, FieldMetadataUpdate, RefreshColumnResult, UpdateFieldMetadataResult, + AlterColumnsResult, FieldMetadataUpdate, FunctionColumnStatus, RefreshColumnResult, + UpdateFieldMetadataResult, }; use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatistics}; use crate::utils::background_cache::BackgroundCache; @@ -4077,6 +4078,54 @@ impl BaseTable for RemoteTable { }) } + async fn function_column_statuses( + &self, + column: Option<&str>, + ) -> Result> { + let mut request = self.apply_branch_query(self.client.get(&format!( + "/v1/table/{}/function_columns/status", + self.identifier + ))); + if let Some(column) = column { + request = request.query(&[("column", column)]); + } + let read_snapshot = self.snapshot_read_state().await; + if let Some(version) = read_snapshot.version { + request = request.query(&[("version", version)]); + } + let request = read_snapshot.freshness.apply(request); + // A typed finalization-pending 503 is a domain result. Let the caller's + // bounded wait policy handle it instead of a generic 5xx retry loop. + let (request_id, response) = self.client.send_with_retry(request, None, false).await?; + if response.status().is_success() { + read_snapshot + .freshness + .observe_headers(&self.freshness, response.headers()); + } + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let statuses: Vec = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse Function column status response: {error}").into(), + request_id, + status_code: None, + })?; + crate::table::function_column_status::validate_statuses(&statuses)?; + if let Some(requested_version) = read_snapshot.version + && let Some(returned_version) = statuses + .iter() + .map(|status| status.table_version) + .find(|version| *version != requested_version) + { + return Err(Error::Runtime { + message: format!( + "Function column status response returned table version {returned_version}, but the table handle is pinned to version {requested_version}" + ), + }); + } + Ok(statuses) + } + async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result { self.check_mutable().await?; let body = alterations @@ -11350,6 +11399,450 @@ mod tests { assert_eq!(schema_requests.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn test_function_column_status_decodes_one_exact_snapshot() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/function_columns/status" + ); + assert_eq!(request.url().query(), None); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":10, + "fresh":6, + "stale":2, + "never_computed":1, + "failed":1, + "last_refresh_job":{ + "job_id":"job-7", + "state":"finished", + "automatic":true, + "completed_at_millis":1790000000000 + }, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "active_job_id":null, + "state":"unobservable", + "failure_streak":0, + "next_run_at_millis":null, + "next_run_at_reason":"authoritative_scheduler_projection_unavailable" + } + }]"#, + ) + .unwrap() + }); + + let statuses = table.function_column_statuses(None).await.unwrap(); + assert_eq!(statuses.len(), 1); + assert_eq!(statuses[0].table_version, 42); + assert_eq!(statuses[0].failed, 1); + assert_eq!( + statuses[0] + .last_refresh_job + .as_ref() + .map(|job| job.job_id.as_str()), + Some("job-7") + ); + assert_eq!( + statuses[0].auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Unobservable + ); + } + + #[tokio::test] + async fn test_function_column_status_filters_with_a_get_query() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().query(), Some("column=embedding")); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!(status.column, "embedding"); + assert!(status.last_refresh_job.is_none()); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Disabled + ); + } + + #[tokio::test] + async fn test_wait_for_function_column_retries_only_typed_finalization_pending() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .header( + "x-lancedb-error-code", + crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE, + ) + .body(b"finalization pending".to_vec()) + .unwrap() + } else { + http::Response::builder() + .status(200) + .body( + br#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"# + .to_vec(), + ) + .unwrap() + } + } + }); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_finalization_code_on_other_status_is_not_retried() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + calls.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .header( + "x-lancedb-error-code", + crate::table::function_column_status::FINALIZATION_PENDING_ERROR_CODE, + ) + .body(b"misclassified pending".to_vec()) + .unwrap() + } + }); + + let error = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap_err(); + assert!(error.to_string().contains("misclassified pending")); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_wait_for_function_column_does_not_retry_generic_500() { + let calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + move |_request| { + calls.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(b"corrupt freshness evidence".to_vec()) + .unwrap() + } + }); + + let error = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap_err(); + assert!(error.to_string().contains("corrupt freshness evidence")); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_function_column_status_decodes_agent_up_to_date() { + let table = Table::new_with_handler("my_table", |_request| { + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":4, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"up_to_date", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::UpToDate + ); + } + + #[tokio::test] + async fn test_function_column_status_decodes_blocked_scheduler_fields() { + let table = Table::new_with_handler("my_table", |_request| { + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":4, + "fresh":2, + "stale":2, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":3, + "effective_cooldown_millis":8000, + "blocked_reason":"preparation_backoff", + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!( + status.auto_refresh.state, + crate::table::FunctionColumnAutoRefreshState::Blocked + ); + assert_eq!(status.auto_refresh.failure_streak, 3); + assert_eq!(status.auto_refresh.effective_cooldown_millis, Some(8000)); + assert_eq!( + status.auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::PreparationBackoff) + ); + } + + #[tokio::test] + async fn test_function_column_status_passes_a_pinned_version() { + let calls = Arc::new(AtomicUsize::new(0)); + let status_calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + let status_calls = status_calls.clone(); + move |request| { + calls.fetch_add(1, Ordering::SeqCst); + match request.url().path() { + "/v1/table/my_table/describe/" => { + assert_eq!(request_body_json(&request)["version"], 42); + http::Response::builder() + .status(200) + .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + assert_eq!(request.method(), "GET"); + let query: std::collections::BTreeMap<_, _> = + request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert_eq!(query.get("version").map(|value| value.as_ref()), Some("42")); + let returned_version = if status_calls.fetch_add(1, Ordering::SeqCst) == 0 { + 42 + } else { + 43 + }; + http::Response::builder() + .status(200) + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":{returned_version}, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + } + }); + table.checkout(42).await.unwrap(); + + let status = table.function_column_status("embedding").await.unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(calls.load(Ordering::SeqCst), 2); + + let error = table.function_column_status("embedding").await.unwrap_err(); + assert!( + error.to_string().contains( + "returned table version 43, but the table handle is pinned to version 42" + ) + ); + assert_eq!(status_calls.load(Ordering::SeqCst), 2); + assert_eq!(calls.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn test_function_column_status_keeps_latest_freshness_headers() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().query_pairs().collect::>(), + vec![( + std::borrow::Cow::Borrowed("column"), + std::borrow::Cow::Borrowed("embedding") + )] + ); + assert_eq!( + request + .headers() + .get("x-lancedb-min-version") + .and_then(|value| value.to_str().ok()), + Some("7") + ); + http::Response::builder() + .status(200) + .body( + r#"[{ + "column":"embedding", + "binding_id":"fb_01", + "function":{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + } + }]"#, + ) + .unwrap() + }, + None, + ); + table.freshness.lock().unwrap().min_version = Some(7); + + let statuses = table + .function_column_statuses(Some("embedding")) + .await + .unwrap(); + assert_eq!(statuses.len(), 1); + } + /// The error listing is table-addressed with optional job and column /// filters, mirroring the server's SQL surface, and the two non-record /// signals come back as their own fields rather than as rows. diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index bd9220754..18a5b7ddf 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -83,6 +83,7 @@ pub mod datafusion; pub(crate) mod dataset; pub mod delete; pub mod freshness; +pub mod function_column_status; pub mod merge; pub mod optimize; pub(crate) mod primary_key; @@ -106,6 +107,11 @@ pub use computed_columns::{ ComputedColumn, ComputedColumnKind, computed_column_from_field, computed_columns, }; pub use delete::DeleteResult; +pub use function_column_status::{ + FunctionColumnAutoRefreshBlockedReason, FunctionColumnAutoRefreshState, + FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus, + FunctionColumnVersionStatus, +}; use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; pub use lance::dataset::scanner::DatasetRecordBatchStream; @@ -961,6 +967,19 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("per-row Function errors are recorded only in LanceDB Enterprise"), }) } + /// Exact four-way freshness status for Function-backed output columns. + /// + /// `column` filters to one user-visible output; `None` returns every + /// Function output. The default returns `NotSupported`. + async fn function_column_statuses( + &self, + _column: Option<&str>, + ) -> Result> { + Err(Error::NotSupported { + message: DocLink::Functions + .append_to("exact Function column status is supported only in LanceDB Enterprise"), + }) + } /// Alter columns in the table. async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result; /// Drop columns from the table. @@ -2246,6 +2265,72 @@ impl Table { .await } + /// Return exact freshness status for all Function-backed output columns. + /// + /// The server evaluates all counts at one table version. Clients never + /// derive counts by joining schema, Job, and error listings. A handle + /// pinned with `checkout` sends that exact version, while a latest handle + /// keeps the existing read-freshness headers. + pub async fn function_column_statuses( + &self, + column: Option<&str>, + ) -> Result> { + let statuses = self.inner.function_column_statuses(column).await?; + function_column_status::validate_statuses(&statuses)?; + Ok(statuses) + } + + /// Return exact freshness status for one Function-backed output column. + pub async fn function_column_status(&self, column: &str) -> Result { + let mut statuses = self.function_column_statuses(Some(column)).await?; + if statuses.len() != 1 || statuses[0].column != column { + return Err(Error::ColumnNotFound { + name: column.to_string(), + }); + } + Ok(statuses.remove(0)) + } + + /// Poll until a Function output has no stale or never-computed rows. + /// + /// Failed rows do not keep the call pending. A typed + /// `function_column_status_finalization_pending` response is retried with + /// bounded exponential backoff; every other error is returned immediately. + pub async fn wait_for_function_column( + &self, + column: &str, + timeout: Option, + ) -> Result { + let started = std::time::Instant::now(); + let mut delay = std::time::Duration::from_millis(250); + loop { + let result = self.function_column_status(column).await; + match result { + Ok(status) if status.stale == 0 && status.never_computed == 0 => return Ok(status), + Ok(_) => {} + Err(error) if function_column_status::is_finalization_pending(&error) => {} + Err(error) => return Err(error), + } + + let sleep_for = match timeout { + Some(timeout) => { + let remaining = timeout.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return Err(Error::Timeout { + message: format!( + "Function column '{column}' did not become fresh before timeout" + ), + }); + } + delay.min(remaining) + } + None => delay, + }; + tokio::time::sleep(sleep_for).await; + delay = std::cmp::min(delay * 2, std::time::Duration::from_secs(1)); + } + } + /// The per-row errors Function refreshes recorded on this table: the /// rows a refresh skipped under its skip policy, with the failing input /// and the error, plus a summary for any fragment whose detail was diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 50434143e..477020fc3 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -21,6 +21,7 @@ //! removed by [`prune_sidecars`]. use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt; use std::io::{Cursor, Read}; use std::ops::Range; @@ -98,6 +99,56 @@ impl DirtyRows { /// `{fragment id -> row-level dirty state}`. A missing fragment is clean. pub type RowStateMap = BTreeMap; +/// Physical rows whose latest Function outcome is an unresolved failure. +pub type FailureRows = BTreeMap; + +/// Evidence for rows whose latest Function outcome is known. +/// +/// `known_rows` includes both successful and failed observations. +/// `failed_rows` is the failure subset. A missing row is unknown, not clean. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FailureEvidence { + pub known_rows: FailureRows, + pub failed_rows: FailureRows, +} + +impl FailureEvidence { + fn is_empty(&self) -> bool { + self.known_rows.is_empty() && self.failed_rows.is_empty() + } + + fn validate(&self) -> Result<()> { + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .known_rows + .get(fragment_id) + .is_some_and(|known| failed.is_subset(known)) + }) { + return Err(invalid( + "failed rows are not covered by the failure evidence update".to_string(), + )); + } + Ok(()) + } + + fn for_fragments(&self, fragments: &HashSet) -> Self { + Self { + known_rows: self + .known_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + failed_rows: self + .failed_rows + .iter() + .filter(|(fragment_id, _)| fragments.contains(fragment_id)) + .map(|(fragment_id, rows)| (*fragment_id, rows.clone())) + .collect(), + } + } +} + /// The single owning value of the freshness sidecar. /// /// `SignatureMap` remains the public facade for callers that only need input @@ -107,6 +158,13 @@ pub type RowStateMap = BTreeMap; struct FreshnessState { signatures: SignatureMap, row_state: RowStateMap, + /// Physical offsets with an exact current-generation outcome. + failure_coverage: FailureRows, + /// The failed subset of `failure_coverage`. + failed_rows: FailureRows, + /// Whether the decoded source used the v3 sidecar format that carries + /// failure evidence. Older formats leave failure rows unclassified. + failure_evidence_recorded: bool, basis: String, // A fresh identity for each begin, even when the basis and dirty rows repeat. intent_id: Uuid, @@ -115,6 +173,8 @@ struct FreshnessState { impl FreshnessState { fn normalize(mut self) -> Result { self.row_state.retain(|_, rows| !rows.is_explicitly_empty()); + self.failure_coverage.retain(|_, rows| !rows.is_empty()); + self.failed_rows.retain(|_, rows| !rows.is_empty()); if self .row_state .keys() @@ -124,6 +184,26 @@ impl FreshnessState { "row state names a fragment without a signature".to_string(), )); } + if self + .failure_coverage + .keys() + .chain(self.failed_rows.keys()) + .any(|fragment_id| !self.signatures.contains_key(fragment_id)) + { + return Err(invalid( + "failure evidence names a fragment without a signature".to_string(), + )); + } + if self.failed_rows.iter().any(|(fragment_id, failed)| { + !self + .failure_coverage + .get(fragment_id) + .is_some_and(|covered| failed.is_subset(covered)) + }) { + return Err(invalid( + "failed rows are not covered by failure evidence".to_string(), + )); + } if self .signatures .values() @@ -138,6 +218,38 @@ impl FreshnessState { } Ok(self) } + + fn invalidate_failure_evidence(&mut self, fragments: impl IntoIterator) { + for fragment_id in fragments { + self.failure_coverage.remove(&fragment_id); + self.failed_rows.remove(&fragment_id); + } + } + + fn invalidate_failure_rows(&mut self, rows: &BTreeMap) { + for (fragment_id, rows) in rows { + if let Some(covered) = self.failure_coverage.get_mut(fragment_id) { + *covered -= rows; + } + if self + .failure_coverage + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failure_coverage.remove(fragment_id); + } + if let Some(failed) = self.failed_rows.get_mut(fragment_id) { + *failed -= rows; + } + if self + .failed_rows + .get(fragment_id) + .is_some_and(RoaringBitmap::is_empty) + { + self.failed_rows.remove(fragment_id); + } + } + } } /// Opaque accepted-basis evidence returned by [`begin_row_repair`] and required by @@ -398,7 +510,8 @@ const SIDECAR_DIR: &str = "_computed"; const SIDECAR_REF: &str = "sidecar:"; const SIDECAR_MAGIC: &[u8; 4] = b"CSIG"; const SIDECAR_FORMAT_V1: u8 = 1; -const SIDECAR_FORMAT: u8 = 2; +const SIDECAR_FORMAT_V2: u8 = 2; +const SIDECAR_FORMAT: u8 = 3; /// How long an unreferenced sidecar is presumed to be a stamp in flight: /// lance's own threshold for unverified files, independent of how much /// version history a cleanup keeps. @@ -446,9 +559,85 @@ fn encode_legacy_sidecar(map: &SignatureMap) -> Result> { Ok(bytes) } +#[cfg(test)] +fn encode_v2_sidecar(state: &FreshnessState) -> Result> { + let state = state.clone().normalize()?; + let basis_len = u16::try_from(state.basis.len()) + .map_err(|_| invalid("freshness basis exceeds u16 bytes".to_string()))?; + let fragment_count = u32::try_from(state.signatures.len()) + .map_err(|_| invalid("too many fragments for a freshness sidecar".to_string()))?; + let mut bytes = Vec::new(); + bytes.extend_from_slice(SIDECAR_MAGIC); + bytes.push(SIDECAR_FORMAT_V2); + bytes.extend_from_slice(state.intent_id.as_bytes()); + bytes.extend_from_slice(&basis_len.to_le_bytes()); + bytes.extend_from_slice(state.basis.as_bytes()); + bytes.extend_from_slice(&fragment_count.to_le_bytes()); + for (fragment_id, signature) in &state.signatures { + let hash = u64::from_str_radix(signature, 16).map_err(|_| { + invalid(format!( + "signature '{signature}' is not a 64-bit hex digest" + )) + })?; + let rows = state + .row_state + .get(fragment_id) + .cloned() + .unwrap_or_else(|| DirtyRows::Rows(RoaringBitmap::new())); + let (kind, bitmap) = match rows { + DirtyRows::Rows(bitmap) => (0u8, bitmap), + DirtyRows::AllExcept(clean) => (1u8, clean), + }; + bytes.extend_from_slice(&fragment_id.to_le_bytes()); + bytes.extend_from_slice(&hash.to_le_bytes()); + bytes.push(kind); + encode_bitmap(&mut bytes, Some(&bitmap))?; + } + Ok(bytes) +} + +fn encode_bitmap(bytes: &mut Vec, bitmap: Option<&RoaringBitmap>) -> Result<()> { + let Some(bitmap) = bitmap.filter(|bitmap| !bitmap.is_empty()) else { + bytes.extend_from_slice(&0u32.to_le_bytes()); + return Ok(()); + }; + let mut encoded = Vec::with_capacity(bitmap.serialized_size()); + bitmap + .serialize_into(&mut encoded) + .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; + let bitmap_len = u32::try_from(encoded.len()) + .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; + bytes.extend_from_slice(&bitmap_len.to_le_bytes()); + bytes.extend_from_slice(&encoded); + Ok(()) +} + +fn decode_bitmap( + cursor: &mut Cursor<&[u8]>, + malformed: &impl Fn() -> Error, +) -> Result> { + let mut bitmap_len = [0u8; 4]; + cursor + .read_exact(&mut bitmap_len) + .map_err(|_| malformed())?; + let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; + if bitmap_len == 0 { + return Ok(None); + } + let mut encoded = vec![0u8; bitmap_len]; + cursor.read_exact(&mut encoded).map_err(|_| malformed())?; + let mut bitmap_reader = Cursor::new(encoded.as_slice()); + let bitmap = RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; + if bitmap_reader.position() != bitmap_len as u64 { + return Err(malformed()); + } + Ok(Some(bitmap)) +} + /// `CSIG`, format byte, 16-byte intent UUID, basis, entry count, then for each fragment its id, -/// 8-byte signature, dirty-row mode and serialized bitmap. All integers are -/// little-endian. Format 1 remains readable as clean row state. +/// 8-byte signature, dirty-row mode and serialized bitmap. Format 3 appends +/// failure-coverage and failed-row bitmaps. All integers are little-endian. +/// Format 1 remains readable as clean row state. fn encode_sidecar(state: &FreshnessState) -> Result> { let state = state.clone().normalize()?; let basis_len = u16::try_from(state.basis.len()) @@ -477,17 +666,12 @@ fn encode_sidecar(state: &FreshnessState) -> Result> { DirtyRows::Rows(bitmap) => (0u8, bitmap), DirtyRows::AllExcept(clean) => (1u8, clean), }; - let mut encoded = Vec::with_capacity(bitmap.serialized_size()); - bitmap - .serialize_into(&mut encoded) - .map_err(|error| invalid(format!("encoding freshness bitmap: {error}")))?; - let bitmap_len = u32::try_from(encoded.len()) - .map_err(|_| invalid("freshness bitmap exceeds u32 bytes".to_string()))?; bytes.extend_from_slice(&fragment_id.to_le_bytes()); bytes.extend_from_slice(&hash.to_le_bytes()); bytes.push(kind); - bytes.extend_from_slice(&bitmap_len.to_le_bytes()); - bytes.extend_from_slice(&encoded); + encode_bitmap(&mut bytes, Some(&bitmap))?; + encode_bitmap(&mut bytes, state.failure_coverage.get(fragment_id))?; + encode_bitmap(&mut bytes, state.failed_rows.get(fragment_id))?; } Ok(bytes) } @@ -526,7 +710,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut magic).map_err(|_| malformed())?; let mut format = [0u8; 1]; cursor.read_exact(&mut format).map_err(|_| malformed())?; - if &magic != SIDECAR_MAGIC || format[0] != SIDECAR_FORMAT { + if &magic != SIDECAR_MAGIC || !matches!(format[0], SIDECAR_FORMAT_V2 | SIDECAR_FORMAT) { return Err(malformed()); } let mut intent_id = [0u8; 16]; @@ -542,6 +726,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { let mut state = FreshnessState { basis, intent_id: Uuid::from_bytes(intent_id), + failure_evidence_recorded: format[0] == SIDECAR_FORMAT, ..Default::default() }; for _ in 0..count { @@ -554,19 +739,7 @@ fn decode_sidecar(bytes: &[u8]) -> Result { cursor.read_exact(&mut signature).map_err(|_| malformed())?; let mut kind = [0u8; 1]; cursor.read_exact(&mut kind).map_err(|_| malformed())?; - let mut bitmap_len = [0u8; 4]; - cursor - .read_exact(&mut bitmap_len) - .map_err(|_| malformed())?; - let bitmap_len = u32::from_le_bytes(bitmap_len) as usize; - let mut encoded = vec![0u8; bitmap_len]; - cursor.read_exact(&mut encoded).map_err(|_| malformed())?; - let mut bitmap_reader = Cursor::new(encoded.as_slice()); - let bitmap = - RoaringBitmap::deserialize_from(&mut bitmap_reader).map_err(|_| malformed())?; - if bitmap_reader.position() != bitmap_len as u64 { - return Err(malformed()); - } + let bitmap = decode_bitmap(&mut cursor, &malformed)?.unwrap_or_default(); let dirty = match kind[0] { 0 => DirtyRows::Rows(bitmap), 1 => DirtyRows::AllExcept(bitmap), @@ -582,6 +755,14 @@ fn decode_sidecar(bytes: &[u8]) -> Result { if !dirty.is_explicitly_empty() { state.row_state.insert(fragment_id, dirty); } + if format[0] == SIDECAR_FORMAT { + if let Some(covered) = decode_bitmap(&mut cursor, &malformed)? { + state.failure_coverage.insert(fragment_id, covered); + } + if let Some(failed) = decode_bitmap(&mut cursor, &malformed)? { + state.failed_rows.insert(fragment_id, failed); + } + } } if cursor.position() != bytes.len() as u64 { return Err(malformed()); @@ -763,12 +944,15 @@ enum StoredFreshnessState { Unreadable, } -async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { +async fn load_freshness_state( + dataset: &Dataset, + column: &str, +) -> Result)>> { let Some(encoded) = field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY) else { - return StoredFreshnessState::Absent; + return Ok(None); }; // Inline JSON is the declaration's empty seed and the pre-sidecar form. - let (read, digest) = match encoded.strip_prefix(SIDECAR_REF) { + let read = match encoded.strip_prefix(SIDECAR_REF) { Some(digest) => ( read_sidecar(dataset, digest).await, Some(digest.to_string()), @@ -783,8 +967,14 @@ async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshn None, ), }; - match read { - Ok(state) => StoredFreshnessState::Present { state, digest }, + let (state, digest) = read; + Ok(Some((state?, digest))) +} + +async fn stored_freshness_state(dataset: &Dataset, column: &str) -> StoredFreshnessState { + match load_freshness_state(dataset, column).await { + Ok(Some((state, digest))) => StoredFreshnessState::Present { state, digest }, + Ok(None) => StoredFreshnessState::Absent, Err(error) => { log::warn!( "computed column '{column}' freshness state is unreadable ({error}); every fragment will be recomputed" @@ -853,6 +1043,38 @@ impl StalenessPlan { } } +/// Strict, internally consistent evidence for a Function-column status read. +/// +/// Unlike [`staleness_against`], this value never converts an unreadable +/// sidecar into a conservative recompute plan. Failure coverage may be +/// partial: the caller combines it with live-row freshness and value evidence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StrictFreshness { + /// No freshness certificate is recorded on this dataset version. + /// + /// This does not prove that no refresh was ever attempted; older failed + /// attempts may be untracked. Assignment and value evidence still decide + /// stale versus never computed. + Absent, + /// The sidecar predates failure evidence. Its staleness plan is still + /// usable; row classification may use freshness, values, and assignment + /// evidence outside this sidecar. + Uncertified { staleness: StalenessPlan }, + /// Exact staleness and current-generation failed rows. + Certified { + staleness: StalenessPlan, + failures: FailureEvidence, + }, +} + +fn incomplete_certificate(column: &str, reason: impl fmt::Display) -> Error { + Error::Runtime { + message: format!( + "computed column '{column}' has no complete freshness certificate: {reason}" + ), + } +} + /// A version of the log since the stamp that bears on carrying freshness /// forward: an append, whose fragments hold no computed value yet, or a /// compaction's rewrite groups, consumed and produced fragment ids. @@ -1158,6 +1380,16 @@ pub async fn staleness_against( } StoredFreshnessState::Present { state: stored, .. } => stored, }; + staleness_from_state(dataset, column, definition_version, inputs, stored).await +} + +async fn staleness_from_state( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + stored: FreshnessState, +) -> Result { let stored_version = field_meta(dataset, column, DEFINITION_VERSION_META_KEY); if stored_version.is_some_and(|version| version != definition_version) { return Ok(StalenessPlan { @@ -1221,6 +1453,71 @@ pub async fn staleness_against( }) } +/// Read exact status evidence without the planner's conservative fallback. +/// +/// A missing metadata key returns [`StrictFreshness::Absent`]. A referenced +/// sidecar that cannot be read or decoded propagates the existing error. The +/// returned plan is certified when the sidecar records a definition and can be +/// decoded. Failure coverage is returned only for live fragments whose stored +/// input signature still matches; stale evidence is omitted. The status +/// provider remains responsible for classifying uncovered live rows as fresh, +/// stale, or never computed, and for reporting an error only when a row is +/// genuinely ambiguous. +pub async fn strict_freshness_against( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, +) -> Result { + let Some((stored, _)) = load_freshness_state(dataset, column).await? else { + return Ok(StrictFreshness::Absent); + }; + let Some(stored_definition) = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) else { + return Err(incomplete_certificate( + column, + "the recorded definition is missing", + )); + }; + let staleness = + staleness_from_state(dataset, column, definition_version, inputs, stored.clone()).await?; + if !stored.failure_evidence_recorded { + return Ok(StrictFreshness::Uncertified { staleness }); + } + if stored_definition != definition_version { + return Ok(StrictFreshness::Certified { + staleness, + failures: FailureEvidence::default(), + }); + } + let mut failures = FailureEvidence::default(); + for fragment in dataset.get_fragments() { + let fragment_id = fragment.id() as u32; + let current = signature_of(dataset, fragment_id, inputs)?.ok_or_else(|| { + incomplete_certificate(column, format!("fragment {fragment_id} is not live")) + })?; + if stored.signatures.get(&fragment_id) != Some(¤t) { + // The old generation's failure evidence no longer describes this + // fragment. Its live rows are stale or never computed, not + // ambiguously failed. + continue; + } + if let Some(covered) = stored.failure_coverage.get(&fragment_id) + && !covered.is_empty() + { + failures.known_rows.insert(fragment_id, covered.clone()); + } + if let Some(failed) = stored.failed_rows.get(&fragment_id) + && !failed.is_empty() + { + failures.failed_rows.insert(fragment_id, failed.clone()); + } + } + Ok(StrictFreshness::Certified { + staleness, + failures, + }) +} + /// What [`record_freshness`] wrote: the table version the stamp landed at, /// if it wrote one, and the entries recorded and dropped for having moved. #[derive(Debug, Default, PartialEq, Eq)] @@ -1251,6 +1548,55 @@ pub async fn record_freshness( definition_version: &str, inputs: &InputFields, computed: SignatureMap, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + None, + ) + .await +} + +/// Record signatures and an explicit current-generation failure outcome in one +/// immutable sidecar transition. +/// +/// `failures.known_rows` must include only physical offsets whose final +/// outcome is known. `failures.failed_rows` is the failed subset. Rows omitted +/// from coverage remain unknown to failure classification; freshness, values, +/// and assignment evidence may still classify them. +pub async fn record_freshness_with_failures( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: &FailureEvidence, +) -> Result { + record_freshness_impl( + latest, + pinned, + column, + definition_version, + inputs, + computed, + Some(failures), + ) + .await +} + +async fn record_freshness_impl( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, + failures: Option<&FailureEvidence>, ) -> Result { let absent = matches!( stored_signatures(latest, column).await, @@ -1270,7 +1616,7 @@ pub async fn record_freshness( } } entries.extend(computed); - if entries.is_empty() && !absent { + if entries.is_empty() && !absent && failures.is_none_or(FailureEvidence::is_empty) { return Ok(FreshnessRecord::default()); } let fragments: Vec = entries.keys().copied().collect(); @@ -1280,7 +1626,19 @@ pub async fn record_freshness( .filter(|(fragment_id, signature)| current.get(fragment_id) == Some(signature)) .collect(); let recorded = verified.len(); - let version = write_signatures(latest, column, definition_version, verified).await?; + let verified_fragments: HashSet = verified.keys().copied().collect(); + let scoped_failures = failures + .map(|failures| failures.for_fragments(&verified_fragments)) + .filter(|failures| !failures.is_empty()); + let version = write_signatures_impl( + latest, + column, + definition_version, + Some(inputs), + verified, + scoped_failures.as_ref(), + ) + .await?; Ok(FreshnessRecord { version: Some(version), recorded, @@ -1582,6 +1940,25 @@ pub async fn write_signatures( definition_version: &str, entries: SignatureMap, ) -> Result { + write_signatures_impl(dataset, column, definition_version, None, entries, None).await +} + +async fn write_signatures_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: Option<&InputFields>, + entries: SignatureMap, + failures: Option<&FailureEvidence>, +) -> Result { + if let Some(failures) = failures { + failures.validate()?; + if inputs.is_none() { + return Err(invalid( + "failure evidence requires input fields for signature validation".to_string(), + )); + } + } let definition_changed = field_meta(dataset, column, DEFINITION_VERSION_META_KEY) .is_some_and(|version| version != definition_version); let live: HashSet = dataset @@ -1619,17 +1996,40 @@ pub async fn write_signatures( } // A signature entry written through this API means the fragment was // recomputed in full. Whole callers keep their old semantics while - // clearing any partial retry state left by a previous publication. + // clearing any partial retry state left by a previous publication. The + // old failure outcome is also unknown unless the failure-aware wrapper + // supplies it below. for fragment_id in &recomputed { state.row_state.remove(fragment_id); } - state.signatures.extend(entries); + state.invalidate_failure_evidence(recomputed.iter().copied()); + state.signatures.extend( + entries + .iter() + .map(|(fragment_id, signature)| (*fragment_id, signature.clone())), + ); state .signatures .retain(|fragment_id, _| live.contains(fragment_id)); state .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + state + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); + if let Some(failures) = failures { + apply_failure_evidence( + dataset, + inputs.expect("failure evidence requires input fields"), + &entries, + &mut state, + failures, + ) + .await?; + } if state.row_state.is_empty() || state_unreadable || signatures_changed { state.basis.clear(); } @@ -1645,6 +2045,70 @@ struct FreshnessWrite { intent_digest: Option, } +async fn apply_failure_evidence( + dataset: &Dataset, + inputs: &InputFields, + accepted: &SignatureMap, + state: &mut FreshnessState, + update: &FailureEvidence, +) -> Result<()> { + update.validate()?; + let physical_rows: BTreeMap = { + let mut rows = BTreeMap::new(); + for fragment in dataset.get_fragments() { + rows.insert(fragment.id() as u32, fragment.physical_rows().await? as u64); + } + rows + }; + let mut applied = HashSet::new(); + for (fragment_id, covered) in &update.known_rows { + let Some(rows) = physical_rows.get(fragment_id) else { + continue; + }; + let Some(current) = signature_of(dataset, *fragment_id, inputs)? else { + continue; + }; + // Evidence belongs to the attempt that produced this accepted + // signature. A concurrent attempt may have stamped a newer signature + // into `state`; that does not make this attempt's rows valid for it. + if accepted.get(fragment_id) != Some(¤t) { + continue; + } + if state.signatures.get(fragment_id) != Some(¤t) { + continue; + } + if covered + .max() + .is_some_and(|offset| u64::from(offset) >= *rows) + { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} exceeds its {rows} physical rows" + ))); + } + if let Some(failed) = state.failed_rows.get_mut(fragment_id) { + *failed -= covered; + } + let coverage = state.failure_coverage.entry(*fragment_id).or_default(); + *coverage |= covered; + applied.insert(*fragment_id); + } + for (fragment_id, failed) in &update.failed_rows { + if !applied.contains(fragment_id) { + continue; + } + if !update.known_rows.contains_key(fragment_id) { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} have no coverage update" + ))); + } + let current = state.failed_rows.entry(*fragment_id).or_default(); + *current |= failed; + } + state.failed_rows.retain(|_, rows| !rows.is_empty()); + state.failure_coverage.retain(|_, rows| !rows.is_empty()); + Ok(()) +} + async fn write_freshness_state( dataset: &mut Dataset, column: &str, @@ -1656,6 +2120,8 @@ async fn write_freshness_state( let state = state.normalize()?; let inline_empty = state.signatures.is_empty() && state.row_state.is_empty() + && state.failure_coverage.is_empty() + && state.failed_rows.is_empty() && state.basis.is_empty() && !retain_empty_sidecar; // The sidecar is durable before the metadata commit references it. @@ -1817,6 +2283,8 @@ pub async fn begin_row_repair( freshness.signatures = signatures_for(dataset, &live.iter().copied().collect::>(), inputs)?; freshness.row_state.clear(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); freshness.basis.clear(); } if state_unreadable || definition_changed { @@ -1826,6 +2294,8 @@ pub async fn begin_row_repair( .iter() .map(|id| (*id, DirtyRows::AllExcept(RoaringBitmap::new()))) .collect(); + freshness.failure_coverage.clear(); + freshness.failed_rows.clear(); } for (fragment_id, repair) in repairs { @@ -1842,6 +2312,9 @@ pub async fn begin_row_repair( let preserve = !state_unreadable && !definition_changed && freshness.signatures.get(fragment_id) == Some(¤t); + if !preserve { + freshness.invalidate_failure_evidence([*fragment_id]); + } let dirty = if preserve { freshness .row_state @@ -1865,6 +2338,12 @@ pub async fn begin_row_repair( freshness .row_state .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failure_coverage + .retain(|fragment_id, _| live.contains(fragment_id)); + freshness + .failed_rows + .retain(|fragment_id, _| live.contains(fragment_id)); freshness.basis = basis.clone(); freshness.intent_id = Uuid::new_v4(); @@ -1958,6 +2437,66 @@ pub async fn finish_row_repair( filled_rows: &BTreeMap, skipped_rows: &BTreeMap, verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + None, + verified_version, + ) + .await +} + +/// Finalize a row repair together with the exact failure evidence observed for +/// those rows. +/// +/// `failures.known_rows` must be a subset of the rows assigned either a +/// value or an explicit skipped outcome. This permits a deferral to become +/// known non-failed without turning it into a failure. `failed_rows` must be a +/// subset of `known_rows`. The same token, input-signature and version +/// fences as [`finish_row_repair`] apply. +#[allow(clippy::too_many_arguments)] +pub async fn finish_row_repair_with_failures( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: &FailureEvidence, + verified_version: Option, +) -> Result { + finish_row_repair_impl( + dataset, + column, + definition_version, + inputs, + token, + filled_rows, + skipped_rows, + Some(failures), + verified_version, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn finish_row_repair_impl( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, + token: &RowStateToken, + filled_rows: &BTreeMap, + skipped_rows: &BTreeMap, + failures: Option<&FailureEvidence>, + verified_version: Option, ) -> Result { if !is_sha256_hex(&token.intent_digest) { return Err(invalid("row repair token is malformed".to_string())); @@ -1971,6 +2510,36 @@ pub async fn finish_row_repair( "row repair result names a fragment outside its token".to_string(), )); } + if let Some(failures) = failures { + failures.validate()?; + for (fragment_id, covered) in &failures.known_rows { + let selected = token.selected_rows.get(fragment_id).ok_or_else(|| { + invalid(format!( + "failure evidence names fragment {fragment_id} outside its token" + )) + })?; + let mut known = filled_rows.get(fragment_id).cloned().unwrap_or_default(); + if let Some(skipped) = skipped_rows.get(fragment_id) { + known |= skipped; + } + if !covered.is_subset(selected) || !covered.is_subset(&known) { + return Err(invalid(format!( + "failure evidence for fragment {fragment_id} covers rows without a final outcome" + ))); + } + } + for (fragment_id, failed) in &failures.failed_rows { + if !failures.known_rows.contains_key(fragment_id) + || skipped_rows + .get(fragment_id) + .is_none_or(|skipped| !failed.is_subset(skipped)) + { + return Err(invalid(format!( + "failed rows for fragment {fragment_id} must be an explicit skipped subset" + ))); + } + } + } dataset.checkout_latest().await?; if verified_version.is_some_and(|version| dataset.version().version != version) { return Err(invalid( @@ -2015,14 +2584,32 @@ pub async fn finish_row_repair( ))); } } - let before = state.row_state.clone(); + let before = state.clone(); + state.invalidate_failure_rows(&token.selected_rows); apply_row_repair( &mut state.row_state, &token.selected_rows, filled_rows, skipped_rows, )?; - if state.row_state == before { + if let Some(failures) = failures { + let accepted = token + .selected_rows + .keys() + .map(|fragment_id| { + state + .signatures + .get(fragment_id) + .cloned() + .map(|signature| (*fragment_id, signature)) + }) + .collect::>() + .ok_or_else(|| { + invalid("row repair failure evidence lost an accepted signature".to_string()) + })?; + apply_failure_evidence(dataset, inputs, &accepted, &mut state, failures).await?; + } + if state == before { return Ok(dataset.version().version); } if current_digest != token.intent_digest.as_str() { @@ -2868,6 +3455,41 @@ mod tests { .unwrap(); } + async fn stamp_v2( + dataset: &mut Dataset, + column: &str, + definition: &str, + entries: SignatureMap, + ) { + let reference = write_sidecar_bytes( + dataset, + encode_v2_sidecar(&FreshnessState { + signatures: entries, + ..Default::default() + }) + .unwrap(), + ) + .await + .unwrap(); + let describes = dataset.version().version.to_string(); + dataset + .update_field_metadata() + .update( + column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), reference), + ( + DEFINITION_VERSION_META_KEY.to_string(), + definition.to_string(), + ), + (RECORDED_AT_VERSION_META_KEY.to_string(), describes), + ], + ) + .unwrap() + .await + .unwrap(); + } + fn fragment_signature(dataset: &Dataset, fragment_id: u32) -> String { signature_of(dataset, fragment_id, &inputs(dataset)) .unwrap() @@ -2894,6 +3516,15 @@ mod tests { (3, DirtyRows::Rows(RoaringBitmap::from_iter([1, 4, 9]))), (7, DirtyRows::AllExcept(RoaringBitmap::from_iter([0, 2]))), ]), + failure_coverage: FailureRows::from([ + (3, RoaringBitmap::from_iter([1, 2, 4, 9])), + (7, RoaringBitmap::from_iter([0, 1, 2, 3])), + ]), + failed_rows: FailureRows::from([ + (3, RoaringBitmap::from_iter([1])), + (7, RoaringBitmap::from_iter([1, 3])), + ]), + failure_evidence_recorded: true, }; let encoded = encode_sidecar(&state).unwrap(); assert_eq!(encoded[4], SIDECAR_FORMAT); @@ -2913,9 +3544,283 @@ mod tests { let state = decode_sidecar(&encode_legacy_sidecar(&signatures).unwrap()).unwrap(); assert_eq!(state.signatures, signatures); assert!(state.row_state.is_empty()); + assert!(state.failure_coverage.is_empty()); + assert!(state.failed_rows.is_empty()); + assert!(!state.failure_evidence_recorded); assert!(state.basis.is_empty()); } + #[test] + fn v2_sidecar_decodes_with_unknown_failure_evidence() { + let state = FreshnessState { + signatures: SignatureMap::from([(1, "0000000000000001".to_string())]), + row_state: RowStateMap::from([(1, DirtyRows::Rows(RoaringBitmap::from_iter([2, 3])))]), + basis: "legacy-intent".to_string(), + intent_id: Uuid::from_u128(1), + ..Default::default() + }; + let decoded = decode_sidecar(&encode_v2_sidecar(&state).unwrap()).unwrap(); + assert_eq!(decoded, state); + assert!(decoded.failure_coverage.is_empty()); + assert!(decoded.failed_rows.is_empty()); + assert!(!decoded.failure_evidence_recorded); + } + + #[tokio::test] + async fn a_first_partial_write_keeps_untouched_legacy_rows_unknown() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, entries).await; + + let StrictFreshness::Uncertified { staleness } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("the v2 sidecar should yield a readable uncertified plan"); + }; + assert_eq!(staleness, StalenessPlan::default()); + + let selected = RoaringBitmap::from_iter([1, 2]); + let repairs = BTreeMap::from([(0, repair(&dataset, 0, selected.clone()))]); + let token = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "legacy-partial", + &repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &token, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("partial v3 evidence is still readable"); + }; + assert_eq!( + staleness.row_dirty.get(&0), + Some(&DirtyRows::Rows(RoaringBitmap::from_iter([1]))) + ); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])), + "only the rows this partial publication observed are covered" + ); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([1])) + ); + assert!( + !failures.known_rows.contains_key(&1), + "the untouched legacy fragment remains unknown" + ); + } + + #[tokio::test] + async fn a_successful_retry_clears_only_its_failed_rows() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let signatures = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + stamp_v2(&mut dataset, COLUMN, &definition, signatures).await; + + let first_selected = RoaringBitmap::from_iter([1, 2]); + let first_repairs = BTreeMap::from([(0, repair(&dataset, 0, first_selected.clone()))]); + let first = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "failed-wave", + &first_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &first, + &BTreeMap::from([(0, RoaringBitmap::from_iter([2]))]), + &BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, first_selected)]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + None, + ) + .await + .unwrap(); + + let retry_selected = RoaringBitmap::from_iter([1]); + let retry_repairs = BTreeMap::from([(0, repair(&dataset, 0, retry_selected.clone()))]); + let retry = begin_row_repair( + &mut dataset, + COLUMN, + &definition, + &ids, + "successful-retry", + &retry_repairs, + ) + .await + .unwrap(); + finish_row_repair_with_failures( + &mut dataset, + COLUMN, + &definition, + &ids, + &retry, + &BTreeMap::from([(0, retry_selected.clone())]), + &BTreeMap::new(), + &FailureEvidence { + known_rows: BTreeMap::from([(0, retry_selected)]), + failed_rows: BTreeMap::new(), + }, + None, + ) + .await + .unwrap(); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &ids) + .await + .unwrap() + else { + panic!("status should remain readable"); + }; + assert!(!failures.failed_rows.contains_key(&0)); + assert_eq!( + failures.known_rows.get(&0), + Some(&RoaringBitmap::from_iter([1, 2])) + ); + } + + #[tokio::test] + async fn an_old_attempt_cannot_rewrite_a_newer_signature_evidence() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let definition = definition_version(EXPRESSION); + let ids = inputs(&dataset); + let old = dataset.clone(); + let old_inputs = ids.clone(); + let old_signature = signature_of(&old, 0, &old_inputs).unwrap().unwrap(); + + rewrite_value(&mut dataset, 0).await; + let new_signature = signature_of(&dataset, 0, &inputs(&dataset)) + .unwrap() + .unwrap(); + assert_ne!(old_signature, new_signature); + + let current_entries = signatures_for(&dataset, &[0, 1], &inputs(&dataset)).unwrap(); + write_signatures(&mut dataset, COLUMN, &definition, current_entries.clone()) + .await + .unwrap(); + let StoredFreshnessState::Present { + state: mut current_state, + .. + } = stored_freshness_state(&dataset, COLUMN).await + else { + panic!("new attempt state"); + }; + current_state + .failure_coverage + .insert(0, RoaringBitmap::from_iter([3, 4])); + current_state + .failed_rows + .insert(0, RoaringBitmap::from_iter([4])); + let write = write_freshness_state( + &mut dataset, + COLUMN, + &definition, + current_state.clone(), + false, + None, + ) + .await + .unwrap(); + assert!(write.version > 0); + let new_evidence = FailureEvidence { + known_rows: current_state.failure_coverage.clone(), + failed_rows: current_state.failed_rows.clone(), + }; + + let record = record_freshness_with_failures( + &mut dataset, + None, + COLUMN, + &definition, + &old_inputs, + SignatureMap::from([(0, old_signature)]), + &FailureEvidence { + known_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1, 2]))]), + failed_rows: BTreeMap::from([(0, RoaringBitmap::from_iter([1]))]), + }, + ) + .await + .unwrap(); + assert_eq!((record.recorded, record.moved), (0, 1)); + + let StrictFreshness::Certified { failures, .. } = + strict_freshness_against(&dataset, COLUMN, &definition, &inputs(&dataset)) + .await + .unwrap() + else { + panic!("current signature evidence should remain readable"); + }; + assert_eq!(failures.known_rows, new_evidence.known_rows); + assert_eq!(failures.failed_rows, new_evidence.failed_rows); + assert_eq!( + failures.failed_rows.get(&0), + Some(&RoaringBitmap::from_iter([4])), + "old S1 failure must not replace the S2 failure" + ); + assert!(!failures.known_rows.contains_key(&1)); + } + + #[test] + fn failure_evidence_must_be_a_subset_of_coverage() { + let state = FreshnessState { + signatures: SignatureMap::from([(3, "0000000000000003".to_string())]), + failure_coverage: FailureRows::from([(3, RoaringBitmap::from_iter([1]))]), + failed_rows: FailureRows::from([(3, RoaringBitmap::from_iter([2]))]), + ..Default::default() + }; + let error = encode_sidecar(&state).unwrap_err(); + assert!( + error + .to_string() + .contains("failed rows are not covered by failure evidence"), + "{error}" + ); + } + #[tokio::test] async fn a_row_repair_clears_filled_rows_and_retains_skipped_rows() { let dir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/src/table/function_column_status.rs b/rust/lancedb/src/table/function_column_status.rs new file mode 100644 index 000000000..729ea33ba --- /dev/null +++ b/rust/lancedb/src/table/function_column_status.rs @@ -0,0 +1,303 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Read-only status for Function-backed table columns. + +use serde::{Deserialize, Serialize}; + +use crate::function::FunctionVersionRef; +use crate::{Error, Result}; + +/// Stable HTTP error code for a status read waiting on its matching finalize. +pub const FINALIZATION_PENDING_ERROR_CODE: &str = "function_column_status_finalization_pending"; + +/// One exact immutable Function revision attached to a table output. +pub type FunctionColumnVersionStatus = FunctionVersionRef; + +/// Latest matching refresh Job projected for a Function output. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnLastRefreshJob { + pub job_id: String, + pub state: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub automatic: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed_at_millis: Option, +} + +/// Automatic-refresh scheduling state that the server can prove. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionColumnAutoRefreshState { + Disabled, + Running, + UpToDate, + Ready, + WaitingInterval, + WaitingBackoff, + Blocked, + Unobservable, +} + +impl FunctionColumnAutoRefreshState { + pub const fn as_str(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Running => "running", + Self::UpToDate => "up_to_date", + Self::Ready => "ready", + Self::WaitingInterval => "waiting_interval", + Self::WaitingBackoff => "waiting_backoff", + Self::Blocked => "blocked", + Self::Unobservable => "unobservable", + } + } +} + +/// Why an enabled automatic refresh is not currently schedulable. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionColumnAutoRefreshBlockedReason { + TableHasMemWal, + InputsNotSettled, + DependencyInFlight, + TableCapacity, + Cancelled, + PreparationBackoff, +} + +impl FunctionColumnAutoRefreshBlockedReason { + pub const fn as_str(self) -> &'static str { + match self { + Self::TableHasMemWal => "table_has_mem_wal", + Self::InputsNotSettled => "inputs_not_settled", + Self::DependencyInFlight => "dependency_in_flight", + Self::TableCapacity => "table_capacity", + Self::Cancelled => "cancelled", + Self::PreparationBackoff => "preparation_backoff", + } + } +} + +/// Automatic-refresh projection for a Function output. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnAutoRefreshStatus { + pub enabled: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub interval_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub active_job_id: Option, + pub state: FunctionColumnAutoRefreshState, + pub failure_streak: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effective_cooldown_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blocked_reason: Option, + /// Null is intentional until the Lance Agent exposes its scheduler decision. + pub next_run_at_millis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_run_at_reason: Option, +} + +/// Exact status of one Function output at one table version. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionColumnStatus { + pub column: String, + pub binding_id: String, + pub function: FunctionColumnVersionStatus, + pub table_version: u64, + pub rows: u64, + pub fresh: u64, + pub stale: u64, + pub never_computed: u64, + pub failed: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_refresh_job: Option, + pub auto_refresh: FunctionColumnAutoRefreshStatus, +} + +impl FunctionColumnStatus { + /// Whether this status is safe to expose as an exact four-way count. + pub fn validate(&self) -> Result<()> { + let classified = self + .fresh + .checked_add(self.stale) + .and_then(|count| count.checked_add(self.never_computed)) + .and_then(|count| count.checked_add(self.failed)); + if classified != Some(self.rows) { + return Err(Error::Runtime { + message: format!( + "Function column '{}' status counts do not partition {} rows", + self.column, self.rows + ), + }); + } + if self.auto_refresh.state == FunctionColumnAutoRefreshState::Blocked + && self.auto_refresh.blocked_reason.is_none() + { + return Err(Error::Runtime { + message: format!( + "Function column '{}' reported a blocked scheduler state without a reason", + self.column + ), + }); + } + if self.auto_refresh.state == FunctionColumnAutoRefreshState::Unobservable + && self.auto_refresh.next_run_at_millis.is_none() + && self + .auto_refresh + .next_run_at_reason + .as_deref() + .is_none_or(str::is_empty) + { + return Err(Error::Runtime { + message: format!( + "Function column '{}' omitted a reason for an unavailable next run", + self.column + ), + }); + } + Ok(()) + } +} + +/// Validate one GET response, whose objects must all describe one snapshot. +pub fn validate_statuses(statuses: &[FunctionColumnStatus]) -> Result<()> { + let mut table_versions = statuses.iter().map(|status| status.table_version); + let Some(first) = table_versions.next() else { + return Ok(()); + }; + if table_versions.any(|version| version != first) { + return Err(Error::Runtime { + message: "Function column statuses came from different table versions".to_string(), + }); + } + statuses.iter().try_for_each(FunctionColumnStatus::validate) +} + +/// Whether an error is the typed transient response used while the data +/// version's matching freshness finalization is still in progress. +pub fn is_finalization_pending(error: &Error) -> bool { + #[cfg(feature = "remote")] + { + error.status_code() == Some(reqwest::StatusCode::SERVICE_UNAVAILABLE) + && error + .remote_error_metadata() + .and_then(|metadata| metadata.error_code.as_deref()) + == Some(FINALIZATION_PENDING_ERROR_CODE) + } + #[cfg(not(feature = "remote"))] + { + let _ = error; + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn status(column: &str, table_version: u64) -> FunctionColumnStatus { + FunctionColumnStatus { + column: column.to_string(), + binding_id: "fb_01".to_string(), + function: FunctionVersionRef { + name: "embed".to_string(), + namespace_path: Vec::new(), + object_id: "embed".to_string(), + location: "objects/embed".to_string(), + version: "7".to_string(), + manifest_digest: "sha256:abc".to_string(), + }, + table_version, + rows: 10, + fresh: 6, + stale: 2, + never_computed: 1, + failed: 1, + last_refresh_job: None, + auto_refresh: FunctionColumnAutoRefreshStatus { + enabled: true, + interval_seconds: Some(60), + active_job_id: None, + state: FunctionColumnAutoRefreshState::Unobservable, + failure_streak: 0, + effective_cooldown_millis: None, + blocked_reason: None, + next_run_at_millis: None, + next_run_at_reason: Some( + "authoritative_scheduler_projection_unavailable".to_string(), + ), + }, + } + } + + #[test] + fn validates_a_single_version_and_four_way_partition() { + validate_statuses(&[status("a", 42), status("b", 42)]).unwrap(); + + let error = validate_statuses(&[status("a", 42), status("b", 43)]).unwrap_err(); + assert!(error.to_string().contains("different table versions")); + + let mut invalid = status("a", 42); + invalid.fresh += 1; + let error = validate_statuses(&[invalid]).unwrap_err(); + assert!(error.to_string().contains("do not partition 10 rows")); + } + + #[test] + fn wire_keeps_job_and_auto_refresh_metadata() { + let mut value = status("a", 42); + value.last_refresh_job = Some(FunctionColumnLastRefreshJob { + job_id: "job-7".to_string(), + state: "finished".to_string(), + automatic: Some(true), + completed_at_millis: Some(1_790_000_000_000), + }); + let encoded = serde_json::to_value(value).unwrap(); + assert_eq!(encoded["last_refresh_job"]["job_id"], "job-7"); + assert_eq!(encoded["auto_refresh"]["enabled"], true); + assert_eq!( + encoded["auto_refresh"]["next_run_at_reason"], + "authoritative_scheduler_projection_unavailable" + ); + } + + #[test] + fn up_to_date_wire_is_stable() { + assert_eq!( + serde_json::to_string(&FunctionColumnAutoRefreshState::UpToDate).unwrap(), + "\"up_to_date\"" + ); + } + + #[test] + fn blocked_auto_refresh_wire_keeps_its_reason() { + let mut value = status("a", 42); + value.auto_refresh.state = FunctionColumnAutoRefreshState::Blocked; + value.auto_refresh.failure_streak = 3; + value.auto_refresh.effective_cooldown_millis = Some(8000); + value.auto_refresh.blocked_reason = + Some(FunctionColumnAutoRefreshBlockedReason::PreparationBackoff); + value.auto_refresh.next_run_at_reason = None; + + let encoded = serde_json::to_value(&value).unwrap(); + assert_eq!(encoded["auto_refresh"]["state"], "blocked"); + assert_eq!( + encoded["auto_refresh"]["blocked_reason"], + "preparation_backoff" + ); + assert_eq!(encoded["auto_refresh"]["failure_streak"], 3); + assert_eq!(encoded["auto_refresh"]["effective_cooldown_millis"], 8000); + value.validate().unwrap(); + + value.auto_refresh.blocked_reason = None; + assert!( + value + .validate() + .unwrap_err() + .to_string() + .contains("blocked scheduler state without a reason") + ); + } +} From a356950bced171427b8eacbe5f30bcfd886be76e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 11 Nov 2026 21:14:30 +0800 Subject: [PATCH 067/203] feat: expose queued Function refresh status (#4959) ## Problem The existing Function `column_status` surface cannot decode the Agent scheduler's `queued` state or the `failure_threshold_reached` and `binding_revision_missing` blocked reasons. It also preserves only the latest refresh job, so a later cancellation can hide an earlier actual failure. ## Change - Adds the `queued`, `failure_threshold_reached`, and `binding_revision_missing` wire states in Rust, Python, and Node. The wire change is additive, while Rust callers must update exhaustive enum matches and public struct literals. - Adds optional `last_failure_job` alongside `last_refresh_job`. The latest cancellation and the most recent actual failure retain separate meanings. - Reuses the canonical Rust `JobFailure` and existing Python/Node `JobFailureInfo` models for nested job failure details instead of introducing a parallel status error model. - Maps the existing public `sql_job_id` field through Node's `JobFailureInfo`. - Keeps `column_status`, `column_statuses`, and `wait_fresh` as the existing API surfaces. There is no new endpoint, row-error list, durable ledger, or unknown-enum fallback. - Documents `queued` versus `running` and the separate latest-attempt and latest-failure jobs in the existing hidden freshness release draft. The new status values are additive but cross-service: `queued`, the two new blocked reasons, and `last_failure_job` require matching Agent/QN and SDK deployments before clients can rely on them. This SDK follow-up does not change the normal `7cc3904a` dependency pin or claim whole ENT-3487 completion. ## Validation The tested private source is `b19c8adbdc936c5976def6c17be47f6d5e3faf3e`, based on product commit `c9bac25ecb8b73b1bd0256bbea65c2621bcf6a94`. The final product docs commit changes generated TypeDoc only. - Rust: 2 selected tests passed, 0 failed, exit 0. The same two Rust blobs are unchanged from their tested `788ef85b` source through `c9bac25e`. - Python: the PyO3 extension built successfully, and the selected native PyO3 SDK test against a mock HTTP REST transport passed 1/0, exit 0. The test requests pinned version 42. - Node: the addon and TypeScript builds passed, Biome passed, and the selected Jest transport test passed 1/0 with 57 filtered tests. Addon SHA-256: `c888e260b61d41e79689ed2f20dd0dc98586a2377ce34f21610b06111734d426`. - Python extension SHA-256: `36c961d8a0cbd2e102a7765f2e47efb4c5af6310baa6262c8e3120407463da2b`. - TypeDoc was generated from the native `native.d.ts` produced by that Node build. A second generation produced no remaining diff. The public diff contains only product, test, and generated API documentation changes. Native runner scripts and preserved compile-failure logs remain private validation evidence. Agent/QN production mapping, mixed-version rollout, and the remaining ENT-3487 server-side work are tracked separately. --- .../FunctionColumnAutoRefreshStatus.md | 5 +- .../FunctionColumnLastRefreshJob.md | 10 ++ .../src/js/interfaces/FunctionColumnStatus.md | 11 ++ docs/src/js/interfaces/JobFailureInfo.md | 10 ++ .../feature-engineering/refresh-column.mdx | 11 ++ nodejs/__test__/remote.test.ts | 49 ++++-- nodejs/lancedb/table.ts | 13 +- nodejs/src/job.rs | 22 ++- nodejs/src/table.rs | 25 ++- python/python/lancedb/_lancedb.pyi | 2 + python/python/tests/test_remote_db.py | 45 ++++-- python/src/job.rs | 22 ++- python/src/table.rs | 5 + rust/lancedb/src/error.rs | 26 +++- rust/lancedb/src/remote/table.rs | 147 +++++++++++++++++- .../src/table/function_column_status.rs | 46 +++++- 16 files changed, 394 insertions(+), 55 deletions(-) diff --git a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md index bc8f7daab..3a203026c 100644 --- a/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md +++ b/docs/src/js/interfaces/FunctionColumnAutoRefreshStatus.md @@ -27,7 +27,9 @@ optional blockedReason: | "dependency_in_flight" | "table_capacity" | "cancelled" - | "preparation_backoff"; + | "preparation_backoff" + | "failure_threshold_reached" + | "binding_revision_missing"; ``` *** @@ -85,6 +87,7 @@ optional nextRunAtReason: string; ```ts state: | "running" + | "queued" | "disabled" | "ready" | "up_to_date" diff --git a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md index 1d7d3b300..a7c1df2aa 100644 --- a/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md +++ b/docs/src/js/interfaces/FunctionColumnLastRefreshJob.md @@ -26,6 +26,16 @@ optional completedAtMillis: bigint; *** +### failure? + +```ts +optional failure: JobFailureInfo; +``` + +Structured failure details for a failed Job. + +*** + ### jobId ```ts diff --git a/docs/src/js/interfaces/FunctionColumnStatus.md b/docs/src/js/interfaces/FunctionColumnStatus.md index 755a8af81..0c299ee2b 100644 --- a/docs/src/js/interfaces/FunctionColumnStatus.md +++ b/docs/src/js/interfaces/FunctionColumnStatus.md @@ -58,6 +58,17 @@ function: FunctionColumnVersionStatus; *** +### lastFailureJob? + +```ts +optional lastFailureJob: FunctionColumnLastRefreshJob; +``` + +Newest failed refresh Job. This remains present when `lastRefreshJob` +is a later cancellation. + +*** + ### lastRefreshJob? ```ts diff --git a/docs/src/js/interfaces/JobFailureInfo.md b/docs/src/js/interfaces/JobFailureInfo.md index fe9ce04e3..cdea222c5 100644 --- a/docs/src/js/interfaces/JobFailureInfo.md +++ b/docs/src/js/interfaces/JobFailureInfo.md @@ -34,6 +34,16 @@ optional retryable: boolean; *** +### sqlJobId? + +```ts +optional sqlJobId: string; +``` + +Isolated SQL job that raised this failure, when supplied by the server. + +*** + ### traceback? ```ts diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index e1a9c43f3..ed4838497 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -197,6 +197,17 @@ println!("{}", final_status.failed); ``` +`auto_refresh.state` reports `queued` while the scheduler has accepted the +refresh but a worker has not started it; `running` means execution has started. +`last_refresh_job` describes the most recent attempt, including a cancellation +or a failure. If a later attempt was cancelled, `last_failure_job` retains the +most recent job that actually failed, so its nested `failure` continues to +explain the failed rows. + +These fields require a matching Agent, Query Node, and SDK deployment. An older +client cannot decode the `queued` state, and an older server can omit the new +optional failure fields. + The wait helpers do not submit or cancel a refresh. They retry only the typed finalization-pending response and propagate other errors. */} diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 6c160ed03..f87c70091 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -681,14 +681,33 @@ describe("remote connection", () => { "stale":2, "never_computed":0, "failed":0, + "last_refresh_job":{ + "job_id":"job-cancelled", + "state":"cancelled", + "automatic":true, + "completed_at_millis":1790000002000 + }, + "last_failure_job":{ + "job_id":"job-failed", + "state":"failed", + "automatic":true, + "completed_at_millis":1790000001000, + "failure":{ + "phase":"finalize", + "message":"worker timed out", + "traceback":"Traceback: timeout", + "retryable":true, + "sql_job_id":"sql-job-7" + } + }, "auto_refresh":{ "enabled":true, "interval_seconds":60, - "state":"blocked", - "failure_streak":3, - "effective_cooldown_millis":8000, - "blocked_reason":"preparation_backoff", - "next_run_at_millis":null + "active_job_id":"job-queued", + "state":"queued", + "failure_streak":1, + "next_run_at_millis":null, + "next_run_at_reason":"job_queued_not_started" } }]`, ); @@ -701,10 +720,22 @@ describe("remote connection", () => { await table.checkout(42); const status = await table.functionColumnStatus("embedding"); expect(status.tableVersion).toBe(42n); - expect(status.autoRefresh.state).toBe("blocked"); - expect(status.autoRefresh.failureStreak).toBe(3); - expect(status.autoRefresh.effectiveCooldownMillis).toBe(8000n); - expect(status.autoRefresh.blockedReason).toBe("preparation_backoff"); + expect(status.autoRefresh.state).toBe("queued"); + expect(status.autoRefresh.activeJobId).toBe("job-queued"); + expect(status.autoRefresh.failureStreak).toBe(1); + expect(status.autoRefresh.nextRunAtReason).toBe( + "job_queued_not_started", + ); + expect(status.lastRefreshJob?.state).toBe("cancelled"); + expect(status.lastRefreshJob?.failure).toBeUndefined(); + expect(status.lastFailureJob?.jobId).toBe("job-failed"); + expect(status.lastFailureJob?.failure).toEqual({ + phase: "finalize", + message: "worker timed out", + traceback: "Traceback: timeout", + retryable: true, + sqlJobId: "sql-job-7", + }); }, ); expect(queries).toEqual([{ column: "embedding", version: "42" }]); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 99eb0d1f9..703fc7926 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -35,6 +35,7 @@ import { FunctionErrorsOptions, IndexConfig, IndexStatistics, + JobFailureInfo, Branches as NativeBranches, OptimizeStats, RTEStats, @@ -274,6 +275,8 @@ export interface FunctionColumnLastRefreshJob { state: string; automatic?: boolean; completedAtMillis?: bigint; + /** Structured failure details for a failed Job. */ + failure?: JobFailureInfo; } /** Automatic-refresh projection for a Function output. */ @@ -284,6 +287,7 @@ export interface FunctionColumnAutoRefreshStatus { state: | "disabled" | "running" + | "queued" | "ready" | "up_to_date" | "waiting_interval" @@ -298,7 +302,9 @@ export interface FunctionColumnAutoRefreshStatus { | "dependency_in_flight" | "table_capacity" | "cancelled" - | "preparation_backoff"; + | "preparation_backoff" + | "failure_threshold_reached" + | "binding_revision_missing"; nextRunAtMillis: bigint | null; nextRunAtReason?: string; } @@ -315,6 +321,11 @@ export interface FunctionColumnStatus { neverComputed: bigint; failed: bigint; lastRefreshJob?: FunctionColumnLastRefreshJob; + /** + * Newest failed refresh Job. This remains present when `lastRefreshJob` + * is a later cancellation. + */ + lastFailureJob?: FunctionColumnLastRefreshJob; autoRefresh: FunctionColumnAutoRefreshStatus; } diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 485035d33..09b245f97 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -138,12 +138,7 @@ impl Job { /// Why the job failed, when it failed and the server reports a reason. #[napi(getter)] pub fn failure(&self) -> Option { - self.inner.failure().map(|failure| JobFailureInfo { - phase: failure.phase, - message: failure.message, - traceback: failure.traceback, - retryable: failure.retryable, - }) + self.inner.failure().map(Into::into) } /// This job's recorded lifecycle events, as an Arrow IPC stream buffer. @@ -216,10 +211,25 @@ impl From for JobInfo { /// The server's account of why a job failed. #[napi(object)] +#[derive(Clone, Debug)] pub struct JobFailureInfo { pub phase: Option, pub message: Option, /// User-code traceback, possibly truncated by the server. pub traceback: Option, pub retryable: Option, + /// Isolated SQL job that raised this failure, when supplied by the server. + pub sql_job_id: Option, +} + +impl From for JobFailureInfo { + fn from(failure: lancedb::error::JobFailure) -> Self { + Self { + phase: failure.phase, + message: failure.message, + traceback: failure.traceback, + retryable: failure.retryable, + sql_job_id: failure.sql_job_id, + } + } } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index f6d3e538e..62fe811ad 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -20,6 +20,7 @@ use napi_derive::napi; use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::NapiErrorExt; use crate::index::Index; +use crate::job::JobFailureInfo; use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; @@ -1868,6 +1869,19 @@ pub struct FunctionColumnLastRefreshJob { pub state: String, pub automatic: Option, pub completed_at_millis: Option, + pub failure: Option, +} + +impl From for FunctionColumnLastRefreshJob { + fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self { + Self { + job_id: job.job_id, + state: job.state, + automatic: job.automatic, + completed_at_millis: job.completed_at_millis.map(BigInt::from), + failure: job.failure.map(Into::into), + } + } } /// Automatic-refresh projection for a Function output. @@ -1899,6 +1913,7 @@ pub struct FunctionColumnStatus { pub never_computed: BigInt, pub failed: BigInt, pub last_refresh_job: Option, + pub last_failure_job: Option, pub auto_refresh: FunctionColumnAutoRefreshStatus, } @@ -1921,14 +1936,8 @@ impl From for FunctionColumnStatus { stale: BigInt::from(status.stale), never_computed: BigInt::from(status.never_computed), failed: BigInt::from(status.failed), - last_refresh_job: status - .last_refresh_job - .map(|job| FunctionColumnLastRefreshJob { - job_id: job.job_id, - state: job.state, - automatic: job.automatic, - completed_at_millis: job.completed_at_millis.map(BigInt::from), - }), + last_refresh_job: status.last_refresh_job.map(Into::into), + last_failure_job: status.last_failure_job.map(Into::into), auto_refresh: FunctionColumnAutoRefreshStatus { enabled: status.auto_refresh.enabled, interval_seconds: status.auto_refresh.interval_seconds.map(BigInt::from), diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 07306c1d9..4c5f5758a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1108,6 +1108,7 @@ class FunctionColumnLastRefreshJob: state: str automatic: Optional[bool] completed_at_millis: Optional[int] + failure: Optional[JobFailureInfo] class FunctionColumnAutoRefreshStatus: enabled: bool @@ -1131,6 +1132,7 @@ class FunctionColumnStatus: never_computed: int failed: int last_refresh_job: Optional[FunctionColumnLastRefreshJob] + last_failure_job: Optional[FunctionColumnLastRefreshJob] auto_refresh: FunctionColumnAutoRefreshStatus class RefreshMaterializedViewResult: diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index fd933b43c..407596d26 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2306,15 +2306,33 @@ def test_remote_function_column_status_passes_pinned_version(): "stale": 2, "never_computed": 0, "failed": 0, + "last_refresh_job": { + "job_id": "job-cancelled", + "state": "cancelled", + "automatic": True, + "completed_at_millis": 1790000002000, + }, + "last_failure_job": { + "job_id": "job-failed", + "state": "failed", + "automatic": True, + "completed_at_millis": 1790000001000, + "failure": { + "phase": "finalize", + "message": "worker timed out", + "traceback": "Traceback: timeout", + "retryable": True, + "sql_job_id": "sql-job-7", + }, + }, "auto_refresh": { "enabled": True, "interval_seconds": 60, - "active_job_id": None, - "state": "blocked", - "failure_streak": 3, - "effective_cooldown_millis": 8000, - "blocked_reason": "preparation_backoff", + "active_job_id": "job-queued", + "state": "queued", + "failure_streak": 1, "next_run_at_millis": None, + "next_run_at_reason": "job_queued_not_started", }, } @@ -2350,10 +2368,19 @@ def test_remote_function_column_status_passes_pinned_version(): 0, 0, ) - assert result.auto_refresh.state == "blocked" - assert result.auto_refresh.failure_streak == 3 - assert result.auto_refresh.effective_cooldown_millis == 8000 - assert result.auto_refresh.blocked_reason == "preparation_backoff" + assert result.auto_refresh.state == "queued" + assert result.auto_refresh.active_job_id == "job-queued" + assert result.auto_refresh.failure_streak == 1 + assert result.auto_refresh.next_run_at_reason == "job_queued_not_started" + assert result.last_refresh_job.state == "cancelled" + assert result.last_refresh_job.failure is None + assert result.last_failure_job.job_id == "job-failed" + failure = result.last_failure_job.failure + assert failure.phase == "finalize" + assert failure.message == "worker timed out" + assert failure.traceback == "Traceback: timeout" + assert failure.retryable is True + assert failure.sql_job_id == "sql-job-7" def test_remote_wait_fresh_retries_only_typed_finalization_pending(): diff --git a/python/src/job.rs b/python/src/job.rs index 79a9cd524..f1fd85844 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -228,7 +228,7 @@ impl From for JobInfo { /// The server's account of why a job failed. #[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)] -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct JobFailureInfo { phase: Option, message: Option, @@ -238,6 +238,18 @@ pub struct JobFailureInfo { sql_job_id: Option, } +impl From for JobFailureInfo { + fn from(failure: lancedb::error::JobFailure) -> Self { + Self { + phase: failure.phase, + message: failure.message, + traceback: failure.traceback, + retryable: failure.retryable, + sql_job_id: failure.sql_job_id, + } + } +} + #[pymethods] impl JobFailureInfo { fn __repr__(&self) -> String { @@ -341,13 +353,7 @@ impl From for JobDescription { .filter(|result| !result.is_null()) .map(|result| result.to_string()), _progress_json: Some(progress_json), - failure: description.failure.map(|failure| JobFailureInfo { - phase: failure.phase, - message: failure.message, - traceback: failure.traceback, - retryable: failure.retryable, - sql_job_id: failure.sql_job_id, - }), + failure: description.failure.map(Into::into), } } } diff --git a/python/src/table.rs b/python/src/table.rs index cf627961c..c4211e44d 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -15,6 +15,7 @@ use crate::{ error::PythonErrorExt, expr::PyExpr, index::{CodeAnalyzerOptions, IndexConfig, extract_index_params}, + job::JobFailureInfo, query::{Query, TakeQuery}, table::scannable::PyScannable, }; @@ -925,6 +926,7 @@ pub struct FunctionColumnLastRefreshJob { pub state: String, pub automatic: Option, pub completed_at_millis: Option, + pub failure: Option, } impl From for FunctionColumnLastRefreshJob { @@ -934,6 +936,7 @@ impl From for FunctionColumnLastRe state: job.state, automatic: job.automatic, completed_at_millis: job.completed_at_millis, + failure: job.failure.map(Into::into), } } } @@ -985,6 +988,7 @@ pub struct FunctionColumnStatus { pub never_computed: u64, pub failed: u64, pub last_refresh_job: Option, + pub last_failure_job: Option, pub auto_refresh: FunctionColumnAutoRefreshStatus, } @@ -1017,6 +1021,7 @@ impl From for FunctionColumnStatus { never_computed: status.never_computed, failed: status.failed, last_refresh_job: status.last_refresh_job.map(Into::into), + last_failure_job: status.last_failure_job.map(Into::into), auto_refresh: status.auto_refresh.into(), } } diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 853ca831f..89ad7a229 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -253,24 +253,48 @@ impl snafu::AsErrorSource for InterruptionSource { /// A job run remotely carries whatever the server reported, which older servers /// do not report at all. Every field is absent rather than invented when the /// backend does not supply it. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub struct JobFailure { /// The stage the job was in, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub phase: Option, /// A human-readable reason, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, /// User-code traceback, possibly truncated by the server. + #[serde(default, skip_serializing_if = "Option::is_none")] pub traceback: Option, /// Whether a retry could clear the failure, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] pub retryable: Option, /// Isolated SQL job that raised this failure, when the server supplies /// one across the Flight SQL boundary. + #[serde(default, skip_serializing_if = "Option::is_none")] pub sql_job_id: Option, /// The underlying error from a job run in this process or a structured /// remote Flight SQL failure. + #[serde(skip)] pub source: Option>, } +impl PartialEq for JobFailure { + fn eq(&self, other: &Self) -> bool { + let source_matches = match (&self.source, &other.source) { + (None, None) => true, + (Some(left), Some(right)) => Arc::ptr_eq(left, right), + _ => false, + }; + self.phase == other.phase + && self.message == other.message + && self.traceback == other.traceback + && self.retryable == other.retryable + && self.sql_job_id == other.sql_job_id + && source_matches + } +} + +impl Eq for JobFailure {} + impl JobFailure { /// A failure whose only known detail is the error that caused it. pub(crate) fn from_source(source: Arc) -> Self { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 222ff527b..37890fd17 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11655,12 +11655,13 @@ mod tests { } #[tokio::test] - async fn test_function_column_status_decodes_blocked_scheduler_fields() { + async fn test_function_column_status_decodes_scheduler_lifecycle_and_failures() { let table = Table::new_with_handler("my_table", |_request| { http::Response::builder() .status(200) .body( - r#"[{ + r#"[ + { "column":"embedding", "binding_id":"fb_01", "function":{ @@ -11676,6 +11677,101 @@ mod tests { "stale":2, "never_computed":0, "failed":0, + "last_refresh_job":{ + "job_id":"job-cancelled", + "state":"cancelled", + "automatic":true, + "completed_at_millis":1790000002000 + }, + "last_failure_job":{ + "job_id":"job-failed", + "state":"failed", + "automatic":true, + "completed_at_millis":1790000001000, + "failure":{ + "phase":"finalize", + "message":"worker timed out", + "traceback":"Traceback: timeout", + "retryable":true, + "sql_job_id":"sql-job-7" + } + }, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "active_job_id":"job-queued", + "state":"queued", + "failure_streak":1, + "next_run_at_millis":null, + "next_run_at_reason":"job_queued_not_started" + } + }, + { + "column":"rerank", + "binding_id":"fb_02", + "function":{ + "name":"rerank", + "object_id":"rerank", + "location":"objects/rerank", + "version":"3", + "manifest_digest":"sha256:def" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":5, + "blocked_reason":"failure_threshold_reached", + "next_run_at_millis":null + } + }, + { + "column":"classify", + "binding_id":"fb_03", + "function":{ + "name":"classify", + "object_id":"classify", + "location":"objects/classify", + "version":"2", + "manifest_digest":"sha256:ghi" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, + "auto_refresh":{ + "enabled":true, + "interval_seconds":60, + "state":"blocked", + "failure_streak":0, + "blocked_reason":"binding_revision_missing", + "next_run_at_millis":null + } + }, + { + "column":"summarize", + "binding_id":"fb_04", + "function":{ + "name":"summarize", + "object_id":"summarize", + "location":"objects/summarize", + "version":"4", + "manifest_digest":"sha256:jkl" + }, + "table_version":42, + "rows":0, + "fresh":0, + "stale":0, + "never_computed":0, + "failed":0, "auto_refresh":{ "enabled":true, "interval_seconds":60, @@ -11690,15 +11786,52 @@ mod tests { .unwrap() }); - let status = table.function_column_status("embedding").await.unwrap(); + let statuses = table.function_column_statuses(None).await.unwrap(); + assert_eq!(statuses.len(), 4); + let status = &statuses[0]; assert_eq!( status.auto_refresh.state, - crate::table::FunctionColumnAutoRefreshState::Blocked + crate::table::FunctionColumnAutoRefreshState::Queued ); - assert_eq!(status.auto_refresh.failure_streak, 3); - assert_eq!(status.auto_refresh.effective_cooldown_millis, Some(8000)); assert_eq!( - status.auto_refresh.blocked_reason, + status.auto_refresh.active_job_id.as_deref(), + Some("job-queued") + ); + assert_eq!( + status.auto_refresh.next_run_at_reason.as_deref(), + Some("job_queued_not_started") + ); + assert_eq!( + status + .last_refresh_job + .as_ref() + .map(|job| job.state.as_str()), + Some("cancelled") + ); + let failure_job = status.last_failure_job.as_ref().unwrap(); + assert_eq!(failure_job.job_id, "job-failed"); + let failure = failure_job.failure.as_ref().unwrap(); + assert_eq!(failure.phase.as_deref(), Some("finalize")); + assert_eq!(failure.message.as_deref(), Some("worker timed out")); + assert_eq!(failure.retryable, Some(true)); + assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job-7")); + + assert_eq!(statuses[1].auto_refresh.failure_streak, 5); + assert_eq!( + statuses[1].auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached) + ); + assert_eq!( + statuses[2].auto_refresh.blocked_reason, + Some(crate::table::FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing) + ); + assert_eq!(statuses[3].auto_refresh.failure_streak, 3); + assert_eq!( + statuses[3].auto_refresh.effective_cooldown_millis, + Some(8000) + ); + assert_eq!( + statuses[3].auto_refresh.blocked_reason, Some(crate::table::FunctionColumnAutoRefreshBlockedReason::PreparationBackoff) ); } diff --git a/rust/lancedb/src/table/function_column_status.rs b/rust/lancedb/src/table/function_column_status.rs index 729ea33ba..15703f4e9 100644 --- a/rust/lancedb/src/table/function_column_status.rs +++ b/rust/lancedb/src/table/function_column_status.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; +use crate::error::JobFailure; use crate::function::FunctionVersionRef; use crate::{Error, Result}; @@ -23,6 +24,9 @@ pub struct FunctionColumnLastRefreshJob { pub automatic: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub completed_at_millis: Option, + /// Why this Job failed, when the server retained a structured failure. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure: Option, } /// Automatic-refresh scheduling state that the server can prove. @@ -31,6 +35,7 @@ pub struct FunctionColumnLastRefreshJob { pub enum FunctionColumnAutoRefreshState { Disabled, Running, + Queued, UpToDate, Ready, WaitingInterval, @@ -44,6 +49,7 @@ impl FunctionColumnAutoRefreshState { match self { Self::Disabled => "disabled", Self::Running => "running", + Self::Queued => "queued", Self::UpToDate => "up_to_date", Self::Ready => "ready", Self::WaitingInterval => "waiting_interval", @@ -64,6 +70,8 @@ pub enum FunctionColumnAutoRefreshBlockedReason { TableCapacity, Cancelled, PreparationBackoff, + FailureThresholdReached, + BindingRevisionMissing, } impl FunctionColumnAutoRefreshBlockedReason { @@ -75,6 +83,8 @@ impl FunctionColumnAutoRefreshBlockedReason { Self::TableCapacity => "table_capacity", Self::Cancelled => "cancelled", Self::PreparationBackoff => "preparation_backoff", + Self::FailureThresholdReached => "failure_threshold_reached", + Self::BindingRevisionMissing => "binding_revision_missing", } } } @@ -113,6 +123,10 @@ pub struct FunctionColumnStatus { pub failed: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub last_refresh_job: Option, + /// Newest failed refresh Job. Unlike `last_refresh_job`, this remains + /// visible when the latest attempt was cancelled. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_failure_job: Option, pub auto_refresh: FunctionColumnAutoRefreshStatus, } @@ -216,6 +230,7 @@ mod tests { never_computed: 1, failed: 1, last_refresh_job: None, + last_failure_job: None, auto_refresh: FunctionColumnAutoRefreshStatus { enabled: true, interval_seconds: Some(60), @@ -253,6 +268,7 @@ mod tests { state: "finished".to_string(), automatic: Some(true), completed_at_millis: Some(1_790_000_000_000), + failure: None, }); let encoded = serde_json::to_value(value).unwrap(); assert_eq!(encoded["last_refresh_job"]["job_id"], "job-7"); @@ -264,11 +280,31 @@ mod tests { } #[test] - fn up_to_date_wire_is_stable() { - assert_eq!( - serde_json::to_string(&FunctionColumnAutoRefreshState::UpToDate).unwrap(), - "\"up_to_date\"" - ); + fn scheduler_wire_names_are_stable() { + for (state, expected) in [ + (FunctionColumnAutoRefreshState::Queued, "queued"), + (FunctionColumnAutoRefreshState::UpToDate, "up_to_date"), + ] { + assert_eq!( + serde_json::to_string(&state).unwrap(), + format!("\"{expected}\"") + ); + } + for (reason, expected) in [ + ( + FunctionColumnAutoRefreshBlockedReason::FailureThresholdReached, + "failure_threshold_reached", + ), + ( + FunctionColumnAutoRefreshBlockedReason::BindingRevisionMissing, + "binding_revision_missing", + ), + ] { + assert_eq!( + serde_json::to_string(&reason).unwrap(), + format!("\"{expected}\"") + ); + } } #[test] From c1fee360457c65e784fe0c7055f91e171a7b7da5 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 11 Nov 2026 23:26:52 +0800 Subject: [PATCH 068/203] chore(deps): upgrade Lance to v15.0.0-beta.17 (#4943) Update the Rust workspace, Java dependency, and Python test dependency to [Lance v15.0.0-beta.17](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.17). This includes the FRI cache and vector-index changes required by current Sophon and retains the RaBitQ prewarm fixes. Lockfiles use the published source and test wheels without unrelated registry version bumps. The dependency dry run also exposed CI resource limits. Use the existing larger x64 runner for GNU Node and compatibility-wheel builds; allow 60 minutes for Mac Python tests, 120 minutes for the compatibility wheel, and 150 minutes for the Mac release wheel. Disable the CLI toolchain action's automatic target cache so only the subsequent downloads-only cache runs. Release optimization, the compatibility wheel's manylinux container and x86-64-v2 baseline, and test coverage stay unchanged. Validation: - Three native SDK regressions pass: refined RQ queries after deferred compaction, deferred index remapping, and ANN approximation planning. - Pinned Rust 1.97.0: `cargo clippy --quiet --locked --features remote --tests --examples -- -D warnings` passes. - Locked offline Rust metadata, Python lock validation, Ruff lint/format, and diff checks pass. The Python lock contains six published beta.17 wheels. - Repository YAML, whitespace and typo checks pass for the workflow changes. Product-source checks are reused for the subsequent CI-only commits. - At head `07033dc6`, all 65 applicable pre-review CI checks pass, including the compatibility wheel, Mac CLI, GNU Node, Mac Python tests, release wheels, and Java checks. Six checks are skipped by tag/main-only conditions or draft-only app behavior; the automated review and security checks run after the Ready transition. The upstream Java publisher succeeded and its beta.17 Maven artifact is available. Six upstream Python wheel builds/uploads succeeded; its Windows ARM job was cancelled. These checks do not establish Sophon performance or aggregate-memory acceptance. --- .github/workflows/cli.yml | 2 + .github/workflows/npm-publish.yml | 3 +- .github/workflows/pypi-publish.yml | 10 +-- .github/workflows/python.yml | 3 +- Cargo.lock | 97 +++++++++++++++--------------- Cargo.toml | 30 ++++----- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 15 ++--- 9 files changed, 86 insertions(+), 78 deletions(-) diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml index 8d8763e1d..e96d5b095 100644 --- a/.github/workflows/cli.yml +++ b/.github/workflows/cli.yml @@ -23,6 +23,8 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1 with: components: clippy + # Use only the downloads-only cache configured below. + cache: false - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: # Restoring compiled targets can exhaust the hosted runner disk. diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index a8dd3993e..1b7d3dcbc 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -66,7 +66,8 @@ jobs: choco install --no-progress protoc rustup target add aarch64-pc-windows-msvc - target: x86_64-unknown-linux-gnu - host: ubuntu-latest + # Fat LTO reached 15.1 GiB before rustc was killed on the 15 GiB runner. + host: ubuntu-2404-8x-x64 features: fp16kernels # https://github.com/napi-rs/napi-rs/blob/main/debian.Dockerfile docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 5aea2ca30..8730e220d 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -36,8 +36,8 @@ concurrency: jobs: linux: name: Python ${{ matrix.config.package_name }} ${{ matrix.config.platform }} manylinux${{ matrix.config.manylinux }} - # The ARM64 release build can exceed an hour with fat LTO on a cold runner. - timeout-minutes: ${{ matrix.config.platform == 'aarch64' && 120 || 60 }} + # ARM64 and compatibility release builds can exceed an hour with cold fat LTO. + timeout-minutes: ${{ (matrix.config.platform == 'aarch64' || matrix.config.package_name == 'lancedb-compat') && 120 || 60 }} strategy: matrix: config: @@ -64,7 +64,8 @@ jobs: - platform: x86_64 manylinux: "2_28" extra_args: "" - runner: ubuntu-22.04 + # Keep fat LTO on the same larger runner as the standard x64 wheel. + runner: ubuntu-2404-8x-x64 package_name: "lancedb-compat" rustflags: "-Ctarget-cpu=x86-64-v2" runs-on: ${{ matrix.config.runner }} @@ -102,7 +103,8 @@ jobs: path: target/wheels/*.whl if-no-files-found: error mac: - timeout-minutes: 90 + # Cold fat LTO was still compiling when the 90-minute limit was reached. + timeout-minutes: 150 runs-on: ${{ matrix.config.runner }} strategy: matrix: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2080789d4..2fabb4a6a 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -179,7 +179,8 @@ jobs: strategy: matrix: features: ["default", "experimental-functions"] - timeout-minutes: 30 + # A cold native build plus experimental-functions tests can exceed 30 minutes. + timeout-minutes: 60 runs-on: macos-15 defaults: run: diff --git a/Cargo.lock b/Cargo.lock index 56642301c..3518272e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3765,8 +3765,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5243,8 +5243,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arc-swap", "arrow", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,7 +5342,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5356,7 +5356,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5365,8 +5365,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrayref", "crunchy", @@ -5376,8 +5376,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5415,8 +5415,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5447,8 +5447,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5473,8 +5473,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5491,8 +5491,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "proc-macro2", "quote", @@ -5501,8 +5501,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-arith", "arrow-array", @@ -5535,8 +5535,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-arith", "arrow-array", @@ -5567,8 +5567,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5599,8 +5599,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arc-swap", "arrow", @@ -5667,12 +5667,13 @@ dependencies = [ "tokio", "tracing", "twox-hash", + "uuid", ] [[package]] name = "lance-index-core" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5695,8 +5696,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5741,8 +5742,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "byteorder", "ethnum", @@ -5759,8 +5760,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5775,8 +5776,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "async-trait", @@ -5790,8 +5791,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arc-swap", "arrow", @@ -5845,8 +5846,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-buffer", @@ -5860,8 +5861,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow", "arrow-array", @@ -5902,8 +5903,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "arrow-array", "arrow-schema", @@ -5916,8 +5917,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f" +version = "15.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index e77e0ffd6..9fc33e6ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 2f72f98a7..514be8540 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.16 + 15.0.0-beta.17 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 036acf075..5ba1d4bbf 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b16", + "pylance==15.0.0b17", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index a5ae1caf8..01693079f 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b16" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b17" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b16" +version = "15.0.0b17" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,11 +4312,12 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" }, - { url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" }, - { url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" }, + { url = "https://pypi.fury.io/lance-format/-/ver_il4JF/pylance-15.0.0b17-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:ee3c3d2baf1f0d788d706638873317740178a81988b71ffda47a2e71d1e15ff3" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2hFd0a/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a5b576e35054d4866d823ebadc9d3c531165628feb29ca1528db15b9082675a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_29zVw5/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47c534032d2f251f396657e47efbc224ee2d1964495d7982a449e5e1cdcf3169" }, + { url = "https://pypi.fury.io/lance-format/-/ver_548nr/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:509db7d8be3eebb111b7d28aa486437424cb3663cfb7f502b71532fa37ba7155" }, + { url = "https://pypi.fury.io/lance-format/-/ver_gmpNu/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd2cc05c2d553d44c54570612e793136e3433fcba28e4d51a503cca8f45435ea" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Otspk/pylance-15.0.0b17-cp310-abi3-win_amd64.whl", hash = "sha256:510c419e21a4daa4c18db4cc5048bd7dfc706924b23e13136306935f2e3e0c25" }, ] [[package]] From e9774ed168d3e82a50ba8cee19f602ca2ac41cfa Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 07:34:54 -0800 Subject: [PATCH 069/203] feat(nodejs): expose Function refresh publication intervals (#4957) Expose `publicationIntervalRows` on TypeScript refresh options and forward it as `publication_interval_rows`. Accept positive safe integers and preserve whole-fragment publication when omitted. ```typescript const job = await table.refreshColumnAsync("embedding", { publicationIntervalRows: 10000, }); await job.wait(); ``` Document the threshold semantics and add coverage for serialization, omission, invalid values, safe-integer boundaries, and Embedded rejection. Closes ENT-3755. --- docs/src/js/classes/Table.md | 6 +++ .../src/js/interfaces/RefreshColumnOptions.md | 13 ++++++ .../feature-engineering/refresh-column.mdx | 15 ++++-- nodejs/__test__/remote.test.ts | 46 +++++++++++++++++++ nodejs/__test__/table.test.ts | 8 ++++ nodejs/lancedb/table.ts | 6 +++ nodejs/src/table.rs | 15 ++++-- 7 files changed, 103 insertions(+), 6 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index aba747a7c..431796843 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1197,6 +1197,11 @@ LanceDB Enterprise it is the server's backfill job. `resourceBudget` for registered Functions. All are LanceDB Enterprise only; a LanceDB Embedded refresh rejects every option other than `batchSize`, `gpuClass` and `gpuCount`. + `publicationIntervalRows` opts into publishing completed Function split + ranges once their accumulated unpublished rows reach the threshold. + It must be a positive safe integer and requires non-Blob Function outputs. + Omit it for whole-fragment publication. Publications can exceed the + threshold, and remaining rows publish at completion. #### Returns @@ -1212,6 +1217,7 @@ const job = await table.refreshColumnAsync("embedding", { memoryBytes: 16 * 1024 ** 3, }, maxConcurrency: 4, + publicationIntervalRows: 10000, errorPolicy: "skip", maxFailedFraction: 0.01, rowTimeoutSeconds: 30, diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index 6cc8f7f8f..c534e0fac 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -117,6 +117,19 @@ Worker count for an expression column; Function columns reject it. *** +### publicationIntervalRows? + +```ts +optional publicationIntervalRows: number; +``` + +Row-count threshold for publishing completed Function split ranges. +Must be a positive safe integer. Omit for whole-fragment publication. +Actual publications can be larger; remaining rows publish at completion. +Requires LanceDB Enterprise with non-Blob Function outputs. + +*** + ### resourceBudget? ```ts diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index ed4838497..1b809b91d 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -414,8 +414,8 @@ and `gpuCount` in the `refreshColumnAsync` options. Completed Function outputs publish with their fragment by default. To opt into -a row-count publication threshold, set `publication_interval_rows` in Python or -`publication_interval_rows()` in Rust: +a row-count publication threshold, set `publication_interval_rows` in Python, +`publicationIntervalRows` in TypeScript, or `publication_interval_rows()` in Rust: ```python Python icon="python" @@ -426,6 +426,13 @@ job = table.refresh_column_async( job.wait() ``` +```typescript TypeScript icon="square-js" +const job = await table.refreshColumnAsync("embedding", { + publicationIntervalRows: 60, +}); +await job.wait(); +``` + ```rust Rust icon="rust" use lancedb::table::RefreshColumnOptions; @@ -443,7 +450,9 @@ individual publication can differ from this value depending on completed work and Function batching; this is not an exact-N contract. Omit it to keep whole-fragment publication. -The TypeScript SDK does not expose the publication threshold option yet. +In TypeScript, the threshold must be a positive safe integer, at most +`Number.MAX_SAFE_INTEGER`. This option requires a supporting LanceDB Enterprise +server and Function outputs without Blob types; Blob inputs are allowed. The job APIs also take the row filter and failure handling of the SQL `REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index f87c70091..4ac08b4c4 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -776,6 +776,7 @@ describe("remote connection", () => { const job = await table.refreshColumnAsync("embedding", { where: "id % 2 = 0", batchSize: 16, + publicationIntervalRows: 60, maxConcurrency: 3, gpuClass: "a10g", gpuCount: 2, @@ -788,6 +789,18 @@ describe("remote connection", () => { }); expect(job.id).toBe("j-9"); await table.refreshColumnAsync("embedding"); + await table.refreshColumnAsync("embedding", { + publicationIntervalRows: undefined, + }); + for (const publicationIntervalRows of [ + 1, + 2 ** 32 + 1, + Number.MAX_SAFE_INTEGER, + ]) { + await table.refreshColumnAsync("embedding", { + publicationIntervalRows, + }); + } await table.refreshColumnAsync("embedding", { resourceBudget: { cpuMillis: 8_000, @@ -799,6 +812,14 @@ describe("remote connection", () => { maxConcurrency: true as unknown as number, }), ).rejects.toThrow(); + for (const publicationIntervalRows of [true, "60", 60n]) { + await expect( + table.refreshColumnAsync("embedding", { + publicationIntervalRows: + publicationIntervalRows as unknown as number, + }), + ).rejects.toThrow(); + } // Invalid options reject before any request is sent. for (const [options, message] of [ [{ maxFailedRows: -1 }, "maxFailedRows"], @@ -806,6 +827,22 @@ describe("remote connection", () => { [{ where: " " }, "where"], [{ maxFailedFraction: 2 }, "max_failed_fraction"], [{ rowTimeoutSeconds: 0 }, "row_timeout_seconds"], + [{ publicationIntervalRows: 0 }, "publicationIntervalRows"], + [{ publicationIntervalRows: -1 }, "publicationIntervalRows"], + [{ publicationIntervalRows: 1.5 }, "publicationIntervalRows"], + [{ publicationIntervalRows: Number.NaN }, "publicationIntervalRows"], + [ + { publicationIntervalRows: Number.POSITIVE_INFINITY }, + "publicationIntervalRows", + ], + [ + { publicationIntervalRows: Number.NEGATIVE_INFINITY }, + "publicationIntervalRows", + ], + [ + { publicationIntervalRows: Number.MAX_SAFE_INTEGER + 1 }, + "publicationIntervalRows", + ], [{ maxConcurrency: 1.5 }, "maxConcurrency"], [{ maxConcurrency: 0 }, "maxConcurrency"], [{ maxConcurrency: -1 }, "maxConcurrency"], @@ -893,6 +930,7 @@ describe("remote connection", () => { expect(bodies).toEqual([ JSON.parse( `{"column": "embedding", "where": "id % 2 = 0", "batch_size": 16, + "publication_interval_rows": 60, "max_concurrency": 3, "gpu_class": "a10g", "gpu_count": 2, "error_policy": "skip", "max_failed_fraction": 0.01, "max_failed_rows": 50, @@ -900,6 +938,14 @@ describe("remote connection", () => { "max_executor_processes_per_worker": 2}`, ), { column: "embedding" }, + { column: "embedding" }, + JSON.parse('{"column": "embedding", "publication_interval_rows": 1}'), + JSON.parse( + '{"column": "embedding", "publication_interval_rows": 4294967297}', + ), + JSON.parse( + '{"column": "embedding", "publication_interval_rows": 9007199254740991}', + ), JSON.parse( `{"column": "embedding", "resource_budget": { diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 80d8296e2..b803e9043 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5686,6 +5686,14 @@ describe("computed columns", () => { await expect( table.refreshColumnAsync("x", { errorPolicy: "skip" }), ).rejects.toThrow("error_policy requires a LanceDB Enterprise refresh"); + for (const refresh of [ + () => table.refreshColumn("x", { publicationIntervalRows: 60 }), + () => table.refreshColumnAsync("x", { publicationIntervalRows: 60 }), + ]) { + await expect(refresh()).rejects.toThrow( + "publication_interval_rows requires a LanceDB Enterprise refresh", + ); + } await expect( table.refreshColumnAsync("x", { maxConcurrency: 4 }), ).rejects.toThrow("max_concurrency requires a LanceDB Enterprise refresh"); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 703fc7926..b38c2381c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -808,6 +808,11 @@ export abstract class Table { * `resourceBudget` for registered Functions. All are LanceDB Enterprise * only; a LanceDB Embedded refresh rejects every option other than * `batchSize`, `gpuClass` and `gpuCount`. + * `publicationIntervalRows` opts into publishing completed Function split + * ranges once their accumulated unpublished rows reach the threshold. + * It must be a positive safe integer and requires non-Blob Function outputs. + * Omit it for whole-fragment publication. Publications can exceed the + * threshold, and remaining rows publish at completion. * @example * ```ts * const job = await table.refreshColumnAsync("embedding", { @@ -817,6 +822,7 @@ export abstract class Table { * memoryBytes: 16 * 1024 ** 3, * }, * maxConcurrency: 4, + * publicationIntervalRows: 10000, * errorPolicy: "skip", * maxFailedFraction: 0.01, * rowTimeoutSeconds: 30, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 62fe811ad..e3bd22c0b 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1649,7 +1649,7 @@ pub struct FunctionWorkerResourceBudget { pub gpu_count: Option, } -fn resource_budget_integer(value: f64, name: &str) -> napi::Result { +fn positive_safe_integer(value: f64, name: &str) -> napi::Result { const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) { return Err(napi::Error::from_reason(format!( @@ -1699,6 +1699,11 @@ pub struct RefreshColumnOptions { pub where_clause: Option, /// Maximum rows per Function call; must be greater than zero. pub batch_size: Option, + /// Row-count threshold for publishing completed Function split ranges. + /// Must be a positive safe integer. Omit for whole-fragment publication. + /// Actual publications can be larger; remaining rows publish at completion. + /// Requires LanceDB Enterprise with non-Blob Function outputs. + pub publication_interval_rows: Option, /// Override the registered Function's maximum concurrent user-code calls /// for this logical execution. pub max_concurrency: Option, @@ -1735,6 +1740,10 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { let mut options = Self::default(); options.where_clause = value.where_clause; options.batch_size = value.batch_size.map(|size| size as usize); + options.publication_interval_rows = value + .publication_interval_rows + .map(|rows| positive_safe_integer(rows, "publicationIntervalRows")) + .transpose()?; options.max_concurrency = positive_u32(value.max_concurrency, "maxConcurrency")?; options.gpu_class = value.gpu_class; options.resource_budget = value @@ -1742,8 +1751,8 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { .map(|budget| { Ok::<_, napi::Error>( LanceFunctionWorkerResourceBudget::new( - resource_budget_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, - resource_budget_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?, + positive_safe_integer(budget.cpu_millis, "resourceBudget.cpuMillis")?, + positive_safe_integer(budget.memory_bytes, "resourceBudget.memoryBytes")?, ) .with_gpu_count(resource_budget_gpu_count(budget.gpu_count)?), ) From ea1cf17f895a6b5046963c0b8a7524ace3d7bea9 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 07:35:43 -0800 Subject: [PATCH 070/203] feat(python): export recorded Function job timelines (#4946) Function jobs can now export their recorded execution timeline with `job.export_timeline(path)` or `await job.export_timeline(path)`. The SDK fetches a fresh Chrome Trace Event recording that opens in Perfetto, including worker split spans and timestamped job phases. Batch counts and latency statistics remain details rather than invented batch intervals. ```python job = db.open_job(job_id) job.export_timeline("refresh.trace.json") async_job = await async_db.open_job(job_id) await async_job.export_timeline("refresh.trace.json") ``` The export does not wait for completion or cancel the job. Running jobs return partial recordings. Local operations and SQL query handles remain unsupported, and servers must support the timeline endpoint. The destination is touched only after a successful fetch; network and filesystem errors propagate. Rust freshness wrappers forward the operation without changing the submitting table's read baseline. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/job.py | 43 ++++++++++++++++++++++++ python/python/tests/test_job.py | 52 ++++++++++++++++++++++++++++++ python/src/job.rs | 7 ++++ rust/lancedb/src/job.rs | 27 ++++++++++++++++ rust/lancedb/src/remote/db.rs | 43 ++++++++++++++++++++++++ rust/lancedb/src/remote/job.rs | 26 +++++++++++++++ rust/lancedb/src/remote/table.rs | 11 +++++++ 8 files changed, 210 insertions(+) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4c5f5758a..4029525e9 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -412,6 +412,7 @@ class Job: ) -> Optional[str]: ... async def cancel(self) -> None: ... async def refresh(self) -> None: ... + async def timeline(self) -> str: ... async def events( self, *, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 86a1295cc..094a7b8d5 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -7,6 +7,8 @@ import asyncio import reprlib import time from datetime import timedelta +from os import PathLike +from pathlib import Path from typing import Any, Callable, Generic, Optional, TypeVar, cast import pyarrow as pa @@ -422,6 +424,31 @@ class AsyncJob(Generic[T]): description = self._inner._description if self._inner is not None else None return getattr(description, name) if description is not None else None + async def export_timeline(self, path: str | PathLike[str]) -> None: + """Write a fresh recorded Function job timeline as Chrome trace JSON. + + Open the file in Perfetto or Chrome tracing. The recording contains + retained split spans grouped by worker and timestamped job phases. + Batch counts and latency statistics are included as details; individual + batch timestamps are not recorded. Running jobs export a partial snapshot + without waiting or cancelling. Download again to include later work. + + Requires a server-side Function job and a server supporting timeline + export. Unsupported operations raise ``NotImplementedError`` or a server + error. The destination is overwritten only after the trace is fetched. + Filesystem errors propagate to the caller. + + Examples + -------- + >>> await job.export_timeline("refresh.trace.json") # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job timeline export requires a server-side Function job" + ) + trace = await self._inner.timeline() + await asyncio.to_thread(Path(path).write_text, trace, encoding="utf-8") + async def events( self, *, @@ -621,6 +648,22 @@ class Job(Generic[T]): def _field(self, name: str) -> Optional[Any]: return getattr(self._inner, name) if self._inner is not None else None + def export_timeline(self, path: str | PathLike[str]) -> None: + """Write Chrome trace JSON for this Function job. + + See :meth:`AsyncJob.export_timeline`. Open the file in Perfetto or + Chrome tracing. + + Examples + -------- + >>> job.export_timeline("refresh.trace.json") # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job timeline export requires a server-side Function job" + ) + return LOOP.run(self._inner.export_timeline(path)) + def events( self, *, diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 07b8a8c5e..690f6414b 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import asyncio +import json import time from datetime import timedelta from types import SimpleNamespace @@ -751,3 +752,54 @@ async def test_query_wait_timeout_requires_keeping_original_handle(): assert "continues on the server" in message assert "keep this handle to continue waiting" in message assert "db.open_job" not in message + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path): + trace = { + "traceEvents": [{"ph": "X", "ts": 0, "dur": 1000}], + "metadata": {"partial": True}, + } + inner = SimpleNamespace( + timeline=AsyncMock(return_value=json.dumps(trace)), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + path = tmp_path / "job.trace.json" + if sync: + await asyncio.to_thread(Job(job).export_timeline, str(path)) + else: + await job.export_timeline(path) + assert json.loads(path.read_text()) == trace + inner.timeline.assert_awaited_once_with() + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_export_timeline_failure_preserves_existing_file(tmp_path): + path = tmp_path / "job.trace.json" + path.write_text("previous recording") + job = AsyncJob( + SimpleNamespace( + timeline=AsyncMock(side_effect=RuntimeError("unsupported server")) + ) + ) + with pytest.raises(RuntimeError, match="unsupported server"): + await job.export_timeline(path) + assert path.read_text() == "previous recording" + with pytest.raises(NotImplementedError, match="server-side Function job"): + await AsyncJob(None).export_timeline(path) + with pytest.raises(NotImplementedError, match="server-side Function job"): + Job(None).export_timeline(path) + + +@pytest.mark.asyncio +async def test_export_timeline_reports_filesystem_errors(tmp_path): + job = AsyncJob( + SimpleNamespace(timeline=AsyncMock(return_value='{"traceEvents":[]}')) + ) + with pytest.raises(FileNotFoundError): + await job.export_timeline(tmp_path / "missing" / "trace.json") diff --git a/python/src/job.rs b/python/src/job.rs index f1fd85844..0d411072f 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -152,6 +152,13 @@ impl Job { self.inner.description().map(JobDescription::from) } + pub fn timeline(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner.timeline().await.infer_error()?.to_string()) + }) + } + #[pyo3(signature = (*, limit=None, filter=None))] pub fn events( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 8644c6a48..d178542b7 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -85,6 +85,11 @@ pub(crate) trait JobHandle: Send + Sync { async fn describe(&self) -> Result { job_detail_not_supported("describing a job") } + /// Chrome Trace Event JSON for a server-side Function job. + async fn timeline(&self) -> Result { + job_detail_not_supported("job timeline export") + } + /// The job's recorded lifecycle events. async fn events(&self, _request: JobEventsRequest) -> Result> { job_detail_not_supported("job event history") @@ -468,6 +473,28 @@ where } } + /// Fetch a recorded Function job timeline as Chrome Trace Event JSON. + /// + /// The snapshot opens in Perfetto or Chrome tracing. It contains retained + /// split and positioned phase spans; batch statistics remain arguments, + /// because individual batch timestamps are not recorded. Running jobs return + /// a partial recording without waiting for completion. Requires server support; + /// in-process operations and SQL query handles do not support this operation. + /// + /// ```no_run + /// # async fn export(job: &lancedb::job::Job) -> Result<(), Box> { + /// let trace = job.timeline().await?; + /// std::fs::write("job.trace.json", trace.to_string())?; + /// # Ok(()) + /// # } + /// ``` + pub async fn timeline(&self) -> Result { + match &self.inner { + JobInner::Handle { handle, .. } => handle.timeline().await, + JobInner::Completed(_) => job_detail_not_supported("job timeline export"), + } + } + /// Waits until the operation reaches a terminal state. /// /// Returns the endpoint's typed result. Unit-result jobs return `()`. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a4952593b..a9d55b511 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -4261,6 +4261,49 @@ mod tests { ); } + #[tokio::test] + async fn test_job_timeline_fetches_recorded_trace_without_waiting() { + let conn = Connection::new_with_handler(|request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "job-1"); + let body = match request.url().path() { + "/v1/jobs/describe" => { + r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"IN_PROGRESS","creation_ms":1}"# + } + "/v1/jobs/timeline" => { + r#"{"traceEvents":[{"ph":"X","pid":1,"tid":1,"ts":0,"dur":1000,"name":"Split 1"}],"metadata":{"partial":true}}"# + } + path => panic!("Unexpected request: {path}"), + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + let trace = job.timeline().await.unwrap(); + assert_eq!(trace["traceEvents"][0]["dur"], 1000); + assert_eq!(trace["metadata"]["partial"], true); + } + + #[tokio::test] + async fn test_job_timeline_rejects_an_unrelated_json_response() { + let conn = Connection::new_with_handler(|request| { + let body = if request.url().path() == "/v1/jobs/describe" { + r#"{"job_id":"job-1","job_type":"function_refresh","job_state":"SUCCEEDED","creation_ms":1}"# + } else { + r#"{"message":"not a trace"}"# + }; + http::Response::builder().status(200).body(body).unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + assert!( + job.timeline() + .await + .unwrap_err() + .to_string() + .contains("not Chrome Trace Event JSON") + ); + } + #[tokio::test] async fn test_job_events_scope_to_that_job() { let schema = Arc::new(Schema::new(vec![Field::new( diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 0c652a3ae..d27c9c666 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -235,6 +235,32 @@ impl JobHandle for RemoteJob { Ok(self.fetch_description().await?.1.into_description()) } + async fn timeline(&self) -> Result { + let request = self + .client + .post("/v1/jobs/timeline") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let trace: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse job timeline: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if !trace + .get("traceEvents") + .is_some_and(serde_json::Value::is_array) + { + return Err(Error::Http { + source: "server response is not Chrome Trace Event JSON; job timeline export requires server support".into(), + request_id, status_code: None, + }); + } + Ok(trace) + } + async fn events(&self, request: JobEventsRequest) -> Result> { let mut body = serde_json::json!({ "job_id": self.job_id }); if let Some(limit) = request.limit { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 37890fd17..3859cb830 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -289,6 +289,10 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -370,6 +374,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::describe(&self.inner).await } + async fn timeline(&self) -> Result { + crate::job::JobHandle::timeline(&self.inner).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -12133,6 +12141,8 @@ mod tests { .body(events.clone()) .unwrap() } + "/v1/jobs/timeline" => http::Response::builder().status(200) + .body(br#"{"traceEvents":[],"metadata":{"partial":true}}"#.to_vec()).unwrap(), other => panic!("unexpected path {other}"), } }); @@ -12149,6 +12159,7 @@ mod tests { .await .unwrap(); assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); + assert_eq!(job.timeline().await.unwrap()["metadata"]["partial"], true); } /// A newly submitted refresh returns a freshness-wrapped handle. Waiting From 08d3f448af3548e66f1d17d09e1b95f19e80798e Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 11 Nov 2026 15:38:06 +0000 Subject: [PATCH 071/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.10=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.11?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 992d126d0..076443831 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.10" +current_version = "0.42.0-beta.11" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 3518272e0..ee2a3d919 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5931,7 +5931,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "ahash", "anyhow", @@ -6042,7 +6042,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "anyhow", "arrow-array", @@ -6085,7 +6085,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "arrow-array", "arrow-buffer", @@ -6110,7 +6110,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 3d3a3f8e1..c06b4f230 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.42.0-beta.10 + 0.42.0-beta.11 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 758e41acd..903be2b77 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.10 + 0.42.0-beta.11 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 514be8540..610c095b9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.10 + 0.42.0-beta.11 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 47fc92237..91d808647 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.10" +version = "0.42.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 3761d6f4f..1a9011b34 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.42.0-beta.10", + "version": "0.42.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 5b7a167d0..00b2918d6 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.42.0-beta.10", + "version": "0.42.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 e902929bf..f94f27216 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.42.0-beta.10", + "version": "0.42.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 a54f47de3..e0eefa2e9 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.42.0-beta.10", + "version": "0.42.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 cc1894e70..f0891fbed 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.42.0-beta.10", + "version": "0.42.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 d5e0309d0..04b65ba86 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.42.0-beta.10", + "version": "0.42.0-beta.11", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 5e9698e7f..e5e0effab 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.42.0-beta.10", + "version": "0.42.0-beta.11", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 5579e1c55..a03e1a794 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.10", + "version": "0.42.0-beta.11", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 102b0f67b..07ca7de02 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.10" +version = "0.42.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 783216243..cbb0142e1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 051db741a..cde8b295a 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.10" +version = "0.42.0-beta.11" edition = "2021" license.workspace = true repository.workspace = true From 9a9b681aaf26dcb32af45fc77d79cdbd49f46c6a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 12 Nov 2026 00:49:00 +0800 Subject: [PATCH 072/203] docs(python): clarify refresh result row counts (#4963) ## Summary `RefreshColumnResult` exposed the canonical refresh counters without documenting their unit. This change describes them as logical rows planned for one refresh: `rows_assigned` counts successful rows written, `rows_failed` counts rows whose computation failed, and `rows_remaining` counts planned rows neither assigned nor terminally skipped. Rows already covered by `rows_failed` are not counted again as remaining. Retry attempts and user-code calls do not change that logical-row scope. The change also documents the source and published versions and the deprecated `rows_filled` alias. The existing skip-policy example is now explicit: a refresh over 2,001 logical rows with 1,891 assigned, 110 failed, and 0 remaining uses 2,001 as the failure-rate denominator. ## Behavior Documentation only. No field names, Python or native behavior, REST wire format, dependencies, or pins change. ## Validation - `git diff --check` - `uvx ruff format --check` - `uvx ruff check` - Imported this Python source with a compatible prebuilt ABI3 extension and asserted the public class and property documentation, the affected source version, and the native extension identity. --- python/python/lancedb/functions.py | 32 +++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 6d0c2ff52..737abc44e 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -873,17 +873,47 @@ class RefreshColumnResult(_RemoteValue): LanceDB Embedded jobs produce this value in process. LanceDB Enterprise decodes the same value from the durable server-job terminal payload. + + Row counters describe logical rows planned for this refresh, not user-code + calls or retry attempts. ``rows_assigned`` counts rows successfully written + with an output value, ``rows_failed`` counts rows whose computation failed, + and ``rows_remaining`` counts planned rows neither assigned nor terminally + skipped. Rows already counted in ``rows_failed`` are covered and are not + counted again in ``rows_remaining``. + + For example, a refresh over 2,001 logical rows that assigns 1,891 values and + fails 110 rows reports ``rows_assigned=1,891``, ``rows_failed=110``, and + ``rows_remaining=0``. Its failure-rate denominator is those 2,001 logical + rows, not the number of execution attempts. """ rows_assigned: _UInt64 + """Number of logical rows successfully assigned an output value by this + refresh. Each row counts once, regardless of retry attempts, and failed rows + are not included.""" + rows_failed: _UInt64 + """Number of logical rows whose computation failed. Rows deferred because + an input was not ready are not failures.""" + rows_remaining: _UInt64 + """Number of planned logical rows neither assigned nor terminally skipped. + Rows already counted in ``rows_failed`` are covered and are not counted + again.""" + source_version: _UInt64 + """Exact table version the refresh read.""" + published_version: Optional[_UInt64] = None + """Table version made visible by the refresh, when one was published.""" @property def rows_filled(self) -> int: - """Deprecated compatibility alias for :attr:`rows_assigned`.""" + """Deprecated compatibility alias for :attr:`rows_assigned`. + + The value is the same successful logical-row count; it does not count + execution attempts. + """ return self.rows_assigned @property From 28bbc81c3e0488c9eca9dab738f6db713f24d12c Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 11 Nov 2026 12:06:00 -0800 Subject: [PATCH 073/203] fix(remote): explain unsupported optimize syntax (#4944) This PR addresses [OSS-2913](https://linear.app/lancedb/issue/OSS-2913) ([#4845](https://github.com/lancedb/lancedb/issues/4845)) and [ENT-2909](https://linear.app/lancedb/issue/ENT-2909): `table.optimize()` on an Enterprise table exposes SQL parser errors when the deployment does not support its generated SQL. The SDK generates the statement itself, but previously propagated unsupported grammar as a generic SQL failure. Parser errors and unknown-option errors reported as `InvalidArgument` now become `NotSupported` (`NotImplementedError` in Python), retaining the original diagnostic and request ID. --- docs/web/maintenance/compaction.mdx | 4 +- rust/lancedb/src/remote/sql_test.rs | 123 ++++++++++++++++ rust/lancedb/src/remote/table.rs | 16 ++- rust/lancedb/src/remote/table/optimize.rs | 162 ++++++++++++++++++++++ 4 files changed, 296 insertions(+), 9 deletions(-) diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 9c8765293..e7b79f768 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -13,8 +13,8 @@ import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompac Every write commits a new table version, and versions accumulate: small files from frequent appends, superseded files from updates and deletes, and rows added since an index was built. In the embedded library, `optimize()` addresses all -three; a deployment handles them in the background and does not support -`optimize()`. +three. Enterprise handles maintenance in the background and also supports +on-demand compaction through `optimize()` on compatible servers. Run optimization as regular table maintenance, particularly after many small writes or a large ingest. diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index efc2ba6a4..cfaf2a625 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -95,6 +95,7 @@ struct TestSqlService { exchanges: ReceivedExchanges, result_overrides: Arc>>, materialized_view_job_handle_supported: bool, + optimize_error: Option, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, @@ -269,6 +270,7 @@ impl Default for TestSqlService { exchanges: Arc::new(std::sync::Mutex::new(Vec::new())), result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), materialized_view_job_handle_supported: false, + optimize_error: None, exchange_drops: Arc::new(AtomicUsize::new(0)), result, large_result, @@ -439,6 +441,11 @@ impl FlightService for TestSqlService { .and_then(|command| command.unpack::().ok().flatten()); if let Some(command) = &initial { self.statements.lock().unwrap().push(command.query.clone()); + if command.query.starts_with("OPTIMIZE ") + && let Some(error) = &self.optimize_error + { + return Err(error.clone()); + } if command.query == "SELECT rejected" { return Err(Status::invalid_argument("invalid statement")); } @@ -3932,3 +3939,119 @@ async fn remote_compact_preserves_omissions_and_explicit_default_values() { shutdown.send(()).unwrap(); } } + +#[tokio::test] +async fn remote_optimize_parser_errors_are_clear_without_resubmission() { + use crate::table::optimize::CompactionOverrides; + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError(\"Expected: end of statement, found: REWRITE at Line: 1\")", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: Expected: TABLE, found: events", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'io_buffer_size'", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: future grammar diagnostic", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'future_option'", + true, + ), + ( + tonic::Code::PermissionDenied, + "ParserError: future grammar diagnostic", + false, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + (tonic::Code::NotFound, "table not found", false), + (tonic::Code::Unavailable, "transport error", false), + ( + tonic::Code::InvalidArgument, + "invalid table configuration", + false, + ), + ] { + let status = Status::new(code, message); + let service = TestSqlService { + adaptive: true, + optimize_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = + client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ); + let error = table + .compact(CompactionOverrides::default()) + .await + .unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error:?}" + ); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("request_id")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_optimize_branch_options_are_not_dropped() { + let service = TestSqlService { + adaptive: true, + optimize_error: Some(Status::invalid_argument( + "ParserError: Expected: ), found: , at Line: 1", + )), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(Some("exp".into())); + let error = table + .compact(crate::table::optimize::CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("compatible release")); + assert_eq!( + *statements.lock().unwrap(), + ["OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'exp', io_buffer_size = 0)"] + ); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3859cb830..48e5652ae 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3717,14 +3717,14 @@ impl BaseTable for RemoteTable { /// `OptimizeAction::All`, `::Prune`, and `::Index` remain unsupported /// remotely: there is no SQL statement yet for version pruning or index /// optimization. A branch-scoped table handle submits a - /// `WITH (branch = '')` clause; the statement does not itself - /// validate the branch exists, so a nonexistent branch surfaces as an - /// async job failure rather than an error from this call. Per-job + /// `WITH (branch = '')` clause; the server resolves and validates + /// the selected target. Per-job /// `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and /// `batch_size` are forwarded in the SQL `WITH` clause. Other non-default /// options are rejected before submission. Servers must support these - /// SQL options; an older server's error is returned without retrying - /// with the settings removed. + /// SQL options. Parser errors and unknown optimize option errors become + /// `NotSupported` with the server diagnostic after one SQL submission. + /// No settings are removed and the operation is never resubmitted. async fn optimize(&self, action: OptimizeAction) -> Result { self.check_mutable().await?; let OptimizeAction::Compact { @@ -3782,9 +3782,11 @@ impl BaseTable for RemoteTable { // value is built afterward. sql_client .submit_as_job(statement, self.namespace.clone(), || async { Ok(()) }) - .await? + .await + .map_err(optimize::map_optimize_error)? .wait() - .await?; + .await + .map_err(optimize::map_optimize_error)?; Ok(OptimizeStats { compaction: Some(lance::dataset::optimize::CompactionMetrics::default()), prune: None, diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 2a42dd3ab..6f4b7f7e8 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -35,10 +35,172 @@ pub(super) fn compaction_sql_options( Ok(result) } +const UNSUPPORTED_OPTIMIZE: &str = "Compaction on an Enterprise table requires support for OPTIMIZE
REWRITE DATA. Upgrade LanceDB Enterprise to a compatible release."; +const UNSUPPORTED_OPTIONS: &str = "The requested compaction options are not supported by this version of LanceDB Enterprise. Upgrade to a compatible release; requested options will not be removed or retried."; + +/// The client generates the whole statement, so parser errors indicate a +/// client/server syntax mismatch. Match option errors without enumerating names. +fn unsupported_optimize_message(message: &str) -> Option<&'static str> { + let message = message.to_ascii_lowercase(); + if message.contains("parsererror") { + Some(UNSUPPORTED_OPTIMIZE) + } else if message.contains("unknown optimize option") { + Some(UNSUPPORTED_OPTIONS) + } else { + None + } +} + +/// Apply compatibility handling only to this constructed operation. +/// Preserve every unrelated SQL/authentication/transport error unchanged. +pub(super) fn map_optimize_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<(&Error, &'static str)> { + match error { + Error::Sql { + message, grpc_code, .. + } if *grpc_code == tonic::Code::InvalidArgument as i32 => { + unsupported_optimize_message(message).map(|reason| (error, reason)) + } + Error::JobFailed { failure, .. } => failure + .source + .as_deref() + .and_then(|source| unsupported(source)), + _ => None, + } + } + if let Some((source, reason)) = unsupported(&error) { + let diagnostic = match &error { + Error::Sql { .. } => error.to_string(), + // JobFailure's Display omits its source, including the SQL request ID. + _ => format!("{error}; {source}"), + }; + Error::NotSupported { + message: format!("{reason} Server diagnostic: {diagnostic}"), + } + } else { + error + } +} + #[cfg(test)] mod tests { use super::*; + use crate::error::JobFailure; use crate::table::{CompactionOptions, CompactionOverrides}; + use std::sync::Arc; + + fn sql_error(code: tonic::Code, message: &str) -> Error { + Error::Sql { + message: message.into(), + request_id: "optimize-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + } + } + + #[test] + fn direct_optimize_error_prints_its_diagnostic_once() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let Error::NotSupported { message } = + map_optimize_error(sql_error(tonic::Code::InvalidArgument, diagnostic)) + else { + panic!("known optimize syntax must be unsupported"); + }; + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn wrapped_optimize_error_keeps_job_context_and_sql_diagnostic() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + source: Some(Arc::new(sql_error( + tonic::Code::InvalidArgument, + diagnostic, + ))), + ..Default::default() + }), + }; + let Error::NotSupported { message } = map_optimize_error(error) else { + panic!("wrapped unsupported optimize SQL must be translated"); + }; + assert!(message.contains(UNSUPPORTED_OPTIMIZE)); + assert!(message.contains("optimize-job")); + assert!(message.contains("SQL planning failed (in planning)")); + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn unrelated_wrapped_sql_errors_pass_through_unchanged() { + let unsupported = "ParserError: Expected: end of statement, found: REWRITE"; + for (code, diagnostic) in [ + (tonic::Code::PermissionDenied, unsupported), + (tonic::Code::Unavailable, unsupported), + (tonic::Code::InvalidArgument, "invalid table configuration"), + ] { + let source = Arc::new(sql_error(code, diagnostic)); + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + sql_job_id: Some("sql-job".into()), + retryable: Some(false), + source: Some(source.clone()), + ..Default::default() + }), + }; + let Error::JobFailed { job_id, failure } = map_optimize_error(error) else { + panic!("{code:?}: unrelated SQL failure must keep its classification"); + }; + assert_eq!(job_id.as_deref(), Some("optimize-job")); + assert_eq!(failure.phase.as_deref(), Some("planning")); + assert_eq!(failure.message.as_deref(), Some("SQL planning failed")); + assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job")); + assert_eq!(failure.retryable, Some(false)); + assert!(Arc::ptr_eq(failure.source.as_ref().unwrap(), &source)); + } + } + + #[test] + fn generated_optimize_syntax_errors_indicate_incompatible_servers() { + for diagnostic in [ + "ParserError: Expected: end of statement, found: REWRITE", + "ParserError: Expected: identifier", + "SQL error: ParserError: future grammar diagnostic", + "parsererror: lowercase diagnostic", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIMIZE) + ); + } + for diagnostic in [ + "Unknown OPTIMIZE option 'io_buffer_size'", + "Error during planning: Unknown OPTIMIZE option 'future_option'", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIONS) + ); + } + for diagnostic in [ + "permission denied", + "table not found", + "connection reset", + "invalid table configuration", + ] { + assert!( + unsupported_optimize_message(diagnostic).is_none(), + "{diagnostic}" + ); + } + } #[test] fn omissions_and_explicit_default_target_are_distinct() { From 42f11d13a2755e44b63876b5a5edd93901291150 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 11 Nov 2026 12:50:07 -0800 Subject: [PATCH 074/203] docs: clarify Python job states and waiting behavior (#4954) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We weren’t explicit about the job states returned by the Python SDK. This documents those values and clarifies the difference between checking the current status and waiting for completion. --- docs/web/basics/jobs.mdx | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 5336d1dfd..47285f5d0 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -42,9 +42,21 @@ print(job.status()) 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. Both `Job.wait()` and -`AsyncJob.wait()` retry transient connection and read errors with capped +In Python, `job.status()` returns the current state: + +| State | Meaning | +| --- | --- | +| `running` | The operation is in progress. | +| `finished` | The operation completed successfully. | +| `failed` | The operation failed. | +| `cancelled` | The operation was cancelled. | + +`job.status()` checks the current state without waiting for completion. +It returns `failed` or `cancelled` for unsuccessful jobs. + +Use `job.wait()` to wait for completion and raise if the job fails or is +cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection +and read errors with capped exponential backoff within the caller's timeout. Without a timeout, retries continue indefinitely. From ee231aad066289febc88bc4088b9c6f93b1e4d49 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 22:56:36 -0800 Subject: [PATCH 075/203] fix(python): validate function package requirements before registration (#4971) Function dependency typos currently reach the environment build before failing. Validate pip requirements with `packaging.requirements.Requirement` and conda requirements with Rattler's MatchSpec parser when constructing a function definition, before source packaging or registration. Errors identify the original entry and its index. ```python @lancedb.function(pip=["numpy", "torch>=2.0,,<3"]) def score(value: float) -> float: return value # ValueError: invalid pip[1] requirement 'torch>=2.0,,<3': ... ``` Preserves pip extras, markers, named references, bare archive/git URLs, and conda channel/build specifications. The existing native extension exposes the conda parser, so no additional Python package is required. Adds regression coverage for invalid and supported forms, including the deprecated `udf` alias. --- Cargo.lock | 288 +++++++++++++++++- python/Cargo.toml | 1 + python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/functions.py | 33 +- .../tests/test_function_requirements.py | 125 ++++++++ python/src/lib.rs | 1 + python/src/util.rs | 8 + 7 files changed, 450 insertions(+), 7 deletions(-) create mode 100644 python/python/tests/test_function_requirements.py diff --git a/Cargo.lock b/Cargo.lock index ee2a3d919..f38252fc5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1422,6 +1422,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "blake3" version = "1.8.5" @@ -2734,7 +2743,7 @@ dependencies = [ "arrow", "arrow-buffer", "base64 0.23.1", - "blake2", + "blake2 0.10.6", "blake3", "chrono", "chrono-tz 0.10.4", @@ -3197,6 +3206,15 @@ dependencies = [ "dirs-sys 0.5.0", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -3442,6 +3460,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.14" @@ -3572,6 +3601,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "file_url" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec49f140842acf886ff3e4fd47600ffdbb5f1b1ba70f6775880e688837a0b174" +dependencies = [ + "itertools 0.15.0", + "percent-encoding", + "thiserror 2.0.18", + "typed-path", + "url", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3616,6 +3658,15 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + [[package]] name = "float8" version = "0.7.0" @@ -3747,6 +3798,15 @@ version = "1.20260804.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + [[package]] name = "fs4" version = "0.13.1" @@ -4323,6 +4383,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "halfbrown" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09" +dependencies = [ + "hashbrown 0.16.1", + "serde", +] + [[package]] name = "hash32" version = "0.3.1" @@ -4428,7 +4498,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ - "dirs", + "dirs 6.0.0", "futures", "http", "indicatif", @@ -5624,7 +5694,7 @@ dependencies = [ "datafusion-functions-nested", "datafusion-physical-expr", "datafusion-physical-plan", - "dirs", + "dirs 6.0.0", "fst", "futures", "half", @@ -6132,6 +6202,7 @@ dependencies = [ "pyo3", "pyo3-async-runtimes", "pyo3-build-config", + "rattler_conda_types", "reqwest 0.13.5", "serde", "serde_json", @@ -6140,6 +6211,29 @@ dependencies = [ "uuid", ] +[[package]] +name = "lazy-regex" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a2cce8a22920a29fdcc8c9170aa5d29edd9fbcf8bea856e24c2cb1c2419f67" +dependencies = [ + "lazy-regex-proc_macros", + "once_cell", + "regex", +] + +[[package]] +name = "lazy-regex-proc_macros" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f1e4b1f1d8c71edb4ff2b2150ec4606445fd2ddf67ddc097655daf59286baa6" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 3.0.3", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -6903,6 +6997,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "nom-language" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29" +dependencies = [ + "nom 8.0.0", +] + [[package]] name = "now" version = "0.1.3" @@ -8587,6 +8690,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" +[[package]] +name = "purl" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60ebe4262ae91ddd28c8721111a0a6e9e58860e211fc92116c4bb85c98fd96ad" +dependencies = [ + "hex", + "percent-encoding", + "serde", + "thiserror 2.0.18", +] + [[package]] name = "pyo3" version = "0.29.3" @@ -8973,6 +9088,99 @@ dependencies = [ "rustversion", ] +[[package]] +name = "rattler_conda_types" +version = "0.58.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda631350e17df9bc789082d6b6c0fbde38e65cba580593ee3317fb6730644f2" +dependencies = [ + "ahash", + "core-foundation 0.10.1", + "dirs 7.0.0", + "fancy-regex 0.19.2", + "file_url", + "fs-err", + "glob", + "hex", + "indexmap 2.14.0", + "itertools 0.15.0", + "jiff", + "lazy-regex", + "memmap2 0.9.10", + "nom 8.0.0", + "nom-language", + "purl", + "rattler_conda_version", + "rattler_digest", + "rattler_macros", + "rattler_redaction", + "regex", + "serde", + "serde-untagged", + "serde_json", + "serde_repr", + "serde_with", + "serde_yaml", + "simd-json", + "smallvec", + "strum", + "tempfile", + "thiserror 2.0.18", + "tracing", + "typed-path", + "url", +] + +[[package]] +name = "rattler_conda_version" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee922b54cd30c198e93c542096a0d671cefba1a97600768b2ec4af3c11c44f55" +dependencies = [ + "itertools 0.15.0", + "nom 8.0.0", + "serde", + "smallvec", + "thiserror 2.0.18", +] + +[[package]] +name = "rattler_digest" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bda554663860e074665f838a4d9a89fbf671f576eaf288d29525114b345adc9" +dependencies = [ + "blake2 0.11.0", + "digest 0.11.3", + "hex", + "md-5", + "serde", + "serde-untagged", + "serde_bytes", + "serde_with", + "sha2 0.11.0", + "url", +] + +[[package]] +name = "rattler_macros" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a42690ed14c8b9d610aafc0f2eb715b85c05f3d3a2a307896e4f8d820aaa284f" +dependencies = [ + "quote", + "syn 3.0.3", +] + +[[package]] +name = "rattler_redaction" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b5ee47d0375643b037205a4fe238b90c518ca3fc83c7c240d82c49ba87d61c" +dependencies = [ + "url", +] + [[package]] name = "raw-cpuid" version = "11.6.0" @@ -9926,6 +10134,28 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -10056,6 +10286,19 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serde_yaml_ng" version = "0.10.0" @@ -10170,7 +10413,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" dependencies = [ "bstr", - "dirs", + "dirs 6.0.0", "os_str_bytes", ] @@ -10235,6 +10478,20 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd-json" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebe141eb4a23ecc4d5de93fa5b139ac65dc07c38037a2fe9a8fb7c9d36bd832" +dependencies = [ + "halfbrown", + "ref-cast", + "serde", + "serde_json", + "simdutf8", + "value-trait", +] + [[package]] name = "simd_cesu8" version = "1.1.1" @@ -10274,6 +10531,9 @@ name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] [[package]] name = "smartstring" @@ -11403,6 +11663,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.0" @@ -11583,6 +11849,18 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "value-trait" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b" +dependencies = [ + "float-cmp", + "halfbrown", + "itoa", + "ryu", +] + [[package]] name = "vcpkg" version = "0.2.15" @@ -12561,7 +12839,7 @@ dependencies = [ "colored", "const-str", "ctor", - "dirs", + "dirs 6.0.0", "futures", "git-version", "humantime", diff --git a/python/Cargo.toml b/python/Cargo.toml index 07ca7de02..7c11d5fdf 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -37,6 +37,7 @@ pyo3-async-runtimes = { version = "0.29", features = [ "tokio-runtime", ] } reqwest.workspace = true +rattler_conda_types = { version = "0.58.3", default-features = false } pin-project.workspace = true futures.workspace = true serde.workspace = true diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4029525e9..521cc46bb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1310,3 +1310,4 @@ class AuthzObject: def __repr__(self) -> str: ... def validate_function_retry_policy(json: str) -> None: ... +def _validate_conda_requirement(requirement: str) -> None: ... diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 737abc44e..4bf028306 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -44,6 +44,7 @@ from typing import ( ) import pyarrow as pa +from packaging.requirements import Requirement from pydantic import ( AfterValidator, BaseModel, @@ -57,6 +58,7 @@ from pydantic import ( 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 ._lancedb import _validate_conda_requirement from .secrets import EnvVarSecret _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) @@ -1701,6 +1703,29 @@ def _packaged_by_source(value: Any) -> bool: return True +def _validate_package_requirements(kind: str, packages: Sequence[str]) -> None: + for index, package in enumerate(packages): + field = f"{kind}[{index}]" + if not isinstance(package, str): + raise TypeError(f"{field} must be a string, got {package!r}") + if not package or package != package.strip(): + raise ValueError( + f"{field} requirement {package!r} must be non-empty and trimmed" + ) + try: + if kind == "conda": + _validate_conda_requirement(package) + else: + candidate = package + if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://", package): + candidate = f"dependency @ {package}" + Requirement(candidate) + except ValueError as error: + raise ValueError( + f"invalid {field} requirement {package!r}: {error}" + ) from error + + def _requirement_name(requirement: str) -> str: requirement = requirement.rpartition("::")[2] match = _REQUIREMENT_NAME.match(requirement.strip()) @@ -2242,6 +2267,7 @@ class FunctionDefinition: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") + _validate_package_requirements("conda" if conda else "pip", conda or pip) gpu_marker = _normalize_gpu_marker(gpu) if gpu_class is not None: _validate_gpu_class_name(gpu_class) @@ -2595,9 +2621,12 @@ def function( 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. + Pip requirements for the remote environment. Syntax is validated at + decoration time, including extras and environment markers. Named direct + references and bare package or git URLs are supported. conda : sequence of str, optional - Conda packages for the remote environment, instead of ``pip``. + Conda packages for the remote environment, instead of ``pip``. MatchSpec + syntax is validated at decoration time, including channels and builds. conda_channels : sequence of str, optional Conda channels in priority order; requires ``conda``. apt : sequence of str, optional diff --git a/python/python/tests/test_function_requirements.py b/python/python/tests/test_function_requirements.py new file mode 100644 index 000000000..6f94d1313 --- /dev/null +++ b/python/python/tests/test_function_requirements.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +from lancedb import function, udf +from lancedb.functions import FunctionDefinition + + +def identity(value: int) -> int: + return value + + +@pytest.mark.parametrize( + "package", + [ + "torch>=2.0,,<3", + "torch>=", + "torch=>2.0", + "torch[", + "torch; python_version >=", + "", + " torch", + "torch ", + ], +) +def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch): + def unexpected_packaging(*args, **kwargs): + pytest.fail("invalid requirements must fail before packaging the function") + + monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging) + with pytest.raises(ValueError) as error: + function(pip=["numpy", package])(identity) + assert "pip[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize( + "package", + [ + "numpy>=1,,<3", + "numpy>=", + "numpy[version=]", + "numpy[unknown_field=value]", + "", + " numpy", + "numpy ", + ], +) +def test_invalid_conda_requirement_names_entry(package): + with pytest.raises(ValueError) as error: + function(conda=["scipy", package])(identity) + assert "conda[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize("kind", ["pip", "conda"]) +@pytest.mark.parametrize("package", [None, 42, ["numpy"]]) +def test_requirement_must_be_a_string(kind, package): + with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"): + function(**{kind: ["numpy", package]})(identity) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "torch>=2.0,<3", + 'requests[security,socks]>=2; python_version >= "3.10"', + "numpy (>=1.26, <3)", + "six @ https://example.com/six-1.16.0.tar.gz", + "six @ git+https://github.com/benjaminp/six.git@main", + "https://example.com/six-1.16.0.tar.gz", + "git+https://github.com/benjaminp/six.git@main", + "git+ssh://git@github.com/benjaminp/six.git@main", + ], +) +def test_supported_pip_requirements_are_preserved(package): + definition = function(pip=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "numpy=1.26", + "numpy>=1.26,<3", + "numpy=1.26=py310_0", + "numpy 1.26 py310_0", + "conda-forge::numpy>=1.26", + "conda-forge/linux-64::numpy>=1.26", + "numpy[version='>=1.26,<3',build='py310*']", + ], +) +def test_supported_conda_requirements_are_preserved(package): + definition = function(conda=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +def test_requirements_still_sort_and_deduplicate(): + definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity) + assert definition.registration_request.runtime.environment.packages == ( + "numpy", + "torch>=2", + ) + + +def test_deprecated_udf_alias_validates_requirements(): + with pytest.warns(DeprecationWarning, match="use lancedb.function"): + with pytest.raises(ValueError, match=r"pip\[0\]"): + udf(pip=["torch>=2.0,,<3"])(identity) + + +def test_direct_function_definition_validates_requirements(): + with pytest.raises(ValueError, match=r"pip\[0\]"): + FunctionDefinition( + identity, + name=None, + input_schema=None, + output_schema=None, + pip=("torch>=2.0,,<3",), + env={}, + python_version=None, + ) diff --git a/python/src/lib.rs b/python/src/lib.rs index f78c4e7bb..b0698d5e0 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -150,6 +150,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(table::tokenize, m)?)?; m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?; m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_conda_requirement, m)?)?; m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?; m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?; m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?; diff --git a/python/src/util.rs b/python/src/util.rs index a956066f1..44efa165a 100644 --- a/python/src/util.rs +++ b/python/src/util.rs @@ -9,6 +9,7 @@ use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, pyfunction, }; +use rattler_conda_types::{MatchSpec, ParseStrictness}; /// A wrapper around a rust builder /// @@ -61,6 +62,13 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> { .map_err(|e| PyValueError::new_err(e.to_string())) } +#[pyfunction(name = "_validate_conda_requirement")] +pub fn validate_conda_requirement(requirement: &str) -> PyResult<()> { + MatchSpec::from_str(requirement, ParseStrictness::Lenient) + .map(|_| ()) + .map_err(|error| PyValueError::new_err(error.to_string())) +} + /// Parse field references with the same identifier syntax as Lance writes. #[pyfunction(name = "_parse_field_path")] pub fn parse_field_path(path: &str) -> PyResult> { From e622254108f15e159627d8a1d8e42e983e45cd81 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 23:32:19 -0800 Subject: [PATCH 076/203] fix(python): use direct lookups for table existence checks (#4974) Table existence checks should not depend on listing every table or searching only the first 100 names. Use a direct lookup for `name in db` and implement `table_exists(table_id)` on synchronous local connections, matching the remote and asynchronous APIs. Native namespace connections use their initialized Rust connection for existence checks; custom namespace clients retain their existing callback. Missing tables return `False`; other lookup errors propagate. ```python if "events" in db: db.drop_table("events") exists = db.table_exists(["analytics", "events"]) all_names = list(db.list_tables()) ``` Clarify that `.tables` contains one page and update deprecation guidance with safe replacements. Add regression coverage for lookups beyond the first page, nested namespaces, native and custom namespace clients, missing tables, permission errors, and lookups that do not list tables. Include an unpublished draft for the table-management guide until the new SDK support ships. --- docs/src/python/python.md | 17 +++++++ docs/web/management/table.mdx | 23 ++++++++- python/python/lancedb/db.py | 56 +++++++++++++++++---- python/python/lancedb/listing.py | 8 +++ python/python/lancedb/namespace.py | 30 ++++++++--- python/python/lancedb/remote/db.py | 13 +++-- python/python/tests/test_db.py | 46 +++++++++++++---- python/python/tests/test_namespace.py | 41 +++++++++++++++ python/python/tests/test_remote_db.py | 26 ++++++++++ python/python/tests/test_sync_api_parity.py | 25 ++++++--- 10 files changed, 246 insertions(+), 39 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index eccaae6ce..8de5b5517 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -42,6 +42,18 @@ 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`. +For existence checks, use `db.table_exists(["events"])` or `"events" in db`. +These look up the table directly and work even when the database has more than +100 tables. For a table in a namespace, include the namespace segments: + +```python +exists = db.table_exists(["analytics", "events"]) +``` + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. Checking `name in db.list_tables().tables` only +searches the first page and can miss an existing table. + Resource listings (`list_storage_integrations`, `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 @@ -1055,6 +1067,11 @@ 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. +Use `await db.table_exists(["events"])` to check for a table in the root +namespace, or `await db.table_exists(["analytics", "events"])` for a table in +a namespace. Checking membership in an awaited listing's `.tables` attribute +only searches one page. + ::: lancedb.listing.AsyncTableListing ::: lancedb.listing.AsyncNamespaceListing diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 2a05b4a0f..23fdbdb4a 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -201,7 +201,7 @@ setting. See [Limits](/basics/limits#schema). ```python Python icon="python" tbl = db.open_table("documents") -db.table_names() +names = list(db.list_tables()) ``` ```typescript TypeScript icon="square-js" @@ -230,6 +230,27 @@ listing. A missing table raises `ValueError` on a local directory and A listing returns one page of names at a time, so check every page. TypeScript has no `tableExists`. +{/* +Draft for the table-existence lookup release (#4974). Once released, replace +the two table-existence paragraphs above with this guidance: + +For Python local, remote, and namespace connections, use +`db.table_exists(["documents"])` or `"documents" in db` to check whether a root +table exists. For an async 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. They look up the table directly, regardless of the number +of tables in the database. + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. To collect every table name, use +`list(db.list_tables())`, or `[name async for name in db.list_tables()]` on an +async connection. The `.tables` attribute holds only one page (100 names by +default), so membership checks against it can miss existing tables. TypeScript +has no `tableExists`. +*/} + ## Rename and clone tables {#rename-clone} diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 73c8305ff..84ebb41a1 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -322,6 +322,9 @@ class DBConnection(EnforceOverrides): def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in + ``list_tables().tables``, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -331,12 +334,20 @@ class DBConnection(EnforceOverrides): Returns ------- bool - True if the table exists, False otherwise. + True if the table exists, False if it is not found. + Other errors, including permission errors, are propagated. Raises ------ NotImplementedError - If the connection type does not support namespace operations. + If the connection type does not support table existence checks. + + Examples + -------- + >>> def check_table(conn): + ... root_exists = conn.table_exists(["events"]) + ... nested_exists = conn.table_exists(["analytics", "events"]) + ... return root_exists, nested_exists """ raise NotImplementedError( "Namespace operations are not supported for this connection type" @@ -348,7 +359,11 @@ class DBConnection(EnforceOverrides): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + ``list_tables().tables`` contains only the first page (100 names by + default). Use ``list(list_tables())`` to collect all names, or + ``table_exists([name])`` to check whether a particular table exists. Parameters ---------- @@ -934,7 +949,7 @@ class DBConnection(EnforceOverrides): def __contains__(self, name: str) -> bool: """Return whether the root namespace contains the named table.""" - return name in self._all_table_names() + return self.table_exists([name]) def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. @@ -1849,6 +1864,10 @@ class LanceDBConnection(DBConnection): ) -> DescribeNamespaceResponse: return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path)) + @override + def table_exists(self, table_id: List[str]) -> bool: + return LOOP.run(self._conn.table_exists(table_id)) + @override def list_tables( self, @@ -1856,7 +1875,11 @@ class LanceDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1894,7 +1917,9 @@ class LanceDBConnection(DBConnection): """Get the names of all tables in the database. The names are sorted. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -1914,7 +1939,8 @@ class LanceDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -2878,6 +2904,9 @@ class AsyncConnection(object): async def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in an awaited listing's + ``tables`` attribute, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -2903,7 +2932,11 @@ class AsyncConnection(object): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> AsyncTableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -2942,7 +2975,9 @@ class AsyncConnection(object): """List all tables in this database, in sorted order .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -2966,7 +3001,8 @@ class AsyncConnection(object): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 8abc9d85b..59aba1431 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -175,6 +175,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]): class AsyncTableListing(_AsyncPagedNameListing): """Awaitable table iterator; awaiting loads one page. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``await db.table_exists([name])`` for existence checks. + For example:: page = await db.list_tables(limit=20) @@ -229,6 +232,10 @@ class _PagedNameListing(Iterator[str]): class TableListing(_PagedNameListing): """Table iterator retaining the current page as a list. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``db.table_exists([name])`` or ``name in db`` for + existence checks. Use ``list(db.list_tables())`` to collect all names. + For example:: page = db.list_tables(limit=20) @@ -239,6 +246,7 @@ class TableListing(_PagedNameListing): @property def tables(self) -> list[str]: + """A copy of the table names in the most recently fetched page.""" return self._inner.tables diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 3356b363c..aa9025641 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -579,12 +579,15 @@ class LanceNamespaceDBConnection(DBConnection): If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1015,6 +1018,8 @@ class LanceNamespaceDBConnection(DBConnection): bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return LOOP.run(self._inner.table_exists(table_id)) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1030,7 +1035,11 @@ class LanceNamespaceDBConnection(DBConnection): limit: Optional[int] = None, ) -> TableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1227,12 +1236,15 @@ class AsyncLanceNamespaceDBConnection: If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1614,6 +1626,8 @@ class AsyncLanceNamespaceDBConnection: bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return await self._inner.table_exists(table_id) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1628,7 +1642,11 @@ class AsyncLanceNamespaceDBConnection: limit: Optional[int] = None, ) -> AsyncTableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ebceba16b..21ad37b36 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -430,7 +430,11 @@ class RemoteDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List a page of tables in this database. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -468,7 +472,9 @@ class RemoteDBConnection(DBConnection): """List the names of all tables in the database. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -488,7 +494,8 @@ class RemoteDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 64bf928c0..80a98bc18 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -282,9 +282,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path): assert empty.page_token is None -def test_db_contains_stops_after_matching_table_page( - tmp_db: lancedb.DBConnection, monkeypatch -): +def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch): calls = [] pages = { None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"), @@ -297,18 +295,44 @@ def test_db_contains_stops_after_matching_table_page( monkeypatch.setattr(tmp_db, "list_tables", list_tables) - assert "table_1" in tmp_db - assert calls == [None] - - calls.clear() - assert "table_2" in tmp_db - assert calls == [None, "next"] - - calls.clear() assert len(tmp_db) == 3 assert calls == [None, "next"] +@pytest.mark.asyncio +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]]) +async def test_local_table_exists_without_listing( + tmp_path, monkeypatch, namespace_path +): + db = lancedb.connect(tmp_path) + for depth in range(1, len(namespace_path) + 1): + db.create_namespace(namespace_path[:depth]) + db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path) + if not namespace_path: + for idx in range(100): + (tmp_path / f"a{idx:03}.lance").mkdir() + assert "events" not in db.list_tables().tables + adb = await lancedb.connect_async(tmp_path) + + def fail_listing(*args, **kwargs): + raise AssertionError("Existence checks must not list tables") + + monkeypatch.setattr(db, "list_tables", fail_listing) + monkeypatch.setattr(adb, "list_tables", fail_listing) + table_id = namespace_path + ["events"] + assert db.table_exists(table_id) is True + assert await adb.table_exists(table_id) is True + assert db.table_exists(namespace_path + ["missing"]) is False + assert await adb.table_exists(namespace_path + ["missing"]) is False + assert ("events" in db) is (not namespace_path) + assert "missing" not in db + assert table_id == namespace_path + ["events"] + + db.drop_table("events", namespace_path=namespace_path) + assert db.table_exists(table_id) is False + assert await adb.table_exists(table_id) is False + + @pytest.mark.asyncio async def test_table_names_async(tmp_path): db = lancedb.connect(tmp_path) diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 5eb9c02bd..9bce1059d 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -34,6 +34,27 @@ PUSHDOWN_DATA = pa.table( ) +@pytest.mark.asyncio +@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) +async def test_custom_namespace_table_exists_uses_namespace_api(table_id): + class ExistenceNamespace(LanceNamespace): + def namespace_id(self): + return "existence-test" + + def table_exists(self, request): + if request.id == ["missing"]: + raise TableNotFoundError("Table not found") + + def describe_table(self, request): + raise AssertionError("Custom existence checks must not open tables") + + namespace = ExistenceNamespace() + db = LanceNamespaceDBConnection(namespace) + adb = lancedb.AsyncLanceNamespaceDBConnection(namespace) + assert db.table_exists(table_id) is (table_id != ["missing"]) + assert await adb.table_exists(table_id) is (table_id != ["missing"]) + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -411,8 +432,16 @@ class TestNamespaceConnection: assert "test_ns" in db.list_namespaces().namespaces schema = pa.schema([pa.field("id", pa.int64())]) + db.create_table("root_table", schema=schema) + assert db.table_exists(["root_table"]) is True + assert "root_table" in db + assert db.table_exists(["missing"]) is False + assert "missing" not in db table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"]) assert table.namespace == ["test_ns"] + assert db.table_exists(["test_ns", "test_table"]) is True + assert db.table_exists(["test_ns", "missing"]) is False + assert "test_table" not in db assert "test_table" in db.table_names(namespace_path=["test_ns"]) assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables @@ -420,7 +449,10 @@ class TestNamespaceConnection: assert opened.namespace == ["test_ns"] db.drop_table("test_table", namespace_path=["test_ns"]) + assert db.table_exists(["test_ns", "test_table"]) is False assert db.list_tables(namespace_path=["test_ns"]).tables == [] + db.drop_table("root_table") + assert "root_table" not in db db.drop_namespace(["test_ns"]) assert "test_ns" not in db.list_namespaces().namespaces @@ -942,12 +974,18 @@ class TestAsyncNamespaceConnection: assert "test_ns" in (await db.list_namespaces()).namespaces schema = pa.schema([pa.field("id", pa.int64())]) + await db.create_table("root_table", schema=schema) + assert await db.table_exists(["root_table"]) is True + assert await db.table_exists(["missing"]) is False table = await db.create_table( "test_table", schema=schema, namespace_path=["test_ns"] ) assert table._namespace_path == ["test_ns"] assert table._namespace_client is None assert table._route_pushdown_to_rust is True + assert await db.table_exists(["test_ns", "test_table"]) is True + assert await db.table_exists(["test_ns", "missing"]) is False + assert await db.table_exists(["test_table"]) is False assert "test_table" in await db.table_names(namespace_path=["test_ns"]) assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables @@ -955,7 +993,10 @@ class TestAsyncNamespaceConnection: assert opened._namespace_path == ["test_ns"] await db.drop_table("test_table", namespace_path=["test_ns"]) + assert await db.table_exists(["test_ns", "test_table"]) is False assert (await db.list_tables(namespace_path=["test_ns"])).tables == [] + await db.drop_table("root_table") + assert await db.table_exists(["root_table"]) is False await db.drop_namespace(["test_ns"]) assert "test_ns" not in (await db.list_namespaces()).namespaces diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 407596d26..952437051 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -22,6 +22,7 @@ import time from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch import uuid +import warnings from packaging.version import Version from lance_namespace.errors import TableNotFoundError @@ -461,6 +462,31 @@ def test_remote_table_exists_rechecks_cached_table(): assert requests == ["/v1/table/ns$table/describe/"] * 2 +@pytest.mark.parametrize("status", [200, 404, 403]) +def test_remote_membership_uses_direct_lookup(status): + requests = [] + + def handler(request): + requests.append(request.path) + assert request.command == "POST" + assert request.path == "/v1/table/t129/describe/" + 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") + + with mock_lancedb_connection(handler) as db: + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + if status in (200, 404): + assert ("t129" in db) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + "t129" in db + assert exc_info.value.status_code == status + assert requests == ["/v1/table/t129/describe/"] + + def paginated_table_listing_handler(request): url = urlparse(request.path) assert url.path in { diff --git a/python/python/tests/test_sync_api_parity.py b/python/python/tests/test_sync_api_parity.py index a12efd0c9..230fb45c6 100644 --- a/python/python/tests/test_sync_api_parity.py +++ b/python/python/tests/test_sync_api_parity.py @@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table): ] -def respond(request, body): - request.send_response(200) +def respond(request, body, status=200): + request.send_response(status) request.send_header("Content-Type", "application/json") request.end_headers() request.wfile.write(json.dumps(body).encode()) @@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute): @pytest.mark.parametrize("tables", [[], ["first", "last"]]) -def test_remote_len_and_contains_follow_pages(tables): +def test_remote_len_paginates_and_contains_looks_up_table(tables): requests = [] def handler(request): requests.append(request.path) - query = parse_qs(urlparse(request.path).query) + url = urlparse(request.path) + if request.command == "POST": + name = url.path.split("/")[3] + assert url.path == f"/v1/table/{name}/describe/" + respond(request, {}, status=200 if name in tables else 404) + return + assert request.command == "GET" + assert url.path == "/v1/namespace/$/table/list" + query = parse_qs(url.query) if tables and "page_token" not in query: respond(request, {"tables": [tables[0]], "page_token": "opaque-next"}) else: @@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables): with mock_lancedb_connection(handler) as db: assert len(db) == len(tables) - assert ("last" in db) == bool(tables) - assert "missing" not in db + assert len(requests) == (2 if tables else 1) requests.clear() - assert ("first" in db) == bool(tables) - assert len(requests) == 1 + for name in ("last", "missing", "first"): + assert (name in db) is (name in tables) + assert requests == [f"/v1/table/{name}/describe/"] + requests.clear() @pytest.mark.parametrize("namespace", [[], ["parent", "child"]]) From 1dee9b006caf2d02de96daf3db3c3bf37c56633b Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 23:32:57 -0800 Subject: [PATCH 077/203] fix(python): reject unsupported Function callables early (#4972) Reject synchronous and asynchronous generator Functions, including class `__call__` methods, during decoration so invalid outputs never reach remote execution. Give actionable errors for lambdas and decorated wrappers such as `functools.lru_cache`. Defaulted callable inputs remain unsupported; the error now names the parameter and explains how to use class initialization fields. ```python @function def double(value: float) -> float: yield value * 2 # TypeError: generator Functions are not supported; return a value instead of # yielding, or return a list for multiple values ``` The deprecated `@udf` alias shares the validation. Adds regression coverage for both decorators, class methods, explicit schemas, and the supported list-return alternative. Fixes https://linear.app/lancedb/issue/ENT-3539 --- python/python/lancedb/functions.py | 39 ++++++- .../python/tests/test_function_packaging.py | 104 +++++++++++++++++- 2 files changed, 138 insertions(+), 5 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 4bf028306..74cc2adf4 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1298,6 +1298,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError(f"unsupported Function annotation: {annotation!r}") +def _validate_callable(function: Any) -> None: + if hasattr(function, "__wrapped__"): + raise TypeError( + "decorated wrappers are not supported; put caching inside the function " + "body or use a class Function with a cache in __init__" + ) + if inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function): + raise TypeError( + "generator Functions are not supported; return a value instead of " + "yielding, or return a list for multiple values" + ) + if inspect.isfunction(function) and function.__name__ == "": + raise TypeError("lambda Functions are not supported; use a named def instead") + + def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Parameter, ...]: parameters = tuple(inspect.signature(function).parameters.values()) for parameter in parameters: @@ -1308,7 +1323,11 @@ def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Paramete ): raise TypeError("Function callables require named, non-variadic parameters") if parameter.default is not inspect.Parameter.empty: - raise TypeError("Function callable defaults are not supported") + raise TypeError( + f"Function callable defaults are not supported: {parameter.name!r}; " + "move configuration parameters to a class Function's __init__ " + "and pass them as binding-time initialization values" + ) return parameters @@ -2201,6 +2220,7 @@ def _class_member(cls: type, name: str) -> Any: def _class_call(cls: type) -> Callable[..., Any]: call = _class_member(cls, "__call__") + _validate_callable(call) if not inspect.isfunction(call) or inspect.iscoroutinefunction(call): raise TypeError("a class Function must define a synchronous __call__ method") close = _class_member(cls, "close") @@ -2257,12 +2277,10 @@ class FunctionDefinition: if not is_class and ( not inspect.isfunction(function) or inspect.iscoroutinefunction(function) ): + _validate_callable(function) raise TypeError( "@function requires a synchronous Python function or a class" ) - function_name = name or function.__name__ - if not _FUNCTION_NAME.fullmatch(function_name): - raise ValueError(f"invalid Function name: {function_name!r}") if pip and conda: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: @@ -2324,6 +2342,11 @@ class FunctionDefinition: "model Functions reserve environment variables " f"{reserved!r}; the worker sets them for the private snapshot" ) + if not is_class: + _validate_callable(function) + function_name = name or function.__name__ + if not _FUNCTION_NAME.fullmatch(function_name): + raise ValueError(f"invalid Function name: {function_name!r}") if is_class: if "<" in function.__qualname__ or "." in function.__qualname__: raise ValueError( @@ -2555,6 +2578,14 @@ def function( reuses them. An instance serves many batches of one binding, so state is shared across them, but not across instances or workers. + Functions and ``__call__`` methods must return a value. Generators, + including async generators, are not supported; return a list to produce + multiple values for a list output. Lambdas and decorated wrappers such as + ``functools.lru_cache`` are not supported. Use a named ``def`` and keep + caches inside the body or in a class instance initialized by ``__init__``. + Callable input parameters cannot have defaults; move configurable values + to class initialization fields instead. + **Initialization.** The annotated parameters of a class's ``__init__`` are the Function's initialization fields. Their values belong to each binding, not to the Function: ``function(text=col("body"), model="small")`` diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 83dfdaeb3..440adc4da 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,7 +20,7 @@ import pyarrow as pa import pytest from lancedb import col -from lancedb.functions import FunctionDefinition, FunctionVersion, function +from lancedb.functions import FunctionDefinition, FunctionVersion, function, udf FIXTURES = ( Path(__file__).parents[3] @@ -127,6 +127,108 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_schemas", [False, True]) +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize( + ("declaration", "statement"), + [ + ("def", "yield value"), + ("def", "yield from [value]"), + ("async def", "yield value"), + ], +) +def test_generator_functions_are_rejected_at_decoration( + helper_package, decorator, explicit_schemas, class_function, declaration, statement +): + signature = ( + "__call__(self, value: int)" if class_function else "generates(value: int)" + ) + source = f"{declaration} {signature} -> int:\n {statement}\n" + if class_function: + source = "class generates:\n" + textwrap.indent(source, " ") + module = helper_package("fx_generator", {"__init__.py": source}) + options = ( + { + "input_schema": pa.schema([pa.field("value", pa.int64(), nullable=False)]), + "output_schema": pa.int64(), + } + if explicit_schemas + else {} + ) + with pytest.raises(TypeError) as error: + decorator(**options)(module.generates) + message = str(error.value) + assert "generator Functions are not supported" in message + assert "return a value" in message + assert "return a list" in message + + +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_name", [False, True]) +def test_lambda_functions_explain_the_named_alternative(decorator, explicit_name): + options = {"name": "double"} if explicit_name else {} + with pytest.raises(TypeError, match="lambda.*use a named def"): + decorator(**options)(lambda value: value * 2) + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("cache_decorator", ["lru_cache", "cache"]) +def test_cached_functions_explain_where_to_keep_caches( + helper_package, class_function, cache_decorator +): + signature = "__call__(self, value: int)" if class_function else "cached(value: int)" + source = ( + f"@functools.{cache_decorator}\ndef {signature} -> int:\n return value * 2\n" + ) + if class_function: + source = "class cached:\n" + textwrap.indent(source, " ") + module = helper_package("fx_cached", {"__init__.py": "import functools\n" + source}) + with pytest.raises(TypeError) as error: + function(module.cached) + message = str(error.value) + assert "decorated wrappers are not supported" in message + assert "inside the function body" in message + assert "class Function with a cache in __init__" in message + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("keyword_only", [False, True]) +def test_callable_defaults_explain_class_initialization( + helper_package, class_function, keyword_only +): + parameters = "value: float, " + ("*, " if keyword_only else "") + parameters += "threshold: float = 0.5" + signature = ( + f"__call__(self, {parameters})" + if class_function + else f"thresholded({parameters})" + ) + source = f"def {signature} -> bool:\n return value >= threshold\n" + if class_function: + source = "class thresholded:\n" + textwrap.indent(source, " ") + module = helper_package("fx_defaults", {"__init__.py": source}) + with pytest.raises(TypeError) as error: + function(module.thresholded) + message = str(error.value) + assert "defaults are not supported: 'threshold'" in message + assert "class Function's __init__" in message + assert "binding-time initialization values" in message + + +def test_function_can_return_a_list_from_a_generator_expression(): + @function + def many(value: int) -> list[int]: + return list(item * 2 for item in range(value)) + + namespace = {} + exec(compile(artifact(many), "user_function.py", "exec"), namespace) + assert namespace["many"](3) == [0, 2, 4] + assert many.registration_request.signature.output.arrow_type == "list" + + @pytest.mark.parametrize("kind", ["function", "class"]) @pytest.mark.parametrize( ("global_value", "value_type"), From 5a38066234552fc1bd9826d12d71fc88fd64be93 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 12 Nov 2026 16:09:13 +0800 Subject: [PATCH 078/203] chore(deps): upgrade Lance to v15.0.0-beta.18 (#4965) Upgrade the Rust Lance dependency, Java lance-core, and Python test dependency from beta.17 to the officially published [v15.0.0-beta.18](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.18) (`079fd77683a7acf056b0912f6ecda938e39ee120`). This provides a compatible SDK for the newer Lance source already adopted downstream. Rust registry versions and checksums are unchanged; the Python lock uses the six published beta.18 wheels. ### Compatibility The adopted release includes [Lance #10863](https://github.com/lance-format/lance/pull/10863): `FilteredReadOptionsProto.has_fragment_ids` distinguishes an explicit empty fragment selection. Older executors ignore this field, so upgrade executors before relying on the corrected empty-selection behavior. Rust callers constructing this generated struct need the new field. [Lance #10112](https://github.com/lance-format/lance/pull/10112) also replaces the internal `hamming_distance_batch` API with `hamming_distance_batch_into`. The Linux Python matrix timeout is raised from 30 to 60 minutes: the Python 3.13 cold native build and both test passes completed, but the job hit its limit during cleanup. Build profiles, test commands, and coverage are unchanged. ### Validation - Three native FRI/ANN regressions passed: deferred-compaction refined RQ, deferred index remapping, and approximate-query builder. - `cargo clippy --quiet --locked --features remote --tests --examples -- -D warnings` passed with pinned Rust 1.97.0. - Locked metadata, formatting, Python Makefile-scope Ruff checks, and `uv lock --check --offline` passed. - YAML, whitespace, end-of-file, and typo checks passed for the timeout-only workflow change. ### Publication and CI Java beta.18 is now published. After [Lance #10968](https://github.com/lance-format/lance/pull/10968) merged, the [normal publication workflow](https://github.com/lance-format/lance/actions/runs/43146352505) built all three JNI targets and published successfully; the Maven jar is available. The upstream Python publication run was cancelled after its Windows ARM job hit the one-hour timeout; six other wheels were published and are the actual artifacts recorded in this lock. Cross-platform SDK CI is still required. No performance claim is made by this dependency update. --- .github/workflows/python.yml | 3 +- Cargo.lock | 96 ++++++++++++++++++------------------ Cargo.toml | 30 +++++------ java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 16 +++--- 6 files changed, 75 insertions(+), 74 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2fabb4a6a..e208ac7cd 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -130,7 +130,8 @@ jobs: run: pytest --doctest-modules python/lancedb linux: name: "Linux: python-3.${{ matrix.python-minor-version }}" - timeout-minutes: 30 + # A cold native build plus both test passes can exhaust 30 minutes. + timeout-minutes: 60 strategy: matrix: python-minor-version: ["10", "13"] diff --git a/Cargo.lock b/Cargo.lock index f38252fc5..4e6d2665a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3825,8 +3825,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5313,8 +5313,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5389,8 +5389,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5412,7 +5412,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5426,7 +5426,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5435,8 +5435,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrayref", "crunchy", @@ -5446,8 +5446,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5485,8 +5485,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5517,8 +5517,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5543,8 +5543,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5561,8 +5561,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "proc-macro2", "quote", @@ -5571,8 +5571,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5605,8 +5605,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5637,8 +5637,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5669,8 +5669,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5742,8 +5742,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5766,8 +5766,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5812,8 +5812,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "byteorder", "ethnum", @@ -5830,8 +5830,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5846,8 +5846,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "async-trait", @@ -5861,8 +5861,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5931,8 +5931,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5973,8 +5973,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5987,8 +5987,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 9fc33e6ab..c45eef6da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 610c095b9..9356288dc 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.17 + 15.0.0-beta.18 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 5ba1d4bbf..6940dce4f 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b17", + "pylance==15.0.0b18", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 01693079f..369d558d2 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b17" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b18" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b17" +version = "15.0.0b18" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,12 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_il4JF/pylance-15.0.0b17-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:ee3c3d2baf1f0d788d706638873317740178a81988b71ffda47a2e71d1e15ff3" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2hFd0a/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a5b576e35054d4866d823ebadc9d3c531165628feb29ca1528db15b9082675a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_29zVw5/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47c534032d2f251f396657e47efbc224ee2d1964495d7982a449e5e1cdcf3169" }, - { url = "https://pypi.fury.io/lance-format/-/ver_548nr/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:509db7d8be3eebb111b7d28aa486437424cb3663cfb7f502b71532fa37ba7155" }, - { url = "https://pypi.fury.io/lance-format/-/ver_gmpNu/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd2cc05c2d553d44c54570612e793136e3433fcba28e4d51a503cca8f45435ea" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Otspk/pylance-15.0.0b17-cp310-abi3-win_amd64.whl", hash = "sha256:510c419e21a4daa4c18db4cc5048bd7dfc706924b23e13136306935f2e3e0c25" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" }, ] [[package]] From 01e9ea44aa0609630cec2f3f728198a36374befd Mon Sep 17 00:00:00 2001 From: Lance Release Date: Thu, 12 Nov 2026 08:12:34 +0000 Subject: [PATCH 079/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.11=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.12?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 076443831..e4989d1eb 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.11" +current_version = "0.42.0-beta.12" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 4e6d2665a..efe0338cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6001,7 +6001,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "ahash", "anyhow", @@ -6112,7 +6112,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "anyhow", "arrow-array", @@ -6155,7 +6155,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arrow-array", "arrow-buffer", @@ -6180,7 +6180,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index c06b4f230..ca77b251c 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.42.0-beta.11 + 0.42.0-beta.12 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 903be2b77..792b434a1 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.11 + 0.42.0-beta.12 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9356288dc..df709fb4f 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.11 + 0.42.0-beta.12 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 91d808647..22cfe6ecc 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.11" +version = "0.42.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 1a9011b34..283a32fdc 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.42.0-beta.11", + "version": "0.42.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 00b2918d6..5fd392245 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.42.0-beta.11", + "version": "0.42.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 f94f27216..ec5103284 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.42.0-beta.11", + "version": "0.42.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 e0eefa2e9..1d45a2ed2 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.42.0-beta.11", + "version": "0.42.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 f0891fbed..d17a3b4e7 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.42.0-beta.11", + "version": "0.42.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 04b65ba86..a7c4a74b6 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.42.0-beta.11", + "version": "0.42.0-beta.12", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e5e0effab..0e3a4a626 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.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a03e1a794..b0d99fb60 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 7c11d5fdf..5a2923216 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.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 cbb0142e1..737c385c1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index cde8b295a..b22a3b8d8 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" edition = "2021" license.workspace = true repository.workspace = true From 478d1d9b0103971dbd31be655bfb7e5073995bd5 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 00:30:19 -0800 Subject: [PATCH 080/203] fix: expose comparable Function runtime identity (#4975) Expose `FunctionVersion.runtime_digest` through Rust and Python, and add `PythonRuntimeSpec.digest` so clients can compare declared environment inputs before registering a Function. Dependency pins, environment variables, Python version, and GPU settings affect this digest; package ordering does not. Clarify that matching `source_digest` alone is insufficient for reuse. Older servers/images leave `runtime_digest` unset, which cannot establish a match. Both digests and the other registration inputs must match before reusing a version. ```python request = definition.registration_request same_source = version.source_digest == request.artifact.digest same_runtime = version.runtime_digest == request.runtime.digest ``` Add shared runtime digest fixtures and coverage for environment-only changes and catalog decoding. Local builds and tests were skipped as requested. --- python/python/lancedb/functions.py | 39 +++ .../tests/test_first_class_function_slice1.py | 34 ++- .../tests/test_first_class_function_slice2.py | 28 ++ python/python/tests/test_remote_db.py | 3 + rust/lancedb/src/function.rs | 39 ++- .../v1/runtime_identity.json | 269 ++++++++++++++++++ 6 files changed, 410 insertions(+), 2 deletions(-) create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 74cc2adf4..a5c741cd8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -495,6 +495,35 @@ class PythonRuntimeSpec(_RemoteValue): object.__setattr__(self, "gpu_class", None) return self + @property + def digest(self) -> str: + """SHA-256 identity of the declared runtime, before building an image. + + Covers Python version, environment sources, environment variables, and + GPU settings. Package and system-package order is ignored; conda channel + order is preserved. Compare with ``runtime_digest`` on + [FunctionVersion][lancedb.functions.FunctionVersion]. + This identifies build inputs, not the resolved contents of unpinned + dependencies or the deployment's default base image. + """ + if self.kind not in {"python", "python_v2"}: + raise ValueError(f"cannot digest unknown runtime kind {self.kind!r}") + value = self._known_dict() + if not value.get("env"): + value.pop("env", None) + environment = value["environment"] + for field in ("packages", "system_packages"): + if field in environment: + environment[field] = sorted(environment[field]) + encoded = json.dumps( + value, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return f"sha256:{hashlib.sha256(encoded).hexdigest()}" + class FunctionImage(_RemoteValue): """A complete OCI Function image identified by its exact manifest digest.""" @@ -536,8 +565,17 @@ class FunctionVersion(_RemoteValue): of the built ``image``. Compare it with ``definition.registration_request.artifact.digest`` to check whether a local [FunctionDefinition][lancedb.functions.FunctionDefinition] has the same source. + It does not cover dependencies, environment variables, Python version, or + GPU settings. Equal source digests alone do not mean a version can be reused. It is ``None`` when the server does not provide a source digest. + ``runtime_digest`` identifies the declared environment inputs. Compare it + with ``definition.registration_request.runtime.digest`` to check whether + the local runtime matches. It is ``None`` for images built before runtime + identity was exposed. A missing digest cannot establish a match. Reusing a + version also requires matching the source and all other registration inputs, + including signature, Secret bindings, models, and execution controls. + ``gpu_class`` is the operator-defined GPU pool fixed into this Function version, or ``None`` when registration used the deployment default. @@ -554,6 +592,7 @@ class FunctionVersion(_RemoteValue): version: _ObjectVersion image: FunctionImage source_digest: Optional[str] = None + runtime_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 f8e225183..867672fe9 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -34,7 +34,7 @@ FIXTURES = ( def fixture(name: str) -> str: - return (FIXTURES / name).read_text() + return (FIXTURES / name).read_text(encoding="utf-8") def job_result(name: str) -> dict: @@ -148,6 +148,38 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize( + "case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"] +) +def test_runtime_digests_match_server_golden_values(case): + runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"])) + assert runtime.digest == case["digest"] + assert ( + PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest + == runtime.digest + ) + + +def test_unknown_runtime_digest_fails_closed(): + runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}') + with pytest.raises(ValueError, match="cannot digest unknown runtime kind"): + runtime.digest + + +@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"]) +def test_function_version_preserves_runtime_digest(runtime_digest): + value = job_result("remote_function_job.json") + legacy = FunctionVersion.from_json(json.dumps(value)) + assert legacy.runtime_digest is None + assert "runtime_digest" not in json.loads(legacy.to_canonical_json()) + value["runtime_digest"] = runtime_digest + version = FunctionVersion.from_json(json.dumps(value)) + assert version.runtime_digest == runtime_digest + assert FunctionVersion.from_json(version.to_canonical_json()) == version + with pytest.raises((TypeError, ValueError)): + version.runtime_digest = "sha256:changed" + + @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") diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 2cc731892..d99a7aa21 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1891,6 +1891,29 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): return value +def test_default_function_runtime_matches_server_identity(): + definition = function(python_version="3.12")(analyze_caption.__wrapped__) + runtime = definition.registration_request.runtime + assert runtime.env == {} + cases = json.loads((FIXTURES / "runtime_identity.json").read_text(encoding="utf-8")) + expected = next( + case["digest"] for case in cases if case["name"] == "empty-environment" + ) + assert runtime.digest == expected + + +def test_environment_changes_do_not_change_source_identity(): + definition = function( + pip=["openai==3.46.0"], + env={"MODE": "test"}, + python_version="3.12", + )(analyze_caption.__wrapped__) + previous = analyze_caption.registration_request + changed = definition.registration_request + assert previous.artifact.digest == changed.artifact.digest + assert previous.runtime.digest != changed.runtime.digest + + def test_local_function_catalog_operations_are_not_supported(tmp_path): db = lancedb.connect(tmp_path) message = "Function catalog operations are not supported by this database" @@ -1950,6 +1973,7 @@ async def test_async_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -1977,6 +2001,7 @@ def test_sync_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -2090,6 +2115,9 @@ def _mock_remote_function_catalog(): )["image"], "signature": body["signature"], "source_digest": body["artifact"]["digest"], + "runtime_digest": PythonRuntimeSpec.from_json( + json.dumps(body["runtime"]) + ).digest, "secret_bindings": body.get("secret_bindings", []), "created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z } diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 952437051..b0098aca3 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -6304,6 +6304,8 @@ def test_remote_function_registration_transports_max_concurrency(): def registered(value: float) -> float: return value + definition["runtime_digest"] = registered.registration_request.runtime.digest + class RegistrationServer(flight.FlightServerBase): def __init__(self): super().__init__("grpc://127.0.0.1:0") @@ -6322,6 +6324,7 @@ def test_remote_function_registration_transports_max_concurrency(): assert len(server.tickets) == 1 assert b'"max_concurrency":4' in server.tickets[0] assert version.max_concurrency == 4 + assert version.runtime_digest == registered.registration_request.runtime.digest @pytest.mark.asyncio diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 3566fc938..e3d47948e 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -594,6 +594,8 @@ pub struct FunctionVersion { image: FunctionImage, #[serde(default, skip_serializing_if = "Option::is_none")] source_digest: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime_digest: Option, signature: FunctionSignature, #[serde(default, skip_serializing_if = "Vec::is_empty")] secret_bindings: Vec, @@ -665,7 +667,9 @@ impl FunctionVersion { /// 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. + /// source, independently of the built image's manifest digest. It excludes + /// dependencies, environment variables, Python version, and GPU settings; + /// matching source alone does not establish that a version can be reused. /// /// ``` /// use lancedb::function::{FunctionArtifactRequest, FunctionVersion}; @@ -678,6 +682,15 @@ impl FunctionVersion { self.source_digest.as_deref() } + /// Digest of canonical runtime inputs, when provided by the server. + /// + /// Includes Python version, environment sources, variables, and GPU settings. + /// A missing digest cannot establish that a local runtime matches. Reusing a + /// version also requires matching its source and other registration inputs. + pub fn runtime_digest(&self) -> Option<&str> { + self.runtime_digest.as_deref() + } + /// Operator-defined GPU class declared at registration. pub fn gpu_class(&self) -> Option<&str> { self.gpu_class.as_deref() @@ -1329,6 +1342,30 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn function_version_preserves_runtime_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.runtime_digest(), None); + assert_eq!(legacy.to_canonical_json().unwrap(), VERSION.trim_end()); + for digest in [Value::Null, serde_json::json!("sha256:runtime-inputs")] { + document["runtime_digest"] = digest.clone(); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime_digest(), digest.as_str()); + 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("runtime_digest").is_none()); + } else { + assert_eq!(encoded_value["runtime_digest"], digest); + } + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + } + } + #[test] fn function_version_preserves_source_digest() { const VERSION: &str = include_str!( diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json new file mode 100644 index 000000000..7bf0c375c --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json @@ -0,0 +1,269 @@ +[ + { + "name": "pip", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "reordered-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "numpy==2.2.0", + "openai==3.40.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "changed-pin", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.46.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:43da49cfcf8ecd47becb5be20b9eff06c5267f9244c18e751b230c624f5ad12a" + }, + { + "name": "changed-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "prod", + "LABEL": "你好" + } + }, + "digest": "sha256:9b305e9188f4ddda5a0b72d2235c2c46ba50de9bf82c699f5060b02e4aa0820d" + }, + { + "name": "changed-python", + "runtime": { + "kind": "python", + "python_version": "3.11", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:8fa58561581414b02d0619e466e3720828d1820d8211b0e73c90ec4b0d3ecd0c" + }, + { + "name": "gpu", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true + }, + "digest": "sha256:3ea9354ff101038937b1f5a3b6639c4cc6dcb88ee975dcb8e1a5dee2500c283c" + }, + { + "name": "gpu-class", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true, + "gpu_class": "a100" + }, + "digest": "sha256:253f0641ef029aed8337bbcb210f7769147d671747406f7ce4fa5dc40d5c5efc" + }, + { + "name": "conda", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "conda-forge", + "defaults" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:9246f88a6b1daceb3090c51930650ea967947142cdc70737c847a6bf72c85d30" + }, + { + "name": "reordered-channels", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "defaults", + "conda-forge" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:12ef13a6f5b8730a719288ab2406e7f6c13634b14dbef2390f0bbe62f847e18d" + }, + { + "name": "system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "zlib1g", + "ffmpeg" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "reordered-system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "ffmpeg", + "zlib1g" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "empty-environment", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + } + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-fields", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [], + "channels": [], + "modules": [], + "system_packages": [] + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + } +] From 7b2dfb9e361bddfbf4b3e16f2d950f377d5b5e33 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:19:05 -0800 Subject: [PATCH 081/203] fix(python): align catalog and database connection inputs (#4983) Align Python catalog connection inputs with database connections, warn when region is ignored, and preserve remote storage settings in opened databases. --- docs/web/basics/catalog.mdx | 18 +++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/catalog.py | 154 ++++++++++++++++++++++-- python/python/lancedb/remote/db.py | 3 +- python/python/tests/test_catalog.py | 176 +++++++++++++++++++++++++++- python/python/type_tests/connect.py | 20 +++- python/src/catalog.rs | 8 +- rust/lancedb/src/catalog.rs | 12 ++ rust/lancedb/src/remote/catalog.rs | 10 ++ rust/lancedb/src/remote/db.rs | 2 +- 10 files changed, 389 insertions(+), 15 deletions(-) diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index 1e95aeca4..519d86067 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -158,6 +158,24 @@ 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. +In Python, `connect_catalog` and `connect_catalog_async` accept the same +connection settings as their database counterparts. Use `host_override` to +share settings that include a `db://` URI; the catalog connection targets +the root of that deployment and ignores the database name. An explicitly +supplied `region` is ignored with a warning, since the HTTP(S) endpoint +selects the deployment. Embedded-only session and namespace settings are +unsupported. + +```python +settings = { + "uri": "db://analytics", + "api_key": "secret", + "host_override": "https://my-server.example", +} +db = lancedb.connect(**settings) +catalog = lancedb.connect_catalog(**settings) +``` + This connection is for database administration, not table or query work: list, create and drop databases through it, then switch to a **database** connection for everything else -- tables, queries, and SQL all run within a diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 521cc46bb..11798a520 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1227,6 +1227,7 @@ async def connect_catalog( sql_host_override: Optional[str] = None, read_consistency_interval: Optional[float] = None, oauth_config: Optional[Any] = None, + storage_options: Optional[dict[str, str]] = None, ) -> Catalog: ... class NameListing: diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py index 338be98b8..5b3b0509c 100644 --- a/python/python/lancedb/catalog.py +++ b/python/python/lancedb/catalog.py @@ -3,13 +3,17 @@ """Remote catalogs manage databases.""" -from functools import cached_property +import os +import warnings +from concurrent.futures import ThreadPoolExecutor from datetime import timedelta +from functools import cached_property from typing import Any, AsyncIterator, Iterator, Optional, Union from . import _lancedb from .background_loop import LOOP from .authz import AsyncAuthorization, Authorization +from .common import URI, sanitize_uri from .db import AsyncConnection, DBConnection from .remote import ClientConfig, OAuthConfig from .remote.db import RemoteDBConnection @@ -163,12 +167,14 @@ class Catalog: client_config=None, sql_host_override: Optional[str] = None, oauth_config: Optional[OAuthConfig] = None, + storage_options: Optional[dict[str, str]] = None, ): self._inner = inner self._api_key = api_key self._client_config = client_config self._sql_host_override = sql_host_override self._oauth_config = oauth_config + self._storage_options = storage_options @cached_property def authz(self) -> Authorization: @@ -198,6 +204,7 @@ class Catalog: self._client_config, self._oauth_config, self._sql_host_override, + self._storage_options, ) def list_databases( @@ -227,28 +234,71 @@ class Catalog: async def connect_catalog_async( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_properties: Optional[dict[str, str]] = None, oauth_config: Optional[OAuthConfig] = None, ) -> AsyncCatalog: - """Connect to an HTTP(S) server's root catalog. + """Connect to a server's root catalog using database connection settings. + + ``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise + ``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with + [connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's + database is ignored and requests target the root catalog. + + ``region`` is ignored with a warning when supplied. Catalog connections use + the explicit endpoint rather than a region-derived Cloud (legacy) endpoint. + ``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable. + Embedded-only ``session``, ``manifest_enabled`` and + ``namespace_client_properties`` are not supported. Root requests omit database-selection headers. API key, client configuration, - OAuth, and table read consistency settings are inherited by opened databases. + OAuth, storage options, and table read consistency settings are inherited by + opened databases. Database names containing slashes remain single logical names. Set ``sql_host_override`` to the SQL service endpoint to execute SQL through returned connections when the catalog endpoint uses HTTPS. """ + if region is not None: + warnings.warn( + "region is ignored by connect_catalog_async; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + for name, value in ( + ("session", session), + ("manifest_enabled", manifest_enabled or None), + ("namespace_client_properties", namespace_client_properties), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + endpoint = host_override if host_override is not None else uri + if endpoint is None: + raise ValueError("uri or host_override is required for catalog connections") if isinstance(client_config, dict): client_config = ClientConfig(**client_config) if client_config is None: client_config = ClientConfig() + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") inner = await _lancedb.connect_catalog( - endpoint, + sanitize_uri(endpoint), api_key=api_key, client_config=client_config, sql_host_override=sql_host_override, @@ -258,32 +308,115 @@ async def connect_catalog_async( else None ), oauth_config=oauth_config, + storage_options=storage_options, ) return AsyncCatalog(inner) def connect_catalog( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_impl: Optional[str] = None, + namespace_client_properties: Optional[dict[str, str]] = None, + namespace_client_pushdown_operations: Optional[list[str]] = None, oauth_config: Optional[OAuthConfig] = None, + **kwargs: Any, ) -> Catalog: - """Connect synchronously to an HTTP(S) server's root catalog. + """Connect synchronously to a root catalog using database connection settings. See [connect_catalog_async][lancedb.connect_catalog_async] for options. + The inputs match [connect][lancedb.connect]; ``region`` is ignored with a + warning when supplied. Namespace client options and embedded session settings + are not supported. ``request_thread_pool`` is deprecated and unused, as in + ``connect``. Local filesystem and object-store catalogs are not supported. + + Examples + -------- + ```python + settings = {"api_key": "secret", "host_override": "https://my-server.example"} + catalog = lancedb.connect_catalog("db://analytics", **settings) + db = lancedb.connect("db://analytics", **settings) + ``` """ + 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}") + for name, value in ( + ("namespace_client_impl", namespace_client_impl), + ("namespace_client_pushdown_operations", namespace_client_pushdown_operations), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + if region is not None: + warnings.warn( + "region is ignored by connect_catalog; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + if request_thread_pool is not None: + warnings.warn( + "request_thread_pool is no longer used and will be removed in " + "a future release.", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(client_config, dict): + client_config = ClientConfig(**client_config) + if client_config is None: + client_config = ClientConfig() + for name, field in ( + ("connection_timeout", "connect_timeout"), + ("read_timeout", "read_timeout"), + ): + if kwargs.get(name) is not None: + warnings.warn( + f"{name} is deprecated and will be removed in a future release. " + f"Please use client_config.timeout_config.{field} instead.", + DeprecationWarning, + stacklevel=2, + ) + setattr( + client_config.timeout_config, + field, + timedelta(seconds=kwargs[name]), + ) + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") return Catalog( LOOP.run( connect_catalog_async( - endpoint, + uri, api_key=api_key, + host_override=host_override, client_config=client_config, sql_host_override=sql_host_override, read_consistency_interval=read_consistency_interval, + storage_options=storage_options, + session=session, + manifest_enabled=manifest_enabled, + namespace_client_properties=namespace_client_properties, oauth_config=oauth_config, ) ), @@ -291,4 +424,5 @@ def connect_catalog( client_config=client_config, sql_host_override=sql_host_override, oauth_config=oauth_config, + storage_options=storage_options, ) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 21ad37b36..4219ca40b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -214,6 +214,7 @@ class RemoteDBConnection(DBConnection): client_config, oauth_config, sql_host_override, + storage_options, ): config = ( ClientConfig(**client_config) @@ -233,7 +234,7 @@ class RemoteDBConnection(DBConnection): result.region = "us-east-1" result.host_override = endpoint result.sql_host_override = sql_host_override - result.storage_options = None + result.storage_options = storage_options result.client_config = replace(config, extra_headers=headers) result._catalog_oauth = oauth_config is not None result._conn = inner diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py index 95b03c6e7..edac21bc1 100644 --- a/python/python/tests/test_catalog.py +++ b/python/python/tests/test_catalog.py @@ -2,7 +2,9 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from datetime import timedelta import json +import warnings import pytest @@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): endpoint, api_key="secret", sql_host_override="invalid://localhost", + storage_options={"azure_storage_account_name": "catalog-account"}, client_config={ "extra_headers": { "X-LanceDB-Database": "wrong", @@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): assert db.table_names() == [] restored = lancedb.deserialize_conn(db.serialize()) assert restored.sql_host_override == "invalid://localhost" + assert restored.storage_options == {"azure_storage_account_name": "catalog-account"} for connection in (db, restored): with pytest.raises(ValueError, match="sql_host_override must use"): connection.execute_query_async("SELECT 1") @@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): ) assert "x-lancedb-database-prefix" not in headers assert headers["x-api-key"] == "secret" + assert headers["x-azure-storage-account-name"] == "catalog-account" @pytest.mark.asyncio @@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server): ] ) catalog = await lancedb.connect_catalog_async( - endpoint, sql_host_override="invalid://localhost" + endpoint, + sql_host_override="invalid://localhost", + storage_options={"account_name": "async-account"}, ) assert isinstance(catalog, lancedb.AsyncCatalog) db = await catalog.connect_database("analytics") @@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server): await catalog.drop_database("full") await catalog.drop_database("missing", ignore_missing=True) assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"} + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-azure-storage-account-name"] == "async-account" @pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"]) @@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint): lancedb.connect_catalog(endpoint) +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"]) +@pytest.mark.asyncio +async def test_catalog_accepts_database_connection_settings( + catalog_server, asynchronous, region +): + endpoint, requests, responses = catalog_server + responses.extend([(200, {"namespaces": []}), (200, {"tables": []})]) + settings = { + "uri": "db://analytics", + "api_key": "shared-secret", + "region": region, + "host_override": endpoint, + "sql_host_override": "invalid://localhost", + "read_consistency_interval": timedelta(seconds=5), + "client_config": {"extra_headers": {"x-shared-setting": "shared"}}, + "storage_options": {"azure_storage_account_name": "shared-account"}, + "session": None, + "manifest_enabled": False, + "namespace_client_properties": None, + } + if not asynchronous: + settings.update( + request_thread_pool=None, + namespace_client_impl=None, + namespace_client_pushdown_operations=None, + ) + with pytest.warns( + UserWarning, match="region is ignored by connect_catalog" + ) as caught: + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert len(caught) == 1 + assert catalog.uri == endpoint + assert ( + [name async for name in catalog.list_databases()] + if asynchronous + else list(catalog.list_databases()) + ) == [] + db = ( + await lancedb.connect_async(**settings) + if asynchronous + else lancedb.connect(**settings) + ) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + root_headers = {key.lower(): value for key, value in requests[0][1].items()} + db_headers = {key.lower(): value for key, value in requests[1][1].items()} + for headers in (root_headers, db_headers): + assert headers["x-api-key"] == "shared-secret" + assert headers["x-shared-setting"] == "shared" + assert headers["x-azure-storage-account-name"] == "shared-account" + assert "x-lancedb-database" not in root_headers + assert db_headers["x-lancedb-database"] == "analytics" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("host_only", [False, True]) +@pytest.mark.asyncio +async def test_catalog_default_region_is_silent_and_api_key_uses_environment( + catalog_server, monkeypatch, asynchronous, host_only +): + endpoint, requests, responses = catalog_server + monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret") + responses.extend([(200, {}), (200, {"tables": []})]) + settings = {"host_override": endpoint} if host_only else {"uri": endpoint} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert caught == [] + assert catalog.uri == endpoint + db = ( + await catalog.connect_database("analytics") + if asynchronous + else catalog.connect_database("analytics") + ) + if not asynchronous: + db = lancedb.deserialize_conn(db.serialize()) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-api-key"] == "environment-secret" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous): + endpoint, _, _ = catalog_server + settings = {"uri": "https://unused.example", "host_override": endpoint} + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert catalog.uri == endpoint + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options, message", + [ + ({}, "uri or host_override is required"), + ({"session": object()}, "session"), + ({"manifest_enabled": True}, "manifest_enabled"), + ({"namespace_client_properties": {}}, "namespace_client_properties"), + ], +) +@pytest.mark.asyncio +async def test_catalog_rejects_unsupported_connection_settings( + catalog_server, asynchronous, options, message +): + _, requests, _ = catalog_server + error = NotImplementedError if options else ValueError + with pytest.raises(error, match=message): + if asynchronous: + await lancedb.connect_catalog_async(**options) + else: + lancedb.connect_catalog(**options) + assert requests == [] + + +@pytest.mark.parametrize( + "options, error, message", + [ + ( + {"namespace_client_impl": "dir"}, + NotImplementedError, + "namespace_client_impl", + ), + ( + {"namespace_client_pushdown_operations": []}, + NotImplementedError, + "namespace_client_pushdown_operations", + ), + ({"unknown_option": True}, ValueError, "Unknown keyword arguments"), + ], +) +def test_catalog_rejects_unsupported_sync_settings(options, error, message): + with pytest.raises(error, match=message): + lancedb.connect_catalog(**options) + + +def test_catalog_accepts_deprecated_sync_settings(catalog_server): + endpoint, _, responses = catalog_server + responses.append((200, {})) + with pytest.warns(DeprecationWarning) as caught: + catalog = lancedb.connect_catalog( + endpoint, + request_thread_pool=2, + connection_timeout=5, + read_timeout=10, + ) + assert len(caught) == 3 + db = catalog.connect_database("analytics") + assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5) + assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10) + + @pytest.mark.parametrize("asynchronous", [False, True]) @pytest.mark.asyncio @pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)]) diff --git a/python/python/type_tests/connect.py b/python/python/type_tests/connect.py index eb2cba37c..6da32d2ec 100644 --- a/python/python/type_tests/connect.py +++ b/python/python/type_tests/connect.py @@ -4,12 +4,30 @@ from typing import assert_type import lancedb -from lancedb import AsyncConnection, DBConnection +from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection def check_connect_type() -> None: assert_type(lancedb.connect("memory://"), DBConnection) + assert_type( + lancedb.connect_catalog( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + Catalog, + ) async def check_connect_async_type() -> None: assert_type(await lancedb.connect_async("memory://"), AsyncConnection) + assert_type( + await lancedb.connect_catalog_async( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + AsyncCatalog, + ) diff --git a/python/src/catalog.rs b/python/src/catalog.rs index fb2e7e8a0..456d62a3c 100644 --- a/python/src/catalog.rs +++ b/python/src/catalog.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -127,7 +128,8 @@ impl DatabaseNames { } #[pyfunction] -#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None))] +#[allow(clippy::too_many_arguments)] +#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None, storage_options=None))] pub fn connect_catalog( py: Python<'_>, endpoint: String, @@ -136,6 +138,7 @@ pub fn connect_catalog( sql_host_override: Option, read_consistency_interval: Option, oauth_config: Option, + storage_options: Option>, ) -> PyResult> { let interval = read_consistency_interval .map(Duration::try_from_secs_f64) @@ -151,6 +154,9 @@ pub fn connect_catalog( if let Some(config) = client_config { builder = builder.client_config(config.into()); } + if let Some(options) = storage_options { + builder = builder.storage_options(options); + } if let Some(endpoint) = sql_host_override { builder = builder.sql_host_override(endpoint); } diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index df80b6de6..dcea8fd90 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -349,6 +349,18 @@ impl ConnectCatalogBuilder { self.options.client_config = config; self } + /// Set storage options inherited by the catalog's remote database connections. + pub fn storage_options( + mut self, + options: impl IntoIterator, impl Into)>, + ) -> Self { + self.options.storage_options.extend( + options + .into_iter() + .map(|(key, value)| (key.into(), value.into())), + ); + self + } /// Set the SQL service endpoint inherited by database connections. /// /// Required to execute SQL when the catalog endpoint uses HTTPS. The SQL diff --git a/rust/lancedb/src/remote/catalog.rs b/rust/lancedb/src/remote/catalog.rs index 95facd04b..c620cf272 100644 --- a/rust/lancedb/src/remote/catalog.rs +++ b/rust/lancedb/src/remote/catalog.rs @@ -30,6 +30,8 @@ pub struct RemoteCatalogOptions { pub api_key: Option, /// Shared transport and authentication settings. pub client_config: ClientConfig, + /// Storage options supported by remote database connections. + pub storage_options: HashMap, /// SQL service endpoint used by returned database connections. /// Required for SQL when the catalog endpoint uses HTTPS. pub sql_host_override: Option, @@ -391,6 +393,10 @@ mod tests { .await; let mut options = RemoteCatalogOptions { api_key: Some("test-key".into()), + storage_options: HashMap::from([( + "azure_storage_account_name".into(), + "catalog-account".into(), + )]), ..Default::default() }; options.client_config.extra_headers = HashMap::from([ @@ -460,6 +466,10 @@ mod tests { ); assert!(!request.headers.contains_key("x-lancedb-database-prefix")); assert_eq!(request.headers["authorization"], "Bearer refreshed"); + assert_eq!( + request.headers["x-azure-storage-account-name"], + "catalog-account" + ); } assert_eq!( requests[0].line, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a9d55b511..549baf345 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -385,7 +385,7 @@ impl RemoteDatabase { sql: options.sql_host_override.clone(), }, config, - RemoteOptions::default(), + StorageOptions(options.storage_options.clone()).into(), options.read_consistency_interval, super::client::ParsedDbUrl { db_name: name.unwrap_or("").to_string(), From ced4799ad51f7ee4dd4bdff40c061ef59d8bb014 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:21:58 -0800 Subject: [PATCH 082/203] fix(python): preserve typed results for reopened refresh jobs (#4981) Restore typed results for reopened Function and SQL-expression refresh jobs while preserving their handles and cached descriptions. Fixes https://linear.app/lancedb/issue/ENT-3441. --- python/python/lancedb/db.py | 10 +- python/python/lancedb/job.py | 7 ++ python/python/tests/test_remote_db.py | 138 ++++++++++++++++++++++++++ python/src/connection.rs | 11 +- rust/lancedb/src/job.rs | 51 ++++++++++ rust/lancedb/src/remote/job.rs | 23 +++++ 6 files changed, 236 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 84ebb41a1..e2138520a 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -67,7 +67,7 @@ from .graph import ( PropertyGraph, _definition_json, ) -from .job import AsyncJob, Job, _typed_job +from .job import AsyncJob, Job, _opened_job, _typed_job from .storage_integration import SecretReference, StorageIntegrationInfo from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery @@ -1450,6 +1450,12 @@ class DBConnection(EnforceOverrides): specification, result, failure and event history, so there is no separate connection-level call for any of them. + For a column refresh, ``wait()`` returns a + [RefreshColumnResult][lancedb.functions.RefreshColumnResult], including + when the refresh was started through SQL. Other job types return + ``None`` from ``wait()``; their persisted result is available through + ``job.result`` after ``job.refresh()``. + Raises `JobNotFoundError` when the server has no such job, the way `open_table` does for a missing table. """ @@ -3626,7 +3632,7 @@ class AsyncConnection(object): """Open a server-side job by id. See [DBConnection.open_job][lancedb.db.DBConnection.open_job]. """ - return AsyncJob(await self._inner.open_job(job_id)) + return _opened_job(await self._inner.open_job(job_id)) async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 094a7b8d5..bf9605567 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -17,6 +17,7 @@ from lancedb.background_loop import LOOP from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url +from .functions import RefreshColumnResult from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -692,3 +693,9 @@ def _typed_job( ) -> AsyncJob[T]: """Bind an internal JSON-producing job to its public result model.""" return AsyncJob(inner, result_decoder) + + +def _opened_job(inner: "_lancedb.Job") -> AsyncJob: + if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"): + return _typed_job(inner, RefreshColumnResult.from_json) + return AsyncJob(inner) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b0098aca3..8fde1209c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2557,6 +2557,144 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): assert exc.value.__cause__.is_transport_error is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "job_type", ["function_refresh", "computed_refresh", "refresh_column"] +) +@pytest.mark.parametrize("running", [False, True]) +@pytest.mark.parametrize("rows_failed", [0, 8]) +async def test_reopened_refresh_job_wait_returns_typed_result( + sync, job_type, running, rows_failed +): + terminal_result = { + "rows_assigned": 400 - rows_failed, + "rows_failed": rows_failed, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + "summary": {"future_field": True}, + } + polls = 0 + + def handler(request): + nonlocal polls + assert request.path == "/v1/jobs/describe" + payload = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert payload == {"job_id": "refresh-1"} + polls += 1 + in_progress = running and polls <= 2 + response = { + "job_id": "refresh-1", + "job_type": job_type, + "job_state": "IN_PROGRESS" if in_progress else "DONE", + "creation_ms": 1000, + "spec": {"column": "derived"}, + } + if not in_progress: + response["result"] = terminal_result + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + observed = [] + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = job.wait(timeout=timedelta(seconds=5), progress=observed.append) + assert job.wait() == result + job.refresh() + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = await job.wait( + timeout=timedelta(seconds=5), progress=observed.append + ) + assert await job.wait() == result + await job.refresh() + assert job.result == terminal_result + + assert isinstance(result, lancedb.RefreshColumnResult) + assert result == lancedb.RefreshColumnResult.model_validate(terminal_result) + assert result.rows_failed == rows_failed + assert observed[-1]["state"] == "finished" + if running: + assert observed[0]["state"] == "running" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("terminal_result", [None, {}]) +async def test_reopened_refresh_job_rejects_missing_or_invalid_result( + sync, terminal_result +): + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + job.wait() + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + await job.wait() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_reopened_unit_job_ignores_additive_result_payload(sync): + terminal_result = {"future_field": True} + + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "index-1", + "job_type": "create_index", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("index-1") + assert job.wait() is None + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("index-1") + assert await job.wait() is None + assert job.result == terminal_result + + @pytest.mark.parametrize("payload", [b"{", b"{}"]) def test_remote_job_wait_does_not_retry_malformed_description(payload): polls = 0 diff --git a/python/src/connection.rs b/python/src/connection.rs index 0be933cf2..69cf54c99 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -24,7 +24,7 @@ use lancedb::{ connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, database::{CreateTableMode, Database, ReadConsistency}, - function::GpuClass as LanceGpuClass, + function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, }; use pyo3::{ @@ -854,7 +854,14 @@ impl Connection { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let job = inner.open_job(&job_id).await.infer_error()?; - Ok(crate::job::Job::new(job)) + match job.job_type().as_deref() { + Some("function_refresh" | "computed_refresh" | "refresh_column") => { + Ok(crate::job::Job::new_typed( + job.into_typed::().infer_error()?, + )) + } + _ => Ok(crate::job::Job::new(job)), + } }) } diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index d178542b7..092ece8b5 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -277,6 +277,42 @@ impl Job<()> { } job } + + /// Decode this job's terminal payload as `T` when waiting. + /// + /// Use this after [`crate::Connection::open_job`] when the job's result + /// type is known. The job identity and cached description are preserved. + /// Missing or incompatible payloads are reported by [`Job::wait`]. + /// A job that completed before its handle was created has only a unit + /// result; converting it fails immediately if `T` cannot decode JSON null. + /// + /// ```no_run + /// # async fn reopen( + /// # db: &lancedb::Connection, id: &str, + /// # ) -> lancedb::Result { + /// let job = db.open_job(id).await? + /// .into_typed::()?; + /// job.wait().await + /// # } + /// ``` + pub fn into_typed(self) -> Result> + where + T: Clone + DeserializeOwned + Send + Sync + 'static, + { + let inner = match self.inner { + JobInner::Handle { handle, .. } => JobInner::Handle { + handle, + decode: Arc::new(TerminalResult::decode::), + }, + JobInner::Completed(()) => { + JobInner::Completed(TerminalResult::local(Value::Null).decode::()?) + } + }; + Ok(Job { + inner, + cache: self.cache, + }) + } } impl Job @@ -750,6 +786,21 @@ mod tests { )); } + #[tokio::test] + async fn completed_unit_job_can_be_retyped_as_unit() { + let job = Job::new_done().into_typed::<()>().unwrap(); + job.wait().await.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + + #[test] + fn completed_unit_job_rejects_an_incompatible_result_type() { + assert!(matches!( + Job::new_done().into_typed::(), + 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); diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index d27c9c666..5a0afa7e8 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -403,6 +403,29 @@ mod tests { ); } + #[tokio::test] + async fn reopened_job_preserves_its_description_and_decodes_the_terminal_result() { + let description: DescribeJobResponse = serde_json::from_str(REFRESH_JOB).unwrap(); + let job = Job::opened( + Box::new(FixtureRemoteJob(REFRESH_JOB)), + description.into_description(), + ); + let raw_result = job.result(); + let job = job.into_typed::().unwrap(); + + assert_eq!(job.job_type().as_deref(), Some("refresh_function_columns")); + assert_eq!(job.state().as_deref(), Some("finished")); + assert_eq!(job.creation_ms(), Some(1787270400001)); + assert_eq!(job.result(), raw_result); + assert_eq!(job.wait().await.unwrap().rows_assigned, 999_998_800); + assert_eq!(job.wait().await.unwrap().published_version, Some(919)); + + let missing = Job::new(Box::new(FixtureRemoteJob(MISSING_RESULT_JOB))) + .into_typed::() + .unwrap(); + assert!(missing.wait().await.is_err()); + } + /// 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)] From 9e03bf97d400572e38d265f5c59acd990c4d818a Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 08:03:11 -0800 Subject: [PATCH 083/203] feat(python): support exist_ok when creating secrets (#4978) Add `exist_ok=False` to synchronous and asynchronous Python `create_secret`. Passing `True` uses `CREATE SECRET IF NOT EXISTS`, preserving an existing credential. The default continues to fail on an existing name; rotation stays explicit through `alter_secret`. ```python db.create_secret("api-key", value, exist_ok=True) await async_db.create_secret("api-key", value, exist_ok=True) ``` The Rust API gains an awaitable builder with `.exist_ok(true)` while existing `create_secret(...).await` calls keep working. Includes Python SQL round-trip coverage and Rust coverage for direct and deferred SQL responses. --- python/python/lancedb/_lancedb.pyi | 7 ++- python/python/lancedb/db.py | 48 ++++++++++++--- python/python/lancedb/remote/db.py | 13 ++++- python/python/tests/test_sql.py | 50 ++++++++++++++++ python/src/connection.rs | 4 +- rust/lancedb/src/connection.rs | 29 +++++++--- rust/lancedb/src/connection/create_secret.rs | 61 ++++++++++++++++++++ rust/lancedb/src/database.rs | 5 +- rust/lancedb/src/remote/db.rs | 12 +++- rust/lancedb/src/remote/sql.rs | 1 + rust/lancedb/src/remote/sql/secret.rs | 29 +++++++--- rust/lancedb/src/remote/sql_test.rs | 48 +++++++++++++-- 12 files changed, 269 insertions(+), 38 deletions(-) create mode 100644 rust/lancedb/src/connection/create_secret.rs diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 11798a520..a64014cb7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -228,7 +228,12 @@ class Connection(object): self, name: str, namespace_path: Optional[List[str]] = None ) -> None: ... async def create_secret( - self, name: str, value: str, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> None: ... async def alter_secret( self, name: str, value: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index e2138520a..59fa5b4c6 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1158,14 +1158,24 @@ class DBConnection(EnforceOverrides): ) def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: """Create a named Secret in this database. - Fails if the name is taken, so a create never silently becomes a - rotation. Nothing reads the value back: it is bound to a Function by + Fails if the name is taken unless ``exist_ok=True``, which leaves the + existing value unchanged. Use :meth:`alter_secret` to rotate a Secret. + Nothing reads the value back: it is bound to a Function by name and resolved by the service when that Function runs. Local connections raise ``NotImplementedError``. + + Examples + -------- + >>> db.create_secret("api-key", "credential", exist_ok=True) # doctest: +SKIP """ raise NotImplementedError( _append_doc_url( @@ -2492,9 +2502,18 @@ class LanceDBConnection(DBConnection): @override def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: - LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path)) + LOOP.run( + self._conn.create_secret( + name, value, exist_ok=exist_ok, namespace_path=namespace_path + ) + ) @override def alter_secret( @@ -3949,17 +3968,30 @@ class AsyncConnection(object): ) async def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: """Create a named Secret in this database. - Fails if the name is taken, so a create never silently becomes a - rotation. Nothing reads the value back. + Fails if the name is taken unless ``exist_ok=True``, which leaves the + existing value unchanged. Use :meth:`alter_secret` to rotate a Secret. + Nothing reads the value back. + + Examples + -------- + >>> await db.create_secret( # doctest: +SKIP + ... "api-key", "credential", exist_ok=True + ... ) """ await self._inner.create_secret( validate_secret_name(name), value, list(validate_namespace_path(namespace_path)), + exist_ok=exist_ok, ) async def alter_secret( diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 4219ca40b..a06af5d62 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1129,9 +1129,18 @@ class RemoteDBConnection(DBConnection): @override def create_secret( - self, name: str, value: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + value: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> None: - LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path)) + LOOP.run( + self._conn.create_secret( + name, value, exist_ok=exist_ok, namespace_path=namespace_path + ) + ) @override def alter_secret( diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py index b4c555635..a479fa5d1 100644 --- a/python/python/tests/test_sql.py +++ b/python/python/tests/test_sql.py @@ -293,6 +293,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent(): assert echoed.column("k").to_pylist() == [10] +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "status"), + [ + (None, "created"), + (False, "created"), + (True, "created"), + (True, "already_exists"), + ], +) +async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status): + flight = pytest.importorskip("pyarrow.flight") + + class SecretServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.writes = [] + + def do_exchange(self, context, descriptor, reader, writer): + self.writes.append((descriptor.command, reader.read_all())) + result = pa.table({"status": [status]}) + writer.begin(result.schema) + writer.write_table(result) + writer.close() + + with SecretServer() as server: + options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {"namespace_path": ["team", "production"]} + if exist_ok is not None: + kwargs["exist_ok"] = exist_ok + if asynchronous: + db = await lancedb.connect_async("db://analytics", **options) + await db.create_secret("api-key", "credential's value", **kwargs) + else: + db = lancedb.connect("db://analytics", **options) + db.create_secret("api-key", "credential's value", **kwargs) + ((command, parameters),) = server.writes + + prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET" + sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1' + assert sql.encode() in command + assert b"credential's value" not in command + assert parameters.column(0).to_pylist() == ["credential's value"] + + @pytest.mark.parametrize("job_id", [None, "sql-job-1"]) def test_sql_input_error_metadata_crosses_native_boundary(job_id): flight = pytest.importorskip("pyarrow.flight") diff --git a/python/src/connection.rs b/python/src/connection.rs index 69cf54c99..1a99c1372 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1036,18 +1036,20 @@ impl Connection { }) } - #[pyo3(signature = (name, value, namespace_path=None))] + #[pyo3(signature = (name, value, namespace_path=None, *, exist_ok=false))] pub fn create_secret( self_: PyRef<'_, Self>, name: String, value: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner .create_secret(name, value, &namespace_path) + .exist_ok(exist_ok) .await .infer_error() }) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index a360818b5..fa35dc459 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -51,8 +51,11 @@ pub use lance_file::version::LanceFileVersion; use lance_io::object_store::StorageOptions; use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; +mod create_secret; mod create_table; +pub use create_secret::CreateSecretBuilder; + pub(crate) fn merge_storage_options( store_params: &mut ObjectStoreParams, pairs: impl IntoIterator, @@ -853,20 +856,30 @@ impl Connection { /// Create a named Secret in this database. /// - /// 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 + /// Fails if the name is taken unless [`CreateSecretBuilder::exist_ok`] is true, + /// in which case the existing value is left unchanged. There is no API that + /// reads a stored credential back; the only /// consumer is a Function that binds the Secret by name. LanceDB Embedded databases /// return [`Error::NotSupported`]. - pub async fn create_secret( + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// connection.create_secret("api-key", "credential", &[]).exist_ok(true).await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_secret( &self, name: impl AsRef, value: impl AsRef, namespace_path: &[String], - ) -> Result<()> { - validate_secret_reference(name.as_ref(), namespace_path)?; - self.internal - .create_secret(name.as_ref(), value.as_ref(), namespace_path) - .await + ) -> CreateSecretBuilder { + CreateSecretBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + value.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// Replace the credential behind an existing Secret. diff --git a/rust/lancedb/src/connection/create_secret.rs b/rust/lancedb/src/connection/create_secret.rs new file mode 100644 index 000000000..265b97571 --- /dev/null +++ b/rust/lancedb/src/connection/create_secret.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_secret_reference; + +/// Configure creation of a named Secret with [`super::Connection::create_secret`]. +#[must_use] +pub struct CreateSecretBuilder { + database: Arc, + name: String, + value: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateSecretBuilder { + pub(super) fn new( + database: Arc, + name: String, + value: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + value, + namespace_path, + exist_ok: false, + } + } + + /// Succeed without changing the stored value when the Secret already exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the Secret, preserving any existing value when `exist_ok` is true. + pub async fn execute(self) -> Result<()> { + validate_secret_reference(&self.name, &self.namespace_path)?; + self.database + .create_secret(&self.name, &self.value, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateSecretBuilder { + type Output = Result<()>; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index bcdfd94b8..7b4859faa 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -635,13 +635,14 @@ pub trait Database: secret_catalog_not_supported() } - /// Create a named Secret in this database. Fails if the name is taken, so - /// a create can never silently become a rotation. + /// Create a named Secret in this database. If the name is taken, fail unless + /// `exist_ok` is true, in which case the stored value is left unchanged. async fn create_secret( &self, _name: &str, _value: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result<()> { secret_catalog_not_supported() } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 549baf345..31808f244 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -44,8 +44,8 @@ use super::client::{ ClientConfig, HeaderProvider, HttpSend, ID_DELIMITER, RequestResultExt, RestfulLanceDbClient, Sender, }; -use super::sql::SqlClient; use super::sql::materialized_view::quote_identifier; +use super::sql::{SecretWriteOperation, SqlClient}; use super::storage_integration as integration_sql; use super::table::RemoteTable; use super::util::parse_server_version; @@ -1044,11 +1044,17 @@ impl Database for RemoteDatabase { name: &str, value: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result<()> { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, true) + .write_secret( + name, + value, + namespace_path, + SecretWriteOperation::Create { exist_ok }, + ) .await .map_err(direct_catalog_resource_error) } @@ -1056,7 +1062,7 @@ impl Database for RemoteDatabase { crate::utils::validate_secret_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .write_secret(name, value, namespace_path, false) + .write_secret(name, value, namespace_path, SecretWriteOperation::Alter) .await .map_err(direct_catalog_resource_error) } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 0b87ff5a5..949b078e3 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -40,6 +40,7 @@ mod function; pub(super) mod materialized_view; mod objects; mod secret; +pub(super) use secret::SecretWriteOperation; mod stream; mod view; diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index bdb70ef6f..6ddc78645 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -13,6 +13,12 @@ use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::TryStreamExt; use std::sync::Arc; + +pub(in crate::remote) enum SecretWriteOperation { + Create { exist_ok: bool }, + Alter, +} + fn secret_info(batches: Vec) -> Result { if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { return Err(Error::Runtime { @@ -47,10 +53,21 @@ impl SqlClient { name: &str, value: &str, namespace: &[String], - create: bool, + operation: SecretWriteOperation, ) -> Result<()> { validate_secret_name(name)?; validate_namespace(namespace)?; + let (prefix, assignment) = match operation { + SecretWriteOperation::Create { exist_ok } => ( + if exist_ok { + "CREATE SECRET IF NOT EXISTS" + } else { + "CREATE SECRET" + }, + "TYPE = GENERIC_STRING ", + ), + SecretWriteOperation::Alter => ("ALTER SECRET", "SET "), + }; let parameters = RecordBatch::try_from_iter(vec![( "", Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, @@ -61,14 +78,10 @@ impl SqlClient { self.object_job( ExecuteQueryRequest { query: format!( - "{} SECRET {} {}SECRET_STRING = $1", - if create { "CREATE" } else { "ALTER" }, + "{} {} {}SECRET_STRING = $1", + prefix, quote_identifier(name), - if create { - "TYPE = GENERIC_STRING " - } else { - "SET " - } + assignment ), default_namespace_path: namespace.to_vec(), parameters: Some(parameters), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index cfaf2a625..471966731 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3214,29 +3214,55 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { }; let exchanges = service.exchanges.clone(); 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); - db.create_secret("api-key", "credential's value", &["team".into()]) + let connection = Connection::new( + Arc::new(db), + Arc::new(crate::embeddings::MemoryRegistry::new()), + ); + connection + .create_secret("api-key", "credential's value", &["team".into()]) .await .unwrap(); - db.alter_secret("api-key", "rotated-value", &["team".into()]) + connection + .create_secret("api-key", "ignored-value", &["team".into()]) + .exist_ok(true) + .await + .unwrap(); + connection + .alter_secret("api-key", "rotated-value", &["team".into()]) + .await + .unwrap(); + connection + .drop_secret("api-key", &["team".into()]) .await .unwrap(); - db.drop_secret("api-key", &["team".into()]).await.unwrap(); assert_eq!( statements.lock().unwrap().as_slice(), ["DROP SECRET IF EXISTS \"api-key\""] ); let seen = exchanges.lock().unwrap(); - assert_eq!(seen.len(), 2); + assert_eq!(seen.len(), 3); assert_eq!( seen[0].0, "CREATE SECRET \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" ); - assert_eq!(seen[1].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert_eq!( + seen[1].0, + "CREATE SECRET IF NOT EXISTS \"api-key\" TYPE = GENERIC_STRING SECRET_STRING = $1" + ); + assert_eq!(seen[2].0, "ALTER SECRET \"api-key\" SET SECRET_STRING = $1"); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); assert_eq!( seen[0] .1 @@ -3259,6 +3285,18 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { .downcast_ref::() .unwrap() .value(0), + "ignored-value" + ); + assert_eq!( + seen[2] + .1 + .as_ref() + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), "rotated-value" ); shutdown.send(()).unwrap(); From a2a0d7f6322d64195243ff606de7924bcb08708b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:20:53 +0800 Subject: [PATCH 084/203] fix(ci): restore the unlocked Rust build cache once (#4997) `build-no-lock` restores Rust build outputs twice: toolchain setup enables its own cache by default before Cargo.lock removal, then the workflow restores an explicit cache afterward. Both restore into the same Cargo and target paths; the implicit action also allows PR cache saves. Disable only toolchain setup's implicit cache. The explicit restore remains after lock removal and retains its main-only save condition. This configuration is inherited unchanged by #4996. Its [failed job](https://github.com/lancedb/lancedb/actions/runs/43229196192/job/131220088196) reported runner ENOSPC while the second cache action was active, before dependency installation or Cargo. Earlier hosted logs confirm two restores into overlapping paths, but the failed job's full logs are unavailable, so the exact disk peak and ENOSPC cause remain unproven. A bounded probe using the resolved composite-action definitions verifies two restores before this change versus one afterward, preserves ordering and main-only saves, and confirms all other workflow configuration is unchanged. The [hosted run](https://github.com/lancedb/lancedb/actions/runs/43230840086/job/131225407007) confirms one successful 1.62 GB cache restore after lock removal and no PR cache save. It reached Cargo and linking without ENOSPC, but hit the inherited 30-minute deadline with the unchanged one-job driver. Free disk was 85 GiB before the build and 79 GiB at cancellation; these endpoint observations do not establish peak disk use or a general ENOSPC guarantee. The complementary two-job repair in #4996 now includes this prerequisite for combined hosted acceptance; this PR remains limited to cache ownership. --- .github/workflows/rust.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 9d28ac5e4..6d2bbf78d 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -154,6 +154,8 @@ jobs: - uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: "stable" + # The explicit cache below runs after lock removal and only saves on main. + cache: false # Remove cargo.lock to force a fresh build - name: Remove Cargo.lock run: rm -f Cargo.lock From ec5e2cd621b605a5e362d81f7a13a449018b14e4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:21:31 +0800 Subject: [PATCH 085/203] ci: use two Cargo jobs for unlocked builds (#4996) Fresh unlocked workspace builds can exhaust the 30-minute CI job while Cargo is restricted to one compiler/linker task. Allow two concurrent tasks while retaining fresh dependency resolution, all workspace features and targets, the existing profile and timeout, and immediate cleanup of completed test executables. The single-cache prerequisite #4997 is included by a normal merge; merge it first under normal review gates. The final combined candidate passed hosted build-no-lock on head `8a3cda494f79a414101db392986cd18a64e5d80d` (tested merge `8d56029`, run [43236975778](https://github.com/lancedb/lancedb/actions/runs/43236975778/job/131247077833)). The build step took 18m42s and the full job 19m58s, within the unchanged 30-minute budget. Exactly one 1,624,797,998-byte cache restore completed; free disk samples before and after the build were 85 GiB and 79 GiB. These are endpoint samples, not peak RAM/disk measurements or a controlled speedup comparison. This job compiles and links targets but does not execute their tests. Temporary diagnostics are removed. The three existing driver tests pass, and the combined workflow and driver match their independently reviewed parents. --- ci/build_no_lock.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ci/build_no_lock.py b/ci/build_no_lock.py index 6ec156432..17d9ad333 100644 --- a/ci/build_no_lock.py +++ b/ci/build_no_lock.py @@ -54,6 +54,7 @@ def main() -> int: ["cargo", "metadata", "--format-version=1", "--no-deps", "--all-features"], stdout=subprocess.PIPE, text=True, + check=False, ) if metadata.returncode: return metadata.returncode @@ -68,7 +69,7 @@ def main() -> int: "--tests", # Bound simultaneous compiler/linker temporary outputs as well as retained files. "--jobs", - "1", + "2", "--message-format=json,json-diagnostic-rendered-ansi", ] cleanup_failed = False From b5623f88819120982731195b37f19b340eed1c02 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:22:21 +0800 Subject: [PATCH 086/203] ci: separate macOS Rust test phases (#4995) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS doctests and library/integration tests currently share a 60-minute job budget. In #4967, compilation and doctests left only 3–4 minutes for an integration group that takes 6–7 minutes on the base revision, so the job was cancelled before it could finish. Run doctests and library/integration tests in separate matrix jobs on both macOS 15 and 26, each retaining the existing 60-minute limit. Preserve the library/integration check names, feature selection, locked dependencies and all existing coverage. This adds runner/build cost but removes the cumulative deadline coupling without reducing coverage. YAML parsing, shell syntax and matrix coverage checks pass. Hosted macOS execution and subsequent beta19 integration still need verification; this does not address the separate unlocked-build timeout. --- .github/workflows/rust.yml | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 6d2bbf78d..a5e5c9c30 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -297,10 +297,12 @@ jobs: run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests macos: + name: ${{ matrix.phase == 'tests' && format('macos ({0})', matrix.mac-runner) || format('macos-doc ({0})', matrix.mac-runner) }} timeout-minutes: 60 strategy: matrix: mac-runner: ["macos-15", "macos-26"] + phase: [tests, doc] runs-on: "${{ matrix.mac-runner }}" defaults: run: @@ -322,16 +324,17 @@ jobs: - name: Install dependencies run: brew install protobuf - name: Run tests + env: + CARGO_TEST_TARGETS: ${{ matrix.phase == 'doc' && '--doc' || '--lib --tests' }} run: | # Don't run the s3 integration tests since docker isn't available # on this image. ALL_FEATURES=`cargo metadata --format-version=1 --no-deps \ | jq -r '.packages[] | .features | keys | .[]' \ | grep -v s3-test | sort | uniq | paste -s -d "," -` - # Run doctests before test binaries fill the runner disk. Examples are - # already built by the Linux job, so avoid retaining them here. - cargo test --profile ci --features $ALL_FEATURES --locked --doc - cargo test --profile ci --features $ALL_FEATURES --locked --lib --tests + # Separate jobs give each phase its own time and disk budget. Examples + # are already built by the Linux job, so avoid retaining them here. + cargo test --profile ci --features $ALL_FEATURES --locked $CARGO_TEST_TARGETS windows: strategy: From b4d1c55f6228e9cf0a389fef07351aacfba09c01 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 00:22:35 +0800 Subject: [PATCH 087/203] test: isolate DynamoDB integration test databases (#4998) The concurrent-append and drop-all DynamoDB tests shared a database prefix. A timeout in the first could leave its table visible to the second. Give each test its own prefix while retaining five independent concurrent appends, the six-row assertion, and all drop/recreate checks. The final two-prefix diff passed both tests in hosted LocalStack across Node 22, 24, 26, and Node 24 experimental, without timing instrumentation ([run 43245851764](https://github.com/lancedb/lancedb/actions/runs/43245851764), head `5896c419`). Concurrency and the 5000 ms budget are unchanged. This fixes cascading fixture contamination; the original timeout remains unexplained, and these passing runs do not prove its root cause was fixed. --- nodejs/__test__/s3_integration.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nodejs/__test__/s3_integration.test.ts b/nodejs/__test__/s3_integration.test.ts index e4bc46806..35ce478a8 100644 --- a/nodejs/__test__/s3_integration.test.ts +++ b/nodejs/__test__/s3_integration.test.ts @@ -282,7 +282,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("can be used to configure a DynamoDB table for commit log", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/concurrent-appends?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, @@ -307,7 +307,7 @@ maybeDescribe("DynamoDB Lock", () => { }); it("clears dynamodb state after dropping all tables", async () => { - const uri = `s3+ddb://${bucket.name}/test?ddbTableName=${commitTable.name}`; + const uri = `s3+ddb://${bucket.name}/drop-all-tables?ddbTableName=${commitTable.name}`; const db = await connect(uri, { storageOptions: CONFIG, readConsistencyInterval: 0, From e61e21035c1f6f9b357510df5e88d0fa4c1be3f8 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 09:01:39 -0800 Subject: [PATCH 088/203] fix(python): explain Function namespace import restrictions (#4982) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plain `import ctypes.util` in a Function currently reports “dynamic namespace access” without explaining the module restriction or a way forward. Give blocked module imports a distinct error that names the modules, explains the reconstructed namespace constraint, and recommends an importable helper supplied through `code=`, `pip=`, or `conda=`. Dynamic namespace operations also get an actionable explanation. Document the full restrictions and the helper alternative in the decorator and Python Functions reference. Add regression coverage for direct imports, `from` imports, global module aliases, class Functions, the deprecated `@udf` alias, and helpers imported normally or shipped with `code=`. Existing import restrictions remain in place. For example, move `ctypes.util.find_library` into `native_diagnostics/__init__.py`, then use: ```python import native_diagnostics from lancedb import function @function(code=[native_diagnostics]) def probe_library(name: str) -> str: return native_diagnostics.find_library(name) ``` Fixes ENT-3408. --- docs/src/python/python.md | 45 +++++++ python/python/lancedb/functions.py | 63 ++++++--- .../tests/test_first_class_function_slice2.py | 7 +- .../python/tests/test_function_packaging.py | 120 ++++++++++++++++++ 4 files changed, 214 insertions(+), 21 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 8de5b5517..35f50c5a8 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -447,6 +447,51 @@ assert scaler(3.0) == 6.0 scaler.close() ``` +### Function packaging restrictions + +The decorator snapshots the Function's source and referenced globals into a new +module. It conservatively rejects imports of `sys`, `builtins`, `importlib`, +`inspect`, `gc`, `ctypes`, and `types`, including submodules such as `ctypes.util` +and `importlib.metadata`. This applies to imports inside function or class bodies +and references to module-level aliases. Even ordinary uses such as `sys.version` +and `ctypes.util.find_library` are blocked: these modules can reach names outside +the reconstructed Function namespace. References to `globals`, `locals`, `vars`, +`eval`, `exec`, `compile`, and `__import__` are rejected as dynamic namespace access. +These restrictions also apply to the deprecated `@udf` alias. + +For legitimate uses, move the code into an importable helper module and ship it +with `code=`, or install its package with `pip=` or `conda=`. Imported helpers keep +their own namespace; the packager does not scan their bodies. Helpers defined in +`__main__` are copied by source and have the same restrictions as the Function. + +For example, put this helper in `native_diagnostics/__init__.py`: + +```python +import ctypes.util + + +def find_library(name: str) -> str: + return ctypes.util.find_library(name) or "" +``` + +Then import the helper and include its source in the Function's artifact: + +```python +import native_diagnostics +from lancedb import function + + +@function(code=[native_diagnostics]) +def probe_library(name: str) -> str: + return native_diagnostics.find_library(name) +``` + +Captured literal globals support `None`, booleans, integers, strings, bytes, +finite floats, and tuples of these values. Construct other objects, including +PyArrow types and schemas, inside the Function or helper module instead. Values +used only in the decorator's `input_schema` or `output_schema` are not captured +globals and can be defined outside the Function. + 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 diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index a5c741cd8..19d4171fb 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1570,10 +1570,23 @@ _NAMESPACE_MODULES = frozenset( ) -def _namespace_acquisition( - definition: ast.FunctionDef, references: set[str] -) -> list[str]: - found = set(references & _DYNAMIC_NAMESPACE_ACCESS) +_NAMESPACE_HELPER_HINT = ( + "Move this code into an importable helper module supplied with code=, pip=, " + "or conda=, then import and call the helper from the Function." +) + + +def _namespace_import_error(modules: Sequence[str]) -> ValueError: + return ValueError( + f"@function cannot package imports from namespace-access modules: {modules!r}. " + f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) " + "are blocked because they can access names outside the packaged " + "Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT + ) + + +def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]: + found: set[str] = set() for node in ast.walk(definition): if isinstance(node, ast.Import): found.update( @@ -1883,11 +1896,17 @@ class _SourcePackager: ) source = ast.unparse(definition) references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n") - dynamic = _namespace_acquisition(definition, references) + dynamic = sorted(references & _DYNAMIC_NAMESPACE_ACCESS) if dynamic: raise ValueError( - f"@function cannot package dynamic namespace access: {dynamic!r}" + f"@function cannot package dynamic namespace access: {dynamic!r}. " + "These operations can access names outside the packaged " + "Function's reconstructed module namespace. Reference dependencies " + "explicitly. " + _NAMESPACE_HELPER_HINT ) + namespace_imports = _namespace_imports(definition) + if namespace_imports: + raise _namespace_import_error(namespace_imports) self._warn_unshipped_direct_imports(definition) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) @@ -1982,10 +2001,7 @@ class _SourcePackager: return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): if value.__name__.split(".")[0] in _NAMESPACE_MODULES: - raise ValueError( - "@function cannot package dynamic namespace access: " - f"{value.__name__!r}" - ) + raise _namespace_import_error([value.__name__]) try: imported = importlib.import_module(value.__name__) except ImportError: @@ -2663,13 +2679,28 @@ def function( Other global values, including Arrow types and schemas, lists, dictionaries, sets, and NumPy arrays, cannot be captured as literals. Define them inside the function or class body instead. - Closures, lambdas, nested definitions, mutable module-level - objects, code that reaches the module namespace another way - (``globals()``/``eval``, ``sys.modules``, ``builtins``), and a + Closures, lambdas, nested definitions, mutable module-level objects, and a non-standard ``__builtins__`` are rejected where they can be seen and - otherwise unsupported. Changing any packaged source, including a module in - ``code``, produces a new Function version; the environment built from - ``pip`` or ``conda`` is reused. + otherwise unsupported. + + **Namespace restrictions.** The packaged source cannot import ``sys``, + ``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``, + including submodules such as ``ctypes.util`` and ``importlib.metadata``. + Referencing a module-level alias for one of these modules is also rejected. + References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, + ``compile``, or ``__import__`` are rejected as dynamic namespace access. + These restrictions are conservative: even ordinary uses such as + ``ctypes.util.find_library`` or ``sys.version`` are blocked because these + modules can reach names outside the reconstructed Function namespace. + Move such code into an importable helper module supplied with ``code=``, + ``pip=``, or ``conda=``, then import and call the helper from the Function. + Helpers imported normally keep their own module namespace; these checks do + not scan their bodies. A helper defined in ``__main__`` is packaged by source + and is subject to the same checks. + + Changing any packaged source, including a module in ``code``, produces a + new Function version; the environment built from ``pip`` or ``conda`` is + reused. Parameters ---------- diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index d99a7aa21..97c0a5f3c 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -888,7 +888,7 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path): spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) - with pytest.raises(ValueError, match="dynamic namespace access"): + with pytest.raises(ValueError, match="imports from namespace-access modules"): function(module.score) @@ -899,7 +899,6 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path): "eval('THRESHOLD')", "(lambda g: g()['THRESHOLD'])(globals)", "__import__('sys').modules[__name__].THRESHOLD", - "sys.modules[__name__].THRESHOLD", ], ) def test_function_rejects_dynamic_namespace_access(access): @@ -911,9 +910,7 @@ def test_function_rejects_dynamic_namespace_access(access): ) with pytest.raises(ValueError, match="dynamic namespace access"): _package_from_text( - "def score(value: int) -> int:\n" - " import sys\n" - f" return value + {access}\n" + f"def score(value: int) -> int:\n return value + {access}\n" ) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 440adc4da..2e285aa33 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -466,6 +466,126 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): return value * factor +@pytest.mark.parametrize( + "module_name", + [ + "sys", + "builtins", + "importlib", + "inspect", + "gc", + "ctypes", + "types", + "ctypes.util", + "importlib.metadata", + ], +) +@pytest.mark.parametrize("import_style", ["import", "from", "global"]) +@pytest.mark.parametrize("class_function", [False, True]) +def test_namespace_module_errors_explain_the_rule_and_remedy( + helper_package, module_name, import_style, class_function +): + statement = f"import {module_name} as namespace_module" + body = f"{statement}\nreturn value\n" + preamble = "" + if import_style == "from": + body = f"from {module_name} import __name__\nreturn value\n" + elif import_style == "global": + preamble = statement + "\n" + body = "return str(namespace_module)\n" + if class_function: + definition = "class blocked:\n def __call__(self, value: str) -> str:\n" + source = preamble + definition + textwrap.indent(body, " ") + else: + definition = "def blocked(value: str) -> str:\n" + source = preamble + definition + textwrap.indent(body, " ") + module = helper_package("fx_namespace_import", {"__init__.py": source}) + + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert "imports from namespace-access modules" in message + assert repr(module_name) in message + assert "builtins, ctypes, gc, importlib, inspect, sys, types" in message + assert "including submodules" in message + assert "reconstructed module namespace" in message + assert "importable helper module" in message + assert "code=, pip=, or conda=" in message + assert "dynamic namespace access" not in message + + +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +def test_udf_namespace_import_error_explains_the_helper_alternative(): + with pytest.raises(ValueError, match="ctypes.util.*importable helper module"): + + @udf + def probe(value: str) -> str: + import ctypes.util + + return str(ctypes.util.find_library(value)) + + +@pytest.mark.parametrize( + "operation", ["globals", "locals", "vars", "eval", "exec", "compile", "__import__"] +) +def test_dynamic_namespace_errors_name_the_operation_and_remedy( + helper_package, operation +): + module = helper_package( + "fx_namespace_operation", + { + "__init__.py": ( + f"def blocked(value: str) -> str:\n return str({operation})\n" + ) + }, + ) + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert f"dynamic namespace access: ['{operation}']" in message + assert "Reference dependencies explicitly" in message + assert "importable helper module" in message + + +@pytest.mark.parametrize("ship_source", [False, True]) +def test_namespace_access_in_importable_helpers_keeps_its_module_namespace( + helper_package, ship_source +): + helpers = helper_package( + "fx_namespace_helper", + { + "__init__.py": """ + import ctypes.util + + def module_name(): + return ctypes.util.__name__ + """, + }, + ) + entry = helper_package( + "fx_namespace_entry", + { + "__init__.py": """ + from fx_namespace_helper import module_name + + def probe(value: str) -> str: + return module_name() + value + """, + }, + ) + options = {"code": [helpers]} if ship_source else {"pip": ["fx-namespace-helper"]} + definition = function(**options)(entry.probe) + if ship_source: + files = bundle_files(definition) + assert "import ctypes.util" in files["fx_namespace_helper/__init__.py"] + source = files["user_function.py"] + else: + source = artifact(definition).decode() + namespace = {} + exec(compile(source, "user_function.py", "exec"), namespace) + assert namespace["probe"]("!") == "ctypes.util!" + + def test_binding_passes_initialization_as_constants(): version = FunctionVersion.from_json( json.dumps( From 8939ef1f016b78e26dd41a77886edd6b83710e7a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:04:32 +0800 Subject: [PATCH 089/203] feat(python): warn on scalar GPU Functions (#4966) GPU Functions that use a scalar callable currently invoke the callable once per row. The SDK documents Arrow-vectorized callables, but silently accepts a scalar GPU callable, which makes it easy to assume that the runtime will batch model work automatically. Warn during Function construction when a GPU callable does not use the documented vectorized form. A callable is recognized as vectorized when every input is annotated as `pyarrow.Array`, or when a single input is annotated as `pyarrow.RecordBatch`. The warning explains the resulting per-row invocation and shows how to opt into batch execution. CPU Functions and the vectorized GPU forms do not emit it. The warning is advisory and does not change registration serialization, the artifact, the runtime adapter, or execution behavior. It is one part of the ENT-3522 documentation-and-warning alternative; it does not claim that a single A10G meets the original batch throughput requirement. Validation on the designated EC2 host reused the compatible existing native extension from `ent3563-sdk-freshness-9336cfb`; this does not claim a new native package or GPU performance run. The final head has a clean source tree and ran: ```bash PYTHONPATH="$sdk/python/python" /home/ec2-user/.venvs/ent3563-0a839fa/bin/python -m pytest -q python/python/tests/test_first_class_function_slice2.py -k 'gpu_marker_uses_gpu_runtime or gpu_scalar_warning_names_the_vectorized_alternative' /home/ec2-user/.venvs/ent3563-0a839fa/bin/ruff format --check python/python/lancedb/functions.py python/python/tests/test_first_class_function_slice2.py /home/ec2-user/.venvs/ent3563-0a839fa/bin/ruff check python/python/lancedb/functions.py python/python/tests/test_first_class_function_slice2.py ``` The actual result was `2 passed, 123 deselected`; both Ruff commands passed. The original 2,000-row single-A10G throughput requirement remains a separate ENT-3522 acceptance gate. --- python/python/lancedb/functions.py | 27 +++++++- .../tests/test_first_class_function_slice2.py | 63 ++++++++++++++++++- 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 19d4171fb..92be658a8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1529,6 +1529,17 @@ def _infer_signature( return FunctionSignature(inputs=tuple(inputs), output=output) +def _is_vectorized_callable(function: Callable[..., Any], *, method: bool) -> bool: + parameters = _callable_parameters(function) + if method: + parameters = parameters[1:] + annotations = get_type_hints(function, include_extras=True) + annotated = tuple(annotations.get(parameter.name) for parameter in parameters) + return (len(annotated) == 1 and annotated[0] is pa.RecordBatch) or ( + bool(annotated) and all(annotation is pa.Array for annotation in annotated) + ) + + # Both spellings strip from packaged source; `udf` is the deprecated alias. _DECORATOR_NAMES = frozenset({"function", "udf"}) @@ -2302,7 +2313,9 @@ class FunctionDefinition: once per row. A callable whose parameters are all annotated as ``pyarrow.Array`` receives whole Arrow arrays and returns a ``pyarrow.Array`` instead. This authoring choice is independent of the - internal artifact adapter in the registration request. + internal artifact adapter in the registration request. GPU Functions should + use the Arrow form when the model supports batches: a scalar GPU callable is + invoked once per row and leaves the model's own batching unavailable. """ def __init__( @@ -2424,6 +2437,18 @@ class FunctionDefinition: signature = signature._copy(update={"initialization": initialization}) else: signature = _infer_signature(function, input_schema, output_schema) + if gpu_marker is not None: + call = _class_call(function) if is_class else function + if not _is_vectorized_callable(call, method=is_class): + warnings.warn( + f"GPU Function {function_name!r} uses a scalar callable, so each " + "row invokes it separately and its model batch is not inferred. " + "For GPU throughput, annotate every input as pyarrow.Array or " + "take one pyarrow.RecordBatch, provide input_schema and " + "output_schema, and batch inside that callable.", + UserWarning, + stacklevel=3, + ) code_files, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 97c0a5f3c..a3a9e3e20 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -18,6 +18,7 @@ import subprocess import sys import typing import urllib.parse +import warnings from typing import Optional import pyarrow as pa @@ -658,9 +659,11 @@ def test_function_image_requires_digest_reference(image): def test_function_gpu_marker_uses_gpu_runtime(): - @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") - def double_on_gpu(value: int) -> int: - return value * 2 + with pytest.warns(UserWarning, match="uses a scalar callable"): + + @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g") + def double_on_gpu(value: int) -> int: + return value * 2 request = json.loads(double_on_gpu.registration_request.to_canonical_json()) assert request["runtime"]["kind"] == "python_v2" @@ -710,6 +713,60 @@ def test_function_gpu_marker_uses_gpu_runtime(): ) +class _GpuScalarFunction: + def __call__(self, value: str) -> int: + return len(value) + + +class _GpuArrayFunction: + def __call__(self, value: pa.Array) -> pa.Array: + return value + + +def test_gpu_scalar_warning_names_the_vectorized_alternative(): + with pytest.warns(UserWarning, match="model batch is not inferred"): + + @function(gpu=True) + def scalar_embedding(value: str) -> list[int]: + return [len(value)] + + input_schema = pa.schema([pa.field("value", pa.string(), nullable=False)]) + with pytest.warns(UserWarning, match="uses a scalar callable"): + class_scalar = function(_GpuScalarFunction, gpu=True) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + + @function( + gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64()) + ) + def array_embedding(value: pa.Array) -> pa.Array: + return value + + @function( + gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64()) + ) + def record_batch_embedding(value: pa.RecordBatch) -> pa.Array: + return value.column(0) + + @function + def cpu_scalar(value: str) -> int: + return len(value) + + class_embedding = function( + _GpuArrayFunction, + gpu=True, + input_schema=input_schema, + output_schema=pa.list_(pa.int64()), + ) + + assert not caught + assert array_embedding.registration_request.batch_size is None + assert record_batch_embedding.registration_request.batch_size is None + assert cpu_scalar.registration_request.batch_size is None + assert class_scalar.registration_request.batch_size is None + assert class_embedding.registration_request.batch_size is None + + def test_unknown_runtime_discards_payload_before_known_field_validation(): for payload in [ { From 10f89b3c32577bf054774b5c74346ba24ee79576 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:09 +0800 Subject: [PATCH 090/203] perf: reduce Blob read buffering and expose read window controls (#4979) Remote Blob reads retain and concatenate intermediate IPC buffers across batches and HTTP requests, increasing peak memory. Decode fragmented IPC bodies using their declared length, assemble Blob values once across batches/requests, and collect large-object Range responses into known-size buffers. Impossible IPC/Range allocations return errors instead of panicking. Closing a remote Blob file releases cached bytes immediately, including while a cross-window read is waiting for the network. Rust and Python expose configurable Blob read buffers. Python sync/async `fetch_blob_files` and `open_blob_file(s)` accept `buffer_size`; the default is 512 KiB and zero disables prefetch. Explicit ranges bypass prefetch. New PE batch-endpoint adoption is separate. Malformed-length and retained-cache regressions fail on the previous implementation and pass after the correction. Real HTTP tests cover buffer propagation, close during blocked input, batch/request aggregation, and large-object fallback. The final extension was rebuilt before Python validation. Non-Blob Arrow arrays may still require alignment copies; a contiguous multi-batch result still requires its final allocation. ## Benchmark Peak client RSS increment in KiB, using `python/benchmarks/bench_fetch_blobs_rss.py`, independent clients and real loopback HTTP. Both extensions were rebuilt from clean, unchanged source with the same toolchain/configuration; loaded artifact hashes were checked. Baseline `42f11d13a2755e44b63876b5a5edd93901291150`, after `0a8a76de5286949d80368f95a5c529adf422c187`. | Equivalent fetch workload | Payload | Before | After | | --- | ---: | ---: | ---: | | Single response, one batch | 48 MiB | 63,812 | 63,896 | | Multiple responses, one batch per response | 144 MiB | 423,104 | 195,628 | | Single response, 12 rows per batch | 48 MiB | 130,520 | 71,348 | | Multiple responses, 12 rows per batch | 144 MiB | 363,144 | 172,748 | | One oversized row, Range fallback | 70 MiB | 182,816 | 85,548 | These are one observation per workload and build, not a statistical distribution or memory upper bound. The single-batch workload shows no improvement. Cloud/Sophon deployment, credentialed S3 and long-running stress have not been exercised. --- docs/src/python/python.md | 9 + python/benchmarks/bench_fetch_blobs_rss.py | 183 ++++++++ python/python/lancedb/_blob.py | 19 + python/python/lancedb/_lancedb.pyi | 7 +- python/python/lancedb/remote/table.py | 13 +- python/python/lancedb/table.py | 56 ++- python/python/tests/test_blob_buffering.py | 236 ++++++++++ python/src/table.rs | 27 +- rust/lancedb/src/blob.rs | 24 + rust/lancedb/src/remote/table/blobs.rs | 424 +++++++++++++++--- .../src/remote/table/blobs/aggregate.rs | 121 +++++ rust/lancedb/src/remote/table/ipc_stream.rs | 123 ++++- .../src/remote/table/ipc_stream/framing.rs | 172 +++++++ 13 files changed, 1326 insertions(+), 88 deletions(-) create mode 100644 python/benchmarks/bench_fetch_blobs_rss.py create mode 100644 python/python/tests/test_blob_buffering.py create mode 100644 rust/lancedb/src/remote/table/blobs/aggregate.rs create mode 100644 rust/lancedb/src/remote/table/ipc_stream/framing.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 35f50c5a8..0e7164c1a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -793,6 +793,15 @@ 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. +Local and remote `BlobFile` handles prefetch 512 KiB for sequential reads by +default. Pass `buffer_size=0` to `fetch_blob_files`, `open_blob_file`, or +`open_blob_files` for sparse reads, or choose another window size in bytes. +Call `file.set_buffer_size(size)` to change it without moving the cursor; +changing the size discards unused prefetched bytes. Explicit `read_range` and +`read_ranges` calls always read exactly the requested intervals and leave the +cursor unchanged. Remote prefetch consumes the HTTP response completely before +returning, so idle handles do not hold request concurrency slots or connections. + 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: diff --git a/python/benchmarks/bench_fetch_blobs_rss.py b/python/benchmarks/bench_fetch_blobs_rss.py new file mode 100644 index 000000000..8281490f0 --- /dev/null +++ b/python/benchmarks/bench_fetch_blobs_rss.py @@ -0,0 +1,183 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Measure fetch_blobs RSS in a fresh client process against real HTTP. + +Run with the uv environment's Python. The server lives in a separate process so +payload generation and Arrow serialization are excluded from the client's RSS. +Each row contains 1 MiB; requests over the server's 64 MiB limit are split by the +SDK. Example: python benchmarks/bench_fetch_blobs_rss.py --rows 48 144 +""" + +import argparse +import json +import resource +import subprocess +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +def serve(batch_rows, row_mib): + import pyarrow as pa + + payload = b"x" * (row_mib << 20) + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def respond(self, status, data, content_type="application/json"): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("phalanx-version", "0.5.0") + self.send_header("x-lancedb-version", "1") + self.end_headers() + for offset in range(0, len(data), 8192): + self.wfile.write(data[offset : offset + 8192]) + + def do_POST(self): + length = int(self.headers.get("Content-Length", 0)) + request_body = self.rfile.read(length) + if self.path.endswith("/describe/"): + self.do_GET() + return + body = json.loads(request_body) + count = len(body["row_ids"]) + if count * row_mib > 64: + self.respond( + 400, + b"fetch_blobs accepts at most 67108864 total blob bytes", + ) + return + schema = pa.schema([pa.field("image", pa.large_binary())]) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, schema) as writer: + for start in range(0, count, batch_rows): + array = pa.array( + [payload] * min(batch_rows, count - start), + type=pa.large_binary(), + ) + writer.write_batch(pa.record_batch([array], schema=schema)) + self.respond(200, sink.getvalue(), "application/vnd.apache.arrow.stream") + + def do_GET(self): + if "/blob/image/" in self.path: + start, end = map(int, self.headers["Range"][6:].split("-")) + body = memoryview(payload)[start : end + 1] + self.send_response(206) + self.send_header("Content-Length", str(len(body))) + self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}") + self.send_header("x-lancedb-version", "1") + self.end_headers() + for offset in range(0, len(body), 8192): + self.wfile.write(body[offset : offset + 8192]) + return + self.respond( + 200, + json.dumps( + { + "table": "test", + "version": 1, + "schema": {"fields": []}, + } + ).encode(), + ) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + print(server.server_port, flush=True) + server.serve_forever() + + +def client(port, rows, row_mib): + import lancedb + + db = lancedb.connect( + "db://rss-test", api_key="test", host_override=f"http://127.0.0.1:{port}" + ) + table = db.open_table("test") + # Reset the Linux high-water mark after imports and connection setup. + with open("/proc/self/clear_refs", "w") as reset: + reset.write("5") + + def memory_kib(field): + with open("/proc/self/status") as status: + return next( + int(line.split()[1]) for line in status if line.startswith(field + ":") + ) + + before = memory_kib("VmRSS") + values = table.fetch_blobs("image", list(range(rows))) + peak = memory_kib("VmHWM") + assert len(values) == rows + assert values.buffers()[2].size == rows * (row_mib << 20) + # Inspect slices without copying the result to Python bytes. + for i in (0, rows - 1): + assert values.slice(i, 1).buffers()[2][i * (row_mib << 20)] == ord("x") + print( + json.dumps( + { + "rows": rows, + "payload_mib": rows * row_mib, + "baseline_rss_kib": before, + "peak_rss_kib": peak, + "peak_delta_kib": peak - before, + "peak_delta_per_payload": (peak - before) / (rows * row_mib * 1024), + "rusage_maxrss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rows", nargs="+", type=int, default=[48, 144]) + parser.add_argument("--batch-rows", type=int, default=48) + parser.add_argument("--row-mib", type=int, default=1) + parser.add_argument("--serve", action="store_true") + parser.add_argument("--client", type=int) + args = parser.parse_args() + if args.serve: + serve(args.batch_rows, args.row_mib) + elif args.client is not None: + client(args.client, args.rows[0], args.row_mib) + else: + server = subprocess.Popen( + [ + sys.executable, + __file__, + "--serve", + "--batch-rows", + str(args.batch_rows), + "--row-mib", + str(args.row_mib), + ], + stdout=subprocess.PIPE, + text=True, + ) + try: + port = server.stdout.readline().strip() + for rows in args.rows: + subprocess.run( + [ + sys.executable, + __file__, + "--client", + port, + "--rows", + str(rows), + "--row-mib", + str(args.row_mib), + ], + check=True, + ) + finally: + server.terminate() + server.wait() + + +if __name__ == "__main__": + main() diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 2c545a17e..fc1925ca6 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -35,6 +35,15 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray] FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]] +def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]: + if size is None: + return None + size = operator.index(size) + if size < 0: + raise ValueError("buffer_size must be non-negative") + return size + + def _normalize_blob_descriptor(value): if isinstance(value, pa.Scalar): value = value.as_py() @@ -58,6 +67,16 @@ class BlobFile(io.RawIOBase): def __init__(self, inner) -> None: self._inner = inner + def set_buffer_size(self, size: int) -> None: + """Set sequential read-ahead bytes (default 512 KiB); 0 disables it. + + Changing the size discards unused prefetched bytes without moving the + cursor. Explicit ``read_range`` and ``read_ranges`` bypass read-ahead. + """ + if self.closed: + raise ValueError("set_buffer_size of closed file") + self._inner.set_buffer_size(_validate_blob_buffer_size(size)) + async def aread(self) -> bytes: if self.closed: raise ValueError("read of closed file") diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a64014cb7..4f1da9ba7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -397,6 +397,7 @@ class BlobFile: def seek(self, position: int) -> None: ... def tell(self) -> int: ... def size(self) -> int: ... + def set_buffer_size(self, size: int) -> None: ... def read_range(self, offset: int, length: int) -> bytes: ... def read_ranges(self, ranges: list[tuple[int, int]]) -> list[bytes]: ... def read_up_to(self, length: int) -> bytes: ... @@ -755,9 +756,11 @@ class Table: requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: ... async def fetch_blob_files( - self, column: str, row_ids: list[int] + self, column: str, row_ids: list[int], buffer_size: Optional[int] = None ) -> list[Optional[BlobFile]]: ... - async def open_blob_file(self, descriptor: str) -> BlobFile: ... + async def open_blob_file( + self, descriptor: str, buffer_size: Optional[int] = None + ) -> 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 3f6bff45e..21749a0a7 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1420,13 +1420,20 @@ class RemoteTable(Table): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": - return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + return LOOP.run( + self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size) + ) def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: - return LOOP.run(self._table.open_blob_file(descriptor)) + return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size)) def head(self, n=5) -> pa.Table: """ diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 762f826c2..424b4b64c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -40,6 +40,7 @@ from ._blob import ( BlobFile, _normalize_blob_descriptor, _normalize_blob_row_ids, + _validate_blob_buffer_size, _wrap_blob_files, strip_auto_row_ids, validate_blob_mode, @@ -2664,6 +2665,8 @@ class Table(ABC): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": """Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles. @@ -2673,6 +2676,8 @@ class Table(ABC): ``pyarrow.Table`` carrying row identity via ``_rowid`` or a ``_lance_row_id`` field on the blob descriptor. Null blob values return ``None``. LanceDB Enterprise requires server version 0.5.0 or newer. + ``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB). + Set it to 0 for sparse reads. Explicit range reads bypass this buffer. ``_rowid`` values stay valid after compaction when the table has stable row ids. @@ -2682,7 +2687,10 @@ class Table(ABC): @abstractmethod def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: """Open a seekable file from a SQL ``blob_descriptor`` result. @@ -2691,6 +2699,7 @@ class Table(ABC): 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. + ``buffer_size`` controls sequential read-ahead (default 512 KiB; 0 disables). ```python rows = db.execute_query( @@ -2701,7 +2710,9 @@ class Table(ABC): ``` """ - def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]: + def open_blob_files( + self, descriptors: Iterable, *, buffer_size: Optional[int] = None + ) -> 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 @@ -2716,7 +2727,10 @@ class Table(ABC): ``` """ for descriptor in descriptors: - yield self.open_blob_file(descriptor) + if buffer_size is None: + yield self.open_blob_file(descriptor) + else: + yield self.open_blob_file(descriptor, buffer_size=buffer_size) @abstractmethod def _execute_query( @@ -3998,13 +4012,20 @@ class LanceTable(Table): self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": - return LOOP.run(self._table.fetch_blob_files(column, row_ids)) + return LOOP.run( + self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size) + ) def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: - return LOOP.run(self._table.open_blob_file(descriptor)) + return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size)) @property def tags(self) -> Tags: @@ -8620,26 +8641,39 @@ class AsyncTable: self, column: str, row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], + *, + buffer_size: Optional[int] = None, ) -> "list[Optional[BlobFile]]": + """Open handles with configurable read-ahead. + + See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files]. + """ + buffer_size = _validate_blob_buffer_size(buffer_size) handles = await self._inner.fetch_blob_files( - column, _normalize_blob_row_ids(row_ids, column) + column, _normalize_blob_row_ids(row_ids, column), buffer_size ) return _wrap_blob_files(handles) async def open_blob_file( - self, descriptor: Union[dict, pa.StructScalar, None] + self, + descriptor: Union[dict, pa.StructScalar, None], + *, + buffer_size: Optional[int] = None, ) -> Optional[BlobFile]: """Open a snapshot-bound descriptor as a seekable file. See [Table.open_blob_file][lancedb.table.Table.open_blob_file]. """ + buffer_size = _validate_blob_buffer_size(buffer_size) descriptor = _normalize_blob_descriptor(descriptor) if descriptor is None: return None - return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor))) + return BlobFile( + await self._inner.open_blob_file(json.dumps(descriptor), buffer_size) + ) async def open_blob_files( - self, descriptors: Iterable + self, descriptors: Iterable, *, buffer_size: Optional[int] = None ) -> AsyncIterator[Optional[BlobFile]]: """Asynchronously iterate over files in descriptor order, preserving nulls. @@ -8654,7 +8688,7 @@ class AsyncTable: ``` """ for descriptor in descriptors: - yield await self.open_blob_file(descriptor) + yield await self.open_blob_file(descriptor, buffer_size=buffer_size) @property def tags(self) -> AsyncTags: diff --git a/python/python/tests/test_blob_buffering.py b/python/python/tests/test_blob_buffering.py new file mode 100644 index 000000000..09fbfb862 --- /dev/null +++ b/python/python/tests/test_blob_buffering.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +import threading +from contextlib import contextmanager +from urllib.parse import urlparse + +import pyarrow as pa +import pytest + +import lancedb +from test_remote_db import ( + BLOB_DESCRIBE_RESPONSE, + blob_descriptor_take_table, + mock_lancedb_connection, +) + + +@contextmanager +def remote_buffer_table(*, http_requests=None, truncate_first=False): + payload = bytes(range(256)) * 4096 + requests = [] + + def handler(request): + path = urlparse(request.path).path + if http_requests is not None: + http_requests.append(path) + if path.endswith("/describe/"): + body = json.dumps(BLOB_DESCRIBE_RESPONSE).encode() + content_type = "application/json" + elif path.endswith("/query/"): + data = json.loads( + request.rfile.read(int(request.headers["Content-Length"])) + ) + assert data["columns"] == ["image"] + table = blob_descriptor_take_table().slice(0, 1) + images = table["image"].combine_chunks() + images = pa.StructArray.from_arrays( + [ + images.field("kind"), + images.field("position"), + pa.array([len(payload)], pa.uint64()), + images.field("blob_id"), + images.field("blob_uri"), + ], + fields=list(images.type), + ) + table = table.set_column(0, table.schema.field(0), images) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, table.schema) as writer: + writer.write_table(table) + body = sink.getvalue().to_pybytes() + content_type = "application/vnd.apache.arrow.stream" + else: + assert path == "/v1/table/test/blob/image/10/bytes" + assert "version=1" in request.path + start, end = map(int, request.headers["Range"][6:].split("-")) + requests.append((start, end + 1)) + body = payload[start : end + 1] + if truncate_first and len(requests) == 1: + body = body[:5] + request.send_response(206) + request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}") + request.send_header("Content-Length", str(len(body))) + request.end_headers() + request.wfile.write(body) + return + request.send_response(200) + request.send_header("Content-Type", content_type) + request.send_header("Content-Length", str(len(body))) + request.send_header("phalanx-version", "0.5.0") + request.send_header("x-lancedb-version", "1") + request.end_headers() + request.wfile.write(body) + + with mock_lancedb_connection(handler, blob_request_concurrency=1) as db: + yield db.open_table("test"), payload, requests + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024]) +async def test_remote_read_ahead_over_http(use_async, buffer_size): + with remote_buffer_table() as (table, payload, requests): + if use_async: + files = await table._table.fetch_blob_files( + "image", [10], buffer_size=buffer_size + ) + else: + files = table.fetch_blob_files("image", [10], buffer_size=buffer_size) + file = files[0] + assert requests == [] + assert file.read(2) == payload[:2] + window = 512 * 1024 if buffer_size is None else max(buffer_size, 2) + assert requests == [(0, window)] + assert file.read(2) == payload[2:4] + assert len(requests) == (2 if buffer_size == 0 else 1) + file.seek(1) + assert file.read(1) == payload[1:2] + assert len(requests) == (3 if buffer_size == 0 else 1) + before = len(requests) + assert file.read_range(0, 1) == payload[:1] + assert len(requests) == before + 1 + assert requests[-1] == (0, 1) + assert file.tell() == 2 + file.set_buffer_size(0) + assert file.read(1) == payload[2:3] + assert requests[-1] == (2, 3) + file.set_buffer_size(16) + assert file.read(1) == payload[3:4] + assert requests[-1] == (3, 19) + file.seek(len(payload) - 1) + assert file.read(4) == payload[-1:] + assert requests[-1] == (len(payload) - 1, len(payload)) + before = len(requests) + assert file.read(1) == b"" + assert len(requests) == before + file.close() + with pytest.raises(ValueError, match="closed"): + file.set_buffer_size(0) + + +def test_short_prefetch_over_http_preserves_cursor(): + with remote_buffer_table(truncate_first=True) as (table, payload, requests): + file = table.fetch_blob_files("image", [10], buffer_size=8)[0] + with pytest.raises(RuntimeError, match="returned 5 bytes, expected 8"): + file.read(6) + assert file.tell() == 0 + assert file.read(3) == payload[:3] + assert file.tell() == 3 + assert requests == [(0, 8), (0, 8)] + file.close() + + +def test_idle_prefetch_releases_http_concurrency_slot(): + with remote_buffer_table() as (table, payload, requests): + first, second = table.fetch_blob_files("image", [10, 10]) + assert first.read(1) == payload[:1] + results = [] + errors = [] + + def read_other(): + try: + results.append(second.read(1)) + except Exception as error: + errors.append(error) + + reader = threading.Thread(target=read_other, daemon=True) + reader.start() + reader.join(timeout=2) + completed_while_first_idle = not reader.is_alive() + first.close() + reader.join(timeout=2) + second.close() + assert completed_while_first_idle, ( + "idle prefetch retained the HTTP request slot" + ) + assert not errors + assert results == [payload[:1]] + assert requests == [(0, 512 * 1024), (0, 512 * 1024)] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_local_buffer_configuration_through_python(tmp_path, use_async): + db = lancedb.connect(tmp_path) + table = db.create_table( + "blobs", [{"image": b"0123456789"}], schema=pa.schema([lancedb.blob("image")]) + ) + row_ids = table.search().with_row_id(True).to_arrow()["_rowid"] + if use_async: + files = await table._table.fetch_blob_files("image", row_ids, buffer_size=0) + else: + files = table.fetch_blob_files("image", row_ids, buffer_size=0) + file = files[0] + assert file.read(2) == b"01" + file.set_buffer_size(4) + assert file.read(2) == b"23" + file.seek(1) + assert file.read(3) == b"123" + assert file.read_range(8, 2) == b"89" + with pytest.raises(ValueError, match="non-negative"): + file.set_buffer_size(-1) + with pytest.raises(TypeError): + file.set_buffer_size(1.5) + file.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_open_descriptor_files_forward_buffer_size(use_async): + with remote_buffer_table() as (table, payload, requests): + descriptor = { + "kind": 1, + "position": 0, + "size": len(payload), + "blob_id": 0, + "blob_uri": "", + "source": { + "uri": "s3://bucket/test.lance", + "version": 1, + "committed_at_micros": 1, + "column": "image", + "row_reference": 10, + "row_is_address": False, + }, + } + if use_async: + files = [ + file + async for file in table._table.open_blob_files( + [None, descriptor], buffer_size=8 + ) + ] + else: + files = list(table.open_blob_files([None, descriptor], buffer_size=8)) + assert files[0] is None + assert files[1].read(1) == payload[:1] + assert requests == [(0, 8)] + files[1].close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_invalid_buffer_size_rejects_before_http(use_async): + http_requests = [] + with remote_buffer_table(http_requests=http_requests) as (table, _, requests): + http_requests.clear() + with pytest.raises(ValueError, match="non-negative"): + if use_async: + await table._table.fetch_blob_files("image", [10], buffer_size=-1) + else: + table.fetch_blob_files("image", [10], buffer_size=-1) + assert requests == [] + assert http_requests == [] diff --git a/python/src/table.rs b/python/src/table.rs index c4211e44d..62c2ee765 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1243,6 +1243,15 @@ impl PyBlobFile { .map_err(|e| blob_file_error("tell", e)) } + fn set_buffer_size(self_: PyRef<'_, Self>, size: usize) -> PyResult<()> { + self_.ensure_open()?; + let inner = self_.inner.clone(); + self_ + .py() + .detach(move || block_on(async move { inner.set_buffer_size(size).await })) + .map_err(|e| blob_file_error("set_buffer_size", e)) + } + fn size(self_: PyRef<'_, Self>) -> u64 { self_.inner.size() } @@ -2019,11 +2028,12 @@ impl Table { } /// Open lazy blob handles for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, buffer_size=None))] pub fn fetch_blob_files( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + buffer_size: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2031,6 +2041,13 @@ impl Table { .fetch_blob_files(column.as_str(), &row_ids) .await .infer_error()?; + if let Some(size) = buffer_size { + for file in handles.iter().flatten() { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } + } Ok(handles .into_iter() .map(|handle| { @@ -2043,16 +2060,22 @@ impl Table { }) } - #[pyo3(signature = (descriptor))] + #[pyo3(signature = (descriptor, buffer_size=None))] pub fn open_blob_file<'py>( self_: PyRef<'py, Self>, descriptor: &str, + buffer_size: Option, ) -> 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()?; + if let Some(size) = buffer_size { + file.set_buffer_size(size) + .await + .map_err(|e| blob_file_error("set_buffer_size", e))?; + } Ok(PyBlobFile { inner: Arc::new(file), closed: AtomicBool::new(false), diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index a8a816fdd..ead1f2410 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -204,6 +204,30 @@ impl BlobFile { lance::dataset::BlobFile::new_external(object_store, path, uri, position, size).into() } + /// Default sequential read-ahead window, in bytes. + pub const DEFAULT_READ_BUFFER_SIZE: usize = 512 * 1024; + + /// Set sequential read-ahead bytes. `0` disables read-ahead. + /// + /// Changing the size discards unused prefetched bytes without moving the + /// cursor. [`Self::read_range`] and [`Self::read_ranges`] bypass read-ahead. + /// The default is [`Self::DEFAULT_READ_BUFFER_SIZE`]. + /// + /// ``` + /// # async fn sparse_read(file: &lancedb::blob::BlobFile) -> lance_core::Result<()> { + /// file.set_buffer_size(0).await?; + /// let header = file.read_up_to(16).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + match &self.inner { + BlobFileInner::Native(file) => file.set_buffer_size(size).await, + #[cfg(feature = "remote")] + BlobFileInner::Remote(file) => file.set_buffer_size(size).await, + } + } + /// Close the handle. pub async fn close(&self) -> lance_core::Result<()> { match &self.inner { diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 65ab13935..345b731c5 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -3,6 +3,11 @@ //! Cloud blob column listing, whole-byte fetch, and seekable HTTP byte-range handles. +mod aggregate; + +use aggregate::BlobAccumulator; +use arrow_buffer::{Buffer, OffsetBuffer}; + use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; @@ -159,9 +164,25 @@ impl BlobRangeRequester for TableBlobRangeRequester { } } -#[derive(Debug, Default)] +#[derive(Debug)] struct RemoteBlobState { cursor: u64, + buffer_size: usize, +} + +impl Default for RemoteBlobState { + fn default() -> Self { + Self { + cursor: 0, + buffer_size: BlobFile::DEFAULT_READ_BUFFER_SIZE, + } + } +} + +#[derive(Debug, Default)] +struct RemoteBlobBuffer { + start: u64, + bytes: Bytes, } /// Seekable Cloud blob handle over HTTP Range. @@ -171,6 +192,9 @@ struct RemoteBlobState { pub struct RemoteBlobFile { requester: Arc, state: Mutex, + // Never held across I/O: close can release cached bytes even while a read + // holds the cursor lock. A reader may retain its own prefix until it ends. + buffer: std::sync::Mutex, closed: AtomicBool, size: u64, version: Option, @@ -181,6 +205,7 @@ impl RemoteBlobFile { Self { requester, state: Mutex::new(RemoteBlobState::default()), + buffer: std::sync::Mutex::new(RemoteBlobBuffer::default()), closed: AtomicBool::new(false), size, version, @@ -190,6 +215,18 @@ impl RemoteBlobFile { /// Close the handle without waiting for an in-flight read. pub(crate) async fn close(&self) -> lance_core::Result<()> { self.closed.store(true, Ordering::Release); + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(()) + } + + pub(crate) async fn set_buffer_size(&self, size: usize) -> lance_core::Result<()> { + self.ensure_open()?; + let mut state = self.state.lock().await; + self.ensure_open()?; + if state.buffer_size != size { + state.buffer_size = size; + self.buffer.lock().unwrap().bytes = Bytes::new(); + } Ok(()) } @@ -228,7 +265,7 @@ impl RemoteBlobFile { let BlobRangeResponse { request_id, response, - _permit, + _permit: permit, } = self .requester .request_range(&range_header, RangeRequestMode::DataRead, self.version) @@ -236,19 +273,9 @@ impl RemoteBlobFile { .map_err(remote_blob_error)?; self.ensure_open()?; validate_partial_response(&response, range.clone(), self.size)?; - let bytes = response - .bytes() - .await - .err_to_http(request_id) - .map_err(remote_blob_error)?; + let bytes = read_blob_body(response, range.end - range.start, request_id).await?; + drop(permit); self.ensure_open()?; - if bytes.len() as u64 != range.end - range.start { - return Err(remote_blob_error(format!( - "byte range returned {} bytes, expected {}", - bytes.len(), - range.end - range.start - ))); - } Ok(bytes) } @@ -275,7 +302,16 @@ impl RemoteBlobFile { let remaining = usize::try_from(remaining).map_err(|_| { lance_core::Error::invalid_input("remaining blob length exceeds addressable memory") })?; - self.read_up_to_locked(&mut state, remaining).await + // Joining a small cached prefix to a large tail would copy the entire + // blob while both allocations are live. Match the native reader's + // bounded reuse rule for whole-blob reads. + let held_len = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, remaining).len(); + if remaining > held_len.saturating_mul(2) { + self.buffer.lock().unwrap().bytes = Bytes::new(); + } + let bytes = self.read_up_to_locked(&mut state, remaining).await?; + self.buffer.lock().unwrap().bytes = Bytes::new(); + Ok(bytes) } pub(crate) async fn read_up_to(&self, len: usize) -> lance_core::Result { @@ -296,14 +332,51 @@ impl RemoteBlobFile { return Ok(Bytes::new()); } - // A partial read must release its HTTP response before returning. Keeping - // it open across calls would hold a connection slot indefinitely and - // prevent other handles from making progress. - let end = state.cursor + target_len as u64; - let bytes = self.read_range(state.cursor..end).await?; + let prefix = cached_prefix(&self.buffer.lock().unwrap(), state.cursor, target_len); + if prefix.len() == target_len { + state.cursor += target_len as u64; + return Ok(prefix); + } + let fetch_start = state.cursor + prefix.len() as u64; + let still_need = target_len - prefix.len(); + let fetch_len = if state.buffer_size == 0 { + still_need as u64 + } else { + (state.buffer_size.max(still_need) as u64).min(self.size - fetch_start) + }; + // Fully consume the response before retaining only its Bytes. read_range + // releases both the connection and the concurrency permit before return. + let data = self + .read_range(fetch_start..fetch_start + fetch_len) + .await?; self.ensure_open()?; - state.cursor = end; - Ok(bytes) + let tail = data.slice(..still_need); + let result = if prefix.is_empty() { + tail + } else { + let mut joined = Vec::new(); + joined.try_reserve_exact(target_len).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob read of {target_len} bytes: {error}" + )) + })?; + joined.extend_from_slice(&prefix); + joined.extend_from_slice(&tail); + Bytes::from(joined) + }; + { + let mut buffer = self.buffer.lock().unwrap(); + // Serialize publishing a new window with close clearing the cache. + self.ensure_open()?; + if state.buffer_size != 0 { + buffer.start = fetch_start; + buffer.bytes = data; + } else { + buffer.bytes = Bytes::new(); + } + } + state.cursor += target_len as u64; + Ok(result) } pub(crate) async fn seek(&self, new_cursor: u64) -> lance_core::Result<()> { @@ -326,6 +399,83 @@ impl RemoteBlobFile { } } +/// Collect a range without retaining a second payload's worth of network chunks. +async fn read_blob_body( + response: Response, + expected: u64, + request_id: String, +) -> lance_core::Result { + let expected = usize::try_from(expected).map_err(|_| { + lance_core::Error::invalid_input("blob range length exceeds addressable memory") + })?; + let length_error = |received| { + remote_blob_error(format!( + "byte range returned {received} bytes, expected {expected}" + )) + }; + let mut chunks = response.bytes_stream(); + let first = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + .ok_or_else(|| length_error(0))?; + if first.len() > expected { + return Err(length_error(first.len())); + } + if first.len() == expected { + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + if !chunk.is_empty() { + return Err(length_error(expected.saturating_add(chunk.len()))); + } + } + return Ok(first); + } + let mut bytes = Vec::new(); + bytes.try_reserve_exact(expected).map_err(|error| { + remote_blob_error(format!( + "cannot allocate blob range of {expected} bytes: {error}" + )) + })?; + bytes.extend_from_slice(&first); + drop(first); + while let Some(chunk) = chunks + .try_next() + .await + .err_to_http(request_id.clone()) + .map_err(remote_blob_error)? + { + let received = bytes.len().saturating_add(chunk.len()); + if received > expected { + return Err(length_error(received)); + } + bytes.extend_from_slice(&chunk); + } + if bytes.len() != expected { + return Err(length_error(bytes.len())); + } + Ok(Bytes::from(bytes)) +} + +fn cached_prefix(buffer: &RemoteBlobBuffer, cursor: u64, length: usize) -> Bytes { + let Some(offset) = cursor.checked_sub(buffer.start) else { + return Bytes::new(); + }; + let Ok(offset) = usize::try_from(offset) else { + return Bytes::new(); + }; + if offset >= buffer.bytes.len() { + return Bytes::new(); + } + let end = offset.saturating_add(length).min(buffer.bytes.len()); + buffer.bytes.slice(offset..end) +} + fn remote_blob_error(error: impl std::fmt::Display) -> lance_core::Error { lance_core::Error::io(format!("remote blob read failed: {error}")) } @@ -434,10 +584,13 @@ impl RemoteTable { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut chunks = Vec::new(); + let mut blobs = BlobAccumulator::new(row_ids.len()); while let Some(ids) = pending.pop() { - match self.fetch_blobs_chunk(column, ids, read_snapshot).await { - Ok(blobs) => chunks.push(blobs), + match self + .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) + .await + { + Ok(()) => {} Err(error) if is_fetch_blobs_byte_limit_error(&error) => { // A single-request call may turn into several requests after a // byte-cap error. No bytes from the failed request were used. @@ -455,7 +608,15 @@ impl RemoteTable { Some(file) => Some(file.read().await?), None => None, }; - chunks.push(LargeBinaryArray::from(vec![blob.as_deref()])); + let blob = match blob { + Some(bytes) => LargeBinaryArray::new( + OffsetBuffer::new(vec![0, bytes.len() as i64].into()), + Buffer::from(bytes), + None, + ), + None => LargeBinaryArray::new_null(1), + }; + blobs.append(&blob)?; } else { let mid = ids.len() / 2; pending.push(&ids[mid..]); @@ -466,15 +627,7 @@ impl RemoteTable { } } - if chunks.len() == 1 { - return Ok(chunks.pop().unwrap()); - } - let chunk_refs: Vec<&dyn Array> = chunks.iter().map(|chunk| chunk as &dyn Array).collect(); - Ok(arrow::compute::concat(&chunk_refs)? - .as_any() - .downcast_ref::() - .expect("concatenating LargeBinary arrays returns LargeBinary") - .clone()) + Ok(blobs.finish()) } async fn fetch_blobs_chunk( @@ -482,7 +635,8 @@ impl RemoteTable { column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, - ) -> Result { + blobs: &mut BlobAccumulator, + ) -> Result<()> { let mut body = serde_json::json!({ "version": read_snapshot.version, "column": column, @@ -502,7 +656,7 @@ impl RemoteTable { Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), }; - let mut blob_chunks: Vec> = Vec::new(); + let mut rows = 0; while let Some(batch) = stream.try_next().await? { let blob_column = batch.column_by_name(column).ok_or_else(|| Error::Http { source: format!("fetch_blobs response is missing the '{column}' column").into(), @@ -525,28 +679,19 @@ impl RemoteTable { status_code: None, }); } - blob_chunks.push(arrow::compute::cast(blob_column, &DataType::LargeBinary)?); - } - let blobs = if blob_chunks.is_empty() { - LargeBinaryArray::from(Vec::>::new()) - } else { - let blob_chunk_refs: Vec<&dyn Array> = blob_chunks.iter().map(AsRef::as_ref).collect(); - arrow::compute::concat(&blob_chunk_refs)? + let array = arrow::compute::cast(blob_column, &DataType::LargeBinary)?; + let array = array .as_any() .downcast_ref::() - .ok_or_else(|| Error::Http { - source: "fetch_blobs could not read the concatenated response as LargeBinary" - .into(), - request_id: request_id.clone(), - status_code: None, - })? - .clone() - }; - if blobs.len() != row_ids.len() { + .expect("casting to LargeBinary returns LargeBinary"); + rows += array.len(); + blobs.append(array)?; + } + if rows != row_ids.len() { return Err(Error::Http { source: format!( "fetch_blobs returned {} rows for {} row ids", - blobs.len(), + rows, row_ids.len() ) .into(), @@ -554,7 +699,7 @@ impl RemoteTable { status_code: None, }); } - Ok(blobs) + Ok(()) } /// Materialize ranges through version-pinned handles, preserving nulls and order. @@ -1893,9 +2038,8 @@ mod tests { [ ("bytes=0-0".to_string(), None), ("bytes=5-8".to_string(), Some("5".to_string())), - ("bytes=0-3".to_string(), Some("5".to_string())), ( - format!("bytes=10-{}", PAYLOAD.len() - 1), + format!("bytes=0-{}", PAYLOAD.len() - 1), Some("5".to_string()) ), ] @@ -1943,7 +2087,7 @@ mod tests { } #[tokio::test] - async fn remote_blob_file_releases_response_after_each_partial_read() { + async fn remote_blob_file_reuses_prefetched_bytes_across_reads_and_seeks() { let requests = Arc::new(StdMutex::new(Vec::new())); let table = mock_remote_blob_table(requests.clone()); let file = table @@ -1961,7 +2105,41 @@ mod tests { assert_eq!(file.tell().await.unwrap(), 24); assert_eq!( requests.lock().unwrap().as_slice(), - ["bytes=0-0", "bytes=0-3", "bytes=4-6", "bytes=20-23"] + ["bytes=0-0", &format!("bytes=0-{}", PAYLOAD.len() - 1)] + ); + } + + #[tokio::test] + async fn remote_buffer_boundaries_and_disabled_read_ahead() { + let requests = Arc::new(StdMutex::new(Vec::new())); + let table = mock_remote_blob_table(requests.clone()); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[..3]); + assert_eq!(file.read_up_to(3).await.unwrap(), &PAYLOAD[3..6]); + file.seek(5).await.unwrap(); + assert_eq!(file.read_up_to(2).await.unwrap(), &PAYLOAD[5..7]); + assert_eq!(file.read_range(5..6).await.unwrap(), &PAYLOAD[5..6]); + assert_eq!(file.tell().await.unwrap(), 7); + file.set_buffer_size(0).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[7..8]); + assert_eq!(file.read_up_to(1).await.unwrap(), &PAYLOAD[8..9]); + assert_eq!( + requests.lock().unwrap().as_slice(), + [ + "bytes=0-0", + "bytes=0-3", + "bytes=4-7", + "bytes=5-5", + "bytes=7-7", + "bytes=8-8" + ] ); } @@ -2198,6 +2376,7 @@ mod tests { .flatten() .unwrap(); + file.set_buffer_size(0).await.unwrap(); let error = file.read_up_to(10).await.unwrap_err(); assert!( error.to_string().contains("returned 5 bytes, expected 10"), @@ -2324,6 +2503,7 @@ mod tests { file.read_up_to(1).await.unwrap_err(), file.seek(0).await.unwrap_err(), file.tell().await.unwrap_err(), + file.set_buffer_size(0).await.unwrap_err(), ] { assert!(error.to_string().contains("already closed"), "got: {error}"); } @@ -2530,10 +2710,114 @@ mod tests { assert!(error.to_string().contains("206"), "got: {error}"); } + #[tokio::test] + async fn impossible_range_capacity_returns_an_error() { + let size = isize::MAX as u64 + 1; + let table = RemoteTable::new_mock( + "videos".to_string(), + move |request| { + let range = request + .headers() + .get(header::RANGE) + .unwrap() + .to_str() + .unwrap(); + let end = if range == "bytes=0-0" { 0 } else { size - 1 }; + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, format!("bytes 0-{end}/{size}")) + .header(VERSION_HEADER, "5") + .body(vec![1]) + .unwrap() + }, + Some(Version::new(0, 5, 0)), + ); + let file = table + .probe_files("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + let error = file.read().await.unwrap_err(); + assert!( + error.to_string().contains("cannot allocate blob range"), + "{error}" + ); + assert_eq!(file.tell().await.unwrap(), 0); + } + + #[derive(Debug)] + struct TrackedRangeBody { + bytes: Vec, + dropped: Arc, + } + + impl AsRef<[u8]> for TrackedRangeBody { + fn as_ref(&self) -> &[u8] { + &self.bytes + } + } + + impl Drop for TrackedRangeBody { + fn drop(&mut self) { + self.dropped.store(true, Ordering::Release); + } + } + + #[tokio::test] + async fn close_releases_existing_cache_after_in_flight_read_ends() { + for cancel in [false, true] { + let release = Arc::new(tokio::sync::Barrier::new(2)); + let started = Arc::new(tokio::sync::Notify::new()); + let dropped = Arc::new(AtomicBool::new(false)); + let file = Arc::new(RemoteBlobFile::new( + Arc::new(BlockingRangeRequester { + release: release.clone(), + started: started.clone(), + block_start: 4, + tracked: Some(dropped.clone()), + }), + PAYLOAD.len() as u64, + Some(5), + )); + file.set_buffer_size(4).await.unwrap(); + assert_eq!(file.read_up_to(1).await.unwrap().as_ref(), &PAYLOAD[..1]); + file.seek(3).await.unwrap(); + assert!( + !dropped.load(Ordering::Acquire), + "warm cache was not retained" + ); + let reader = { + let file = file.clone(); + tokio::spawn(async move { file.read_up_to(2).await }) + }; + started.notified().await; + tokio::time::timeout(Duration::from_millis(50), file.close()) + .await + .expect("close waited for I/O") + .unwrap(); + if cancel { + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + } else { + release.wait().await; + let error = reader.await.unwrap().unwrap_err(); + assert!(error.to_string().contains("already closed"), "{error}"); + } + assert!( + dropped.load(Ordering::Acquire), + "closed handle retained its old window (cancel={cancel})" + ); + } + } + #[derive(Debug)] struct BlockingRangeRequester { release: Arc, started: Arc, + block_start: usize, + tracked: Option>, } #[async_trait::async_trait] @@ -2544,17 +2828,31 @@ mod tests { _mode: RangeRequestMode, _version: Option, ) -> Result { - if range_header == "bytes=0-3" { + let (start, end) = range_header + .strip_prefix("bytes=") + .unwrap() + .split_once('-') + .unwrap(); + let start: usize = start.parse().unwrap(); + let end: usize = end.parse().unwrap(); + if start == self.block_start { self.started.notify_one(); self.release.wait().await; } + let bytes = match &self.tracked { + Some(dropped) if start == 0 => Bytes::from_owner(TrackedRangeBody { + bytes: PAYLOAD[start..=end].to_vec(), + dropped: dropped.clone(), + }), + _ => Bytes::copy_from_slice(&PAYLOAD[start..=end]), + }; let response = http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header( header::CONTENT_RANGE, - format!("bytes 0-{}/{}", PAYLOAD.len() - 1, PAYLOAD.len()), + format!("bytes {start}-{end}/{}", PAYLOAD.len()), ) - .body(PAYLOAD.to_vec()) + .body(bytes) .unwrap(); Ok(("hung".to_string(), Response::from(response)).into()) } @@ -2567,6 +2865,8 @@ mod tests { let requester: Arc = Arc::new(BlockingRangeRequester { release: release.clone(), started: started.clone(), + block_start: 0, + tracked: None, }); let file = Arc::new(RemoteBlobFile::new( requester, diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs new file mode 100644 index 000000000..e8e794fa0 --- /dev/null +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Flatten response batches once, releasing each source buffer as it is copied. + +use std::collections::VecDeque; + +use arrow_array::{Array, LargeBinaryArray}; +use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, OffsetBuffer}; +use arrow_schema::ArrowError; + +pub(super) struct BlobAccumulator { + offsets: Vec, + nulls: NullBufferBuilder, + values: VecDeque, + bytes: i64, +} + +impl BlobAccumulator { + pub(super) fn new(rows: usize) -> Self { + let mut offsets = Vec::with_capacity(rows + 1); + offsets.push(0); + Self { + offsets, + nulls: NullBufferBuilder::new(rows), + values: VecDeque::new(), + bytes: 0, + } + } + + pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + let offsets = array.value_offsets(); + let start = offsets[0]; + let length = offsets[array.len()] - start; + let total = self.bytes.checked_add(length).ok_or_else(|| { + ArrowError::ComputeError("fetch_blobs result exceeds i64 byte offsets".into()) + })?; + self.offsets.extend( + offsets[1..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + if let Some(nulls) = array.nulls() { + self.nulls.append_buffer(nulls); + } else { + self.nulls.append_n_non_nulls(array.len()); + } + if length != 0 { + self.values.push_back( + array + .values() + .slice_with_length(start as usize, length as usize), + ); + } + self.bytes = total; + Ok(()) + } + + pub(super) fn finish(mut self) -> LargeBinaryArray { + let values = match self.values.len() { + 0 => Buffer::default(), + 1 => self.values.pop_front().unwrap(), + _ => { + let mut values = MutableBuffer::new(self.bytes as usize); + // Do not retain all decoded batches alongside the final allocation. + // Drop each source allocation immediately after copying its bytes. + while let Some(chunk) = self.values.pop_front() { + values.extend_from_slice(&chunk); + } + values.into() + } + }; + LargeBinaryArray::new( + OffsetBuffer::new(self.offsets.into()), + values, + self.nulls.finish(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_buffer_is_not_copied() { + let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); + let mut result = BlobAccumulator::new(3); + result.append(&array).unwrap(); + let output = result.finish(); + assert_eq!(output.values().as_ptr(), array.values().as_ptr()); + assert_eq!(output, array); + } + + #[test] + fn slices_batches_nulls_and_empty_values_keep_order() { + let array = LargeBinaryArray::from(vec![ + Some(b"unused".as_slice()), + Some(b"alpha"), + None, + Some(b""), + Some(b"beta"), + ]); + let mut result = BlobAccumulator::new(6); + result.append(&array.slice(1, 3)).unwrap(); + result.append(&array.slice(4, 1)).unwrap(); + result.append(&array.slice(2, 2)).unwrap(); + assert_eq!( + result.finish(), + LargeBinaryArray::from(vec![ + Some(b"alpha".as_slice()), + None, + Some(b""), + Some(b"beta"), + None, + Some(b""), + ]) + ); + assert_eq!(BlobAccumulator::new(0).finish().len(), 0); + } +} diff --git a/rust/lancedb/src/remote/table/ipc_stream.rs b/rust/lancedb/src/remote/table/ipc_stream.rs index af31a9b28..08b3b1dea 100644 --- a/rust/lancedb/src/remote/table/ipc_stream.rs +++ b/rust/lancedb/src/remote/table/ipc_stream.rs @@ -3,6 +3,10 @@ //! Incremental decoding of response bodies that use Arrow IPC stream framing. +mod framing; + +use framing::{FramingError, IpcFraming}; + use arrow_array::RecordBatch; use arrow_buffer::Buffer; use arrow_ipc::reader::StreamDecoder; @@ -10,7 +14,6 @@ use bytes::Bytes; use datafusion_common::DataFusionError; use datafusion_physical_plan::SendableRecordBatchStream; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; -use futures::stream::BoxStream; use futures::{Stream, StreamExt, TryStreamExt}; use crate::error::{BoxError, Error, Result}; @@ -35,7 +38,7 @@ where E: Into + 'static, { let mut body = IpcStreamBody { - chunks: chunks.map_err(Into::into).boxed(), + framing: IpcFraming::new(chunks.map_err(Into::into).boxed()), chunk: Buffer::default(), decoder: StreamDecoder::new(), finished: false, @@ -62,7 +65,7 @@ where } struct IpcStreamBody { - chunks: BoxStream<'static, std::result::Result>, + framing: IpcFraming, /// The part of the current chunk that has not been decoded yet. chunk: Buffer, decoder: StreamDecoder, @@ -80,11 +83,12 @@ impl IpcStreamBody { async fn next_batch(&mut self) -> Result> { while !self.finished { if self.chunk.is_empty() { - match self.chunks.next().await { - Some(Ok(chunk)) => self.chunk = chunk.into(), - Some(Err(error)) => return Err(self.interrupted(error)), - None if read_end_of_stream(&mut self.decoder) => self.finished = true, - None => { + match self.framing.next_buffer().await { + Ok(Some(chunk)) => self.chunk = chunk, + Err(FramingError::Interrupted(error)) => return Err(self.interrupted(error)), + Err(FramingError::Arrow(error)) => return Err(error.into()), + Ok(None) if read_end_of_stream(&mut self.decoder) => self.finished = true, + Ok(None) => { return Err(self.interrupted( "the response ended before the Arrow end-of-stream marker".into(), )); @@ -208,6 +212,37 @@ mod tests { .collect() } + #[tokio::test] + async fn impossible_ipc_body_lengths_return_errors() { + let batches = batches(); + let messages = messages(&batches[0].schema(), &batches, IpcWriteOptions::default()); + for length in [-1, i64::MAX - 31, i64::MAX] { + let mut message = messages[1].clone(); + let metadata_len = u32::from_le_bytes(message[4..8].try_into().unwrap()) as usize; + let metadata = arrow_ipc::root_as_message(&message[8..8 + metadata_len]).unwrap(); + let field = metadata + ._tab + .vtable() + .get(arrow_ipc::Message::VT_BODYLENGTH); + assert_ne!(field, 0, "fixture must contain a body length field"); + let offset = 8 + metadata._tab.loc() + field as usize; + message[offset..offset + 8].copy_from_slice(&length.to_le_bytes()); + // A valid schema and message metadata followed by just one body byte. + message.truncate(8 + metadata_len + 1); + let (_, returned, error) = read(vec![ + Ok(Bytes::copy_from_slice(&messages[0])), + Ok(Bytes::from(message)), + ]) + .await; + assert!(returned.is_empty()); + let error = error.unwrap().to_string(); + assert!( + error.contains("body length") || error.contains("cannot allocate IPC message"), + "unexpected error for length {length}: {error}" + ); + } + } + /// The schema, the batches yielded, and the error that ended the stream. async fn read( chunks: Vec>, @@ -278,6 +313,78 @@ mod tests { assert_eq!(output, input); } + #[tokio::test] + async fn fragmented_body_keeps_only_its_declared_allocation() { + use arrow_array::LargeBinaryArray; + + let bytes = vec![42; 3 * 1024 * 1024 + 13]; + let array = LargeBinaryArray::from(vec![bytes.as_slice()]); + let batch = RecordBatch::try_from_iter([("blob", Arc::new(array) as ArrayRef)]).unwrap(); + let body = messages( + &batch.schema(), + std::slice::from_ref(&batch), + IpcWriteOptions::default(), + ) + .concat(); + let (_, output, error) = read(chunks(&body, 8191)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, [batch]); + let blobs = output[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!( + blobs.values().capacity() <= bytes.len() + 256, + "IPC body retained {} bytes for {} value bytes", + blobs.values().capacity(), + bytes.len() + ); + } + + #[rstest] + #[case(false)] + #[case(true)] + #[tokio::test] + async fn zero_body_batches_and_legacy_prefixes(#[case] legacy: bool) { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let input = [vec![], vec![1, 2], vec![]] + .into_iter() + .map(|values| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(values))]) + .unwrap() + }) + .collect::>(); + let options = IpcWriteOptions::try_new(8, legacy, arrow_ipc::MetadataVersion::V4).unwrap(); + let body = messages(&schema, &input, options).concat(); + let (_, output, error) = read(chunks(&body, 1)).await; + assert!(error.is_none(), "{error:?}"); + assert_eq!(output, input); + } + + #[tokio::test] + async fn partial_next_prefix_still_delivers_a_zero_body_batch() { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let empty = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(Vec::::new()))], + ) + .unwrap(); + let nonempty = + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1]))]) + .unwrap(); + let messages = messages( + &schema, + &[empty.clone(), nonempty], + IpcWriteOptions::default(), + ); + let cutoff = messages[..2].concat().len() + 1; + let body = messages.concat(); + let (_, output, error) = read(chunks(&body[..cutoff], 1)).await; + assert_eq!(output, [empty]); + assert_interrupted(error, 1, 0); + } + /// The server answers an empty result with the schema and the end-of-stream marker. #[tokio::test] async fn empty_result_keeps_its_schema() { diff --git a/rust/lancedb/src/remote/table/ipc_stream/framing.rs b/rust/lancedb/src/remote/table/ipc_stream/framing.rs new file mode 100644 index 000000000..da20c8e99 --- /dev/null +++ b/rust/lancedb/src/remote/table/ipc_stream/framing.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Frame IPC bodies before decoding, avoiding StreamDecoder's growing scratch buffer. + +use arrow_buffer::Buffer; +use arrow_schema::ArrowError; +use bytes::Bytes; +use futures::StreamExt; +use futures::stream::BoxStream; + +use crate::error::BoxError; + +pub(super) enum FramingError { + Interrupted(BoxError), + Arrow(ArrowError), +} + +#[derive(Clone, Copy)] +enum Frame { + Header { + bytes: [u8; 4], + read: usize, + continuation: bool, + }, + Metadata(usize), + Body(usize), + End, +} + +impl Default for Frame { + fn default() -> Self { + Self::Header { + bytes: [0; 4], + read: 0, + continuation: false, + } + } +} + +pub(super) struct IpcFraming { + chunks: BoxStream<'static, Result>, + chunk: Buffer, + frame: Frame, +} + +impl IpcFraming { + pub(super) fn new(chunks: BoxStream<'static, Result>) -> Self { + Self { + chunks, + chunk: Buffer::default(), + frame: Frame::default(), + } + } + + pub(super) async fn next_buffer(&mut self) -> Result, FramingError> { + let buffer = match self.frame { + Frame::Header { + mut bytes, + mut read, + continuation, + } => { + // Forward even a partial prefix immediately. StreamDecoder may + // need that byte to yield the preceding zero-body record batch. + self.fill_chunk().await?; + let take = self.chunk.len().min(4 - read); + let buffer = self.chunk.slice_with_length(0, take); + self.chunk.advance(take); + bytes[read..read + take].copy_from_slice(&buffer); + read += take; + self.frame = if read == 4 { + match u32::from_le_bytes(bytes) { + u32::MAX if !continuation => Frame::Header { + bytes: [0; 4], + read: 0, + continuation: true, + }, + 0 => Frame::End, + length => Frame::Metadata(length as usize), + } + } else { + Frame::Header { + bytes, + read, + continuation, + } + }; + buffer + } + Frame::Metadata(length) => { + let metadata = self.read_exact(length).await?; + let message = arrow_ipc::root_as_message(&metadata).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "Invalid IPC message: {error}" + ))) + })?; + let length = usize::try_from(message.bodyLength()).map_err(|_| { + FramingError::Arrow(ArrowError::IpcError( + "IPC message body length is negative or exceeds addressable memory".into(), + )) + })?; + self.frame = if length == 0 { + Frame::default() + } else { + Frame::Body(length) + }; + metadata + } + Frame::Body(length) => { + let body = self.read_exact(length).await?; + self.frame = Frame::default(); + body + } + Frame::End => { + // Forward trailing bytes to the decoder so it rejects data after EOS. + if !self.chunk.is_empty() { + return Ok(Some(std::mem::take(&mut self.chunk))); + } + return self + .chunks + .next() + .await + .transpose() + .map(|chunk| chunk.map(Buffer::from)) + .map_err(FramingError::Interrupted); + } + }; + Ok(Some(buffer)) + } + + async fn read_exact(&mut self, length: usize) -> Result { + self.fill_chunk().await?; + if self.chunk.len() >= length { + let buffer = self.chunk.slice_with_length(0, length); + self.chunk.advance(length); + return Ok(buffer); + } + // The declared length is untrusted. Arrow's infallible aligned allocator + // can panic on its layout or abort on OOM; Vec exposes both as errors. + // StreamDecoder handles any array-specific alignment when decoding. + let mut buffer = Vec::new(); + buffer.try_reserve_exact(length).map_err(|error| { + FramingError::Arrow(ArrowError::IpcError(format!( + "cannot allocate IPC message of {length} bytes: {error}" + ))) + })?; + while buffer.len() < length { + self.fill_chunk().await?; + let take = self.chunk.len().min(length - buffer.len()); + buffer.extend_from_slice(&self.chunk[..take]); + self.chunk.advance(take); + } + Ok(Buffer::from_vec(buffer)) + } + + async fn fill_chunk(&mut self) -> Result<(), FramingError> { + while self.chunk.is_empty() { + self.chunk = self + .chunks + .next() + .await + .ok_or_else(|| { + FramingError::Interrupted( + "the response ended before the Arrow end-of-stream marker".into(), + ) + })? + .map_err(FramingError::Interrupted)? + .into(); + } + Ok(()) + } +} From 725eee8a47399ec634ad20b98e4968334d89b27d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:13 +0800 Subject: [PATCH 091/203] fix: prevent unsafe write retries and bound Blob uploads (#4977) Ambiguous gateway failures can occur after a write commits, so replaying the operation can append duplicate rows. Non-idempotent writes now retry only known precommit failures. Multipart retries reuse the same upload ID, part ID, and encoded bytes; ambiguous completion returns an unknown-outcome error without abort or replay. A definite 409/429 completion rejection triggers best-effort cleanup using the call's retry budget. Replayable parts and the shared byte-based partition target default to 64 MiB. Dictionary-bearing batches are compacted before size estimation and again when actual compressed IPC framing requires further splitting: keys are remapped without changing their types or schema, view backing buffers are collected, and ListView/LargeListView child ranges are compacted as an interval union so overlapping views retain sharing. Parts are prepared on demand; a single row and its schema can still exceed the target. Multipart progress starts at zero and counts each acknowledged IPC body once. Rust write builders and Python/TypeScript `add` expose per-call retry overrides. Atomic `create_table` pre-encodes to a temporary file and rejects compressed IPC over 256 MiB before sending any request; the schema-first import guidance now includes Python, TypeScript, and Rust examples. The shared partition target also affects local automatic partitioning. At `cb2a79473bd1b51b950c9fa3e9f247f929c8ac3b`, 70 targeted Rust cases pass on source verified against the committed four-file patch. With a 16 KiB target and 128 unique 1 KiB dictionary values, the original ordinary dictionary reproducer drops from 128 requests / 16,942,080 bytes to 16 / 143,488; ListView and LargeListView drop from 128 / 17,056,768 to 16 / 149,632. Encoded HTTP bodies are decoded to check values, nulls, slices, metadata, changing dictionaries, and overlapping views; additional cases cover framing-driven splitting, oversized rows, stable retry bytes/IDs, acknowledged progress, and atomic create. Real HTTP fault tests commit Blob payloads to a local Lance table and verify byte equality, no duplicate append, and zero abort/replay after ambiguous completion. The earlier 811 remote and 7 progress cases at `f36d217110a25f6b501c0255df9aaa60e3c8000a`, Linux Python remote database/options results (437 cases plus 8 fixture consumers), Node retry-binding evidence, and Rust/TypeScript documentation example checks remain historical validation. Python/Node extensions were not rebuilt for the dictionary follow-up; these results do not establish current binding integration or fresh cross-platform/minimum-dependency CI acceptance. A separate real Query Node lifecycle experiment used SDK `b8efe7d2d63647d4962789ca5fc042b59efe073d` and Sophon `58b7895c7c287810fff4e89f13226fc5fa60d9ef`. After the actual listener forced a connection closed, a surviving QN accepted a retry with identical upload ID, part ID, and IPC bytes. Ordinary insert and complete response-loss scenarios sent no replay or abort; fresh reads observed exactly one commit and exact Blob bytes in all three scenarios. This local experiment used a 1-second drain grace, two 32 KiB payloads, and one distinct staged part. It validates acknowledgement-loss recovery at those revisions, not concurrent overlapping attempts, large uploads, physical orphan cleanup, the later dictionary encoding change, or the original sixth-insert EOF. The part target is not a process memory limit: source/ancestor buffers and temporary compaction allocations may coexist. Struct/FixedSizeList parent nulls can retain hidden child keys; this is not complete logical-reachability GC for every Arrow combination, and retained hidden values may affect wire size. The current local Lance 15.0.0-beta.17 rejects ListView/LargeListView persistence; the tests establish remote client IPC encoding behavior, not native or Cloud persistence support. Live Cloud, full workspace/Clippy, the original ordinary-insert disconnect root cause, and Sophon's asynchronous transaction cleanup behavior are not established. Cancelling during staging retains the existing server-session cleanup limitation. Function reader delivery is separate. --- docs/src/js/interfaces/AddDataOptions.md | 12 + docs/web/ingestion/insert.mdx | 102 ++- nodejs/__test__/remote.test.ts | 59 ++ nodejs/lancedb/table.ts | 16 + nodejs/src/table.rs | 8 +- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/remote/table.py | 5 + python/python/lancedb/table.py | 17 + python/python/tests/test_remote_db.py | 302 ++++++- python/src/table.rs | 6 +- rust/lancedb/src/data/scannable.rs | 8 +- rust/lancedb/src/remote/client.rs | 65 +- rust/lancedb/src/remote/db.rs | 145 ++- rust/lancedb/src/remote/retry.rs | 35 +- rust/lancedb/src/remote/table.rs | 441 +++++++--- rust/lancedb/src/remote/table/insert.rs | 875 +++++++++++++++---- rust/lancedb/src/remote/table/write_tests.rs | 436 +++++++++ rust/lancedb/src/remote/util.rs | 283 +++++- rust/lancedb/src/table/add_data.rs | 12 + rust/lancedb/src/table/merge.rs | 10 + rust/lancedb/src/table/update.rs | 9 + rust/lancedb/src/table/write_progress.rs | 27 +- 22 files changed, 2484 insertions(+), 390 deletions(-) create mode 100644 rust/lancedb/src/remote/table/write_tests.rs diff --git a/docs/src/js/interfaces/AddDataOptions.md b/docs/src/js/interfaces/AddDataOptions.md index f1f57b98b..567269471 100644 --- a/docs/src/js/interfaces/AddDataOptions.md +++ b/docs/src/js/interfaces/AddDataOptions.md @@ -71,3 +71,15 @@ await table.add(data, { }, }); ``` + +*** + +### retries? + +```ts +optional retries: number; +``` + +Override the remote retry budget for this call (0 to 255). Zero disables +retries, including multipart parts. Ambiguous commits are never replayed. +Ignored by LanceDB Embedded. diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index befc1c37b..923a71b0e 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -150,6 +150,10 @@ Python and TypeScript report elapsed time in seconds; Rust returns a `Duration`. The expected row count may be unknown for streaming input. On the final update, it falls back to the number of rows written. +For remote multipart writes, rows count input scanning, while bytes count +acknowledged IPC parts. Bytes start at zero and a retried part is counted once, +after acknowledgement. Scanned rows and staged bytes do not imply a commit. + Keep callbacks short and use the write operation's result to determine success. The final `done` update means progress reporting has ended; it can also occur after a write fails or is cancelled. Input errors before writing starts may @@ -164,11 +168,29 @@ from a TypeScript callback are logged and do not abort the write. 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 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. +repeating an append can duplicate rows. Current clients do not automatically +replay non-idempotent writes after `500`, `502`, `503`, or `504`, or after a +response is lost. A plain `503` does not prove that a write was rejected before +commit. Connection failures before sending, `409` transaction conflicts, and +explicit `429` rate-limit rejections may be retried within `RetryConfig` limits. Idempotent multipart +parts have a separate retry policy described below. + +If multipart completion times out, loses its response, or receives a `5xx`, the +error reports **commit outcome unknown**. The client neither aborts the upload +nor resends completion or the input under +a new upload ID: aborting at this point could delete already committed data. +Check the table using your record IDs before retrying the operation. + +Configure connection-wide limits with `client_config.retry_config` in Python +(`lancedb.remote.RetryConfig`) or `clientConfig.retryConfig` in TypeScript. +Override the budget for one `add()` with Python `table.add(data, retries=0)` +or TypeScript `table.add(data, { retries: 0 })`. The value must be an integer +between 0 and 255. Rust write builders also provide a per-call override, for +example `table.add(data).retries(0).execute().await?`, +`table.update().retries(0)`, and `table.merge_insert(&["id"]).retries(0)`. +This disables transport retries for that operation, including multipart part +retries; it does not change local transaction conflict handling. Increasing a +retry budget never makes ambiguous commits safe to replay. ## Configure large uploads {#bulk-ingests-into-a-remote-table} @@ -176,26 +198,41 @@ IDs, or choose an upsert policy designed for replay. This section applies only to LanceDB Enterprise tables (`db://` connections). LanceDB Embedded writes are unaffected. -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: +Large measured inputs, unknown-length streams, and explicit parallel uploads use +multipart writes when the server supports them. The client slices large batches +before IPC encoding and buffers each part for replay. A disconnected request, +read timeout, or configured retryable staging status retries exactly the same +upload ID, part ID, and IPC bytes. `RetryConfig.statuses` controls status retries; +an empty list disables them. The default includes `500`, `502`, `503`, and `504`. +The server replaces that part's staged transaction, so losing +its response does not append the rows twice. Exhausting the part retry budget +aborts the uncommitted session; it does not restart the entire upload. +A complete request rejected with a transaction conflict (`409`) or rate limit +(`429`) also triggers best-effort cleanup. Cleanup uses the call's retry budget; +its failure does not replace the original error. Ambiguous completion outcomes +never trigger cleanup or replay. -```text -lancedb.remote.errors.HttpError: operation timed out -``` +Part size still affects memory and HTTP timeouts. A single blob row cannot be +split across Arrow batches; a very large row may require a larger timeout and +more memory. No connection-pool or keepalive setting guarantees that a write +response will arrive. Two environment variables control how a multipart write's parts are cut. Both are picked up automatically by the Python and TypeScript clients, for clients that support these settings: | Variable | Default | What it controls | |----------|---------|------------------| -| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 8 GiB | Maximum size of a single insert part, in LZ4-compressed Arrow IPC bytes. Set to `0` to disable splitting and send one request per partition. | -| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Maximum wall-clock time, in whole seconds, that any one insert part may stay open. Set to `0` to disable the time-based cut. | +| `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` | 64 MiB | Target LZ4-compressed IPC bytes per replayable part. A single indivisible row and its IPC schema may exceed the target. `0` disables byte-based cuts and can require buffering a whole partition. | +| `LANCE_CLIENT_MAX_REQUEST_DURATION` | Half the read timeout | Time spent filling a replayable payload, in whole seconds. `0` disables time-based cuts. HTTP deadlines are configured separately in `timeout_config`. | -A part is cut after the input batch that reaches either limit, so cuts fall between batches. Lower the byte budget, with smaller input batches, when large ingests hit the read timeout; lower the duration when uploads are slow or throttled and the byte budget isn't the limiting factor. +A part is cut after an encoding slice reaches either limit. Input batches are +sliced to approximately 8 MiB before encoding, preserving row order. Peak +additional memory scales with active writers and the part budget. Lower +`write_parallelism` or the byte budget to reduce memory use. ```bash Bash icon="terminal" -export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=1073741824 # 1 GiB -export LANCE_CLIENT_MAX_REQUEST_DURATION=120 # 2 minutes +export LANCE_CLIENT_MAX_BYTES_PER_REQUEST=33554432 # 32 MiB +export LANCE_CLIENT_MAX_REQUEST_DURATION=30 # payload preparation budget ``` @@ -203,6 +240,41 @@ Splitting into more parts does not change the final table. The server stages the the write. This upload protocol is separate from repeating an application-level `add()` after a timeout. +Remote `create_table(name, data)` remains one atomic request, including overwrite +and `exist_ok` modes. The client encodes into an automatically removed temporary +file before sending, rejects payloads larger than 256 MiB of compressed IPC, and +never silently creates an empty table as a fallback. Encoding and input failures +therefore issue no create request. Temporary disk usage is bounded by this budget; +individual oversized rows can still need substantial encoding memory. + +For larger imports, create the schema first and upload with progress reporting. +The empty table becomes visible immediately; `add()` commits its rows atomically. +The following examples use an existing connection `db`, an Arrow `schema`, and +input `data` matching that schema (an Arrow reader in Rust): + + +```python Python icon="python" +table = db.create_table("items", schema=schema) +table.add(data, progress=True) +``` + +```typescript TypeScript icon="square-js" +const table = await db.createEmptyTable("items", schema); +await table.add(data, { + progress: (p) => console.log(`Rows written: ${p.outputRows}`), +}); +``` + +```rust Rust icon="rust" +let table = db.create_empty_table("items", schema).execute().await?; +table + .add(data) + .progress(|p| println!("Rows written: {}", p.output_rows())) + .execute() + .await?; +``` + + ## Complete write workflow {#complete-example} diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 4ac08b4c4..a9989b84e 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -483,6 +483,65 @@ describe("remote connection", () => { expect(insertRequests).toBe(2); }); + it.each([ + { status: 429, retries: undefined, attempts: 2 }, + { status: 429, retries: 0, attempts: 1 }, + { status: 504, retries: undefined, attempts: 1 }, + { status: 504, retries: 0, attempts: 1 }, + ])("applies per-call add retries: %j", async (scenario) => { + let attempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + expect(req.url).toContain("/insert/"); + req.resume(); + req.on("end", () => { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + }); + }, + async (db) => { + const table = await db.openTable("items"); + const result = table.add([{ id: 1n }], { retries: scenario.retries }); + if (scenario.attempts === 2) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + for (const retries of [-1, 256, 1.5]) { + await expect(table.add([{ id: 2n }], { retries })).rejects.toThrow( + "retries must be an integer between 0 and 255", + ); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [429, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(scenario.attempts); + }); + it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index b38c2381c..185088424 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -137,6 +137,13 @@ export interface AddDataOptions { * when the blob is read later. */ allowExternalBlobOutsideBases?: boolean; + + /** + * Override the remote retry budget for this call (0 to 255). Zero disables + * retries, including multipart parts. Ambiguous commits are never replayed. + * Ignored by LanceDB Embedded. + */ + retries?: number; } export interface UpdateOptions { @@ -1320,6 +1327,14 @@ export class LocalTable extends Table { } async add(data: Data, options?: Partial): Promise { + if ( + options?.retries !== undefined && + (!Number.isInteger(options.retries) || + options.retries < 0 || + options.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } const mode = options?.mode ?? "append"; const schema = await this.schema(); @@ -1342,6 +1357,7 @@ export class LocalTable extends Table { mode, progress, options?.allowExternalBlobOutsideBases, + options?.retries, ); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index e3bd22c0b..7076bbec1 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -134,7 +134,7 @@ impl Table { #[napi( catch_unwind, - ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean" + ts_args_type = "buf: Buffer, mode: string, progressCallback?: (progress: WriteProgressInfo) => void, allowExternalBlobOutsideBases?: boolean, retries?: number" )] pub async fn add( &self, @@ -142,6 +142,7 @@ impl Table { mode: String, progress_callback: Option, allow_external_blob_outside_bases: Option, + retries: Option, ) -> napi::Result { let batches = ipc_file_to_batches(buf.to_vec()) .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?; @@ -157,6 +158,11 @@ impl Table { }) .collect::>>()?; let mut op = self.inner_ref()?.add(batches); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + op = op.retries(retries); + } op = if mode == "append" { op.mode(AddDataMode::Append) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4f1da9ba7..15234532d 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -544,6 +544,7 @@ class Table: progress: Optional[Any] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: ... async def update( self, updates: Dict[str, str], where: Optional[str] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 21749a0a7..6730e6694 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -719,6 +719,7 @@ class RemoteTable(Table): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -753,6 +754,9 @@ class RemoteTable(Table): using too much memory. allow_external_blob_outside_bases: bool, default False Not supported in LanceDB Enterprise. Setting this raises. + retries: int, optional + Override the retry budget for this call (0 to 255). Zero disables + retries, including multipart parts. Ambiguous commits are never replayed. Returns ------- @@ -770,6 +774,7 @@ class RemoteTable(Table): progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) ) finally: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 424b4b64c..3161eda30 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2256,6 +2256,7 @@ class Table(ABC): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -2316,6 +2317,10 @@ class Table(ABC): Store blob URIs that sit outside registered blob bases. The row keeps a reference, so the object has to stay readable. Local tables only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. Returns ------- @@ -4821,6 +4826,7 @@ class LanceTable(Table): progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add data to the table. If vector columns are missing and the table @@ -4852,6 +4858,10 @@ class LanceTable(Table): allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. LanceDB Embedded only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. Returns ------- @@ -4869,6 +4879,7 @@ class LanceTable(Table): progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) ) finally: @@ -7080,6 +7091,7 @@ class AsyncTable: progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, allow_external_blob_outside_bases: bool = False, + retries: Optional[int] = None, ) -> AddResult: """Add more data to the [AsyncTable][lancedb.table.AsyncTable]. @@ -7118,6 +7130,10 @@ class AsyncTable: allow_external_blob_outside_bases: bool, default False Allow blob URIs outside registered bases. See :meth:`Table.add`. LanceDB Embedded only. + retries: int, optional + Override the remote retry budget for this call (0 to 255). Zero + disables retries, including multipart parts. Ambiguous commits are + never replayed. Ignored by LanceDB Embedded. """ schema = await self.schema() @@ -7172,6 +7188,7 @@ class AsyncTable: progress=progress, write_parallelism=write_parallelism, allow_external_blob_outside_bases=allow_external_blob_outside_bases, + retries=retries, ) except RuntimeError as e: if "Cast error" in str(e): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 8fde1209c..448fd6c39 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -59,20 +59,124 @@ import pyarrow as pa from utils import start_server_thread -def make_mock_http_handler(handler): +def make_mock_http_handler(handler, *, buffer_body=True): class MockLanceDBHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): handler(self) def do_POST(self): - handler(self) + if not buffer_body: + handler(self) + return - def do_PUT(self): - handler(self) + # HTTP/1.0 closes after the response. Leaving a streamed upload unread + # can reset the connection while the client is still writing its body. + # Keep the original framing so handlers can inspect the actual request. + source = self.rfile + body = bytearray() + if self.headers.get("Transfer-Encoding") == "chunked": + while True: + line = source.readline() + assert line.endswith(b"\r\n") + body.extend(line) + size = int(line.split(b";")[0], 16) + if size == 0: + while True: + line = source.readline() + assert line.endswith(b"\r\n") + body.extend(line) + if line == b"\r\n": + break + break + chunk = source.read(size + 2) + assert len(chunk) == size + 2 and chunk[-2:] == b"\r\n" + body.extend(chunk) + else: + size = int(self.headers.get("Content-Length", 0)) + body.extend(source.read(size)) + assert len(body) == size + self.rfile = io.BytesIO(body) + try: + handler(self) + finally: + self.rfile.close() + self.rfile = source + + do_PUT = do_POST return MockLanceDBHandler +@pytest.mark.parametrize("chunked", [False, True]) +@pytest.mark.parametrize("read_body", [False, True]) +def test_mock_http_handler_waits_for_body(chunked, read_body): + body = ( + b"7;ext=value\r\npayload\r\n0\r\nX-Trailer: value\r\n\r\n" + if chunked + else b"payload" + ) + received = [] + + def handler(request): + if read_body: + assert (request.headers.get("Transfer-Encoding") == "chunked") == chunked + received.append(request.rfile.read(len(body))) + request.send_response(200) + request.end_headers() + + with http.server.HTTPServer( + ("127.0.0.1", 0), make_mock_http_handler(handler) + ) as server: + thread = start_server_thread(server) + try: + with socket.create_connection(server.server_address, timeout=2) as client: + framing = ( + "Transfer-Encoding: chunked" if chunked else "Content-Length: 7" + ) + client.sendall( + f"POST / HTTP/1.0\r\nHost: localhost\r\n{framing}\r\n\r\n".encode() + ) + client.settimeout(0.1) + with pytest.raises(TimeoutError): + client.recv(1024) + client.settimeout(2) + client.sendall(body) + assert client.recv(1024).startswith(b"HTTP/1.0 200") + finally: + server.shutdown() + thread.join() + assert received == ([body] if read_body else []) + + +@pytest.mark.parametrize("disconnect", [False, True]) +def test_mock_http_handler_allows_early_failure(disconnect): + def handler(request): + if disconnect: + request.connection.shutdown(socket.SHUT_RDWR) + request.close_connection = True + else: + request.send_response(413) + request.end_headers() + + with http.server.HTTPServer( + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=False) + ) as server: + thread = start_server_thread(server) + try: + with socket.create_connection(server.server_address, timeout=2) as client: + client.sendall( + b"POST / HTTP/1.0\r\nHost: localhost\r\nContent-Length: 7\r\n\r\n" + ) + response = client.recv(1024) + if disconnect: + assert response == b"" + else: + assert response.startswith(b"HTTP/1.0 413") + finally: + server.shutdown() + thread.join() + + @pytest.mark.parametrize("db_name", ["a" * 64, "invalid..database"]) def test_connect_rejects_invalid_cloud_dns_hostname(db_name): with pytest.raises(ValueError, match="DNS labels must contain 1 to 63 bytes"): @@ -80,9 +184,9 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name): @contextlib.contextmanager -def mock_lancedb_connection(handler, **client_config): +def mock_lancedb_connection(handler, *, buffer_body=True, **client_config): with http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body) ) as server: port = server.server_address[1] handle = start_server_thread(server) @@ -108,9 +212,9 @@ def mock_lancedb_connection(handler, **client_config): @contextlib.asynccontextmanager -async def mock_lancedb_connection_async(handler, **client_config): +async def mock_lancedb_connection_async(handler, *, buffer_body=True, **client_config): with http.server.HTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(handler) + ("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body) ) as server: port = server.server_address[1] handle = start_server_thread(server) @@ -135,6 +239,76 @@ async def mock_lancedb_connection_async(handler, **client_config): handle.join() +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.parametrize("retries", [None, 0]) +@pytest.mark.parametrize("status", [429, 504]) +@pytest.mark.asyncio +async def test_add_retry_override(sync_api, retries, status): + attempts = 0 + + def handler(request): + nonlocal attempts + if request.path.endswith("/describe/"): + payload = { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": True} + ] + }, + } + request.send_response(200) + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + return + assert request.path.endswith("/insert/") + body = bytearray() + if request.headers.get("Transfer-Encoding") == "chunked": + while True: + size = int(request.rfile.readline().strip(), 16) + if size == 0: + request.rfile.readline() + break + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body.extend( + request.rfile.read(int(request.headers.get("Content-Length", 0))) + ) + assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}] + attempts += 1 + request.send_response(status if attempts == 1 else 200) + request.end_headers() + request.wfile.write(b'{"version": 2}') + + config = { + "retry_config": { + "retries": 3, + "statuses": [429, 504], + "backoff_factor": 0, + "backoff_jitter": 0, + } + } + expected_success = status == 429 and retries is None + if sync_api: + with mock_lancedb_connection(handler, **config) as db: + table = db.open_table("test") + if expected_success: + assert table.add([{"id": 1}], retries=retries).version == 2 + else: + with pytest.raises((HttpError, RetryError)): + table.add([{"id": 1}], retries=retries) + else: + async with mock_lancedb_connection_async(handler, **config) as db: + table = await db.open_table("test") + if expected_success: + assert (await table.add([{"id": 1}], retries=retries)).version == 2 + else: + with pytest.raises((HttpError, RetryError)): + await table.add([{"id": 1}], retries=retries) + assert attempts == (2 if expected_success else 1) + + @pytest.fixture def missing_table_handler(cached, namespace_path): request_ids = [] @@ -1248,7 +1422,7 @@ async def test_create_table_timeout_is_actionable(timeout_config): request.close_connection = True async with mock_lancedb_connection_async( - handler, timeout_config=timeout_config + handler, buffer_body=False, timeout_config=timeout_config ) as db: batch = pa.record_batch({"id": [1, 2]}) reader = pa.RecordBatchReader.from_batches(batch.schema, [batch]) @@ -5076,10 +5250,14 @@ def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested) @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) -@pytest.mark.parametrize("mode", ["merge", "overwrite"]) +@pytest.mark.parametrize( + "mode,part_status", + [("merge", 200), ("overwrite", 200), ("overwrite", 503)], + ids=["merge", "overwrite", "overwrite-retry"], +) @pytest.mark.parametrize("target_with_ranges", [False, True]) async def test_remote_writes_normalize_blob_layouts( - use_async, mode, target_with_ranges + use_async, mode, part_status, target_with_ranges, mem_db ): description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE)) if target_with_ranges: @@ -5088,29 +5266,77 @@ async def test_remote_writes_normalize_blob_layouts( for name in ("position", "size") ) received = [] + paths = [] + staged = {} + part_attempts = [] + published = mem_db.create_table( + "published", + [{"id": 0, "image": b"before"}], + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), + ) def handler(request): - if request.path == "/v1/table/test/describe/": + path = urlparse(request.path).path + query = parse_qs(urlparse(request.path).query) + status = 200 + if path == "/v1/table/test/describe/": response = description else: - expected = "merge_insert" if mode == "merge" else "insert" - assert urlparse(request.path).path == f"/v1/table/test/{expected}/" - if request.headers.get("Transfer-Encoding") == "chunked": - body = bytearray() - while size := int(request.rfile.readline().split(b";")[0], 16): - body.extend(request.rfile.read(size)) - assert request.rfile.read(2) == b"\r\n" - assert request.rfile.read(2) == b"\r\n" + paths.append(path.removeprefix("/v1/table/test/")) + body = request.rfile.read() + if path == "/v1/table/test/multipart_write/create": + assert mode == "overwrite" + assert paths == ["multipart_write/create"] + assert not query and not body + response = {"upload_id": "blob-overwrite"} + elif path == "/v1/table/test/insert/": + assert mode == "overwrite" + assert query["mode"] == ["overwrite"] + assert query["upload_id"] == ["blob-overwrite"] + part_id = query["upload_part_id"][0] + assert str(uuid.UUID(part_id)) == part_id + part_attempts.append((part_id, body)) + assert published.version == 1 + assert published.search().select(["id"]).to_list() == [{"id": 0}] + if staged: + assert staged == {part_id: body} + else: + staged[part_id] = body + assert body[-8:] == b"\xff\xff\xff\xff\x00\x00\x00\x00" + received.append(pa.ipc.open_stream(body).read_all()) + status = part_status if len(part_attempts) == 1 else 200 + response = {} + elif path == "/v1/table/test/multipart_write/complete": + assert mode == "overwrite" + assert query == {"upload_id": ["blob-overwrite"]} and not body + expected_attempts = 2 if part_status == 503 else 1 + assert paths == ["multipart_write/create"] + [ + "insert/" + ] * expected_attempts + ["multipart_write/complete"] + assert len(staged) == len(received) == 1 + assert part_attempts == [part_attempts[0]] * expected_attempts + assert published.version == 1 + published.add(received[0], mode="overwrite") + response = {"version": published.version} else: - body = request.rfile.read(int(request.headers["Content-Length"])) - received.append(pa.ipc.open_stream(body).read_all()) - response = { - "version": 2, - "num_updated_rows": 0, - "num_inserted_rows": 2, - "num_deleted_rows": 0, - } - request.send_response(200) + assert mode == "merge" + assert path == "/v1/table/test/merge_insert/" + # merge_insert still streams a chunked body; preserve its framing. + if request.headers.get("Transfer-Encoding") == "chunked": + stream = io.BytesIO(body) + body = bytearray() + while size := int(stream.readline().split(b";")[0], 16): + body.extend(stream.read(size)) + assert stream.read(2) == b"\r\n" + assert stream.read(2) == b"\r\n" + received.append(pa.ipc.open_stream(body).read_all()) + response = { + "version": 2, + "num_updated_rows": 0, + "num_inserted_rows": 2, + "num_deleted_rows": 0, + } + request.send_response(status) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", "0.5.0") request.end_headers() @@ -5143,7 +5369,23 @@ async def test_remote_writes_normalize_blob_layouts( else: result = table.add(data, mode="overwrite") if use_async: - await result + result = await result + assert result.version == 2 + + if mode == "overwrite": + assert published.version == 2 + hits = published.search().select(["id"]).with_row_id(True).to_arrow() + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + assert set(by_id) == {1, 2} + row_ids = [by_id[1], by_id[2]] + assert published.fetch_blobs("image", row_ids).to_pylist() == [b"payload", None] + payload, null = published.fetch_blob_files("image", row_ids) + assert null is None + with payload: + assert payload.read_range(1, 3) == b"ayl" + assert payload.read() == b"payload" + else: + assert paths == ["merge_insert/"] assert len(received) == 1 images = received[0]["image"].combine_chunks() diff --git a/python/src/table.rs b/python/src/table.rs index 62c2ee765..e76bae00a 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1471,7 +1471,7 @@ impl Table { }) } - #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false))] + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))] pub fn add<'a>( self_: PyRef<'a, Self>, data: PyScannable, @@ -1479,6 +1479,7 @@ impl Table { progress: Option>, write_parallelism: Option, allow_external_blob_outside_bases: bool, + retries: Option, ) -> PyResult> { let mut op = self_ .inner_ref()? @@ -1491,6 +1492,9 @@ impl Table { } else { return Err(PyValueError::new_err(format!("Invalid mode: {}", mode))); } + if let Some(retries) = retries { + op = op.retries(retries); + } if let Some(write_parallelism) = write_parallelism { op = op.write_parallelism(write_parallelism); } diff --git a/rust/lancedb/src/data/scannable.rs b/rust/lancedb/src/data/scannable.rs index 0f810941a..cfad157b8 100644 --- a/rust/lancedb/src/data/scannable.rs +++ b/rust/lancedb/src/data/scannable.rs @@ -504,7 +504,7 @@ impl Scannable for PeekedScannable { /// when known; otherwise `sample_rows` row count is used as a lower bound /// estimate. /// -/// Targets roughly 1 million rows or 2 GB per partition, capped at +/// Targets roughly 1 million rows or 64 MiB per partition, capped at /// `max_partitions` (typically the number of available CPU cores). pub(crate) fn estimate_write_partitions( sample_bytes: usize, @@ -519,7 +519,7 @@ pub(crate) fn estimate_write_partitions( let total_rows = total_rows_hint.unwrap_or(sample_rows); let total_bytes = total_rows * bytes_per_row; let by_rows = total_rows.div_ceil(1_000_000); - let by_bytes = total_bytes.div_ceil(2 * 1024 * 1024 * 1024); + let by_bytes = total_bytes.div_ceil(64 * 1024 * 1024); by_rows.max(by_bytes).max(1).min(max_partitions) } @@ -813,8 +813,8 @@ mod tests { #[test] fn test_scales_by_byte_size() { - // 100k rows at 40KB/row = ~4GB total → ceil(4GB / 2GB) = 2 - let sample_bytes = 40_000 * 10; + // 100k rows at 1KB/row exceeds one 64 MiB partition. + let sample_bytes = 1_000 * 10; assert_eq!( estimate_write_partitions(sample_bytes, 10, Some(100_000), 8), 2 diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index e0722bfbc..b16d0091d 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -69,14 +69,9 @@ pub trait HeaderProvider: Send + Sync + std::fmt::Debug { async fn get_headers(&self) -> Result>; } -/// Default maximum bytes per insert request (8 GiB). -/// -/// Sized so a multipart part can hold at least one full Lance data file (the -/// default is 1M rows / 90 GB per file), which keeps fragments from being split -/// into undersized files across parts. The time-based cut -/// ([`DEFAULT_MAX_REQUEST_DURATION_DIVISOR`]) bounds request duration on slow -/// uploads, so a large byte budget does not risk the read timeout. -const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 8 * 1024 * 1024 * 1024; +/// Default target size for replayable multipart IPC payloads (64 MiB). +/// A single oversized row (including its schema) may exceed the target. +const DEFAULT_MAX_BYTES_PER_REQUEST: u64 = 64 * 1024 * 1024; /// The default max request duration is the read timeout divided by this, leaving /// headroom for the server to finalize and acknowledge a part before the read @@ -114,28 +109,22 @@ pub struct ClientConfig { /// Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another environment /// variable that contains the user ID value. pub user_id: Option, - /// Maximum number of bytes to send in a single insert HTTP request. + /// Target compressed IPC bytes per multipart request. Defaults to 64 MiB. /// - /// During a multipart write, each partition's data is split into one or more - /// parts of at most this many (Arrow IPC, compressed) bytes, each uploaded as - /// a separate request under the shared upload id. This bounds how long any - /// one request stays open, so large bulk ingests do not exceed the client - /// read timeout while the server streams the part to object storage. - /// - /// The request body is still streamed (not buffered), so this does not - /// increase peak memory. Set to `Some(0)` to disable splitting (one request - /// per partition). You can also set the `LANCE_CLIENT_MAX_BYTES_PER_REQUEST` - /// environment variable. Defaults to 8 GiB. + /// Parts are buffered for retries with the same upload and part IDs. Input + /// batches are sliced before encoding. A single row and its schema are + /// indivisible and may exceed the target. Peak additional memory is bounded + /// by the number of active writers times the part size (plus encoding buffers). + /// Set to `Some(0)` to disable byte-based cuts, or configure + /// `LANCE_CLIENT_MAX_BYTES_PER_REQUEST`. Disabling cuts can require buffering + /// an entire partition for replay. pub max_bytes_per_request: Option, - /// Maximum wall-clock time to spend uploading a single insert HTTP request. + /// Maximum time spent filling a replayable multipart payload. /// - /// Complements [`Self::max_bytes_per_request`]: during a multipart write a - /// part is cut when it reaches either the byte budget or this duration, - /// whichever comes first. The client read timeout also covers the - /// request-body upload, so a slow or throttled upload of a large part can - /// hit that timeout before the byte budget is reached; cutting by time keeps - /// each request short enough that it completes (and the server acknowledges - /// the part) within the read timeout. + /// A part is cut after encoding a batch slice when either its byte budget + /// or this duration is reached. This does not impose a network deadline; + /// `timeout_config` controls HTTP timeouts. Timed-out parts are retried using + /// their original payload and transaction ID. /// /// Set to `Some(Duration::ZERO)` to disable the time-based cut. You can also /// set the `LANCE_CLIENT_MAX_REQUEST_DURATION` environment variable (integer @@ -306,8 +295,9 @@ pub struct RetryConfig { /// You can also set the `LANCE_CLIENT_RETRY_STATUSES` environment variable /// to set this value. Use a comma-separated list of integer values. /// - /// Note that write operations will never be retried on 5xx errors as this may - /// result in duplicated writes. + /// Non-idempotent writes do not replay ambiguous 5xx responses. Multipart + /// parts can retry configured statuses because each replay replaces the same + /// staged transaction. Completion is never replayed. /// /// The default is 409, 429, 500, 502, 503, 504. pub statuses: Option>, @@ -888,6 +878,16 @@ impl RestfulLanceDbClient { Ok((request_id, response)) } + pub(crate) fn with_retries(&self, retries: Option) -> Self { + let mut client = self.clone(); + if let Some(retries) = retries { + client.retry_config.retries = retries; + client.retry_config.connect_retries = retries; + client.retry_config.read_retries = retries; + } + client + } + /// Send the request using retries configured in the RetryConfig. /// If retry_5xx is false, 5xx requests will not be retried regardless of the statuses configured /// in the RetryConfig. @@ -963,6 +963,13 @@ impl RestfulLanceDbClient { return Err(source); } retry_counter.increment_request_failures(source)?; + if status.is_server_error() { + log::warn!( + "Retrying request {} after gateway status {}", + request_id, + status + ); + } } Err(err) if err.is_connect() => { retry_counter.increment_connect_failures(err)?; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 31808f244..b562f41df 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -31,7 +31,7 @@ use crate::job::Job; use crate::listing::{ListingOptions, ListingPage}; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::job::{PauseJobResponse, RemoteJob, ResumeJobResponse, job_state_to_client}; -use crate::remote::util::stream_as_body; +use crate::remote::util::create_body; use crate::secrets::SecretInfo; use crate::table::BaseTable; use crate::utils::{ @@ -1497,7 +1497,7 @@ impl Database for RemoteDatabase { } } let data_schema = request.data.schema(); - let body = stream_as_body(request.data.scan_as_stream())?; + let body = create_body(request.data.scan_as_stream()).await?; let identifier = build_table_identifier(&request.name, &request.namespace_path)?; let req = self @@ -2623,6 +2623,147 @@ mod tests { assert_eq!(table.name(), "table1"); } + #[tokio::test] + async fn test_create_table_over_budget_never_reaches_server() { + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0u8; 8 * 1024 * 1024]; + SmallRng::seed_from_u64(42).fill_bytes(&mut bytes); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(arrow_array::LargeBinaryArray::from(vec![Some( + bytes.as_slice(), + )]))], + ) + .unwrap(); + for overwrite in [false, true] { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |_| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = + Box::new(arrow_array::RecordBatchIterator::new( + (0..34).map(|_| Ok(batch.clone())).collect::>(), + batch.schema(), + )); + let mut create = conn.create_table("table1", input); + if overwrite { + create = create.mode(CreateTableMode::Overwrite); + } + let error = create.execute().await.unwrap_err(); + let message = error.to_string(); + assert!(message.contains("single-request budget"), "{message}"); + assert!( + message.contains("schema=") && message.contains("progress=True"), + "{message}" + ); + // The same assertion covers a new half-table and damage to an + // existing table under overwrite: neither mode sends a request. + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 0); + } + } + + #[tokio::test] + async fn test_create_table_slices_large_batches_in_one_atomic_request() { + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |request| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let bytes = request.body().unwrap().as_bytes().unwrap(); + let batches = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None) + .unwrap() + .collect::, _>>() + .unwrap(); + assert!(batches.len() > 1); + assert_eq!( + batches.iter().map(|b| b.num_rows()).sum::(), + 4_000_000 + ); + http::Response::builder().status(200).body("").unwrap() + }); + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from_iter_values(0..4_000_000))], + ) + .unwrap(); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_create_table_compacts_dictionary_slices_in_one_atomic_request() { + use arrow_array::{Array, DictionaryArray, StringArray, cast::AsArray, types::Int32Type}; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * 72 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(72 * 1024) + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut batches = Vec::new(); + for values in [strings.clone(), strings.iter().rev().cloned().collect()] { + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(0..128), + Arc::new(StringArray::from(values)), + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "category", + dict.data_type().clone(), + false, + )])); + batches.push(RecordBatch::try_new(schema, vec![Arc::new(dict)]).unwrap()); + } + let schema = batches[0].schema(); + let expected = strings + .iter() + .chain(strings.iter().rev()) + .cloned() + .collect::>(); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = requests.clone(); + let wire_schema = schema.clone(); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/table/table1/create/"); + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let body = request.body().unwrap().as_bytes().unwrap(); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), wire_schema); + let batches = reader.collect::, _>>().unwrap(); + assert!( + (2..=8).contains(&batches.len()), + "dictionary produced {} encoding slices", + batches.len() + ); + let actual = batches + .iter() + .flat_map(|batch| { + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + values + .as_string::() + .iter() + .map(|s| s.unwrap().to_owned()) + .collect::>() + }) + .collect::>(); + assert_eq!(actual, expected); + assert!(body.len() < 2 * bytes.len() + 64 * 1024); + http::Response::builder().status(200).body("").unwrap() + }); + let input: Box = Box::new( + arrow_array::RecordBatchIterator::new(batches.into_iter().map(Ok), schema), + ); + conn.create_table("table1", input).execute().await.unwrap(); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); + } + #[tokio::test] async fn test_create_table_already_exists() { let conn = Connection::new_with_handler(|_| { diff --git a/rust/lancedb/src/remote/retry.rs b/rust/lancedb/src/remote/retry.rs index 51c9b2126..c0ef2bd11 100644 --- a/rust/lancedb/src/remote/retry.rs +++ b/rust/lancedb/src/remote/retry.rs @@ -63,7 +63,7 @@ impl<'a> RetryCounter<'a> { /// Increment the appropriate failure counter based on the error type. /// /// For `Error::Http` whose source is a connect error, increments - /// `connect_failures`. For read errors (`is_body` or `is_decode`), + /// `connect_failures`. For read errors (`is_timeout`, `is_body` or `is_decode`), /// increments `read_failures`. For all other errors, increments /// `request_failures`. Calls `check_out_of_retries` to enforce global limits. pub fn increment_from_error(&mut self, source: crate::Error) -> crate::Result<()> { @@ -74,7 +74,7 @@ impl<'a> RetryCounter<'a> { if reqwest_err.is_some_and(|e| e.is_connect()) { self.connect_failures += 1; - } else if reqwest_err.is_some_and(|e| e.is_body() || e.is_decode()) { + } else if reqwest_err.is_some_and(|e| e.is_timeout() || e.is_body() || e.is_decode()) { self.read_failures += 1; } else { self.request_failures += 1; @@ -187,6 +187,37 @@ mod tests { )); } + #[tokio::test] + async fn test_increment_from_error_read_timeout() { + 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 err = reqwest::Client::builder() + .read_timeout(Duration::from_millis(100)) + .build() + .unwrap() + .get(format!("http://{address}/")) + .send() + .await + .unwrap_err(); + assert!(err.is_timeout() && !err.is_connect()); + let config = test_config(); + let mut counter = RetryCounter::new(&config, "part-1".into()); + counter + .increment_from_error(Error::Http { + request_id: "part-1".into(), + status_code: None, + source: Box::new(err), + }) + .unwrap(); + assert_eq!(counter.read_failures, 1); + assert_eq!(counter.request_failures, 0); + server.abort(); + } + #[test] fn test_increment_from_error_request() { let config = test_config(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 48e5652ae..cc495a83f 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5,6 +5,8 @@ pub mod blobs; pub mod insert; mod ipc_stream; mod optimize; +#[cfg(test)] +mod write_tests; use self::insert::{RemoteWriteExec, WriteOp}; use super::client::RequestResultExt; @@ -1420,13 +1422,18 @@ impl RemoteTable { Ok(bodies) } - async fn create_multipart_write(&self) -> Result { + async fn create_multipart_write(&self, retries: Option) -> Result { let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/multipart_write/create", self.identifier ))); - let (request_id, response) = self.send(request, true).await?; + let client = self.client.with_retries(retries); + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = client + .send_with_retry(freshness_request.apply(request), None, true) + .await?; let response = self.check_table_response(&request_id, response).await?; + freshness_request.observe_headers(&self.freshness, response.headers()); 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(), @@ -1452,7 +1459,7 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self.send(request, false).await?; let response = self.check_table_response(&request_id, response).await?; 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 { @@ -1468,7 +1475,7 @@ impl RemoteTable { Ok(AddResult { version }) } - async fn abort_multipart_write(&self, upload_id: &str) -> Result<()> { + async fn abort_multipart_write(&self, upload_id: &str, retries: Option) -> Result<()> { let request = self.apply_branch_query( self.client .post(&format!( @@ -1477,7 +1484,14 @@ impl RemoteTable { )) .query(&[("upload_id", upload_id)]), ); - let (request_id, response) = self.send(request, true).await?; + let freshness = self.snapshot_freshness_headers(); + let client = self.client.with_retries(retries); + let (request_id, response) = client + .send_with_retry(freshness.apply(request), None, true) + .await?; + if response.status().is_success() { + freshness.observe_headers(&self.freshness, response.headers()); + } self.check_table_response(&request_id, response).await?; Ok(()) } @@ -1975,43 +1989,96 @@ mod test_utils { } } +#[derive(Debug)] +struct UnknownWriteOutcome { + upload_id: String, + source: Error, +} + +impl std::fmt::Display for UnknownWriteOutcome { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Multipart write {} commit outcome unknown; no abort or replay was attempted. Check the table before retrying: {}", + self.upload_id, self.source + ) + } +} + +impl std::error::Error for UnknownWriteOutcome { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.source) + } +} + impl RemoteTable { fn is_retryable_write_error(&self, err: &Error) -> bool { + // Transaction conflicts and explicit rate limits reject the write. + // A gateway 5xx says nothing about whether its manifest was committed. + let safe_status = |status| { + matches!(status, StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + && self.client.retry_config.statuses.contains(&status) + }; match err { Error::Http { source, status_code, .. } => { - // Don't retry read errors (is_body/is_decode): the - // server may have committed the write already, and - // without an idempotency key we'd duplicate data. source .downcast_ref::() .is_some_and(|e| e.is_connect()) - || status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) - } - // send_with_retry exhausted its internal retries on a retryable - // status. The outer loop can still retry the whole operation with - // a fresh session. - Error::Retry { status_code, .. } => { - status_code.is_some_and(|s| self.client.retry_config.statuses.contains(&s)) + || status_code.is_some_and(safe_status) } + Error::Retry { status_code, .. } => status_code.is_some_and(safe_status), _ => false, } } + async fn send_write_request( + &self, + request: RequestBuilder, + freshness: FreshnessHeaders, + retries: Option, + ) -> Result<(String, Response)> { + let client = self.client.with_retries(retries); + let mut counter = crate::remote::retry::RetryCounter::new( + &client.retry_config, + uuid::Uuid::new_v4().to_string(), + ); + loop { + let req = request.try_clone().ok_or_else(|| Error::Runtime { + message: "Write request cannot be replayed".into(), + })?; + let result = async { + let (id, response) = client.send(freshness.apply(req)).await?; + let response = self.check_table_response(&id, response).await?; + freshness.observe_headers(&self.freshness, response.headers()); + Ok((id, response)) + } + .await; + match result { + Err(err) if self.is_retryable_write_error(&err) => { + counter.increment_from_error(err)?; + tokio::time::sleep(counter.next_sleep_time()).await; + } + result => return result, + } + } + } + async fn add_single_partition(&self, output: PreprocessingOutput) -> Result { use crate::remote::retry::RetryCounter; let _guard = output.tracker.as_ref().map(|t| t.track_task()); + let client = self.client.with_retries(output.retries); let freshness_request = self.snapshot_freshness_headers(); let mut insert: Arc = Arc::new( RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), output.plan, WriteOp::Insert { overwrite: output.overwrite, @@ -2026,7 +2093,7 @@ impl RemoteTable { ); let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); + RetryCounter::new(&client.retry_config, uuid::Uuid::new_v4().to_string()); loop { let stream = execute_plan(insert.clone(), Default::default())?; @@ -2062,61 +2129,82 @@ impl RemoteTable { output: PreprocessingOutput, num_partitions: usize, ) -> Result { - use crate::remote::retry::RetryCounter; - - let mut retry_counter = - RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); - - loop { - let freshness_request = self.snapshot_freshness_headers(); - let upload_id = self.create_multipart_write().await?; - - let result = self - .execute_multipart_inserts(&upload_id, &output, num_partitions) - .await; - - match result { - Ok(()) => match self.complete_multipart_write(&upload_id).await { - Ok(result) => { - if output.overwrite { - self.invalidate_schema_cache(); - } - self.track_write_version(freshness_request, result.version); - return Ok(result); + if let Some(tracker) = &output.tracker { + tracker.use_wire_bytes(); + } + let freshness_request = self.snapshot_freshness_headers(); + let upload_id = self.create_multipart_write(output.retries).await?; + if let Err(err) = self + .execute_multipart_inserts(&upload_id, &output, num_partitions) + .await + { + if let Err(abort_err) = self.abort_multipart_write(&upload_id, output.retries).await { + log::warn!( + "Failed to abort multipart write {}: {}", + upload_id, + abort_err + ); + } + return Err(err); + } + // A lost complete response can mean a successful commit. Neither repeat + // complete nor start a new upload session without a server commit token. + let result = match self.complete_multipart_write(&upload_id).await { + Ok(result) => result, + Err(err) => { + let (request_id, status_code) = match &err { + Error::Http { + request_id, + status_code, + .. } - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { - log::warn!( - "Failed to abort multipart write {}: {}", - upload_id, - abort_err - ); - } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); - } - }, - Err(e) => { - if let Err(abort_err) = self.abort_multipart_write(&upload_id).await { + | Error::Retry { + request_id, + status_code, + .. + } => (request_id.clone(), *status_code), + _ => return Err(err), + }; + // These responses positively reject the commit. Cleanup remains + // best effort and must not replace the original write error. + if matches!( + status_code, + Some(StatusCode::CONFLICT | StatusCode::TOO_MANY_REQUESTS) + ) { + if let Err(abort_err) = + self.abort_multipart_write(&upload_id, output.retries).await + { log::warn!( - "Failed to abort multipart write {}: {}", + "Failed to abort rejected multipart write {}: {}", upload_id, abort_err ); } - if output.rescannable && self.is_retryable_write_error(&e) { - retry_counter.increment_from_error(e)?; - tokio::time::sleep(retry_counter.next_sleep_time()).await; - continue; - } - return Err(e); + return Err(err); } + if status_code.is_some_and(|status| !status.is_server_error()) { + return Err(err); + } + log::warn!( + "Multipart write {} completion failed; commit outcome may be unknown: {}. Check the table before retrying.", + upload_id, + err + ); + return Err(Error::Http { + request_id, + status_code, + source: Box::new(UnknownWriteOutcome { + upload_id, + source: err, + }), + }); } + }; + if output.overwrite { + self.invalidate_schema_cache(); } + self.track_write_version(freshness_request, result.version); + Ok(result) } async fn execute_multipart_inserts( @@ -2125,10 +2213,7 @@ impl RemoteTable { output: &PreprocessingOutput, num_partitions: usize, ) -> Result<()> { - debug_assert!( - output.rescannable, - "multipart inserts require rescannable input for retry support" - ); + let client = self.client.with_retries(output.retries); let plan = Arc::new( datafusion_physical_plan::repartition::RepartitionExec::try_new( @@ -2141,7 +2226,7 @@ impl RemoteTable { RemoteWriteExec::new_multipart( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client, plan, output.overwrite, upload_id.to_string(), @@ -3000,6 +3085,7 @@ impl BaseTable for RemoteTable { crate::table::computed_columns::ensure_supported_function_metadata(table_schema.as_ref())?; let table_def = TableDefinition::try_from_rich_schema(table_schema.clone())?; + let mut use_multipart = false; let num_partitions = if self.server_version.support_multipart_write() { // Peek at the first batch to estimate write partitions (same as // NativeTable) and, regardless of `write_parallelism`, to detect a @@ -3012,20 +3098,29 @@ impl BaseTable for RemoteTable { // sends one schema-only request. let mut peeked = PeekedScannable::new(add.data); let n = match peeked.peek().await { - Some(first_batch) => match add.write_parallelism { - Some(parallelism) if parallelism > 1 => parallelism, - Some(_) => 1, - None => { - let max_partitions = - lance_core::utils::tokio::get_num_compute_intensive_cpus(); - estimate_write_partitions( - first_batch.get_array_memory_size(), - first_batch.num_rows(), - peeked.num_rows(), - max_partitions, - ) + Some(first_batch) => { + let estimated_bytes = peeked.num_rows().map(|rows| { + first_batch.get_array_memory_size().saturating_mul(rows) + / first_batch.num_rows().max(1) + }); + // Unknown-length streams also need bounded requests, even + // when they cannot be rescanned or only use one writer. + use_multipart = estimated_bytes.is_none_or(|bytes| bytes > 64 * 1024 * 1024); + match add.write_parallelism { + Some(parallelism) if parallelism > 1 => parallelism, + Some(_) => 1, + None => { + let max_partitions = + lance_core::utils::tokio::get_num_compute_intensive_cpus(); + estimate_write_partitions( + first_batch.get_array_memory_size(), + first_batch.num_rows(), + peeked.num_rows(), + max_partitions, + ) + } } - }, + } None => 1, }; add.data = Box::new(peeked); @@ -3041,7 +3136,7 @@ impl BaseTable for RemoteTable { } let _finish = FinishOnDrop(output.tracker.clone()); - if num_partitions > 1 { + if use_multipart || num_partitions > 1 { self.add_multipart(output, num_partitions).await } else { self.add_single_partition(output).await @@ -3278,7 +3373,7 @@ impl BaseTable for RemoteTable { let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, update.retries) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3316,7 +3411,7 @@ impl BaseTable for RemoteTable { .json(&body); let freshness_request = self.snapshot_freshness_headers(); let (request_id, response) = self - .send_with_freshness(request, true, freshness_request) + .send_write_request(request, freshness_request, None) .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3363,6 +3458,7 @@ impl BaseTable for RemoteTable { self.check_mutable().await?; let timeout = params.timeout; + let client = self.client.with_retries(params.retries); let query = MergeInsertRequest::try_from(params)?; // Drive merge_insert through the same RemoteWriteExec streaming path as @@ -3407,7 +3503,7 @@ impl BaseTable for RemoteTable { RemoteWriteExec::new( self.name.clone(), self.identifier.clone(), - self.client.clone(), + client.clone(), input, WriteOp::MergeInsert { query, timeout }, None, @@ -3420,7 +3516,7 @@ impl BaseTable for RemoteTable { ); let mut retry_counter = crate::remote::retry::RetryCounter::new( - &self.client.retry_config, + &client.retry_config, uuid::Uuid::new_v4().to_string(), ); @@ -14748,41 +14844,116 @@ mod tests { } #[tokio::test] - async fn test_add_retries_on_retryable_status() { - // Verify that rescannable data retries on retryable status codes (e.g. 502) - // and eventually succeeds. - let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); - let describe_body = describe_response(&batch.schema()); - - let attempt = Arc::new(AtomicUsize::new(0)); - let attempt_clone = attempt.clone(); - - let table = - Table::new_with_handler("my_table", move |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_body.clone()) - .unwrap(), - "/v1/table/my_table/insert/" => { - let n = attempt_clone.fetch_add(1, Ordering::SeqCst); - if n < 2 { - http::Response::builder() - .status(502) - .body("bad gateway".to_string()) - .unwrap() - } else { - http::Response::builder() + async fn test_add_write_retry_policy_and_override() { + for status in [429, 500, 502, 503, 504] { + for retries in [None, Some(0)] { + let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() .status(200) - .body(r#"{"version": 3}"#.to_string()) - .unwrap() + .body(describe.clone()) + .unwrap(); } + let n = observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(if n == 0 { status } else { 200 }) + .body(r#"{"version":3}"#.to_string()) + .unwrap() + }); + let mut add = table.add(batch); + if let Some(retries) = retries { + add = add.retries(retries); } - path => panic!("Unexpected request path: {}", path), - }); + let result = add.execute().await; + let safe_retry = status == 429 && retries.is_none(); + assert_eq!( + result.is_ok(), + safe_retry, + "{status}, {retries:?}: {result:?}" + ); + assert_eq!( + attempts.load(Ordering::SeqCst), + if safe_retry { 2 } else { 1 } + ); + } + } + } - let result = table.add(batch).execute().await.unwrap(); - assert_eq!(result.version, 3); - assert_eq!(attempt.load(Ordering::SeqCst), 3); + #[tokio::test] + async fn test_mutations_do_not_replay_gateway_failures() { + for status in [500, 502, 503, 504] { + for op in ["update", "delete", "merge_insert"] { + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let describe = describe_response(&batch.schema()); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let table = Table::new_with_handler("my_table", move |req| { + if req.url().path().ends_with("describe/") { + return http::Response::builder() + .status(200) + .body(describe.clone()) + .unwrap(); + } + assert!(req.url().path().contains(op)); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(status) + .body("gateway fault".to_string()) + .unwrap() + }); + let result = match op { + "update" => table + .update() + .column("id", "id + 1") + .execute() + .await + .map(|_| ()), + "delete" => table.delete("true").await.map(|_| ()), + _ => { + let reader = + RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_insert_all(); + merge.execute(Box::new(reader)).await.map(|_| ()) + } + }; + assert!(result.is_err(), "{op}, {status}"); + assert_eq!(attempts.load(Ordering::SeqCst), 1, "{op}, {status}"); + } + } + } + + #[test] + fn test_write_retry_policy_for_both_error_variants() { + let table = RemoteTable::new_mock_with_config( + "my_table".into(), + |_| http::Response::builder().body("").unwrap(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(1), + statuses: Some(vec![429, 500, 502, 503, 504]), + ..Default::default() + }, + ..Default::default() + }, + ); + for status in [429, 500, 502, 503, 504] { + let err = Error::Http { + request_id: "test".into(), + status_code: Some(StatusCode::from_u16(status).unwrap()), + source: "gateway response".into(), + }; + assert_eq!(table.is_retryable_write_error(&err), status == 429); + let mut counter = + crate::remote::retry::RetryCounter::new(&table.client.retry_config, "test".into()); + let exhausted = counter.increment_request_failures(err).unwrap_err(); + assert!(matches!(exhausted, Error::Retry { .. })); + assert_eq!(table.is_retryable_write_error(&exhausted), status == 429); + } } #[tokio::test] @@ -14931,7 +15102,7 @@ mod tests { let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap(); let result = table - .add(vec![batch]) + .add(vec![batch.clone(), batch]) .write_parallelism(2) .execute() .await @@ -15335,7 +15506,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_write_abort_on_complete_failure() { + async fn test_multipart_write_does_not_abort_on_complete_failure() { let abort_count = Arc::new(AtomicUsize::new(0)); let abort_count_c = abort_count.clone(); @@ -15386,7 +15557,7 @@ mod tests { let result = table.add(vec![batch]).write_parallelism(2).execute().await; assert!(result.is_err()); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } fn retry_config_no_backoff() -> ClientConfig { @@ -15405,9 +15576,9 @@ mod tests { #[tokio::test] async fn test_multipart_write_retry_on_partition_failure() { - // All inserts for the first upload session return 503 (retryable). - // After exhausting internal retries, the outer loop retries with a - // new session and succeeds. + // A staging failure is retried in the same upload session. + let insert_count = Arc::new(AtomicUsize::new(0)); + let insert_count_c = insert_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let complete_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -15435,7 +15606,9 @@ mod tests { if path == "/v1/table/my_table/insert/" { // Fail all inserts for the first session - if query.contains("upload_id=upload-1") { + assert!(query.contains("upload_id=upload-1")); + assert!(query.contains("upload_part_id=")); + if insert_count_c.fetch_add(1, Ordering::SeqCst) == 0 { return http::Response::builder() .status(503) .body("Service Unavailable".to_string()) @@ -15477,14 +15650,16 @@ mod tests { .unwrap(); assert_eq!(result.version, 7); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); assert_eq!(complete_count.load(Ordering::SeqCst), 1); } #[tokio::test] - async fn test_multipart_write_retry_on_complete_failure() { - // Complete returns 503 for the first session, succeeds for the second. + async fn test_multipart_complete_unknown_outcome_never_aborts_or_replays() { + // A gateway failure may hide a committed write. No abort or replay is safe. + let complete_count = Arc::new(AtomicUsize::new(0)); + let complete_count_c = complete_count.clone(); let create_count = Arc::new(AtomicUsize::new(0)); let abort_count = Arc::new(AtomicUsize::new(0)); @@ -15516,6 +15691,7 @@ mod tests { } if path == "/v1/table/my_table/multipart_write/complete" { + complete_count_c.fetch_add(1, Ordering::SeqCst); // Fail complete for first session if query.contains("upload_id=upload-1") { return http::Response::builder() @@ -15548,11 +15724,12 @@ mod tests { .write_parallelism(2) .execute() .await - .unwrap(); + .unwrap_err(); - assert_eq!(result.version, 9); - assert_eq!(create_count.load(Ordering::SeqCst), 2); - assert_eq!(abort_count.load(Ordering::SeqCst), 1); + assert!(result.to_string().contains("commit outcome unknown")); + assert_eq!(complete_count.load(Ordering::SeqCst), 1); + assert_eq!(create_count.load(Ordering::SeqCst), 1); + assert_eq!(abort_count.load(Ordering::SeqCst), 0); } // ---- Read freshness header tests ------------------------------------ diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index ebae823e1..0de1c21cc 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -17,7 +17,7 @@ use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, }; -use futures::{SinkExt, StreamExt}; +use futures::StreamExt; use http::header::CONTENT_TYPE; use lance::io::exec::utils::InstrumentedRecordBatchStreamAdapter; @@ -268,6 +268,17 @@ impl RemoteWriteExec { error_tx: tokio::sync::oneshot::Sender, tracker: Option>, ) -> DataFusionResult { + let data: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( + data.schema(), + data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, crate::remote::util::IPC_BATCH_BYTES) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }), + )); let options = arrow_ipc::writer::IpcWriteOptions::default() .try_with_compression(Some(CompressionType::LZ4_FRAME))?; let writer = arrow_ipc::writer::StreamWriter::try_new_with_options( @@ -347,55 +358,55 @@ impl PartRequestCtx<'_, S> { /// whenever the current one reaches `max_bytes` (Arrow IPC, compressed) or /// has been uploading for `max_duration`, whichever comes first. /// - /// Each part is a separate `/insert?upload_id=...&upload_part_id=...` request - /// whose body is still streamed through a bounded channel, so peak memory - /// stays at a couple of batches regardless of `max_bytes`. The server stages - /// every part under the shared `upload_id` and merges them atomically when - /// the caller completes the multipart write. An empty partition stages - /// nothing: the multipart write always has at least one non-empty partition - /// to commit. + /// Each part has a fixed IPC body and transaction ID. A retry replaces the + /// same staged transaction instead of adding another part. Only the final + /// complete request makes staged rows visible. Parts are prepared on demand; + /// the target does not bound memory retained by input or ancestor buffers. /// - /// The byte budget targets a good on-disk fragment size; the duration budget - /// bounds request time so a slow or throttled upload does not keep a request - /// open past the client read timeout (which also covers the request body). + /// The duration budget limits payload preparation time; HTTP timeouts are + /// handled by retrying the prepared payload. async fn send_multipart_chunked( &self, max_bytes: u64, max_duration: Option, - mut input: SendableRecordBatchStream, + input: SendableRecordBatchStream, tracker: Option>, ) -> DataFusionResult<()> { let schema = input.schema(); + let max_batch_bytes = (max_bytes as usize).clamp(1, crate::remote::util::IPC_BATCH_BYTES); + let stream = input.flat_map(move |batch| match batch { + Ok(batch) => futures::stream::iter( + crate::remote::util::split_batch(batch, max_batch_bytes) + .map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); + let mut input: SendableRecordBatchStream = + Box::pin(RecordBatchStreamAdapter::new(schema.clone(), stream)); - // A part always starts from a batch we already hold: the first batch of - // the partition, or the look-ahead batch from the previous part. This - // keeps empty partitions from staging a part and stops a size cut that - // lands exactly on the end of input from emitting a trailing empty part. - let mut first = match input.next().await { - Some(batch) => batch?, - None => return Ok(()), - }; - + let mut pending = std::collections::VecDeque::new(); loop { - let input_ended = self + let first = match pending.pop_front() { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => break, + }, + }; + if self .send_one_part( - &schema, max_bytes, max_duration, first, &mut input, + &mut pending, &tracker, ) - .await?; - - if input_ended { + .await? + { break; } - - first = match input.next().await { - Some(batch) => batch?, - None => break, - }; } Ok(()) @@ -431,143 +442,137 @@ impl PartRequestCtx<'_, S> { &self, request: reqwest::RequestBuilder, freshness_request: Option, - ) -> DataFusionResult<()> { - let (request_id, response) = self - .client - .send(request) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + ) -> crate::Result<()> { + let (request_id, response) = self.client.send(request).await?; let response = RemoteTable::::handle_table_not_found(self.table_name, response, &request_id) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let response = self - .client - .check_response(&request_id, response) - .await - .map_err(|e| DataFusionError::External(Box::new(e)))?; + .await?; + let response = self.client.check_response(&request_id, response).await?; self.freshness .observe(freshness_request, response.headers()); - response.bytes().await.map_err(|e| { - DataFusionError::External(Box::new(Error::Http { - source: Box::new(e), - request_id: request_id.clone(), - status_code: None, - })) + response.bytes().await.map_err(|e| Error::Http { + source: Box::new(e), + request_id: request_id.clone(), + status_code: None, })?; Ok(()) } - /// Stream one part, starting from `first` and pulling from `input` until the - /// part reaches `max_bytes`, has been uploading for `max_duration`, or the - /// input ends. The body is streamed through a bounded channel concurrently - /// with the request, so peak memory stays at a couple of batches. Wire bytes - /// are recorded on `tracker` as each chunk is produced, so progress advances - /// smoothly rather than jumping once per completed part. Returns whether the - /// input was exhausted while filling this part. + /// Encode each part before sending so a lost staging response can be retried + /// with exactly the same transaction ID and bytes. async fn send_one_part( &self, - schema: &arrow_schema::SchemaRef, max_bytes: u64, max_duration: Option, first: RecordBatch, input: &mut SendableRecordBatchStream, + queued: &mut std::collections::VecDeque, tracker: &Option>, ) -> DataFusionResult { - let (mut chunk_tx, chunk_rx) = - futures::channel::mpsc::channel::, std::io::Error>>(2); - let body = reqwest::Body::wrap_stream(chunk_rx); - - let part_id = uuid::Uuid::new_v4().to_string(); - let (request, freshness_request) = self.build_part_request(&part_id, body); - - // Measured from just before the request is sent, matching the window the - // client read timeout applies to the upload. + let schema = input.schema(); + let options = arrow_ipc::writer::IpcWriteOptions::default() + .try_with_compression(Some(CompressionType::LZ4_FRAME))?; + let mut writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; let started = Instant::now(); - let tracker = tracker.clone(); - // Unlike `stream_as_http_body`, this producer also cuts the part at the - // byte/time budget and reports back whether the input ended, so it drives - // its own bounded mpsc channel joined with the request instead of reusing - // that helper. - let producer = async move { - let options = arrow_ipc::writer::IpcWriteOptions::default() - .try_with_compression(Some(CompressionType::LZ4_FRAME)) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let mut writer = - arrow_ipc::writer::StreamWriter::try_new_with_options(Vec::new(), schema, options) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - - let mut part_bytes: u64 = 0; - let mut input_ended = false; - let mut pending = Some(first); - loop { - let batch = match pending.take() { - Some(batch) => batch, - None => match input.next().await { - Some(Ok(batch)) => batch, - Some(Err(e)) => { - // Abort the body so the server does not treat the - // truncated stream as a successful write; the - // original error is surfaced to the caller. - let _ = chunk_tx - .send(Err(std::io::Error::other("input stream error"))) - .await; - return Err(e); - } - None => { - input_ended = true; - break; - } - }, - }; - writer - .write(&batch) - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let chunk = std::mem::take(writer.get_mut()); - let chunk_len = chunk.len(); - part_bytes += chunk_len as u64; - if chunk_tx.send(Ok(chunk)).await.is_err() { - // The request finished or failed; stop producing. + let mut pending = Some(first); + let mut has_batch = false; + let mut input_ended = false; + loop { + let batch = match pending.take().or_else(|| queued.pop_front()) { + Some(batch) => batch, + None => match input.next().await { + Some(batch) => batch?, + None => { + input_ended = true; + break; + } + }, + }; + let before = writer.get_ref().len(); + writer.write(&batch)?; + // Reserve the EOS marker. A rejected batch starts a fresh stream, + // so its dictionary messages are encoded again with fresh state. + if (writer.get_ref().len() as u64).saturating_add(8) > max_bytes { + if has_batch { + writer.get_mut().truncate(before); + queued.push_front(batch); break; } - if let Some(ref t) = tracker { - t.record_bytes(chunk_len); - } - if part_bytes >= max_bytes - || max_duration.is_some_and(|limit| started.elapsed() >= limit) - { - break; + if batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + queued.push_front(crate::remote::util::compact_batch_dictionaries( + batch.slice(middle, batch.num_rows() - middle), + )?); + pending = Some(crate::remote::util::compact_batch_dictionaries( + batch.slice(0, middle), + )?); + writer = arrow_ipc::writer::StreamWriter::try_new_with_options( + Vec::new(), + &schema, + options.clone(), + )?; + continue; } + // A single row and its schema cannot be split further. } - - writer - .finish() - .map_err(|e| DataFusionError::External(Box::new(e)))?; - let tail = std::mem::take(writer.get_mut()); - if !tail.is_empty() { - let tail_len = tail.len(); - if chunk_tx.send(Ok(tail)).await.is_ok() - && let Some(ref t) = tracker - { - t.record_bytes(tail_len); - } + has_batch = true; + if writer.get_ref().len() as u64 >= max_bytes + || max_duration.is_some_and(|limit| started.elapsed() >= limit) + { + break; } - Ok::(input_ended) - }; + } + writer.finish()?; + let body = bytes::Bytes::from(writer.into_inner()?); + let part_id = uuid::Uuid::new_v4().to_string(); + let mut retries = + crate::remote::retry::RetryCounter::new(&self.client.retry_config, part_id.clone()); + loop { + let (request, freshness) = self.build_part_request(&part_id, body.clone().into()); + match self.send_part_request(request, freshness).await { + Ok(()) => { + if let Some(tracker) = tracker { + tracker.record_bytes(body.len()); + } + return Ok(input_ended); + } + Err(err) if retryable_part_error(&err, &self.client.retry_config.statuses) => { + let cause = err.to_string(); + retries + .increment_from_error(err) + .map_err(|err| DataFusionError::External(Box::new(err)))?; + log::warn!( + "Retrying multipart upload {} part {} after {}; reusing the same payload", + self.upload_id, + part_id, + cause + ); + tokio::time::sleep(retries.next_sleep_time()).await; + } + Err(err) => return Err(DataFusionError::External(Box::new(err))), + } + } + } +} - let send = self.send_part_request(request, freshness_request); - - // `join!` rather than `tokio::spawn`: the producer borrows `input` (and - // `schema`), so it cannot satisfy the `'static` bound a spawned task - // needs. Running both futures on this task lets them make progress - // concurrently without that constraint. - let (producer_result, send_result) = futures::join!(producer, send); - // Prefer the producer error (e.g. NaN rejection) over any HTTP error it - // induced. - let input_ended = producer_result?; - send_result?; - - Ok(input_ended) +fn retryable_part_error(err: &Error, statuses: &[reqwest::StatusCode]) -> bool { + match err { + Error::Http { + status_code: Some(status), + .. + } => statuses.contains(status), + Error::Http { source, .. } => source.downcast_ref::().is_some_and(|err| { + err.is_connect() + || err.is_timeout() + || err.is_body() + || err.is_decode() + || err.is_request() + }), + _ => false, } } @@ -697,13 +702,10 @@ impl ExecutionPlan for RemoteWriteExec { let max_request_duration = self.max_request_duration; let stream = futures::stream::once(async move { - // Multipart writes with a byte budget split the partition into - // several bounded, still-streamed requests so no single request - // stays open long enough to hit the client read timeout. This path - // is insert-only (guarded above). - if let (Some(upload_id), Some(max_bytes)) = - (upload_id.as_deref(), max_bytes_per_request) - { + // Multipart payloads remain replayable even when byte-based cuts + // are disabled. Single-request writes never replay ambiguous errors. + if let Some(upload_id) = upload_id.as_deref() { + let max_bytes = max_bytes_per_request.unwrap_or(u64::MAX); let overwrite = matches!(op, WriteOp::Insert { overwrite: true }); let ctx = PartRequestCtx { client: &client, @@ -1220,7 +1222,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1237,7 +1239,102 @@ mod tests { let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); while stream.next().await.transpose().unwrap().is_some() {} - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + assert_eq!(insert_count.load(Ordering::SeqCst), 6); + } + + #[tokio::test] + async fn test_multipart_respects_disabled_status_retries() { + use futures::StreamExt; + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |_| { + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(503) + .body("unavailable") + .unwrap() + }); + client.retry_config.statuses.clear(); + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let input = input_plan_from_batches(batch.schema(), vec![batch]).await; + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(64 * 1024 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + assert!(stream.next().await.unwrap().is_err()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_multipart_splits_one_batch_within_encoded_byte_budget() { + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(7).fill_bytes(&mut bytes); + let values = arrow_array::LargeBinaryArray::from_iter_values(bytes.chunks_exact(1024)); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + false, + )])); + let input = input_plan_from_batches( + schema.clone(), + vec![arrow_array::RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap()], + ) + .await; + let decoded = Arc::new(Mutex::new(Vec::new())); + let observed = decoded.clone(); + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + assert!( + body.len() <= 16 * 1024, + "encoded part exceeded its budget: {}", + body.len() + ); + let reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + let mut decoded = observed.lock().unwrap(); + for batch in reader { + let batch = batch.unwrap(); + let values = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + for value in values.iter() { + decoded.extend_from_slice(value.unwrap()); + } + } + count.fetch_add(1, Ordering::SeqCst); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert!(requests.load(Ordering::SeqCst) > 1); + assert_eq!(*decoded.lock().unwrap(), bytes); } #[tokio::test] @@ -1376,7 +1473,7 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - // A 1-byte budget forces every batch into its own part. + // A 1-byte budget forces every row into its own part. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1394,13 +1491,13 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} let ids = part_ids.lock().unwrap().clone(); - assert_eq!(ids.len(), 3, "expected one part id per part: {ids:?}"); + assert_eq!(ids.len(), 6, "expected one part id per part: {ids:?}"); assert!( ids.iter().all(|id| !id.is_empty()), "part ids must be non-empty: {ids:?}" ); let unique: HashSet<&String> = ids.iter().collect(); - assert_eq!(unique.len(), 3, "part ids must be distinct: {ids:?}"); + assert_eq!(unique.len(), 6, "part ids must be distinct: {ids:?}"); } #[tokio::test] @@ -1446,8 +1543,8 @@ mod tests { while stream.next().await.transpose().unwrap().is_some() {} } - // 2 parts from partition 0 + 1 part from partition 1. - assert_eq!(insert_count.load(Ordering::SeqCst), 3); + // 4 single-row parts from partition 0 + 2 from partition 1. + assert_eq!(insert_count.load(Ordering::SeqCst), 6); } #[tokio::test] @@ -1551,7 +1648,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_records_progress_within_a_part() { + async fn test_multipart_records_acknowledged_bytes() { use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use futures::StreamExt; @@ -1577,9 +1674,7 @@ mod tests { })); let tracker = Arc::new(WriteProgressTracker::new(callback, None)); - // A large byte budget keeps all three batches in one part; smooth - // progress therefore requires bytes to be reported per chunk rather than - // once when the part completes. + // Count encoded bytes once when the part is acknowledged. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1603,8 +1698,8 @@ mod tests { ); let observed = observed.lock().unwrap(); assert!( - observed.len() > 1, - "expected multiple incremental progress updates within the part: {observed:?}" + observed.len() == 1, + "expected one progress update per acknowledged part: {observed:?}" ); assert!( observed.windows(2).all(|w| w[1] >= w[0]), @@ -1615,4 +1710,454 @@ mod tests { "final progress should report bytes: {observed:?}" ); } + #[tokio::test] + async fn test_multipart_nested_dictionary_values_and_retries() { + use arrow_array::{ + Array, ArrayRef, BinaryArray, DictionaryArray, ListArray, RecordBatch, StructArray, + UInt8Array, types::UInt8Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; + use arrow_cast::cast; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * 1024]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let mut batches = Vec::new(); + for shift in [0, 1] { + let values = BinaryArray::from_iter( + std::iter::once(None).chain(bytes.chunks_exact(1024).skip(shift).map(Some)), + ); + let keys = UInt8Array::from(vec![ + Some(120), + Some(1), + None, + Some(1), + Some(2), + Some(0), + Some(3), + Some(4), + ]); + let dict = Arc::new(DictionaryArray::::new(keys, Arc::new(values))); + let field = Arc::new( + Field::new("category", dict.data_type().clone(), true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ); + let entries = StructArray::new(vec![field].into(), vec![dict], None); + let list = ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::new(ScalarBuffer::from(vec![0, 1, 3, 5, 6, 6, 8])), + Arc::new(entries), + Some(NullBuffer::from(vec![true, true, true, true, false, true])), + ); + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", list.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + // The discarded first row references a large, otherwise unused value. + batches.push( + RecordBatch::try_new(schema, vec![Arc::new(list)]) + .unwrap() + .slice(1, 5), + ); + } + let schema = batches[0].schema(); + let plain_type = DataType::List(Arc::new(Field::new_list_field( + DataType::Struct( + vec![ + Field::new("category", DataType::Binary, true) + .with_metadata(HashMap::from([("field-meta".into(), "retained".into())])), + ] + .into(), + ), + false, + ))); + let expected: Vec = batches + .iter() + .map(|b| cast(b.column(0), &plain_type).unwrap()) + .collect(); + let expected = + arrow_select::concat::concat(&expected.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let mut client = crate::remote::client::test_utils::client_with_handler(move |request| { + let query: HashMap<_, _> = request.url().query_pairs().into_owned().collect(); + assert_eq!(query["upload_id"], "upload-1"); + let body = request.body().unwrap().as_bytes().unwrap().to_vec(); + let mut requests = observed.lock().unwrap(); + requests.push((query["upload_part_id"].clone(), body)); + http::Response::builder() + .status(if requests.len() == 1 { 503 } else { 200 }) + .body("{}") + .unwrap() + }); + client.retry_config.backoff_factor = 0.0; + client.retry_config.backoff_jitter = 0.0; + use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; + let acknowledged = Arc::new(AtomicUsize::new(0)); + let acknowledged_c = acknowledged.clone(); + let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { + acknowledged_c.store(p.output_bytes(), Ordering::SeqCst); + })); + let tracker = Arc::new(WriteProgressTracker::new(callback, None)); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + Some(tracker), + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + let requests = requests.lock().unwrap(); + assert!(requests.len() >= 2); + assert_eq!( + requests[0], requests[1], + "retry must reuse part id and encoded bytes" + ); + let mut decoded = Vec::new(); + for (_, body) in &requests[1..] { + assert!(body.len() <= 16 * 1024, "part size: {}", body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + decoded.push(cast(batch.unwrap().column(0), &plain_type).unwrap()); + } + } + let actual = + arrow_select::concat::concat(&decoded.iter().map(|a| a.as_ref()).collect::>()) + .unwrap(); + assert_eq!(actual.as_ref(), expected.as_ref()); + let total: usize = requests[1..].iter().map(|(_, b)| b.len()).sum(); + assert_eq!(acknowledged.load(Ordering::SeqCst), total); + assert!( + total < 16 * 1024, + "unused dictionary values leaked: {total}" + ); + } + + #[rstest::rstest] + #[case(false, "linear", 1024)] + #[case(true, "linear", 1024)] + #[case(false, "linear", 1000)] + #[case(true, "linear", 1000)] + #[case(false, "nested", 1024)] + #[case(true, "nested", 1024)] + #[case(false, "sharing", 1024)] + #[case(true, "sharing", 1024)] + #[case(false, "empty", 1024)] + #[case(true, "empty", 1024)] + #[tokio::test] + async fn test_multipart_list_view_dictionary_ranges( + #[case] large: bool, + #[case] layout: &str, + #[case] value_bytes: usize, + ) { + if large { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } else { + check_list_view_dictionary_ranges::(layout, value_bytes).await; + } + } + + async fn check_list_view_dictionary_ranges( + layout: &str, + value_bytes: usize, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, GenericListViewArray, Int32Array, ListArray, + RecordBatch, StringArray, StructArray, cast::AsArray, types::Int32Type, + }; + use arrow_buffer::{NullBuffer, OffsetBuffer}; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + use std::collections::HashMap; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|c| c.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let mut expected = Vec::new(); + let mut batches = Vec::new(); + let nested = layout != "linear"; + for reverse in [false, true] + .into_iter() + .take(if layout == "nested" { 2 } else { 1 }) + { + let values: Vec<_> = if reverse { + strings.iter().rev().cloned().collect() + } else { + strings.clone() + }; + let keys: Vec = (0..128) + .map(|i| if layout == "sharing" { i % 2 } else { i }) + .collect(); + // A sliced child has its own nonzero physical offset. + let dict = DictionaryArray::::new( + Int32Array::from_iter_values(std::iter::once(127).chain(keys.iter().copied())), + Arc::new(StringArray::from(values.clone())), + ) + .slice(1, 128); + let mut offsets = Vec::new(); + let mut sizes = Vec::new(); + let mut valid = Vec::new(); + let start = usize::from(layout == "nested"); + for row in 0..128 + start { + let (offset, size, is_valid) = match layout { + "empty" if row % 2 == 0 => (80, 48, false), + "empty" => (128, 0, true), + "nested" if row % 17 == 0 => (80, 48, false), + "nested" if row % 13 == 0 => (128, 0, true), + "nested" => (4 + (row * 7) % 64, 3, true), + "sharing" => (4 + (row % 2) * 4, 64, true), + _ => (row, 1, true), + }; + offsets.push(O::from_usize(offset).unwrap()); + sizes.push(O::from_usize(size).unwrap()); + valid.push(is_valid); + if row >= start { + expected.push(is_valid.then(|| { + (offset..offset + size) + .map(|i| values[keys[i] as usize].clone()) + .collect::>() + })); + } + } + let item = Arc::new( + Field::new("category", dict.data_type().clone(), false) + .with_metadata(HashMap::from([("item-meta".into(), "retained".into())])), + ); + let views = GenericListViewArray::::new( + item, + offsets.into(), + sizes.into(), + Arc::new(dict), + Some(NullBuffer::from(valid)), + ); + let view_count = views.len(); + let column: ArrayRef = if nested { + let field = Arc::new(Field::new("views", views.data_type().clone(), true)); + let entries = StructArray::new(vec![field].into(), vec![Arc::new(views)], None); + Arc::new(ListArray::new( + Arc::new(Field::new_list_field(entries.data_type().clone(), false)), + OffsetBuffer::from_lengths(std::iter::repeat_n(1, view_count)), + Arc::new(entries), + None, + )) + } else { + Arc::new(views) + }; + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![Field::new("categories", column.data_type().clone(), true)], + HashMap::from([("schema-meta".into(), "retained".into())]), + )); + batches.push( + RecordBatch::try_new(schema, vec![column]) + .unwrap() + .slice(start, 128), + ); + } + let schema = batches[0].schema(); + let logical_bytes: usize = expected.iter().flatten().flatten().map(String::len).sum(); + let input = input_plan_from_batches(schema.clone(), batches).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let sharing = layout == "sharing"; + let empty = layout == "empty"; + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + for batch in reader { + let batch = batch.unwrap(); + for row in 0..batch.num_rows() { + let column = if nested { + batch + .column(0) + .as_list::() + .value(row) + .as_struct() + .column(0) + .slice(0, 1) + } else { + batch.column(0).slice(row, 1) + }; + let views = column + .as_any() + .downcast_ref::>() + .unwrap(); + if empty { + assert_eq!(views.values().len(), 0, "null/empty views retain no child"); + } + if sharing { + assert_eq!( + views.values().len(), + 68, + "overlapping ranges must share their child" + ); + } + decoded_c.lock().unwrap().push(if views.is_null(0) { + None + } else { + let value = arrow_cast::cast(&views.value(0), &DataType::Utf8).unwrap(); + Some( + value + .as_string::() + .iter() + .map(|v| v.unwrap().to_owned()) + .collect::>(), + ) + }); + } + } + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), expected); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "ListView IPC: large={}, layout={layout}, value_bytes={value_bytes}, parts={}, first={}, total={total}", + O::IS_LARGE, + lengths.len(), + lengths[0] + ); + // Every selected row in these cases fits the target, including IPC framing. + assert!( + lengths.iter().all(|n| *n <= 16 * 1024), + "oversized parts: {lengths:?}" + ); + assert!( + total <= (2 * logical_bytes).max(16 * 1024), + "dictionary upload amplified: {total}" + ); + if sharing { + assert_eq!(lengths.len(), 1); + } + } + + #[rstest::rstest] + #[case(1024, false)] + // Dictionary data fits the target; IPC framing forces the sender to split again. + #[case(1000, false)] + #[case(1024, true)] + #[case(20 * 1024, false)] + #[tokio::test] + async fn test_multipart_dictionary_payload_is_not_repeated_per_row( + #[case] value_bytes: usize, + #[case] use_views: bool, + ) { + use arrow_array::{ + Array, ArrayRef, DictionaryArray, Int32Array, RecordBatch, StringArray, + StringViewArray, types::Int32Type, + }; + use arrow_ipc::reader::StreamReader; + use futures::StreamExt; + use rand::{RngCore, SeedableRng, rngs::SmallRng}; + + let mut bytes = vec![0; 128 * value_bytes]; + SmallRng::seed_from_u64(4977).fill_bytes(&mut bytes); + let strings: Vec = bytes + .chunks_exact(value_bytes) + .map(|chunk| chunk.iter().map(|b| char::from(b'!' + b % 90)).collect()) + .collect(); + let values: ArrayRef = if use_views { + Arc::new(StringViewArray::from_iter_values(&strings)) + } else { + Arc::new(StringArray::from(strings.clone())) + }; + let array = + DictionaryArray::::try_new(Int32Array::from_iter_values(0..128), values) + .unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![Field::new( + "category", + array.data_type().clone(), + false, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap(); + let input = input_plan_from_batches(schema.clone(), vec![batch]).await; + let lengths = Arc::new(Mutex::new(Vec::new())); + let observed = lengths.clone(); + let decoded = Arc::new(Mutex::new(Vec::new())); + let decoded_c = decoded.clone(); + let client = crate::remote::client::test_utils::client_with_handler(move |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + observed.lock().unwrap().push(body.len()); + let reader = StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + assert_eq!(reader.schema(), schema); + let mut rows = 0; + for batch in reader { + let batch = batch.unwrap(); + rows += batch.num_rows(); + let values = arrow_cast::cast(batch.column(0), &DataType::Utf8).unwrap(); + let values = values.as_any().downcast_ref::().unwrap(); + decoded_c + .lock() + .unwrap() + .extend(values.iter().map(|v| v.unwrap().to_owned())); + } + assert!( + body.len() <= 16 * 1024 || rows == 1, + "oversized divisible part: {} bytes, {rows} rows", + body.len() + ); + http::Response::builder().status(200).body("{}").unwrap() + }); + let exec = RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + input, + false, + "upload-1".into(), + None, + None, + Some(16 * 1024), + None, + ); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + while stream.next().await.transpose().unwrap().is_some() {} + assert_eq!(*decoded.lock().unwrap(), strings); + let lengths = lengths.lock().unwrap(); + let total: usize = lengths.iter().sum(); + eprintln!( + "dictionary IPC: value_bytes={value_bytes}, views={use_views}, parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + assert!( + total <= 2 * bytes.len(), + "dictionary upload amplified: parts={}, first={}, total={total}", + lengths.len(), + lengths[0] + ); + } } diff --git a/rust/lancedb/src/remote/table/write_tests.rs b/rust/lancedb/src/remote/table/write_tests.rs new file mode 100644 index 000000000..c97619af1 --- /dev/null +++ b/rust/lancedb/src/remote/table/write_tests.rs @@ -0,0 +1,436 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Real HTTP faults with a local Lance table behind the staging fixture. This +//! exercises SDK behavior; it does not model Sophon's asynchronous txn cleanup. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{LargeBinaryArray, RecordBatch}; +use arrow_ipc::reader::StreamReader; +use arrow_schema::{DataType, Field, Schema}; +use lance::arrow::json::JsonSchema; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use super::RemoteTable; +use crate::remote::client::{ClientConfig, RestfulLanceDbClient, RetryConfig, TimeoutConfig}; +use crate::remote::db::ServerVersion; +use crate::table::AddDataBuilder; + +#[derive(Clone, Copy, Debug)] +enum Fault { + Close, + Timeout, + Status(u16), +} + +#[derive(Default)] +struct State { + creates: usize, + completes: usize, + aborts: usize, + attempts: Vec<(String, Vec)>, + parts: HashMap>, +} + +async fn read_request(socket: &mut tokio::net::TcpStream) -> (String, Vec) { + let mut header = Vec::new(); + while !header.ends_with(b"\r\n\r\n") { + header.push(socket.read_u8().await.unwrap()); + assert!(header.len() < 64 * 1024); + } + let header = String::from_utf8(header).unwrap(); + let path = header.split_whitespace().nth(1).unwrap().to_owned(); + let length = header + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap_or(0); + assert!( + !header + .to_ascii_lowercase() + .contains("transfer-encoding: chunked") + ); + let mut body = vec![0; length]; + socket.read_exact(&mut body).await.unwrap(); + (path, body) +} + +async fn respond(socket: &mut tokio::net::TcpStream, status: u16, body: &str) { + let response = format!( + "HTTP/1.1 {status} Result\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; +} + +#[tokio::test] +async fn multipart_http_faults_preserve_committed_blob_payloads() { + for complete_fault in [false, true] { + for fault in [ + Fault::Close, + Fault::Timeout, + Fault::Status(500), + Fault::Status(502), + Fault::Status(503), + Fault::Status(504), + ] { + let dir = tempfile::tempdir().unwrap(); + let db = crate::connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![crate::blob::blob("payload", true)])); + let stored = db + .create_empty_table("stored", schema.clone()) + .execute() + .await + .unwrap(); + let state = Arc::new(Mutex::new(State::default())); + let server_state = state.clone(); + let server_table = stored.clone(); + 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 tasks = tokio::task::JoinSet::new(); + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let state = server_state.clone(); + let table = server_table.clone(); + tasks.spawn(async move { + let (path, body) = read_request(&mut socket).await; + let mut apply_fault = false; + let response; + if path.contains("multipart_write/create") { + state.lock().unwrap().creates += 1; + response = r#"{"upload_id":"00000000-0000-0000-0000-000000000001"}"# + .to_string(); + } else if path.contains("/insert/") { + let url = url::Url::parse(&format!("http://localhost{path}")).unwrap(); + let params: HashMap<_, _> = url.query_pairs().into_owned().collect(); + assert_eq!(params["upload_id"], "00000000-0000-0000-0000-000000000001"); + let part = params["upload_part_id"].clone(); + let mut state = state.lock().unwrap(); + apply_fault = !complete_fault && state.attempts.is_empty(); + state.attempts.push((part.clone(), body.clone())); + // Match the verified server contract: replace the txn + // associated with this part ID before acknowledging it. + state.parts.insert(part, body); + response = "{}".into(); + } else if path.contains("multipart_write/complete") { + let parts = { + let mut state = state.lock().unwrap(); + state.completes += 1; + state.parts.values().cloned().collect::>() + }; + for body in parts { + let reader = + StreamReader::try_new(std::io::Cursor::new(body), None) + .unwrap(); + let batches = reader.collect::, _>>().unwrap(); + table.add(batches).execute().await.unwrap(); + } + apply_fault = complete_fault; + response = r#"{"version":2}"#.into(); + } else if path.contains("multipart_write/abort") { + state.lock().unwrap().aborts += 1; + panic!("abort must never follow a possibly committed complete"); + } else { + panic!("unexpected request {path}"); + } + if apply_fault { + match fault { + Fault::Close => return, + Fault::Timeout => { + tokio::time::sleep(Duration::from_secs(2)).await; + return; + } + Fault::Status(status) => { + respond( + &mut socket, + status, + "gateway fault after staging/commit", + ) + .await; + return; + } + } + } + respond(&mut socket, 200, &response).await; + }); + } + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "us-east-1", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + timeout_config: TimeoutConfig { + read_timeout: Some(Duration::from_secs(1)), + ..Default::default() + }, + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let remote = Arc::new(RemoteTable::new_with_sql_client( + client, + "test".into(), + "test".into(), + vec![], + "test".into(), + ServerVersion(semver::Version::new(0, 4, 0)), + None, + )); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(schema.as_ref()).unwrap()}).to_string()); + let payload_a = vec![17u8; 32 * 1024]; + let payload_b = vec![29u8; 32 * 1024]; + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::LargeBinary, + true, + )])), + vec![Arc::new(LargeBinaryArray::from(vec![ + Some(payload_a.as_slice()), + Some(payload_b.as_slice()), + ]))], + ) + .unwrap(); + let progress = Arc::new(Mutex::new(Vec::new())); + let seen = progress.clone(); + let result = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await; + if complete_fault { + assert!( + result + .unwrap_err() + .to_string() + .contains("commit outcome unknown"), + "{fault:?}" + ); + } else { + result.unwrap(); + } + assert_eq!( + stored.count_rows(None).await.unwrap(), + 2, + "{fault:?}, complete={complete_fault}" + ); + let payloads = stored.fetch_blobs("payload", &[0, 1]).await.unwrap(); + assert_eq!(payloads.value(0), payload_a); + assert_eq!(payloads.value(1), payload_b); + let state = state.lock().unwrap(); + assert_eq!((state.creates, state.completes, state.aborts), (1, 1, 0)); + assert_eq!(state.parts.len(), 1); + assert_eq!(state.attempts.len(), if complete_fault { 1 } else { 2 }); + if !complete_fault { + assert_eq!(state.attempts[0], state.attempts[1]); + } + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert_eq!(last.0, 2); + assert!(last.1 > 0 && last.2); + assert_eq!( + progress.first().unwrap().1, + 0, + "scan is not an acknowledgement" + ); + assert!(progress.windows(2).all(|pair| pair[0].1 <= pair[1].1)); + assert_eq!(last.1, state.parts.values().map(Vec::len).sum::()); + server.abort(); + } + } +} + +#[tokio::test] +async fn multipart_retries_sixth_part_after_reused_connection_closes() { + use datafusion_execution::TaskContext; + use datafusion_physical_plan::ExecutionPlan; + use futures::TryStreamExt; + + 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 attempts = Vec::new(); + let (mut socket, _) = listener.accept().await.unwrap(); + for n in 0..6 { + let (path, body) = read_request(&mut socket).await; + attempts.push((path, body)); + if n == 5 { + break; + } + // Keep one connection pooled for the first five acknowledged parts. + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") + .await + .unwrap(); + } + // The sixth part was staged, but the peer closes before response headers. + drop(socket); + let (mut socket, _) = listener.accept().await.unwrap(); + attempts.push(read_request(&mut socket).await); + respond(&mut socket, 200, "{}").await; + attempts + }); + let client = RestfulLanceDbClient::try_new( + &crate::remote::client::parse_db_url("db://test").unwrap(), + "test-region", + Some(format!("http://{address}")), + Default::default(), + ClientConfig { + retry_config: RetryConfig { + retries: Some(3), + read_retries: Some(3), + connect_retries: Some(3), + backoff_factor: Some(0.0), + backoff_jitter: Some(0.0), + ..Default::default() + }, + ..Default::default() + }, + None, + ) + .unwrap(); + let input = arrow_array::record_batch!(("id", Int32, [1, 2, 3, 4, 5, 6])).unwrap(); + let plan = Arc::new( + crate::table::datafusion::scannable_exec::ScannableExec::new(Box::new(input), None), + ); + let exec = super::insert::RemoteWriteExec::new_multipart( + "test".into(), + "test".into(), + client, + plan, + false, + "upload-1".into(), + None, + None, + Some(1), + None, + ); + exec.execute(0, Arc::new(TaskContext::default())) + .unwrap() + .try_collect::>() + .await + .unwrap(); + let attempts = server.await.unwrap(); + assert_eq!(attempts.len(), 7); + assert_eq!( + attempts[5], attempts[6], + "retry must reuse both part ID and bytes" + ); + let unique: std::collections::HashSet<_> = attempts.iter().map(|(path, _)| path).collect(); + assert_eq!(unique.len(), 6, "the staged sixth txn must be replaced"); +} + +#[tokio::test] +async fn multipart_rejections_preserve_progress_and_cleanup_boundaries() { + // Stage rejection, definite complete rejection, and ambiguous successful responses. + for (stage_status, complete_status, complete_body, cleanup) in [ + (503, 200, "{}", true), + (200, 409, "transaction conflict", true), + (200, 429, "rate limited", true), + (200, 200, "{}", false), + (200, 200, "not json", false), + (200, 503, "gateway failure", false), + ] { + for abort_status in [200, 503] { + let requests = Arc::new(Mutex::new(Vec::new())); + let observed = requests.clone(); + let progress = Arc::new(Mutex::new(Vec::new())); + let during_request = progress.clone(); + let remote = Arc::new(RemoteTable::new_mock( + "test".into(), + move |request| { + let path = request.url().path(); + observed.lock().unwrap().push(path.to_owned()); + let (status, body) = if path.ends_with("/create") { + (200, r#"{"upload_id":"rejected-upload"}"#) + } else if path.ends_with("/insert/") { + let progress = during_request.lock().unwrap(); + assert!(!progress.is_empty(), "must execute the scan tracker"); + assert!(progress.iter().all(|p: &(usize, usize, bool)| p.1 == 0)); + (stage_status, "{}") + } else if path.ends_with("/complete") { + (complete_status, complete_body) + } else if path.ends_with("/abort") { + (abort_status, "cleanup response") + } else { + panic!("unexpected request {path}") + }; + http::Response::builder() + .status(status) + .body(body.to_owned()) + .unwrap() + }, + Some(semver::Version::new(0, 4, 0)), + )); + let input = arrow_array::record_batch!(("id", Int32, [1, 2])).unwrap(); + remote.seed_schema(&serde_json::json!({"version": 1, "schema": JsonSchema::try_from(input.schema().as_ref()).unwrap()}).to_string()); + let seen = progress.clone(); + let error = AddDataBuilder::new(remote, Box::new(input), None) + .write_parallelism(2) + .retries(0) + .progress(move |p| { + seen.lock() + .unwrap() + .push((p.output_rows(), p.output_bytes(), p.done())) + }) + .execute() + .await + .unwrap_err(); + let requests = requests.lock().unwrap(); + let count = |suffix: &str| { + requests + .iter() + .filter(|path| path.ends_with(suffix)) + .count() + }; + assert_eq!(count("/create"), 1); + assert_eq!(count("/insert/"), 1); + assert_eq!(count("/complete"), usize::from(stage_status == 200)); + assert_eq!( + count("/abort"), + usize::from(cleanup), + "cleanup must honor retries=0: {error}" + ); + assert_eq!( + error.to_string().contains("commit outcome unknown"), + !cleanup, + "{error}" + ); + let progress = progress.lock().unwrap(); + let last = progress.last().unwrap(); + assert!(last.2); + assert_eq!(last.0, 2); + if stage_status != 200 { + assert!( + progress.iter().all(|p| p.1 == 0), + "unacknowledged bytes reported" + ); + } + } + } +} diff --git a/rust/lancedb/src/remote/util.rs b/rust/lancedb/src/remote/util.rs index 1c368e2f5..dcfaf9312 100644 --- a/rust/lancedb/src/remote/util.rs +++ b/rust/lancedb/src/remote/util.rs @@ -1,7 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use arrow_array::{ + Array, ArrayRef, GenericListViewArray, OffsetSizeTrait, RecordBatch, UInt64Array, + cast::AsArray, make_array, +}; +use arrow_buffer::ScalarBuffer; +use arrow_data::ArrayData; use arrow_ipc::CompressionType; +use arrow_schema::{ArrowError, DataType, Field}; +use arrow_select::{dictionary::garbage_collect_any_dictionary, take::take}; use futures::{Stream, StreamExt}; use reqwest::Response; @@ -9,6 +17,269 @@ use crate::{Result, arrow::SendableRecordBatchStream}; use super::db::ServerVersion; +fn has_dictionary(data: &ArrayData) -> bool { + matches!(data.data_type(), DataType::Dictionary(_, _)) + || data.child_data().iter().any(has_dictionary) +} + +fn has_list_view(data: &ArrayData) -> bool { + matches!( + data.data_type(), + DataType::ListView(_) | DataType::LargeListView(_) + ) || data.child_data().iter().any(has_list_view) +} + +// Arrow take on ordinary lists copies nested ListView ranges through +// MutableArrayData, losing sharing. Select child row IDs instead, then apply +// that selection recursively to the real children. +fn take_dictionary_rows( + array: &dyn Array, + indices: &UInt64Array, +) -> std::result::Result { + let data = array.to_data(); + if !has_list_view(&data) { + return take(array, indices, None); + } + let item = || std::sync::Arc::new(Field::new_list_field(DataType::UInt64, false)); + let proxy_type = match data.data_type() { + DataType::List(_) | DataType::Map(_, _) => DataType::List(item()), + DataType::LargeList(_) => DataType::LargeList(item()), + DataType::FixedSizeList(_, size) => DataType::FixedSizeList(item(), *size), + DataType::Struct(fields) => DataType::Struct( + fields + .iter() + .map(|f| f.as_ref().clone().with_data_type(DataType::UInt64)) + .collect(), + ), + // ListView take already preserves sharing; its actual child selection + // is performed by compact_list_view before dictionary collection. + _ => return take(array, indices, None), + }; + let children = data + .child_data() + .iter() + .map(|child| UInt64Array::from_iter_values(0..child.len() as u64).to_data()) + .collect(); + let proxy = make_array( + data.clone() + .into_builder() + .data_type(proxy_type) + .child_data(children) + .build()?, + ); + let selected = take(proxy.as_ref(), indices, None)?.to_data(); + let children = data + .child_data() + .iter() + .zip(selected.child_data()) + .map(|(child, ids)| { + let ids = UInt64Array::from(ids.clone()); + Ok(take_dictionary_rows(make_array(child.clone()).as_ref(), &ids)?.to_data()) + }) + .collect::, ArrowError>>()?; + Ok(make_array( + selected + .into_builder() + .data_type(data.data_type().clone()) + .child_data(children) + .build()?, + )) +} + +fn compact_list_view( + views: &GenericListViewArray, +) -> std::result::Result { + let mut ranges: Vec<_> = (0..views.len()) + .filter_map(|row| { + let start = views.value_offsets()[row].as_usize(); + let size = views.value_sizes()[row].as_usize(); + (views.is_valid(row) && size != 0).then(|| (start, start + size)) + }) + .collect(); + ranges.sort_unstable(); + let mut union: Vec<(usize, usize, usize)> = Vec::with_capacity(ranges.len()); + let mut len = 0; + for (start, end) in ranges { + if let Some(last) = union.last_mut().filter(|last| start <= last.1) { + let end = end.max(last.1); + len += end - last.1; + last.1 = end; + } else { + union.push((start, end, len)); + len += end - start; + } + } + let mut offsets = Vec::with_capacity(views.len()); + let mut sizes = Vec::with_capacity(views.len()); + for row in 0..views.len() { + let size = views.value_sizes()[row]; + if views.is_null(row) || size.as_usize() == 0 { + offsets.push(O::usize_as(0)); + sizes.push(O::usize_as(0)); + } else { + let start = views.value_offsets()[row].as_usize(); + let range = union[union.partition_point(|r| r.0 <= start) - 1]; + // Removing gaps cannot increase a valid original offset. + offsets.push(O::from_usize(range.2 + start - range.0).unwrap()); + sizes.push(size); + } + } + // Each child position is selected once, even for unsorted, overlapping views. + let indices = UInt64Array::from_iter_values( + union + .iter() + .flat_map(|&(start, end, _)| (start..end).map(|i| i as u64)), + ); + let child = take_dictionary_rows(views.values().as_ref(), &indices)?; + views + .to_data() + .into_builder() + .offset(0) + .buffers(vec![ + ScalarBuffer::from(offsets).into_inner(), + ScalarBuffer::from(sizes).into_inner(), + ]) + .child_data(vec![child.to_data()]) + .build() +} + +fn compact_dictionary_data(data: ArrayData) -> std::result::Result { + let data = match data.data_type() { + DataType::Dictionary(_, _) => { + let array = make_array(data); + garbage_collect_any_dictionary(array.as_any_dictionary())?.to_data() + } + DataType::ListView(_) => compact_list_view(make_array(data).as_list_view::())?, + DataType::LargeListView(_) => compact_list_view(make_array(data).as_list_view::())?, + // Selecting dictionary values retains view backing buffers, which IPC + // otherwise serializes in full even when most views are unreferenced. + DataType::Utf8View => make_array(data).as_string_view().gc().to_data(), + DataType::BinaryView => make_array(data).as_binary_view().gc().to_data(), + _ => data, + }; + let children = data + .child_data() + .iter() + .cloned() + .map(compact_dictionary_data) + .collect::, _>>()?; + data.into_builder().child_data(children).build() +} + +/// Compact dictionaries retained by row slices without changing the schema. +/// Row slices (and `take` alone) retain the original dictionary lookup tables. +/// Struct/fixed-size-list validity does not mask child slots, so values hidden +/// only by those ancestor nulls may remain referenced. +pub(super) fn compact_batch_dictionaries( + batch: RecordBatch, +) -> std::result::Result { + let columns = batch + .columns() + .iter() + .map(|array| { + let data = array.to_data(); + if !has_dictionary(&data) { + return Ok(array.clone()); + } + // Normalize container offsets and select their child rows before + // collecting dictionaries nested in lists/structs/maps. + let data = if matches!(data.data_type(), DataType::Dictionary(_, _)) { + data + } else { + let indices = UInt64Array::from_iter_values(0..array.len() as u64); + take_dictionary_rows(array.as_ref(), &indices)?.to_data() + }; + Ok(make_array(compact_dictionary_data(data)?)) + }) + .collect::, ArrowError>>()?; + RecordBatch::try_new_with_options( + batch.schema(), + columns, + &arrow_array::RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) +} + +/// Split batches before IPC encoding, preserving row order and allowing a single +/// oversized row. Compact each dictionary before measuring or splitting it so +/// descendants never repeatedly scan or encode the full source dictionary. +/// Yield slices on demand so compacted dictionary copies are not all retained. +pub(super) fn split_batch( + batch: RecordBatch, + max_bytes: usize, +) -> impl Iterator> { + let mut pending = vec![batch]; + std::iter::from_fn(move || { + while let Some(batch) = pending.pop() { + let batch = match compact_batch_dictionaries(batch) { + Ok(batch) => batch, + Err(err) => { + pending.clear(); + return Some(Err(err)); + } + }; + let size: usize = batch + .columns() + .iter() + .map(|array| { + array + .to_data() + .get_slice_memory_size() + .unwrap_or_else(|_| array.get_buffer_memory_size()) + }) + .sum(); + if size > max_bytes && batch.num_rows() > 1 { + let middle = batch.num_rows() / 2; + pending.push(batch.slice(middle, batch.num_rows() - middle)); + pending.push(batch.slice(0, middle)); + } else { + return Some(Ok(batch)); + } + } + None + }) +} + +pub(super) const IPC_BATCH_BYTES: usize = 8 * 1024 * 1024; +pub(super) const MAX_CREATE_BYTES: usize = 256 * 1024 * 1024; + +/// Validate the entire create payload before issuing its single atomic request. +/// A truncated IPC stream can be accepted as EOF by Arrow readers, so failing a +/// live request body after exceeding the budget cannot guarantee atomic failure. +/// Spooling bounds memory while ensuring an oversized input never reaches create. +pub(super) async fn create_body(data: SendableRecordBatchStream) -> Result { + use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; + let io_error = |err: std::io::Error| crate::Error::Other { + message: "Failed to prepare atomic remote create payload".into(), + source: Some(Box::new(err)), + }; + let file = tempfile::tempfile().map_err(io_error)?; + let mut file = tokio::fs::File::from_std(file); + let mut stream = Box::pin(stream_as_ipc(data)?); + let mut bytes = 0usize; + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + bytes = bytes.saturating_add(chunk.len()); + if bytes > MAX_CREATE_BYTES { + return Err(crate::Error::InvalidInput { + message: format!( + "Remote create_table exceeds the {MAX_CREATE_BYTES}-byte single-request budget. \ + Create the table with db.create_table(name, schema=...), then upload with \ + table.add(data, progress=True)." + ), + }); + } + file.write_all(&chunk).await.map_err(io_error)?; + } + file.rewind().await.map_err(io_error)?; + let stream = futures::stream::try_unfold(file, |mut file| async move { + let mut chunk = vec![0; 64 * 1024]; + let len = file.read(&mut chunk).await?; + chunk.truncate(len); + Ok::<_, std::io::Error>((len != 0).then_some((chunk, file))) + }); + Ok(reqwest::Body::wrap_stream(stream)) +} + pub fn stream_as_ipc( data: SendableRecordBatchStream, ) -> Result>> { @@ -18,6 +289,13 @@ pub fn stream_as_ipc( let buf = Vec::with_capacity(WRITE_BUF_SIZE); let writer = arrow_ipc::writer::StreamWriter::try_new_with_options(buf, &data.schema(), options)?; + let data = data.flat_map(|batch| match batch { + Ok(batch) => futures::stream::iter( + split_batch(batch, IPC_BATCH_BYTES).map(|batch| batch.map_err(Into::into)), + ) + .left_stream(), + Err(err) => futures::stream::iter([Err(err)]).right_stream(), + }); let stream = futures::stream::try_unfold( (data, writer, false), move |(mut data, mut writer, finished)| async move { @@ -42,11 +320,6 @@ pub fn stream_as_ipc( Ok(stream) } -pub fn stream_as_body(data: SendableRecordBatchStream) -> Result { - let stream = stream_as_ipc(data)?; - Ok(reqwest::Body::wrap_stream(stream)) -} - pub fn parse_server_version(req_id: &str, rsp: &Response) -> Result { let version = rsp .headers() diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 8c5dc4b45..d6323449d 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -65,6 +65,7 @@ pub struct AddDataBuilder { pub(crate) progress_callback: Option, pub(crate) write_parallelism: Option, pub(crate) allow_external_blob_outside_bases: bool, + pub(crate) retries: Option, } impl std::fmt::Debug for AddDataBuilder { @@ -93,9 +94,18 @@ impl AddDataBuilder { progress_callback: None, write_parallelism: None, allow_external_blob_outside_bases: false, + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries, + /// including retries of idempotent multipart parts. Ambiguous commits are + /// never replayed, regardless of this setting. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + pub fn mode(mut self, mode: AddDataMode) -> Self { self.mode = mode; self @@ -217,6 +227,7 @@ impl AddDataBuilder { mode: self.mode, tracker, allow_external_blob_outside_bases: self.allow_external_blob_outside_bases, + retries: self.retries, }) } } @@ -231,6 +242,7 @@ pub struct PreprocessingOutput { pub mode: AddDataMode, pub tracker: Option>, pub allow_external_blob_outside_bases: bool, + pub retries: Option, } /// Check that the input schema is valid for insert. diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 3f37c540d..fe131d907 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -75,6 +75,7 @@ pub struct MergeInsertBuilder { pub(crate) when_not_matched_by_source_delete: bool, pub(crate) when_not_matched_by_source_delete_filt: Option, pub(crate) timeout: Option, + pub(crate) retries: Option, pub(crate) use_index: bool, pub(crate) use_rte: Option, pub(crate) validate_single_shard: bool, @@ -91,12 +92,21 @@ impl MergeInsertBuilder { when_not_matched_by_source_delete: false, when_not_matched_by_source_delete_filt: None, timeout: None, + retries: None, use_index: true, use_rte: None, validate_single_shard: true, } } + /// Override the remote transport retry budget for this operation. `0` + /// disables retries. Ambiguous write results are never replayed. This is + /// independent of local transaction conflict retries. + pub fn retries(&mut self, retries: u8) -> &mut Self { + self.retries = Some(retries); + self + } + /// Rows that exist in both the source table (new data) and /// the target table (old data) will be updated, replacing /// the old row with the corresponding matching row. diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index d9828fff1..55980c5ff 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -26,6 +26,7 @@ pub struct UpdateBuilder { parent: Arc, pub(crate) filter: Option, pub(crate) columns: Vec<(String, String)>, + pub(crate) retries: Option, } impl UpdateBuilder { @@ -34,9 +35,17 @@ impl UpdateBuilder { parent, filter: None, columns: Vec::new(), + retries: None, } } + /// Override the remote retry budget for this call. `0` disables retries. + /// Ambiguous write results are never replayed. Ignored by embedded tables. + pub fn retries(mut self, retries: u8) -> Self { + self.retries = Some(retries); + self + } + /// Limits the update operation to rows matching the given filter /// /// If a row does not match the filter then it will be left unchanged. diff --git a/rust/lancedb/src/table/write_progress.rs b/rust/lancedb/src/table/write_progress.rs index 191c3284d..12e4dd62c 100644 --- a/rust/lancedb/src/table/write_progress.rs +++ b/rust/lancedb/src/table/write_progress.rs @@ -6,7 +6,7 @@ //! You can add a callback to process progress in [`crate::table::AddDataBuilder::progress`]. //! [`WriteProgress`] is the struct passed to the callback. -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -30,12 +30,19 @@ impl WriteProgress { self.elapsed } - /// Number of rows written so far. + /// Number of rows processed by the input scan. + /// + /// This does not indicate that the rows have been committed. pub fn output_rows(&self) -> usize { self.output_rows } - /// Number of bytes written so far. + /// Number of bytes processed by the writer. + /// + /// Remote multipart writes report acknowledged IPC part bytes, starting at + /// zero. Retransmitted parts are counted once. Other writers report their + /// encoded bytes when available, otherwise the scanned Arrow memory size. + /// This does not indicate that the write has been committed. pub fn output_bytes(&self) -> usize { self.output_bytes } @@ -94,6 +101,8 @@ pub(crate) struct WriteProgressTracker { /// Wire bytes tracked separately by the insert layer. When set (> 0), /// this takes precedence over the in-memory bytes from `rows_and_bytes`. wire_bytes: AtomicUsize, + /// Multipart writes select this before scanning, including zero acknowledgements. + wire_bytes_enabled: AtomicBool, active_tasks: Arc, total_tasks: AtomicUsize, start: Instant, @@ -107,6 +116,7 @@ impl WriteProgressTracker { Self { rows_and_bytes: std::sync::Mutex::new((0, 0)), wire_bytes: AtomicUsize::new(0), + wire_bytes_enabled: AtomicBool::new(false), active_tasks: Arc::new(AtomicUsize::new(0)), total_tasks: AtomicUsize::new(1), start: Instant::now(), @@ -115,6 +125,11 @@ impl WriteProgressTracker { } } + /// Select wire-byte progress, including zero, before polling the input plan. + pub fn use_wire_bytes(&self) { + self.wire_bytes_enabled.store(true, Ordering::Relaxed); + } + /// Set the total number of parallel write tasks (the write parallelism). pub fn set_total_tasks(&self, n: usize) { self.total_tasks.store(n, Ordering::Relaxed); @@ -179,7 +194,11 @@ impl WriteProgressTracker { let wire = self.wire_bytes.load(Ordering::Relaxed); // Prefer wire bytes (actual I/O size) when the insert layer is // tracking them; fall back to in-memory Arrow size otherwise. - let output_bytes = if wire > 0 { wire } else { in_memory_bytes }; + let output_bytes = if self.wire_bytes_enabled.load(Ordering::Relaxed) || wire > 0 { + wire + } else { + in_memory_bytes + }; WriteProgress { elapsed: self.start.elapsed(), output_rows: rows, From da40aa6c44b0eaf5f2003e5837e1a4f5e7c3799b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:23 +0800 Subject: [PATCH 092/203] test: isolate SQL reader timeout from submission latency (#5000) The reader timeout regression can fail on a busy runner while submitting its real loopback Flight exchange, before it ever calls `reader()`. Freeze Tokio time and inhibit automatic clock advancement during submission, then let the existing 200ms result timeout fire. Preserve the exact result-stage error through both describe APIs and a second reader, and verify that the timeout closes the server response stream. With a diagnostic-only 300ms wall-clock delay in request-header preparation, main fails with `SQL query submission timed out`; the repaired fixture passes the same scenario through the real Flight/reader path. The focused regression and all 54 adjacent SQL tests pass locally. Hosted Linux and macOS CLI tests and the complete PR CI pass on `fb96931be004166a479cc031aca4b1db05f4b78d`. --- rust/lancedb/src/remote/sql_test.rs | 33 +++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 471966731..d94defac4 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -607,7 +607,15 @@ impl FlightService for TestSqlService { )); } if query == "SELECT exchange stall" { - return Ok(Response::new(futures::stream::pending().boxed())); + let dropped = DropSignal(self.exchange_drops.clone()); + return Ok(Response::new( + futures::stream::pending() + .map(move |message| { + let _dropped = &dropped; + message + }) + .boxed(), + )); } let rows = parameters.ok_or_else(|| Status::invalid_argument("exchange without parameters"))?; @@ -990,13 +998,26 @@ async fn an_abandoned_reader_leaves_the_rows_for_the_next_one() { async fn a_reader_that_times_out_reports_the_failure() { let mut client_config = ClientConfig::default(); client_config.timeout_config.timeout = Some(Duration::from_millis(200)); - let (client, _shutdown) = start_sql_service(TestSqlService::default(), client_config).await; + let service = TestSqlService::default(); + let drops = service.exchange_drops.clone(); + let (client, _shutdown) = start_sql_service(service, client_config).await; - let stalled = client - .execute(parameterized("SELECT exchange stall", parameter_row())) - .await - .unwrap(); + // Real loopback I/O must finish before the clock can advance to the timeout. + // A blocking task inhibits Tokio's automatic clock advance during submission. + tokio::time::pause(); + let submission_client = client.clone(); + let stalled = tokio::task::spawn_blocking(move || { + tokio::runtime::Handle::current().block_on( + submission_client.execute(parameterized("SELECT exchange stall", parameter_row())), + ) + }) + .await + .unwrap() + .unwrap(); + assert_eq!(drops.load(Ordering::SeqCst), 0); assert_overall_timeout(stalled.reader().await, "result"); + tokio::time::resume(); + wait_for(&drops, 1, "a timed-out reader must end the call").await; let Err(retried) = stalled.reader().await else { panic!("the rows are gone, so a second reader cannot succeed"); }; From 9b13e8f72530c8b1950c09685f6920711154a539 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 02:05:39 +0800 Subject: [PATCH 093/203] feat(python): materialize remote blobs at the query snapshot (#4973) Python remote queries materialize Blob v2 payloads with `blob_mode="bytes"` through synchronous and asynchronous `to_arrow`, `to_list`, `to_pandas`, and `to_batches`. Deferred reads bind to the actual producing dataset without changing the caller's live table handle, including concurrent writes and same-name DROP/CREATE. Trust only the authoritative `x-lancedb-query-version` plus `x-lancedb-query-snapshot`. A numeric version alone cannot distinguish a recreated table; the ordinary live watermark and user-supplied Arrow metadata cannot establish provenance. An independent immutable handle carries the original identity through every batch, byte-limit split, and large-Blob Range fallback, and requires a verified response echo before accepting payloads. Aliases, NULL/empty results, rerankers, and hybrid legs retain consistent provenance. Missing capability, mixed identities, or a serving node ignoring the precondition fails explicitly; ordinary descriptor queries remain available on older servers. The source docs distinguish Enterprise SQL payload bytes from SDK descriptors. Server dependency: https://github.com/lancedb/sophon/pull/10211. Validation uses retained, independently audited local evidence: 724 Python cases passed (one optional PyAV skip), 67 focused SDK Rust cases passed, 36 server checks passed, and 15 actual REST/SDK scenarios passed across retained runs. These cover sync/async and Arrow file/stream recreation, concurrent overwrite, deletion of a selected version, legacy capabilities, forged IPC metadata, WAL exclusion, and actual mid-batch recreation. The original aggregate experiment exited 101 because its extra harness assumed a Python batch size would split the native result; its 36 server checks and 13 completed scenarios remain valid. The corrected native-batch experiment passed separately for sync and async. No aggregate all-green claim is made. The public batched-range operation has separate cross-partition identity integration in https://github.com/lancedb/sophon/pull/10219 and https://github.com/lancedb/lancedb/pull/4994. This change does not claim to fix that loop. Realtime/MemWAL remains outside Blob v2 GA, without disabling existing writes or compaction. No dependency pins changed. Merge/rollout hold remains: upgrade every serving node before enabling the new SDK capability, verify proxy forwarding of both authoritative headers and the verification echo, and preserve queried versions for later reads. Missing or inconsistent capability fails explicitly; identity does not retain versions or authenticate storage paths. Actual deployed proxy/Cloud/PE behavior and production retention remain unverified. Old SDKs do not gain incarnation protection from a server-only upgrade. Published documentation retains the Early access badge and released Enterprise instructions, including explicit fetches for copying. The new Enterprise `blob_mode="bytes"` guidance, snapshot-bound copy example, future streaming restrictions and GA wording remain source-only MDX drafts until release. The correction distinguishing released Enterprise SQL bytes from SDK descriptors remains visible. Documentation validation checked comment boundaries, visible instructions, Python example syntax and whitespace; the site was not built. This documentation-only revision reuses the implementation evidence above. --- docs/web/management/table.mdx | 102 +++++- docs/web/sql/dql/blob-descriptor.mdx | 8 +- python/python/lancedb/_lancedb.pyi | 7 +- python/python/lancedb/query.py | 138 ++++++-- python/python/tests/test_remote_db.py | 457 +++++++++++++++++++++++-- python/src/table.rs | 16 +- rust/lancedb/src/remote/table.rs | 171 ++++++++- rust/lancedb/src/remote/table/blobs.rs | 30 +- rust/lancedb/src/table.rs | 23 ++ 9 files changed, 876 insertions(+), 76 deletions(-) diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 23fdbdb4a..031342fbc 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -375,8 +375,16 @@ file, up to 64 KiB by default, and larger values are stored outside it. A `blob` column keeps metadata separate from the payload bytes, so queries can filter rows without loading the blobs. -Most queries return descriptors, which contain metadata about the blob instead -of its bytes. You can +{/* Draft for Blob v2 GA. Confirm release status before removing Early access. + +Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled +are outside the GA support scope. +*/} + +SDK queries return descriptors by default, which contain metadata about the +blob instead of its bytes. Enterprise SQL queries return payload bytes by +default; use `blob_descriptor(column)` to select metadata instead. With an SDK, +you can [read the bytes in the query results](#multimodal-blob-query-results) or [fetch them by row ID](#multimodal-read-blobs). @@ -500,14 +508,41 @@ 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`. +{/* Draft for the Enterprise Python bytes release. Replace the released instructions above only after SDK and serving-node rollout. + +`blob_mode="bytes"` also supports Enterprise queries. The SDK locks all blob +fetches, including streaming batches, to both the version in +`x-lancedb-query-version` and the incarnation/revision identity in +`x-lancedb-query-snapshot`, captured from the same query response. Every payload +request verifies that identity against the actual opened dataset before reading +rows. Concurrent writes therefore preserve the selected payloads. Dropping and +recreating a table, even at the same location and version, cannot substitute the +replacement's bytes: the original snapshot is served or the read fails explicitly. + +Upgrade the SDK and every serving node to support snapshot identities. A server +that reports only a numeric query version, a legacy `x-lancedb-version` watermark, +or Arrow schema metadata does not enable deferred bytes. Missing or unsupported +identities raise `NotImplementedError`; use `"descriptions"` until the upgrade is +complete. Ordinary queries, descriptors, and independent `fetch_blobs` calls keep +working. Old SDKs keep their existing behavior and do not gain this protection +from a server-only upgrade. Realtime/MemWAL and historical manifests without a +native transaction identity do not support deferred bytes. Snapshot identities +do not retain old versions; deleting the selected version still fails explicitly. +In-memory tables and namespace `QueryTable` pushdown do not support bytes mode. +On an Enterprise table, sync `Table.to_pandas()` and `Table.to_arrow()` are not +supported; use `table.search()` instead. A query's `to_pandas()` also raises in +the default `"lazy"` mode because remote lazy handles are not supported. +*/} + ###### Copy a subset of blob rows {#multimodal-copy-subset} -Blob query results describe the stored payload; they are not the bytes to -insert into another table. These APIs return different values: +SDK descriptors identify stored payloads; materialize the bytes before inserting +them into another table. These APIs return different values: | Read path | Value | | --- | --- | -| SQL or an Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | +| Enterprise SQL | Raw payload bytes by default. | +| An SDK Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | | `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | | A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | @@ -545,6 +580,50 @@ Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches for larger subsets; `fetch_blobs` materializes all requested bytes in memory. For incremental decoding, use `fetch_blob_files` instead. +{/* Draft for the Enterprise Python bytes release. Replace the copy example above when snapshot-bound remote bytes are released. + +For Enterprise tables, prefer server-side `CREATE TABLE AS SELECT` or +`INSERT INTO ... SELECT` to copy blobs without a client round trip: + +```sql +CREATE TABLE image_subset AS SELECT id, image FROM images WHERE id < 100; +-- To append to an existing destination: +INSERT INTO image_subset SELECT id, image FROM images WHERE id >= 100 AND id < 200; +``` + +For SDK copies, query with `blob_mode="bytes"` to bind selection and payload +reads to one snapshot. The following example copies up to 100 rows from an +existing `images` table with an integer `id` and a blob `image` column. + +```python +import lancedb +import pyarrow as pa + +source = db.open_table("images") +hits = ( + source.search() + .where("id < 100") + .select(["id", "image"]) + .limit(100) + .to_arrow(blob_mode="bytes") +) +subset = db.create_table( + "image_subset", + schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), +) +if hits.num_rows: + subset.add(hits) +``` + +Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches +for larger subsets; `fetch_blobs` materializes all requested bytes in memory. +For incremental decoding, use `fetch_blob_files` instead. + +Remote bytes mode requires a server that supports snapshot-bound Blob reads. +Older servers and Realtime/MemWAL tables can still return descriptors, but +bytes mode raises an explicit unsupported-operation error before fetching payloads. +*/} + `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 @@ -579,6 +658,19 @@ 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`. +{/* Draft for the Enterprise Python bytes release. Replace the streaming restrictions above after release. + +Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, +including no blobs inside lists, namespace `QueryTable` pushdown, or query +shapes that cannot preserve their row results. Enterprise queries require a +valid `x-lancedb-query-version` and `x-lancedb-query-snapshot` response headers. +Legacy v1 bytes are limited to +eligible local plain scans. For local queries, 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} The lazy-handle calls below require pylance. The query example expects `tbl_async`, diff --git a/docs/web/sql/dql/blob-descriptor.mdx b/docs/web/sql/dql/blob-descriptor.mdx index 5021f2d20..7ba83311c 100644 --- a/docs/web/sql/dql/blob-descriptor.mdx +++ b/docs/web/sql/dql/blob-descriptor.mdx @@ -15,10 +15,10 @@ 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 +A plain `SELECT` of a [BlobV2](/management/table#managed-blobs) column returns +its payload as `large_binary`. `blob_descriptor` instead returns a small +struct describing where the payload lives, without reading the payload. +Pass one row's descriptor to the SDK's blob file reader to open that payload directly: diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 15234532d..956806cde 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -749,7 +749,12 @@ class Table: def take_row_ids(self, row_ids: list[int]) -> TakeQuery: ... async def blob_columns(self) -> list[str]: ... async def fetch_blobs( - self, column: str, row_ids: list[int] + self, + column: str, + row_ids: list[int], + *, + version: Optional[int] = None, + snapshot_identity: Optional[str] = None, ) -> pa.LargeBinaryArray: ... async def fetch_blob_ranges( self, diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index bab40be95..f99aaeb73 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio +import re from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor from datetime import timedelta @@ -194,20 +195,57 @@ def _unsupported_blob_pandas_error(reason: str) -> RuntimeError: ) -def _supports_local_blob_fetch( +def _supports_blob_fetch( async_table: "AsyncTable", pushdown_operations: Iterable[str] ) -> bool: - # Remote tables and QueryTable pushdown answer queries on a server, so a - # fetch through this handle could read another version. - return async_table._inner._is_native() and "QueryTable" not in pushdown_operations + # Remote queries carry their producing snapshot in response metadata. + # Namespace QueryTable pushdown has no equivalent snapshot contract. + return ( + not async_table._inner._is_native() or "QueryTable" not in pushdown_operations + ) + + +def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]: + value = (schema.metadata or {}).get(b"lancedb:query_version", b"") + if not value.isdigit() or not 0 < int(value) < 2**64: + raise NotImplementedError( + "blob_mode='bytes' requires a stable table snapshot: the query response " + "has a missing, invalid, or inconsistent x-lancedb-query-version header. " + "Upgrade the server and use a table without Realtime/MemWAL, or use " + "blob_mode='descriptions'." + ) + identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"") + if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity): + raise NotImplementedError( + "blob_mode='bytes' requires a trustworthy query snapshot identity: " + "missing or unsupported x-lancedb-query-snapshot. Upgrade the server " + "on every serving node, or use blob_mode='descriptions'." + ) + return int(value), identity.decode("ascii") + + +def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table: + """Preserve a snapshot only when every query leg used the same identity.""" + keys = (b"lancedb:query_version", b"lancedb:query_snapshot") + snapshots = { + tuple((source.schema.metadata or {}).get(key) for key in keys) + for source in sources + } + metadata = dict(result.schema.metadata or {}) + for key in keys: + metadata.pop(key, None) + snapshot = next(iter(snapshots)) if len(snapshots) == 1 else None + if snapshot is not None and all(value is not None for value in snapshot): + metadata.update(zip(keys, snapshot)) + return result.replace_schema_metadata(metadata) def _blob_bytes_without_snapshot_error() -> NotImplementedError: return NotImplementedError( "blob_mode='bytes' cannot safely materialize blob columns without a " - "stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown " - "run the query on a server, so the blob fetch could read another table " - "version. Use blob_mode='descriptions' to inspect descriptors. To read " + "stable table snapshot. Namespace QueryTable pushdown does not bind " + "the query and blob fetches to one table version. " + "Use blob_mode='descriptions' to inspect descriptors. To read " "payloads, select row IDs with with_row_id(True), then call " "table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, " "row_ids). Keep the source unchanged between selection and fetching." @@ -1297,9 +1335,9 @@ class LanceQueryBuilder(ABC): columns without pylance. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Enterprise blob queries support only ``"descriptions"`` until a - stable - table snapshot can bind the query and blob fetches. + Enterprise queries support ``"bytes"`` at the query response's + snapshot and ``"descriptions"`` without payload reads. Remote + ``"lazy"`` handles are not supported. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and optional flattening. @@ -1307,6 +1345,10 @@ class LanceQueryBuilder(ABC): validate_blob_mode(blob_mode) if _is_remote_query_table(self._table): blob_sources = self._validated_blob_sources(blob_mode) + if blob_mode == "bytes": + return flatten_columns( + self.to_arrow(timeout=timeout, blob_mode=blob_mode), flatten + ).to_pandas(**kwargs) return _finish_remote_pandas( self.to_arrow(timeout=timeout), blob_mode=blob_mode, @@ -1629,7 +1671,8 @@ class LanceQueryBuilder(ABC): _query_is_plain_blob_scan(query) and getattr(self, "_reranker", None) is None and not _query_needs_lance_scanner(self) - and _supports_local_blob_fetch( + and self._table._table._inner._is_native() + and _supports_blob_fetch( self._table._table, getattr(self._table, "_pushdown_operations", ()), ) @@ -1650,11 +1693,12 @@ class LanceQueryBuilder(ABC): if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, self._columns, blob_sources) - if blob_sources and not _supports_local_blob_fetch( + if blob_sources and not _supports_blob_fetch( self._table._table, getattr(self._table, "_pushdown_operations", ()) ): raise _blob_bytes_without_snapshot_error() - reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources) + if not _is_remote_query_table(self._table): + reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources) return blob_sources def _blob_output_schema(self) -> pa.Schema: @@ -1667,9 +1711,20 @@ class LanceQueryBuilder(ABC): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return replace_blob_columns_with_bytes_sync( - tbl, blob_sources, self._table.fetch_blobs - ) + reject_unmatched_blob_outputs(tbl.schema, blob_sources) + if _is_remote_query_table(self._table) and blob_sources: + version, identity = _remote_blob_snapshot(tbl.schema) + + async def fetch_at_version(column, row_ids): + return await self._table._table._inner.fetch_blobs( + column, row_ids, version=version, snapshot_identity=identity + ) + + def fetch_blobs(column, row_ids): + return LOOP.run(fetch_at_version(column, row_ids)) + else: + fetch_blobs = self._table.fetch_blobs + return replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs) def _finalize_blob_query_table( self, @@ -2386,6 +2441,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): rs_table = result_set.read_all() result_set = self._reranker.rerank_vector(self._str_query, rs_table) check_reranker_result(result_set) + result_set = _merge_query_snapshot(result_set, rs_table) # convert result_set back to RecordBatchReader result_set = pa.RecordBatchReader.from_batches( result_set.schema, result_set.to_batches() @@ -2599,8 +2655,10 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): query = self._query_for_scan(blob_sources) results = self._table._execute_query(query, timeout=timeout).read_all() if self._reranker is not None: + source = results results = self._reranker.rerank_fts(self._query, results) check_reranker_result(results) + results = _merge_query_snapshot(results, source) return self._finalize_blob_query_table( results, blob_mode=blob_mode, blob_sources=blob_sources ) @@ -2847,6 +2905,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): with_row_ids=True, offset=self._offset, ) + results = _merge_query_snapshot(results, fts_results, vector_results) return self._finish_hybrid_results( results, blob_mode=blob_mode, blob_sources=blob_sources ) @@ -3559,9 +3618,8 @@ class AsyncQueryBase(object): _query_is_plain_blob_scan(query) and getattr(self, "_reranker", None) is None and not _query_needs_lance_scanner(self) - and _supports_local_blob_fetch( - self._table, self._table._pushdown_operations - ) + and self._table._inner._is_native() + and _supports_blob_fetch(self._table, self._table._pushdown_operations) ) def select(self, columns: Union[List[str], dict[str, str]]) -> Self: @@ -3766,11 +3824,14 @@ class AsyncQueryBase(object): if blob_mode != "bytes": return blob_sources reject_unfetchable_blob_columns(schema, projection, blob_sources) - if blob_sources and not _supports_local_blob_fetch( + if blob_sources and not _supports_blob_fetch( self._table, self._table._pushdown_operations ): raise _blob_bytes_without_snapshot_error() - reject_unmatched_blob_outputs(await self._blob_output_schema(), blob_sources) + if self._table._inner._is_native(): + reject_unmatched_blob_outputs( + await self._blob_output_schema(), blob_sources + ) return blob_sources async def _blob_output_schema(self) -> pa.Schema: @@ -3783,9 +3844,21 @@ class AsyncQueryBase(object): return tbl if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) - return await replace_blob_columns_with_bytes( - tbl, blob_sources, self._table.fetch_blobs - ) + reject_unmatched_blob_outputs(tbl.schema, blob_sources) + if ( + self._table is not None + and not self._table._inner._is_native() + and blob_sources + ): + version, identity = _remote_blob_snapshot(tbl.schema) + + async def fetch_blobs(column, row_ids): + return await self._table._inner.fetch_blobs( + column, row_ids, version=version, snapshot_identity=identity + ) + else: + fetch_blobs = self._table.fetch_blobs + return await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs) async def to_arrow( self, @@ -3811,7 +3884,8 @@ class AsyncQueryBase(object): ``fetch_blobs`` reads. ``"descriptions"`` returns them without it. ``"bytes"`` returns payload bytes for supported row-addressable blob columns and raises for blobs inside lists. - LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``. + Enterprise queries fetch bytes at the version reported by the query + response. Namespace query pushdown refuses ``"bytes"``. """ blob_sources = await self._validated_blob_sources(blob_mode) if blob_mode == "bytes" and blob_sources: @@ -3893,9 +3967,9 @@ class AsyncQueryBase(object): columns without pylance. Other local blob v2 queries return descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`. - LanceDB Enterprise blob queries support only ``"descriptions"`` until a - stable - table snapshot can bind the query and blob fetches. + Enterprise queries support ``"bytes"`` at the query response's + snapshot and ``"descriptions"`` without payload reads. Remote + ``"lazy"`` handles are not supported. **kwargs Forwarded to pyarrow.Table.to_pandas after query execution and optional flattening. @@ -3903,6 +3977,9 @@ class AsyncQueryBase(object): validate_blob_mode(blob_mode) if self._table is not None and not self._table._inner._is_native(): await self._validated_blob_sources(blob_mode) + if blob_mode == "bytes": + tbl = await self.to_arrow(timeout=timeout, blob_mode=blob_mode) + return flatten_columns(tbl, flatten).to_pandas(**kwargs) return await self._remote_to_pandas( flatten=flatten, timeout=timeout, blob_mode=blob_mode, **kwargs ) @@ -4508,7 +4585,9 @@ class AsyncFTSQuery(AsyncStandardQuery): ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: + source = results results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) @@ -4835,7 +4914,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: + source = results results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) @@ -5027,6 +5108,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): ): result = result.drop(["_rowid"]) + result = _merge_query_snapshot(result, fts_results, vector_results) return AsyncRecordBatchReader(result, max_batch_length=max_batch_length) async def explain_plan(self, verbose: Optional[bool] = False): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 448fd6c39..561a0f900 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5462,14 +5462,34 @@ def blob_descriptor_take_table(): @contextlib.contextmanager -def blob_remote_table(*, server_version=Version("0.5.0"), location=None): +def blob_remote_table( + *, + server_version=Version("0.5.0"), + location=None, + version_header="1", + framing="file", + requests=None, + state=None, + empty=False, + schema_version=None, + search_scores=False, + snapshot_supported=True, + identity_header="v1:" + "a" * 64, + verify_identity=True, +): + if state is None: + state = {"version": 1} + def handler(request): if 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.send_header("phalanx-version", str(server_version)) request.end_headers() response = dict(BLOB_DESCRIBE_RESPONSE) + response["version"] = body.get("version") or state["version"] if location is not None: response["location"] = str(location) request.wfile.write(json.dumps(response).encode()) @@ -5502,9 +5522,22 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): elif request.path == "/v1/table/test/query/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) + if requests is not None: + requests.append(("query", body)) columns = body.get("columns") - assert columns in (None, ["id", "image"], ["id"], ["image"]) - if columns == ["id"]: + assert columns in ( + None, + ["id", "image"], + ["id"], + ["image"], + {"payload": "image"}, + ) + if isinstance(columns, dict): + response_table = blob_query_response_table().select(["image", "_rowid"]) + response_table = response_table.rename_columns(["payload", "_rowid"]) + if not body.get("with_row_id", False): + response_table = response_table.drop(["_rowid"]) + elif columns == ["id"]: response_table = blob_query_response_table().select(["id"]) else: if columns == ["image"]: @@ -5521,25 +5554,86 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): response_table = blob_query_response_table() if not body.get("with_row_id", False): response_table = response_table.drop(["_rowid"]) + if search_scores and not body.get("filter", "").startswith("_rowid IN"): + if body.get("vector"): + response_table = response_table.append_column( + "_distance", pa.array([0.1, 0.2, 0.3], type=pa.float32()) + ) + elif body.get("full_text_query"): + response_table = response_table.append_column( + "_score", pa.array([3.0, 2.0, 1.0], type=pa.float32()) + ) + if empty: + response_table = response_table.slice(0, 0) + if schema_version is not None: + response_table = response_table.replace_schema_metadata( + { + b"lancedb:query_version": schema_version.encode(), + b"lancedb:query_snapshot": ("v1:" + "f" * 64).encode(), + } + ) request.send_response(200) - request.send_header("Content-Type", "application/vnd.apache.arrow.file") - request.send_header("x-lancedb-version", "1") + request.send_header( + "Content-Type", f"application/vnd.apache.arrow.{framing}" + ) + header = ( + version_header(body) if callable(version_header) else version_header + ) + if header is not None: + request.send_header("x-lancedb-version", header) + if snapshot_supported: + request.send_header("x-lancedb-query-version", header) + identity = ( + identity_header(body) + if callable(identity_header) + else identity_header + ) + if identity is not None: + request.send_header("x-lancedb-query-snapshot", identity) request.end_headers() - with pa.ipc.new_file(request.wfile, response_table.schema) as writer: - writer.write_table(response_table) + writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream + with writer_factory(request.wfile, response_table.schema) as writer: + writer.write_table(response_table, max_chunksize=1) elif request.path == "/v1/table/test/fetch_blobs/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) assert body["column"] == "image" - assert body["row_ids"] == [10, 20, 30] + if requests is not None: + requests.append(("fetch_blobs", body)) + payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""} + if state["version"] > 1 and body.get("version") != 1: + payloads = {row: b"new-version" for row in payloads} response_table = pa.table( - {"image": pa.array([b"alpha", None, b"gamma"], type=pa.large_binary())} + { + "image": pa.array( + [payloads[row] for row in body["row_ids"]], + type=pa.large_binary(), + ) + } ) request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + if verify_identity and request.headers.get("x-lancedb-query-snapshot"): + request.send_header( + "x-lancedb-query-snapshot", + request.headers["x-lancedb-query-snapshot"], + ) request.end_headers() with pa.ipc.new_stream(request.wfile, response_table.schema) as writer: writer.write_table(response_table) + elif request.path == "/v1/table/test/insert/": + if request.headers.get("Transfer-Encoding") == "chunked": + while size := int(request.rfile.readline().split(b";")[0], 16): + request.rfile.read(size) + assert request.rfile.read(2) == b"\r\n" + assert request.rfile.read(2) == b"\r\n" + else: + request.rfile.read(int(request.headers.get("Content-Length", 0))) + state["version"] += 1 + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps({"version": state["version"]}).encode()) else: request.send_response(404) request.end_headers() @@ -5548,6 +5642,222 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None): yield db.open_table("test") +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +@pytest.mark.parametrize("method", ["to_arrow", "to_list", "to_pandas", "to_batches"]) +async def test_remote_blob_bytes_conversion(use_async, framing, method): + if method == "to_pandas": + pytest.importorskip("pandas") + requests = [] + with blob_remote_table(framing=framing, requests=requests) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + query = query.select(["id", "image"]) + if method == "to_batches": + kwargs = {"max_batch_length" if use_async else "batch_size": 1} + reader = query.to_batches(blob_mode="bytes", **kwargs) + if use_async: + reader = await reader + batches = [batch async for batch in reader] + else: + batches = list(reader) + assert all(batch.num_rows == 1 for batch in batches) + result = pa.Table.from_batches(batches, schema=reader.schema).to_pylist() + else: + result = getattr(query, method)(blob_mode="bytes") + if use_async: + result = await result + if method == "to_arrow": + assert result.schema.field("image").type == pa.large_binary() + result = result.to_pylist() + elif method == "to_pandas": + result = result.to_dict("records") + assert result == [ + {"id": 1, "image": b"alpha"}, + {"id": 2, "image": None}, + {"id": 3, "image": b"gamma"}, + ] + fetches = [body for path, body in requests if path == "fetch_blobs"] + assert fetches + assert all(body["version"] == 1 for body in fetches) + assert [row for body in fetches for row in body["row_ids"]] == [10, 20, 30] + descriptor_queries = [ + body + for path, body in requests + if path == "query" and body.get("filter", "").startswith("_rowid IN") + ] + assert all(body["version"] == 1 for body in descriptor_queries) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_keeps_query_snapshot_during_writes(use_async, framing): + requests = [] + state = {"version": 1} + with blob_remote_table( + framing=framing, requests=requests, state=state + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + kwargs = {"max_batch_length" if use_async else "batch_size": 1} + reader = query.select(["id", "image"]).to_batches(blob_mode="bytes", **kwargs) + if use_async: + reader = await reader + # The query has selected v1; commit v2 before consuming any payloads. + write = table.add([{"id": 4, "image": b"new-version"}]) + if use_async: + await write + version = await table.version() if use_async else table.version + assert version == 2 + if use_async: + rows = [row async for batch in reader for row in batch.to_pylist()] + else: + rows = [row for batch in reader for row in batch.to_pylist()] + assert [row["image"] for row in rows] == [b"alpha", None, b"gamma"] + fetches = [body for path, body in requests if path == "fetch_blobs"] + assert all(body["version"] == 1 for body in fetches) + # Snapshot fetches must not check out the caller's live handle. + version = await table.version() if use_async else table.version + assert version == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("version_header", [None, "invalid", "0", "-1", str(2**64)]) +async def test_remote_blob_bytes_invalid_snapshot(use_async, version_header): + requests = [] + with blob_remote_table( + version_header=version_header, requests=requests, schema_version="1" + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_empty_results(use_async, framing): + requests = [] + with blob_remote_table( + empty=True, framing=framing, requests=requests + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + result = query.to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result.num_rows == 0 + assert result.schema.field("image").type == pa.large_binary() + assert result.column_names == ["id", "image"] + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("kind", ["vector", "fts", "hybrid"]) +@pytest.mark.parametrize("rerank", [False, True]) +async def test_remote_blob_bytes_search_queries(use_async, kind, rerank): + with blob_remote_table(search_scores=True) as remote_table: + if use_async: + query = remote_table._table.query() + if kind in ("vector", "hybrid"): + query = query.nearest_to([1.0, 2.0]) + if kind in ("fts", "hybrid"): + query = query.nearest_to_text("hello") + elif kind == "vector": + query = remote_table.search([1.0, 2.0], vector_column_name="vector") + elif kind == "fts": + query = remote_table.search("hello", query_type="fts") + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + if rerank: + from lancedb.rerankers import RRFReranker + + class StripMetadataReranker(RRFReranker): + def rerank_vector(self, query, vector_results): + return vector_results.append_column( + "_relevance_score", pa.array([3.0, 2.0, 1.0]) + ).replace_schema_metadata(None) + + def rerank_fts(self, query, fts_results): + return self.rerank_vector(query, fts_results) + + def rerank_hybrid(self, query, vector_results, fts_results): + return ( + super() + .rerank_hybrid(query, vector_results, fts_results) + .replace_schema_metadata(None) + ) + + kwargs = {"query_string": "hello"} if kind == "vector" else {} + query = query.rerank(StripMetadataReranker(), **kwargs) + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result["image"].to_pylist() == [b"alpha", None, b"gamma"] + assert "_rowid" not in result.column_names + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_hybrid_rejects_different_snapshots(use_async): + def header(body): + return "2" if body.get("full_text_query") else "1" + + requests = [] + with blob_remote_table( + search_scores=True, version_header=header, requests=requests + ) as remote_table: + if use_async: + query = ( + remote_table._table.query() + .nearest_to([1.0, 2.0]) + .nearest_to_text("hello") + ) + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + with pytest.raises( + NotImplementedError, match="inconsistent x-lancedb-query-version" + ): + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("with_row_id", [False, True]) +async def test_remote_blob_bytes_alias_and_explicit_row_ids(use_async, with_row_id): + with blob_remote_table() as remote_table: + query = remote_table._table.query() if use_async else remote_table.search() + query = query.select({"payload": "image"}) + if with_row_id: + query = query.with_row_id() if use_async else query.with_row_id(True) + result = query.to_arrow(blob_mode="bytes") + if use_async: + result = await result + assert result["payload"].to_pylist() == [b"alpha", None, b"gamma"] + assert ("_rowid" in result.column_names) == with_row_id + if with_row_id: + assert result["_rowid"].to_pylist() == [10, 20, 30] + + def test_remote_blob_columns_and_fetch(): with blob_remote_table() as table: assert table.blob_columns() == ["image"] @@ -5569,7 +5879,7 @@ def test_sync_remote_blob_pandas_avoids_storage_access( raise AssertionError("remote storage must not be opened") monkeypatch.setattr(lance, "dataset", fail_dataset) - with blob_remote_table(location=location) as table: + with blob_remote_table(location=location, version_header=None) as table: monkeypatch.setattr(table, "to_lance", fail_dataset) query = table.search().select(["id", "image"]) if blob_mode == "descriptions": @@ -5582,8 +5892,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access( NotImplementedError, match="stable table snapshot" ) as exc: query.to_pandas(blob_mode=blob_mode) - assert "fetch_blobs(column, row_ids)" in str(exc.value) - assert "with_row_id(True)" in str(exc.value) + if blob_mode == "bytes": + assert "x-lancedb-query-version" in str(exc.value) + else: + assert "fetch_blobs(column, row_ids)" in str(exc.value) + assert "with_row_id(True)" in str(exc.value) @pytest.mark.asyncio @@ -5667,7 +5980,7 @@ async def test_async_remote_blob_descriptions_to_pandas_uses_server(monkeypatch) @pytest.mark.asyncio @pytest.mark.parametrize("blob_mode", ["bytes", "lazy"]) async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode): - with blob_remote_table() as remote_table: + with blob_remote_table(version_header=None) as remote_table: table = remote_table._table async def fail_uri(): @@ -5692,8 +6005,8 @@ async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob @pytest.mark.parametrize("method", ["to_arrow", "to_list"]) -def test_remote_search_bytes_refused_before_query(monkeypatch, method): - with blob_remote_table() as table: +def test_remote_search_bytes_requires_response_version(method): + with blob_remote_table(version_header=None) as table: query = table.search().select(["id", "image"]) descriptions = getattr(query, method)(blob_mode="descriptions") images = ( @@ -5703,19 +6016,15 @@ def test_remote_search_bytes_refused_before_query(monkeypatch, method): ) assert "_lance_row_id" not in images[0] - def fail_query(*args, **kwargs): - raise AssertionError("bytes must be refused before the query runs") - - monkeypatch.setattr(table, "_execute_query", fail_query) - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): getattr(query, method)(blob_mode="bytes") with pytest.raises(ValueError, match="blob_mode must be one of"): table.to_pandas(blob_mode="handles") @pytest.mark.asyncio -async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch): - with blob_remote_table() as remote_table: +async def test_async_remote_to_arrow_bytes_requires_response_version(monkeypatch): + with blob_remote_table(version_header=None) as remote_table: table = remote_table._table async def fail_fetch(*args, **kwargs): @@ -5723,8 +6032,7 @@ async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch): monkeypatch.setattr(table, "fetch_blobs", fail_fetch) query = table.query().select(["id", "image"]) - monkeypatch.setattr(query, "to_batches", fail_fetch) - with pytest.raises(NotImplementedError, match="stable table snapshot"): + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): await query.to_arrow(blob_mode="bytes") with pytest.raises(NotImplementedError, match="stable table snapshot"): await table.to_arrow(blob_mode="bytes") @@ -5821,7 +6129,7 @@ def test_remote_blob_query_to_pandas(): @pytest.mark.parametrize("blob_mode", ["default", "lazy", "bytes"]) def test_remote_blob_query_to_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode): - with blob_remote_table() as table: + with blob_remote_table(version_header=None) as table: def fail_fetch(*args, **kwargs): raise AssertionError("blob fetch must not use an unpinned remote table") @@ -6884,3 +7192,102 @@ def test_remote_optimize_rejects_explicit_pruning_before_submitting(): table.optimize(delete_unverified=True) assert server.tickets == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("framing", ["file", "stream"]) +async def test_remote_blob_bytes_rejects_legacy_watermark(use_async, framing): + requests = [] + with blob_remote_table( + framing=framing, + snapshot_supported=False, + version_header="1", + schema_version="1", + requests=requests, + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + descriptors = query.to_arrow(blob_mode="descriptions") + if use_async: + descriptors = await descriptors + assert descriptors.num_rows == 3 + assert pa.types.is_struct(descriptors.schema.field("image").type) + query = table.query() if use_async else table.search() + with pytest.raises(NotImplementedError, match="x-lancedb-query-version"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("identity_header", [None, "", "v2:" + "a" * 64, "v1:broken"]) +async def test_remote_blob_bytes_requires_trustworthy_identity( + use_async, identity_header +): + requests = [] + with blob_remote_table( + identity_header=identity_header, schema_version="1", requests=requests + ) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + # Ordinary descriptors still work, even with forged Arrow schema metadata. + result = query.to_arrow(blob_mode="descriptions") + if use_async: + result = await result + assert result.num_rows == 3 + with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_rejects_unverified_serving_node(use_async): + with blob_remote_table(verify_identity=False) as remote_table: + table = remote_table._table if use_async else remote_table + query = table.query() if use_async else table.search() + with pytest.raises( + NotImplementedError, match="did not verify the query snapshot identity" + ): + result = query.to_arrow(blob_mode="bytes") + if use_async: + await result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnations( + use_async, +): + requests = [] + + def identity(body): + return "v1:" + ("b" if body.get("full_text_query") else "a") * 64 + + with blob_remote_table( + search_scores=True, identity_header=identity, requests=requests + ) as remote_table: + if use_async: + query = ( + remote_table._table.query() + .nearest_to([1.0, 2.0]) + .nearest_to_text("hello") + ) + else: + query = ( + remote_table.search(query_type="hybrid", vector_column_name="vector") + .vector([1.0, 2.0]) + .text("hello") + ) + with pytest.raises( + NotImplementedError, match="inconsistent x-lancedb-query-version" + ): + result = query.select(["id", "image"]).to_arrow(blob_mode="bytes") + if use_async: + await result + assert not any(path == "fetch_blobs" for path, _ in requests) diff --git a/python/src/table.rs b/python/src/table.rs index e76bae00a..31cf8d25c 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1978,14 +1978,28 @@ impl Table { } /// Read blob bytes for `row_ids` from blob v2 column `column`. - #[pyo3(signature = (column, row_ids))] + #[pyo3(signature = (column, row_ids, *, version=None, snapshot_identity=None))] pub fn fetch_blobs( self_: PyRef<'_, Self>, column: String, row_ids: Vec, + version: Option, + snapshot_identity: Option, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { + let inner = match (version, snapshot_identity) { + (None, None) => inner, + (Some(version), Some(identity)) => inner + .query_snapshot_with_identity(version, &identity) + .await + .infer_error()?, + _ => { + return Err(PyValueError::new_err( + "deferred blob reads require both query version and snapshot identity", + )); + } + }; let blobs: LargeBinaryArray = inner .fetch_blobs(column.as_str(), &row_ids) .await diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index cc495a83f..d560a4802 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -95,6 +95,34 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp"); const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version"); const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version"); +const QUERY_SNAPSHOT_HEADER: &str = "x-lancedb-query-snapshot"; + +fn valid_query_snapshot_identity(value: &str) -> bool { + value.strip_prefix("v1:").is_some_and(|digest| { + digest.len() == 64 + && digest + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} + +fn check_query_snapshot_response( + expected: Option<&str>, + response: &reqwest::Response, +) -> Result<()> { + if let Some(expected) = expected + && response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + != Some(expected) + { + return Err(Error::NotSupported { message: "Blob response did not verify the query snapshot identity; upgrade every serving node".into() }); + } + Ok(()) +} + +const QUERY_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-query-version"); /// Asks for stream framing, which is decoded as it arrives. Servers that do not /// stream query results ignore this and answer with file framing. const QUERY_ACCEPT: &str = @@ -613,6 +641,7 @@ pub struct RemoteTable { /// Stamped onto every branch-accepting request so reads and writes resolve /// on the branch's own version chain rather than main's. branch: Option, + expected_query_snapshot: Option, } impl std::fmt::Debug for RemoteTable { @@ -855,6 +884,7 @@ impl RemoteTable { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -891,6 +921,7 @@ impl RemoteTable { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, + expected_query_snapshot: None, } } @@ -1170,20 +1201,37 @@ impl RemoteTable { .and_then(|value| value.to_str().ok()) .map(str::to_owned); let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?; + let table_version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); - match framing { + // Legacy version headers are freshness watermarks, not proof that the + // query and a later Blob read use the same immutable dataset. + let query_version = response + .headers() + .get(&QUERY_VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version > 0); + + let query_identity = response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .map(str::to_owned); + + let stream = match framing { ArrowIpcFraming::Stream => { - let table_version = response - .headers() - .get(&VERSION_HEADER) - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.parse().ok()); ipc_stream::read_ipc_stream( response.bytes_stream(), request_id.to_string(), table_version, ) - .await + .await? } ArrowIpcFraming::File => { // File framing keeps its footer at the end, so the whole body is @@ -1192,9 +1240,21 @@ impl RemoteTable { let reader = FileReader::try_new(Cursor::new(body), None)?; let schema = reader.schema(); let stream = futures::stream::iter(reader).map_err(DataFusionError::from); - Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) + Box::pin(RecordBatchStreamAdapter::new(schema, stream)) as SendableRecordBatchStream } + }; + // Bind subsequent blob reads to the response's snapshot, never to a + // version sampled from the live table before or after the query. + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_version"); + metadata.remove("lancedb:query_snapshot"); + if let Some(identity) = query_identity { + metadata.insert("lancedb:query_snapshot".into(), identity); } + if let Some(version) = query_version { + metadata.insert("lancedb:query_version".into(), version.to_string()); + } + Ok(with_stream_metadata(stream, metadata)) } fn apply_query_params( @@ -1620,9 +1680,37 @@ impl RemoteTable { streams.await? }; + if let Some(first) = streams.first() { + let schema = first.schema(); + if streams.iter().skip(1).any(|stream| { + stream.schema().metadata().get("lancedb:query_version") + != schema.metadata().get("lancedb:query_version") + }) { + return Err(Error::Runtime { + message: "Remote query responses refer to different table snapshots; retry the query against a fixed version".into(), + }); + } + } + + let identities_agree = streams.first().is_none_or(|first| { + streams.iter().skip(1).all(|stream| { + stream.schema().metadata().get("lancedb:query_snapshot") + == first.schema().metadata().get("lancedb:query_snapshot") + }) + }); Ok(streams .into_iter() .map(|stream| { + // Ordinary descriptor queries remain usable during an upgrade. + // Deferred bytes require every leg's identity, so never preserve + // the first leg's capability when another leg lacks or differs. + let stream = if identities_agree { + stream + } else { + let mut metadata = stream.schema().metadata().clone(); + metadata.remove("lancedb:query_snapshot"); + with_stream_metadata(stream, metadata) + }; let stream = restore_projection_order(stream, &query.base().select); match deadline { Some((deadline, timeout)) => { @@ -1673,6 +1761,26 @@ impl RemoteTable { } } +fn with_stream_metadata( + stream: SendableRecordBatchStream, + metadata: HashMap, +) -> SendableRecordBatchStream { + let schema = Arc::new( + stream + .schema() + .as_ref() + .clone() + .with_metadata(metadata.clone()), + ); + let batches = stream.map(move |batch| { + batch.map(|mut batch| { + batch.schema_metadata_mut().clone_from(&metadata); + batch + }) + }); + Box::pin(RecordBatchStreamAdapter::new(schema, batches)) +} + fn restore_projection_order( stream: Pin>, select: &Select, @@ -1921,6 +2029,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1948,6 +2057,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } @@ -1984,6 +2094,7 @@ mod test_utils { wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, + expected_query_snapshot: None, } } } @@ -2570,6 +2681,23 @@ impl BaseTable for RemoteTable { } } } + async fn query_snapshot_with_identity( + &self, + version: u64, + identity: &str, + ) -> Result> { + if version == 0 || !valid_query_snapshot_identity(identity) { + return Err(Error::InvalidInput { + message: "invalid or unsupported query snapshot identity".into(), + }); + } + let mut snapshot = self.with_branch(self.branch.clone()); + *snapshot.version.write().await = Some(version); + snapshot.reset_freshness(None, true); + snapshot.expected_query_snapshot = Some(identity.to_owned()); + Ok(Arc::new(snapshot)) + } + async fn query_snapshot(&self) -> Result> { let description = self.describe().await?; let TableDescription { @@ -6704,8 +6832,15 @@ mod tests { assert_eq!(request_sizes.lock().unwrap().as_slice(), &[1024, 1]); } + #[rstest::rstest] + #[case(false)] + #[case(true)] #[tokio::test] - async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range() { + async fn test_fetch_blobs_splits_byte_limited_requests_and_reads_large_blob_by_range( + #[case] guarded: bool, + ) { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // Simulate a lower byte cap so this test exercises the same 400 response // without allocating 64 MiB of blob data. let requests = Arc::new(std::sync::Mutex::new(Vec::new())); @@ -6714,8 +6849,15 @@ mod tests { "my_table", semver::Version::new(0, 5, 0), move |request| { + if guarded { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + } let path = request.url().path(); if path == "/v1/table/my_table/describe/" { + assert!( + !guarded, + "a later describe cannot establish the producing identity" + ); return http::Response::builder() .status(200) .body(br#"{"version":42,"schema":{"fields":[]}}"#.to_vec()) @@ -6766,6 +6908,7 @@ mod tests { return http::Response::builder() .status(200) .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .body(write_ipc_stream_uncompressed(&batch)) .unwrap(); } @@ -6781,12 +6924,14 @@ mod tests { match range { "bytes=0-0" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-0/10") .header(VERSION_HEADER, "42") .body(b"0".to_vec()) .unwrap(), "bytes=0-9" => http::Response::builder() .status(206) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) .header(reqwest::header::CONTENT_RANGE, "bytes 0-9/10") .body(b"0123456789".to_vec()) .unwrap(), @@ -6795,6 +6940,14 @@ mod tests { }, ); + let table = if guarded { + table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap() + } else { + table + }; let blobs = table .fetch_blobs("image", &[10, 20, 30, 40, 20]) .await diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 345b731c5..a0051c955 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -33,8 +33,8 @@ use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; use crate::table::{AnyQuery, BaseTable}; use super::{ - FreshnessHeaders, FreshnessState, ReadSnapshot, RemoteTable, VERSION_HEADER, - freshness_headers_snapshot, + FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, + VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit @@ -93,6 +93,7 @@ struct TableBlobRangeRequester { version: Option, branch: Option, source_uri: Option, + expected_query_snapshot: Option, source_commit_micros: Option, row_is_address: bool, freshness: Arc>, @@ -125,6 +126,9 @@ impl BlobRangeRequester for TableBlobRangeRequester { .apply(self.client.get(&self.path)) .header(header::RANGE, range_header) }; + if let Some(identity) = &self.expected_query_snapshot { + request = request.header(QUERY_SNAPSHOT_HEADER, identity); + } if let Some(version) = version.or(self.version) { request = request.query(&[("version", version)]); } @@ -140,6 +144,10 @@ impl BlobRangeRequester for TableBlobRangeRequester { request = request.query(&[("source_commit_micros", timestamp)]); } let (request_id, response) = self.client.send_with_retry(request, None, true).await?; + if response.status().is_success() || response.status() == StatusCode::RANGE_NOT_SATISFIABLE + { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } // Preserve 416 size-probe responses so the caller can detect empty blobs. if response.status() == StatusCode::RANGE_NOT_SATISFIABLE && matches!(mode, RangeRequestMode::SizeProbe) @@ -531,7 +539,11 @@ impl RemoteTable { // A dotted path needs client-side validation because the server may // report an internal type mismatch when the path crosses a list. Use // an already cached schema for top-level list fields as well. - if column.contains('.') || self.schema_cache.try_get().is_some() { + // Guarded readers must validate the producing identity on the server + // before consulting any schema resolved from a later logical binding. + if self.expected_query_snapshot.is_none() + && (column.contains('.') || self.schema_cache.try_get().is_some()) + { let schema = self.schema().await?; crate::blob::reject_list_blob_column(schema.as_ref(), column)?; } @@ -539,6 +551,9 @@ impl RemoteTable { } async fn explain_list_blob_bad_request(&self, column: &str, error: Error) -> Error { + if self.expected_query_snapshot.is_some() { + return error; + } let is_bad_request = match &error { Error::Http { status_code: Some(code), @@ -648,9 +663,17 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) .json(&body); + let request = if let Some(identity) = &self.expected_query_snapshot { + request.header(QUERY_SNAPSHOT_HEADER, identity) + } else { + request + }; let (request_id, response) = self .send_with_freshness(request, true, read_snapshot.freshness) .await?; + if response.status().is_success() { + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + } let mut stream = match self.read_arrow_response(&request_id, response).await { Ok(stream) => stream, Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), @@ -1023,6 +1046,7 @@ impl RemoteTable { version: read_snapshot.version, branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), source_uri: source.map(|source| source.uri.clone()), + expected_query_snapshot: self.expected_query_snapshot.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)), diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 18a5b7ddf..db68ab290 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -832,6 +832,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "blob_columns is not supported on this table type".into(), }) } + /// Bind a remote payload reader to an identity from its producing query. + async fn query_snapshot_with_identity( + &self, + _version: u64, + _identity: &str, + ) -> Result> { + Err(Error::NotSupported { + message: "query snapshot identities are not supported on this table type".into(), + }) + } /// Materialize blob bytes for the given row ids. See [`Table::fetch_blobs`]. async fn fetch_blobs(&self, _column: &str, _row_ids: &[u64]) -> Result { Err(Error::NotSupported { @@ -1352,6 +1362,19 @@ impl Table { }) } + /// Create an independent remote handle constrained by a query response. + #[doc(hidden)] + pub async fn query_snapshot_with_identity(&self, version: u64, identity: &str) -> Result { + Ok(Self { + inner: self + .inner + .query_snapshot_with_identity(version, identity) + .await?, + database: self.database.clone(), + embedding_registry: self.embedding_registry.clone(), + }) + } + /// Count the number of rows in this dataset. /// /// # Arguments From 9755c57d4111425b81f6fe4494ed58a3bf5cc416 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 03:20:20 +0800 Subject: [PATCH 094/203] fix: prune Function outcomes for replaced fragments (#5005) An input-preserving merge can fail freshness preservation after a successful data write: the replaced fragment loses its signature, but its known/failed-row records remain and fail sidecar validation. This affects tables with persisted Function outcome metadata. Prune both outcome maps with the same live-fragment set used for signatures and row state. Outcomes on untouched fragments remain intact, and inserted rows remain pending fill. The regression performs a real mixed update/insert and reopens the resulting snapshot to check both output columns. Native validation on Linux: the exact regression fails before the fix with `failure evidence names a fragment without a signature`. At `20b10d80408cb455d9e5827f5d7d36a117622dea`, all 24 discovered `table::freshness::tests::function_write_` cases pass, including the new real merge regression. Test lists, counts and logs were retained and SHA-256 verified. [Current-head CI passed both workspace Clippy configurations](https://github.com/lancedb/lancedb/actions/runs/43274052568/job/131377627811). A separate package-only, default-feature Clippy command reported dead-code errors in seven files unchanged from the base; that local failure is retained rather than represented as a pass. Other hosted gates are pending. This does not claim downstream Sophon integration or deployed acceptance. --- rust/lancedb/src/table/freshness.rs | 97 +++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 477020fc3..645653a46 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -1879,6 +1879,8 @@ pub async fn preserve_function_freshness( pending_fill.retain(|id, _| live.contains(id)); state.signatures.retain(|id, _| live.contains(id)); state.row_state.retain(|id, _| live.contains(id)); + state.failure_coverage.retain(|id, _| live.contains(id)); + state.failed_rows.retain(|id, _| live.contains(id)); state.basis.clear(); let reference = write_sidecar(dataset, &state.normalize()?).await?; let fill_reference = if pending_fill.is_empty() { @@ -3029,6 +3031,101 @@ mod tests { } } + #[tokio::test] + async fn function_write_prunes_outcomes_for_replaced_fragments() { + let table = fresh_function_table().await; + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + let failures = FailureEvidence { + known_rows: BTreeMap::from([ + (0, RoaringBitmap::from_iter([0, 1])), + (1, RoaringBitmap::from_iter([0, 1])), + ]), + failed_rows: BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]), + }; + for column in ["search_text", "search_token_count"] { + record_freshness_with_failures( + &mut dataset, + None, + column, + "fb_01K3TEXT", + &inputs, + signatures.clone(), + &failures, + ) + .await + .unwrap(); + } + + // Replace all of fragment 0, insert one uncomputed row, and leave + // fragment 1 (including its retained failure evidence) untouched. + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "e"]), + ("spare", Int32, [1, 1, 1]) + ) + .unwrap(); + let mut merge = + MergeInsertBuilder::try_new(Arc::new(dataset), vec!["title".into()]).unwrap(); + merge.when_matched(WhenMatched::UpdateAll); + merge.when_not_matched(WhenNotMatched::InsertAll); + let (merged, stats) = merge + .try_build() + .unwrap() + .execute_reader(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let mut dataset = merged.as_ref().clone(); + assert!(!dataset.get_fragments().iter().any(|f| f.id() == 0)); + assert!(dataset.get_fragments().iter().any(|f| f.id() == 1)); + preserve_function_freshness( + &mut dataset, + FunctionWrite::Merge { + source_schema: &source.schema(), + on: &["title".into()], + num_inserted_rows: stats.num_inserted_rows, + }, + ) + .await + .unwrap(); + + let reopened = dataset + .checkout_version(dataset.version().version) + .await + .unwrap(); + for column in ["search_text", "search_token_count"] { + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&reopened, column, "fb_01K3TEXT", &inputs) + .await + .unwrap() + else { + panic!("the preserved sidecar should retain failure evidence"); + }; + assert_eq!( + failures.known_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([0, 1]))]) + ); + assert_eq!( + failures.failed_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]) + ); + assert_eq!(staleness.pending_fill.len(), 1); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] From 1806dc232395d2a446a2eef17886194b5dd27051 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 12 Nov 2026 11:34:14 -0800 Subject: [PATCH 095/203] ci(java): publish beta releases to Fury instead of Maven Central (#5011) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Java publishing has failed since `v0.42.0-beta.10` because the `lancedb` Sonatype org hit Maven Central's monthly release-count limit: ```text Publishing blocked: your organization has reached its monthly release count limit. Grace period ended 2026-11-08. Usage resets 2026-12-01. ``` This sends beta tags to `https://maven.fury.io/lancedb/` instead, matching how Python publishes betas to `pypi.fury.io/lancedb`. Stable releases still go to Maven Central. ```text tag contains "beta" -> setup-java server "fury" -> mvn deploy -P deploy-to-fury otherwise -> setup-java server "ossrh" -> mvn deploy -P deploy-to-ossrh ``` - `java/pom.xml`: new `deploy-to-fury` profile that points `distributionManagement` at Fury. - `java/README.md`: explains how to add the Fury and `maven.lance.org` repositories to use a beta. Requires a `FURY_TOKEN` secret with push access to the `lancedb` Fury account. The token is passed as the Maven username with a placeholder password. That follows Gemfury's convention but hasn't been tested against Fury yet. ## Evidence Running the beta path locally (`deploy -pl lancedb-core -am -P deploy-to-fury`) against a file repository deployed `lancedb-parent` (POM) and `lancedb-core` (JAR, POM, sources, javadoc). `help:effective-pom -P deploy-to-fury` resolves the release repository to `https://maven.fury.io/lancedb/`. ## Merge Risk **Door:** Two-way. This only changes where future betas are published; reverting the workflow restores Central publishing. **Blast Radius:** `release-ci`. Beta consumers need the extra repository; stable consumers are unaffected. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .github/workflows/java-publish.yml | 20 +++++++++++++----- java/README.md | 34 ++++++++++++++++++++++++++++++ java/pom.xml | 9 ++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/.github/workflows/java-publish.yml b/.github/workflows/java-publish.yml index 094aa552a..35d052de9 100644 --- a/.github/workflows/java-publish.yml +++ b/.github/workflows/java-publish.yml @@ -39,9 +39,11 @@ jobs: distribution: temurin java-version: 8 cache: "maven" - server-id: ossrh - server-username: SONATYPE_USER - server-password: SONATYPE_TOKEN + # Betas go to Fury and stable releases to Maven Central, which limits + # how many releases an organization may publish each month. + server-id: ${{ contains(github.ref, 'beta') && 'fury' || 'ossrh' }} + server-username: ${{ contains(github.ref, 'beta') && 'FURY_TOKEN' || 'SONATYPE_USER' }} + server-password: ${{ contains(github.ref, 'beta') && 'FURY_PASSWORD' || 'SONATYPE_TOKEN' }} gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} gpg-passphrase: MAVEN_GPG_PASSPHRASE - name: Set git config @@ -52,8 +54,16 @@ jobs: if: github.event_name == 'pull_request' run: | ./mvnw --batch-mode -DskipTests package -pl lancedb-core -am - - name: Publish - if: startsWith(github.ref, 'refs/tags/v') + - name: Publish to Fury + if: startsWith(github.ref, 'refs/tags/v') && contains(github.ref, 'beta') + run: | + ./mvnw --batch-mode -DskipTests deploy -pl lancedb-core -am -P deploy-to-fury + env: + FURY_TOKEN: ${{ secrets.FURY_TOKEN }} + # Fury authenticates with the token as the username; the password is ignored. + FURY_PASSWORD: NOPASS + - name: Publish to Maven Central + if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta') run: | echo "use-agent" >> ~/.gnupg/gpg.conf echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf diff --git a/java/README.md b/java/README.md index fd163b9f1..85e7e85ba 100644 --- a/java/README.md +++ b/java/README.md @@ -1,5 +1,39 @@ # LanceDB Java Enterprise Client +## Installation + +Stable releases of `com.lancedb:lancedb-core` are published to Maven Central. + +Beta releases are published to `https://maven.fury.io/lancedb/` instead. They +depend on Lance beta releases, which are published to `https://maven.lance.org`. +To use a beta, add both repositories alongside Maven Central: + +```xml + + + lancedb + https://maven.fury.io/lancedb/ + + + lance + https://maven.lance.org + + +``` + +For Gradle: + +```kotlin +repositories { + mavenCentral() + maven { url = uri("https://maven.fury.io/lancedb/") } + maven { url = uri("https://maven.lance.org") } +} +``` + +Use an explicit version, including the full `-beta.N` suffix. Beta versions are +Maven releases, not `SNAPSHOT` versions. + ## Configuration and Initialization ### LanceDB Cloud (legacy) diff --git a/java/pom.xml b/java/pom.xml index df709fb4f..fc89ebe4c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -318,6 +318,15 @@ + + deploy-to-fury + + + fury + https://maven.fury.io/lancedb/ + + + deploy-to-ossrh From 6d24446a3043fcb22a73c2c9aed21b62a5648938 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 04:03:04 +0800 Subject: [PATCH 096/203] feat: add negotiated batched blob range reads across SDKs (#4994) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Existing Rust and Python blob range calls must keep working when only the SDK is upgraded. Add negotiated batched range reads across Rust, Python sync/async and TypeScript, preserving ordered NULLs, duplicates and branch/version reads with splitting and reassembly at 1,024 ranges or 64 MiB per request. Only a successful describe response advertising `x-lancedb-blob-ranges: 1` selects the batched endpoint. Missing or unknown capability values select the existing descriptor-query plus BlobFile Range GET route before the operation. Endpoint failures never switch protocols. HTTP 400 preserves the server message and request ID as Rust `InvalidInput` / Python `ValueError`; other errors retain their existing semantics. The operation binds both numeric version and immutable snapshot identity from its producing query or first range response. Every later partition and oversized-range piece sends that original identity and requires an equal response identity before decoding. Same-name table recreation therefore fails explicitly instead of returning mixed old/new payloads; no partial array is returned on later failure. Targets `main`. The read-buffering prerequisite #4979, safe-write prerequisite #4977 and deferred-query identity prerequisite #4973 are merged into main; #5000 also supplies the merged SQL timeout-test prerequisite. Server support is [Sophon #10219](https://github.com/lancedb/sophon/pull/10219), including #10211. Exact SDK `1497b508324662180086a4d1e0a6eb9e0b3970db` and server `f39712c2c150b220eb831e00f6663c9eef32dce5` passed a real local SDK → REST → PE experiment: one Rust harness test, 14 assertion groups, 38 REST range requests and 34 PE RPCs. All four sync/async × warm/cold table-recreation cases failed explicitly before the second descriptor lookup or PE dispatch, with no mixed payload or partial result. The other groups retained 1,025-range success, 70 MiB reassembly, branch/version reads, overwrite snapshot consistency, error behavior and TypeScript buffer ownership. Bindings were rebuilt and their loaded hashes verified. This is local interoperability evidence, not Cloud, mixed-fleet or deployed header-forwarding acceptance. The server dependency upgrade, External/cache/URI-policy acceptance and validated rollout remain required. Enforcing PE support must precede QN and SDK enablement; identity does not retain versions or freeze External objects. This PR does not claim deployed support or complete ENT-3100/GA acceptance. Published documentation retains the Early access badge and released Enterprise instructions, including explicit fetches for copying. The new Enterprise `blob_mode="bytes"` guidance, snapshot-bound copy example, future streaming restrictions and GA wording remain source-only MDX drafts until release. The correction distinguishing released Enterprise SQL bytes from SDK descriptors remains visible. Documentation validation checked comment boundaries, visible instructions, Python example syntax and whitespace; the site was not built. The main integration keeps these release gates unchanged. Main integration at `0491d9bdcc65ce5d52ea93e1083c89e951ea4f9d` normally merges main `9b13e8f72530c8b1950c09685f6920711154a539`, including its Lance beta.18 dependency. Focused current-source validation passed: 493 remote-table/query/Blob/IPC/write-progress Rust tests, 23 shared create/write-body tests, 59 native Blob integration tests and 7 public HTTP range tests. Rebuilt Python passed 468 selected tests (one optional PyAV test skipped), and rebuilt TypeScript passed 194 selected tests across four suites; lint/format, TypeScript compilation and API documentation generation passed. Shared tests include actual HTTP multipart failures, acknowledgment boundaries, dictionary compaction and native Blob compaction. The 598 unrelated Jest cases excluded by the focused shared-suite selector were not run. The retained 14-group joint REST/PE experiment used the earlier exact candidates stated above. Operation-identity/range/IPC code is unchanged, but dependencies and shared write interfaces changed with main; the new local checks validate the SDK combination and do not constitute a fresh final-head SDK/server joint, Cloud or rollout run. Early access and every remaining server/External/cache/policy/dependency/rollout condition remain in force. CI snapshot on this head (2026-11-12 18:30 UTC): `build-no-lock` failed in the standalone `ci/tests/test_build_no_lock.py` fixture at the retained-rlib assertion, before the actual SDK no-lock build. The fixture, helper and Rust workflow are byte-identical to main; the fixture does not load SDK source. The underlying CI/environment cause is not diagnosed here. Other jobs remained pending/running at the snapshot, so CI is not reported as passing. Failure: https://github.com/lancedb/lancedb/actions/runs/43280277756/job/131399418284. --- docs/src/js/classes/Table.md | 42 ++ docs/src/js/globals.md | 1 + docs/src/js/type-aliases/BlobRangeRequest.md | 39 ++ docs/web/management/table.mdx | 27 + nodejs/__test__/blob_ranges.test.ts | 589 ++++++++++++++++ nodejs/__test__/table.test.ts | 37 + nodejs/lancedb/blob.ts | 10 + nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 49 +- nodejs/src/blob.rs | 50 +- nodejs/src/table.rs | 29 +- python/python/lancedb/table.py | 12 +- python/python/tests/test_blob_ranges.py | 380 +++++++++++ python/python/tests/test_remote_db.py | 46 +- rust/lancedb/src/blob.rs | 2 +- rust/lancedb/src/remote/db.rs | 10 +- rust/lancedb/src/remote/table.rs | 28 + rust/lancedb/src/remote/table/blobs.rs | 400 ++++++++++- .../src/remote/table/blobs/aggregate.rs | 136 +++- rust/lancedb/src/table.rs | 21 +- rust/lancedb/tests/remote_blob_ranges.rs | 634 ++++++++++++++++++ 21 files changed, 2473 insertions(+), 70 deletions(-) create mode 100644 docs/src/js/type-aliases/BlobRangeRequest.md create mode 100644 nodejs/__test__/blob_ranges.test.ts create mode 100644 python/python/tests/test_blob_ranges.py create mode 100644 rust/lancedb/tests/remote_blob_ranges.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 431796843..3150d94ec 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -650,6 +650,48 @@ tables; no partial handles are returned. *** +### fetchBlobRanges() + +```ts +abstract fetchBlobRanges( + column, + requests, + options?): Promise<(null | Buffer)[]> +``` + +Materializes row-specific byte ranges at the table's current checkout. +Preserves request order, duplicates, and nulls. Zero length returns an empty +buffer for a non-null blob. Invalid ranges or missing rows reject the entire +call. See [Table.fetchBlobs](Table.md#fetchblobs) for row-ID validity across versions. + +Remote tables use the batched endpoint when the server advertises support, +splitting at 1024 ranges and 64 MiB, including individual larger ranges. +Older servers use descriptor queries and BlobFile range reads. Both protocols +use one exact branch and version. Errors from an advertised endpoint propagate +without switching protocols. All output bytes occupy memory. + +#### Parameters + +* **column**: `string` + +* **requests**: readonly [`BlobRangeRequest`](../type-aliases/BlobRangeRequest.md)[] + +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`Promise`<(`null` \| `Buffer`)[]> + +#### Example + +```ts +const bytes = await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1024n }, +]); +``` + +*** + ### fetchBlobs() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 19d7ceb97..beed7c8af 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -169,6 +169,7 @@ - [BlobMode](type-aliases/BlobMode.md) - [BlobOptions](type-aliases/BlobOptions.md) - [BlobRange](type-aliases/BlobRange.md) +- [BlobRangeRequest](type-aliases/BlobRangeRequest.md) - [BlobReadOptions](type-aliases/BlobReadOptions.md) - [BlobUri](type-aliases/BlobUri.md) - [Data](type-aliases/Data.md) diff --git a/docs/src/js/type-aliases/BlobRangeRequest.md b/docs/src/js/type-aliases/BlobRangeRequest.md new file mode 100644 index 000000000..daa231260 --- /dev/null +++ b/docs/src/js/type-aliases/BlobRangeRequest.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobRangeRequest + +# Type Alias: BlobRangeRequest + +```ts +type BlobRangeRequest: object; +``` + +One row-specific range for [Table.fetchBlobRanges](../classes/Table.md#fetchblobranges). + +## Type declaration + +### length + +```ts +length: bigint; +``` + +Number of bytes to read, as a uint64. Zero returns an empty non-null value. + +### offset + +```ts +offset: bigint; +``` + +Byte offset from the beginning of the logical blob, as a uint64. + +### rowId + +```ts +rowId: bigint | number; +``` + +A row ID from a query with row IDs enabled. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 031342fbc..bf6bf3edd 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -736,6 +736,10 @@ The other fetch methods load bytes directly: | 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` | +{/* Draft for the TypeScript cross-row Blob range release. Replace the row above: +| Byte slices across many rows in one call | `fetch_blob_ranges` | `fetchBlobRanges` | `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 @@ -759,6 +763,21 @@ The other fetch methods load bytes directly: +{/* Draft for the TypeScript cross-row Blob range release. + +Upcoming-release draft: TypeScript adds `fetchBlobRanges` for cross-row slices. +Until that SDK release is available, use `fetchBlobFiles` and `readRanges`. +Server-side batching requires a deployment with the validated range capability; +older servers continue using the descriptor and Range path selected before the +read. An error from the selected batched endpoint is returned without fallback. +A batched call keeps the native snapshot identity from its first range response +across every partition and requires each serving node to verify it. Missing identity +support or a replaced/deleted snapshot fails the whole call; upgrade all serving +nodes before selecting the batched endpoint with a new SDK. +Custom TypeScript `Table` subclasses must implement the new abstract method. + +*/} + 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 @@ -770,6 +789,14 @@ exclusive `end`, and Rust takes `start..end` ranges: + {/* Draft for the TypeScript cross-row Blob range release. + {`// Upcoming-release draft: slices from more than one row. +const slices = await blobTable.fetchBlobRanges("image", [ + { rowId: rowIds[0]!, offset: 0n, length: 6n }, + { rowId: rowIds[1]!, offset: 7n, length: 5n }, +]); +`}{"\n"} + */} {TsBlobApiRanges} diff --git a/nodejs/__test__/blob_ranges.test.ts b/nodejs/__test__/blob_ranges.test.ts new file mode 100644 index 000000000..7d2fab566 --- /dev/null +++ b/nodejs/__test__/blob_ranges.test.ts @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createHash } from "crypto"; +import { getEventListeners } from "events"; +import { createReadStream } from "fs"; +import * as http from "http"; +import { AddressInfo } from "net"; +import { + Table as ArrowTable, + Binary, + Field, + LargeBinary, + Struct, + Uint8, + Uint32, + Uint64, + Utf8, + tableToIPC, + vectorFromArray, +} from "apache-arrow"; +import { BlobRangeRequest, Connection, Table, connect } from "../lancedb"; + +jest.setTimeout(30000); + +const IDENTITY = `v1:${"a".repeat(64)}`; +const MIB = 1024 * 1024; +type Range = { + // biome-ignore lint/style/useNamingConvention: Matches the server JSON contract. + row_id: number; + offset: number; + length: number; +}; +type Request = { + column: string; + branch: string | null; + version: number | null; + ranges: Range[]; + identity?: string; +}; + +function payload(row: number, offset: number, length: number, version: number) { + const bytes = Buffer.alloc(length); + for (let i = 0; i < length; i++) { + bytes[i] = (row * 17 + ((offset + i) % 251) + version) % 251; + } + return bytes; +} + +async function withRangeServer( + run: (db: Connection, calls: Request[], paths: string[]) => Promise, + fault?: string | number, + capability: string | null = "1", + onStall?: () => void, +) { + let takes = 0; + const calls: Request[] = []; + const paths: string[] = []; + const server = http.createServer((req, res) => { + req.setTimeout(15000); + paths.push(req.url ?? ""); + if ( + req.url === "/v1/table/test/describe/" || + req.url === "/v1/table/test/branches/list/" + ) { + res.writeHead(200, { + "Content-Type": "application/json", + "phalanx-version": "1.13.0-beta.0", + ...(req.url.endsWith("/describe/") && capability !== null + ? { "x-lancedb-blob-ranges": capability } + : {}), + }); + const response = req.url.endsWith("branches/list/") + ? { + branches: { + experiment: { + parentBranch: null, + parentVersion: 1, + createAt: 1, + manifestSize: 1, + }, + }, + } + : { version: 8, schema: { fields: [] } }; + res.end(JSON.stringify(response)); + return; + } + if (capability !== "1" && req.method === "GET") { + const url = new URL(req.url!, "http://localhost"); + expect(url.searchParams.get("branch")).toBe("experiment"); + expect(url.searchParams.get("version")).toBe("3"); + const [start, end] = req.headers.range!.slice(6).split("-").map(Number); + const bytes = Buffer.from("alpha").subarray(start, end + 1); + res + .writeHead(206, { + "Content-Range": `bytes ${start}-${end}/5`, + "Content-Length": bytes.length, + "x-lancedb-version": "3", + }) + .end(bytes); + return; + } + expect(req.method).toBe("POST"); + expect(req.url).toBe( + capability === "1" + ? "/v1/table/test/fetch_blob_ranges/" + : "/v1/table/test/query/", + ); + const chunks: Buffer[] = []; + let size = 0; + req.on("data", (chunk: Buffer) => { + size += chunk.length; + expect(size).toBeLessThanOrEqual(256 * 1024); + chunks.push(chunk); + }); + req.on("end", () => { + if (capability !== "1") { + const body = JSON.parse(Buffer.concat(chunks).toString()) as { + branch: string; + version: number; + filter: string; + }; + expect(body.branch).toBe("experiment"); + expect(body.version).toBe(3); + takes++; + const ids = (body.filter.match(/\d+/g) ?? []) + .map(Number) + .filter((id) => [10, 20, 40].includes(id)) + .reverse(); + const descriptor = new Struct([ + new Field("kind", new Uint8(), false), + new Field("position", new Uint64(), false), + new Field("size", new Uint64(), false), + new Field("blob_id", new Uint32(), false), + new Field("blob_uri", new Utf8(), false), + ]); + const arrow = new ArrowTable({ + image: vectorFromArray( + ids.map((id) => + id === 20 + ? null + : { + kind: 0, + position: 0n, + size: id === 40 ? 0n : 5n, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_id: 0, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_uri: "", + }, + ), + descriptor, + ), + _rowid: vectorFromArray(ids.map(BigInt), new Uint64()), + }); + expect(takes).toBeGreaterThan(0); + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "3", + }) + .end(tableToIPC(arrow, "stream")); + return; + } + const body = JSON.parse(Buffer.concat(chunks).toString()) as Request; + body.identity = req.headers["x-lancedb-query-snapshot"] as + | string + | undefined; + calls.push(body); + expect(body.column).toBe("image"); + expect(body.branch).toBe("experiment"); + expect(body.ranges.length).toBeLessThanOrEqual(1024); + expect( + body.ranges.reduce((sum, range) => sum + range.length, 0), + ).toBeLessThanOrEqual(64 * MIB); + const version = body.version ?? (calls.length === 1 ? 7 : 8); + const failure = + calls.length > 1 || String(fault).startsWith("first-") + ? fault + : undefined; + if (failure === "recreated" || failure === "gone") { + res + .writeHead(failure === "recreated" ? 400 : 404) + .end("query snapshot identity mismatch: source gone or replaced"); + return; + } + if (failure === "stall" && calls.length === 2) { + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "7", + "x-lancedb-query-snapshot": IDENTITY, + }); + res.flushHeaders(); + onStall?.(); + return; + } + if (typeof failure === "number") { + res.writeHead(failure).end("ordinary server failure"); + return; + } + if (failure === "disconnect") { + req.socket.destroy(); + return; + } + let values = body.ranges.map((range) => + range.row_id === 20 + ? null + : payload(range.row_id, range.offset, range.length, version), + ); + if (failure === "count") values = []; + if (failure === "length") values = [Buffer.alloc(0)]; + const arrow = new ArrowTable({ + [failure === "column" ? "wrong" : "value"]: vectorFromArray( + values, + failure === "type" ? new Binary() : new LargeBinary(), + ), + }); + let ipc = tableToIPC(arrow, "stream"); + if (failure === "eos") ipc = ipc.subarray(0, ipc.length - 8); + if (failure === "body") ipc = ipc.subarray(0, Math.floor(ipc.length / 2)); + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + connection: "close", + "Content-Length": ipc.length + (failure === "transport" ? 10 : 0), + ...(failure === "version" ? {} : { "x-lancedb-version": version }), + ...(["missing-identity", "first-missing-identity"].includes( + String(failure), + ) + ? {} + : { + "x-lancedb-query-snapshot": + failure === "wrong-identity" + ? `v1:${"b".repeat(64)}` + : failure === "first-invalid-identity" + ? "broken" + : IDENTITY, + }), + }); + // Fragment the generated IPC payload across actual HTTP writes. + for (let i = 0; i < ipc.length; i += 8192) + res.write(ipc.subarray(i, i + 8192)); + res.end(); + }); + }); + server.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const port = (server.address() as AddressInfo).port; + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + clientConfig: { + retryConfig: { retries: 2, connectRetries: 2, readRetries: 2 }, + blobRequestConcurrency: 1, + timeoutConfig: { timeout: 20 }, + }, + }); + try { + await run(db, calls, paths); + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } +} + +async function open(db: Connection, version?: number): Promise
{ + return db.openTable("test", [], { branch: "experiment", version }); +} + +describe("fetchBlobRanges", () => { + it.each([null, "0", "2"])( + "uses old routes before data requests for capability %s", + async (capability) => { + await withRangeServer( + async (db, calls, paths) => { + // Reopening exercises both the initial and cached database describe paths. + for (let i = 0; i < 2; i++) { + const table = await open(db, 3); + const requests = [ + { rowId: 10n, offset: 1n, length: 3n }, + { rowId: 20n, offset: 0n, length: 1n }, + { rowId: 40n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 5n, length: 0n }, + { rowId: 10n, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("lph"), + null, + Buffer.alloc(0), + Buffer.alloc(0), + Buffer.from("lph"), + ]); + for (const row of [ + { rowId: 10n, offset: 4n, length: 2n }, + { rowId: 99n, offset: 0n, length: 1n }, + ]) + await expect( + table.fetchBlobRanges("image", [row]), + ).rejects.toThrow(); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + expect(paths).toHaveLength(before); + } + expect(calls).toHaveLength(0); + expect(paths.some((path) => path.includes("fetch_blob_ranges"))).toBe( + false, + ); + }, + undefined, + capability, + ); + }, + ); + + it("renegotiates advertised support when reopening a cached table", async () => { + await withRangeServer(async (db, calls) => { + for (let i = 0; i < 2; i++) { + const table = await open(db); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, i === 0 ? 7 : 8)]); + } + expect(calls).toHaveLength(2); + }); + }); + + it("cancels while waiting for a later response body and releases the only permit", async () => { + let markStalled!: () => void; + const stalled = new Promise((resolve) => { + markStalled = resolve; + }); + await withRangeServer( + async (db, calls) => { + const table = await open(db); + const controller = new AbortController(); + const pending = table.fetchBlobRanges( + "image", + Array.from({ length: 2049 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + { signal: controller.signal }, + ); + const rejected = expect(pending).rejects.toMatchObject({ + name: "AbortError", + }); + await stalled; + controller.abort(); + await rejected; + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + expect(calls).toHaveLength(2); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, 8)]); + expect(calls).toHaveLength(3); + }, + "stall", + "1", + () => markStalled(), + ); + }); + it.each([undefined, 3])( + "preserves order, nulls, duplicates and snapshot (checkout %s)", + async (version) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db, version); + const requests: BlobRangeRequest[] = Array.from( + { length: 1025 }, + (_, i) => ({ + rowId: i % 9 === 0 ? 20 : 10 + (i % 7), + offset: BigInt(i), + length: BigInt(i % 4), + }), + ); + requests.push( + { rowId: 10n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 2n, length: 3n }, + { rowId: 10n, offset: 2n, length: 3n }, + ); + const result = await table.fetchBlobRanges("image", requests); + expect(result).toEqual( + requests.map((range) => + Number(range.rowId) === 20 + ? null + : payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + version ?? 7, + ), + ), + ); + expect(calls.map((body) => body.version)).toEqual([ + version ?? null, + version ?? 7, + ]); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, version ?? 8)]); + expect(calls[2].version).toBe(version ?? null); + expect( + paths.filter((path) => path.endsWith("fetch_blob_ranges/")), + ).toHaveLength(3); + }); + }, + ); + + it("partitions the byte budget and reassembles one range larger than 64 MiB", async () => { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = [ + { rowId: 10n, offset: 3n, length: BigInt(65 * MIB) }, + { rowId: 30n, offset: 7n, length: 2n }, + ]; + const result = await table.fetchBlobRanges("image", requests); + for (const [i, range] of requests.entries()) { + expect(result[i]?.length).toBe(Number(range.length)); + expect( + createHash("sha256") + .update(result[i] as Buffer) + .digest("hex"), + ).toBe( + createHash("sha256") + .update( + payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + 7, + ), + ) + .digest("hex"), + ); + } + expect(calls).toHaveLength(2); + expect(calls.map((body) => body.version)).toEqual([null, 7]); + }); + }); + + it.each([ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ])("rejects the whole call after a later %s failure", async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(); + expect(calls).toHaveLength(2); + expect( + paths.every( + (path) => + path.endsWith("describe/") || + path.endsWith("branches/list/") || + path.endsWith("fetch_blob_ranges/"), + ), + ).toBe(true); + }, fault); + }); + + it.each(["missing-identity", "wrong-identity", "recreated", "gone"])( + "retains original identity through row and byte partitions (%s)", + async (fault) => { + for (const huge of [false, true]) { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = huge + ? [{ rowId: 10n, offset: 0n, length: BigInt(64 * MIB + 1) }] + : Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })); + await expect( + table.fetchBlobRanges("image", requests), + ).rejects.toThrow(); + expect(calls.map((call) => call.identity)).toEqual([ + undefined, + IDENTITY, + ]); + expect(calls.map((call) => call.version)).toEqual([null, 7]); + }, fault); + } + }, + ); + + it.each(["first-missing-identity", "first-invalid-identity"])( + "requires a first authoritative bulk identity (%s)", + async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(/snapshot identity/); + expect(calls).toHaveLength(1); + expect(paths).toHaveLength(before + 1); + }, fault); + }, + ); + + it("validates integers, overflow and cancellation and leaves empty calls at zero I/O", async () => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + for (const request of [ + { rowId: -1, offset: 0n, length: 1n }, + { rowId: 1.5, offset: 0n, length: 1n }, + { rowId: Number.MAX_SAFE_INTEGER + 1, offset: 0n, length: 1n }, + { rowId: -1n, offset: 0n, length: 1n }, + { rowId: 1n << 64n, offset: 0n, length: 1n }, + { rowId: 10n, offset: -1n, length: 1n }, + { rowId: 10n, offset: 0n, length: -1n }, + { rowId: 10n, offset: 0n, length: 1n << 64n }, + { rowId: 20n, offset: (1n << 64n) - 1n, length: 1n }, + ]) { + await expect( + table.fetchBlobRanges("image", [request]), + ).rejects.toThrow(); + } + // Runtime type validation must also reject a number passed as an offset. + await expect( + table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0 as unknown as bigint, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + controller.abort(new Error("cancelled by caller")); + await expect( + table.fetchBlobRanges( + "image", + [{ rowId: 10n, offset: 0n, length: 1n }], + { signal: controller.signal }, + ), + ).rejects.toThrow("cancelled by caller"); + expect(paths).toHaveLength(before); + expect(calls).toHaveLength(0); + }); + }); + + it("records the loaded native artifact", async () => { + const artifacts = Object.keys(require.cache).filter( + (path) => path.endsWith(".node") && path.includes("lancedb"), + ); + expect(artifacts.length).toBeGreaterThan(0); + for (const path of artifacts) { + const hash = createHash("sha256"); + for await (const chunk of createReadStream(path)) hash.update(chunk); + console.log( + `loaded native artifact=${path} sha256=${hash.digest("hex")}`, + ); + } + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index b803e9043..59d6929b4 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3019,6 +3019,43 @@ describe("when dealing with blob columns", () => { expect(bytes.map((b) => b?.toString())).toEqual(["new", "hi"]); }); + it("fetchBlobRanges reads local ranges with order, duplicates, nulls and validation", async () => { + const { table, rowIds } = await openBlobTable(); + const [alphaId, betaId, nullId] = rowIds; + const requests = [ + { rowId: betaId, offset: 1n, length: 3n }, + { rowId: alphaId, offset: 0n, length: 2n }, + { rowId: nullId, offset: 0n, length: 1n }, + { rowId: alphaId, offset: 5n, length: 0n }, + { rowId: betaId, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("eta"), + Buffer.from("al"), + null, + Buffer.alloc(0), + Buffer.from("eta"), + ]); + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + await expect( + table.fetchBlobRanges("image", [ + { rowId: alphaId, offset: 4n, length: 2n }, + ]), + ).rejects.toThrow(); + await expect( + table.fetchBlobRanges("image", [ + { rowId: (1n << 63n) - 1n, offset: 0n, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + expect( + await table.fetchBlobRanges("image", requests, { + signal: controller.signal, + }), + ).toHaveLength(5); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + }); + it("discovers blob columns", async () => { const { table } = await openBlobTable(); expect(await table.blobColumns()).toEqual(["image"]); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 67e662175..a46484314 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -305,6 +305,16 @@ export async function runWithSignal( } } +/** One row-specific range for {@link Table.fetchBlobRanges}. */ +export type BlobRangeRequest = { + /** A row ID from a query with row IDs enabled. */ + rowId: bigint | number; + /** Byte offset from the beginning of the logical blob, as a uint64. */ + offset: bigint; + /** Number of bytes to read, as a uint64. Zero returns an empty non-null value. */ + length: bigint; +}; + /** A half-open byte range `[start, end)` for {@link BlobFile.readRanges}. */ export type BlobRange = { start: bigint; diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 35697dc8c..08a254bdb 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -91,6 +91,7 @@ export type { BlobInput, BlobOptions, BlobRange, + BlobRangeRequest, BlobReadOptions, BlobUri, } from "./blob"; diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 185088424..136eb1d6c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -17,7 +17,12 @@ import { tableFromIPC, } from "./arrow"; -import { BlobFile, BlobReadOptions, runWithSignal } from "./blob"; +import { + BlobFile, + BlobRangeRequest, + BlobReadOptions, + runWithSignal, +} from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { IndexOptions } from "./indices"; import { Job } from "./job"; @@ -683,6 +688,31 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(Buffer | null)[]>; + /** + * Materializes row-specific byte ranges at the table's current checkout. + * Preserves request order, duplicates, and nulls. Zero length returns an empty + * buffer for a non-null blob. Invalid ranges or missing rows reject the entire + * call. See {@link Table.fetchBlobs} for row-ID validity across versions. + * + * Remote tables use the batched endpoint when the server advertises support, + * splitting at 1024 ranges and 64 MiB, including individual larger ranges. + * Older servers use descriptor queries and BlobFile range reads. Both protocols + * use one exact branch and version. Errors from an advertised endpoint propagate + * without switching protocols. All output bytes occupy memory. + * + * @example + * ```ts + * const bytes = await table.fetchBlobRanges("image", [ + * { rowId: 10n, offset: 0n, length: 1024n }, + * ]); + * ``` + */ + abstract fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]>; + /** * Opens lazy blob handles for `column` at the given row IDs using the * table's current checkout. @@ -1510,6 +1540,23 @@ export class LocalTable extends Table { return values.map((value) => value ?? null); } + async fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]> { + const rowIds = rowIdsToBigInts(requests.map((request) => request.rowId)); + const ranges = requests.map((request, i) => ({ + rowId: rowIds[i], + offset: request.offset, + length: request.length, + })); + const values = await runWithSignal(options?.signal, (signal) => + this.inner.fetchBlobRanges(column, ranges, signal), + ); + return values.map((value) => value ?? null); + } + async fetchBlobFiles( column: string, rowIds: readonly (bigint | number)[], diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index 59cf61af6..b55154019 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -21,6 +21,25 @@ pub struct BlobRange { pub end: BigInt, } +#[napi(object)] +pub struct BlobRangeRequest { + pub row_id: BigInt, + pub offset: BigInt, + pub length: BigInt, +} + +impl BlobRangeRequest { + pub(crate) fn parse(self) -> napi::Result { + let row_id = parse_u64(self.row_id, "row id")?; + let offset = parse_u64(self.offset, "offset")?; + let length = parse_u64(self.length, "length")?; + offset + .checked_add(length) + .ok_or_else(|| napi::Error::from_reason("blob range offset + length overflows u64"))?; + Ok(lancedb::blob::BlobRangeRequest::new(row_id, offset, length)) + } +} + #[napi] pub struct BlobFile { inner: Arc, @@ -205,14 +224,25 @@ pub fn parse_row_ids(row_ids: Vec) -> napi::Result> { .collect() } -pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec> { - (0..array.len()) - .map(|i| { - if array.is_null(i) { - None - } else { - Some(Buffer::from(array.value(i).to_vec())) - } - }) - .collect() +pub fn copy_blob_buffers(array: LargeBinaryArray) -> napi::Result>> { + let allocation_error = + |error| napi::Error::from_reason(format!("cannot allocate blob result: {error}")); + let mut result = Vec::new(); + result + .try_reserve_exact(array.len()) + .map_err(allocation_error)?; + for value in array.iter() { + let buffer = value + .map(|value| { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(value.len()) + .map_err(allocation_error)?; + bytes.extend_from_slice(value); + Ok::<_, napi::Error>(Buffer::from(bytes)) + }) + .transpose()?; + result.push(buffer); + } + Ok(result) } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 7076bbec1..f6abeb553 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -17,7 +17,7 @@ use napi::bindgen_prelude::*; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; -use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable}; +use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::NapiErrorExt; use crate::index::Index; use crate::job::JobFailureInfo; @@ -420,7 +420,32 @@ impl Table { .fetch_blobs(column.as_str(), &row_ids) .await .default_error()?; - Ok(copy_blob_buffers(array)) + copy_blob_buffers(array) + }) + } + + #[napi(catch_unwind)] + pub fn fetch_blob_ranges<'env>( + &self, + env: &'env Env, + column: String, + requests: Vec, + signal: Option, + ) -> napi::Result>>> { + let mut ranges = Vec::new(); + ranges.try_reserve_exact(requests.len()).map_err(|error| { + napi::Error::from_reason(format!("cannot allocate blob range requests: {error}")) + })?; + for request in requests { + ranges.push(request.parse()?); + } + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let array = table + .fetch_blob_ranges(column.as_str(), ranges) + .await + .default_error()?; + copy_blob_buffers(array) }) } diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 3161eda30..5f0af7a66 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2661,8 +2661,12 @@ class Table(ABC): results are returned. Row IDs can be obtained from a query with ``with_row_id(True)``. - LanceDB Enterprise reads the requested ranges through version-pinned blob - handles using HTTP byte-range requests. + LanceDB Enterprise uses the batched endpoint when the server advertises + support, partitioning at 1024 ranges and 64 MiB, including individual + larger ranges. Older servers use descriptor queries and BlobFile range + reads. Both protocols read one exact branch and version without changing + the table's checkout. Errors from an advertised endpoint propagate without + switching protocols. The final output occupies memory. """ @abstractmethod @@ -8652,6 +8656,10 @@ class AsyncTable: column: str, requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: + """Materialize row-specific byte ranges. + + See [Table.fetch_blob_ranges][lancedb.table.Table.fetch_blob_ranges]. + """ return await self._inner.fetch_blob_ranges(column, list(requests)) async def fetch_blob_files( diff --git a/python/python/tests/test_blob_ranges.py b/python/python/tests/test_blob_ranges.py new file mode 100644 index 000000000..c65dfb8ae --- /dev/null +++ b/python/python/tests/test_blob_ranges.py @@ -0,0 +1,380 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Exercise the public sync/async range APIs over bounded loopback HTTP.""" + +import asyncio +import hashlib +import json +from pathlib import Path +import socket +import threading + +import lancedb._lancedb as native +import pyarrow as pa +import pytest + +from lancedb.remote.errors import HttpError, TableNotFoundError +from test_remote_db import mock_lancedb_connection + +MIB = 1024 * 1024 +IDENTITY = "v1:" + "a" * 64 +ROUTE = "/v1/table/test/fetch_blob_ranges/" + + +def payload(row, offset, length, version): + pattern = bytes((row * 17 + i + version) % 251 for i in range(251)) + start = offset % 251 + return (pattern * ((start + length + 250) // 251))[start : start + length] + + +class RangeServer: + def __init__(self, fault=None): + self.fault = fault + self.calls = [] + self.fetches = [] + self.identities = [] + self.stalled = threading.Event() + self.release = threading.Event() + + def __call__(self, request): + request.connection.settimeout(15) + size = int(request.headers.get("Content-Length", 0)) + assert size <= 256 * 1024 + body = json.loads(request.rfile.read(size) or b"{}") + self.calls.append((request.command, request.path, body)) + if request.path in ( + "/v1/table/test/describe/", + "/v1/table/test/branches/list/", + ): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.send_header("phalanx-version", "1.13.0-beta.0") + if request.path.endswith("/describe/"): + request.send_header("x-lancedb-blob-ranges", "1") + request.end_headers() + response = ( + { + "branches": { + "experiment": { + "parentBranch": None, + "parentVersion": 1, + "createAt": 1, + "manifestSize": 1, + } + } + } + if request.path.endswith("branches/list/") + else {"version": 8, "schema": {"fields": []}} + ) + request.wfile.write(json.dumps(response).encode()) + return + assert (request.command, request.path) == ("POST", ROUTE) + self.fetches.append(body) + self.identities.append(request.headers.get("x-lancedb-query-snapshot")) + assert body["column"] == "image" + assert body["branch"] == "experiment" + ranges = body["ranges"] + assert len(ranges) <= 1024 + assert sum(r["length"] for r in ranges) <= 64 * MIB + version = body["version"] or (7 if len(self.fetches) == 1 else 8) + values = [ + None + if r["row_id"] == 20 + else payload(r["row_id"], r["offset"], r["length"], version) + for r in ranges + ] + fault = ( + self.fault + if len(self.fetches) > 1 or str(self.fault).startswith("first-") + else None + ) + if fault in ("recreated", "gone"): + request.send_response(400 if fault == "recreated" else 404) + request.end_headers() + request.wfile.write( + b"query snapshot identity mismatch: source gone or replaced" + ) + return + if fault == "stall" and len(self.fetches) == 2: + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", str(version)) + request.send_header("x-lancedb-query-snapshot", IDENTITY) + request.end_headers() + request.wfile.flush() + self.stalled.set() + assert self.release.wait(15), "test did not release stalled response" + return + if fault == "structured400": + request.send_response(400) + request.send_header("x-lancedb-error-code", "invalid_input") + request.end_headers() + request.wfile.write(b'{"error":"range exceeds blob size"}') + return + if isinstance(fault, int): + request.send_response(fault) + request.end_headers() + request.wfile.write(b"ordinary server failure") + return + if fault == "disconnect": + request.connection.shutdown(socket.SHUT_RDWR) + return + column = "wrong" if fault == "column" else "value" + data_type = pa.binary() if fault == "type" else pa.large_binary() + if fault == "count": + values = [] + elif fault == "length": + values = [b""] + batch = pa.table({column: pa.array(values, type=data_type)}) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batch.schema) as writer: + writer.write_table(batch, max_chunksize=257) + ipc = sink.getvalue().to_pybytes() + if fault == "eos": + ipc = ipc[:-8] + elif fault == "body": + ipc = ipc[: len(ipc) // 2] + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + if fault != "version": + request.send_header("x-lancedb-version", str(version)) + if fault not in ("missing-identity", "first-missing-identity"): + identity = ( + "broken" + if fault == "first-invalid-identity" + else "v1:" + "b" * 64 + if fault == "wrong-identity" + else IDENTITY + ) + request.send_header("x-lancedb-query-snapshot", identity) + request.send_header( + "Content-Length", str(len(ipc) + (10 if fault == "transport" else 0)) + ) + request.end_headers() + for i in range(0, len(ipc), 8192): + request.wfile.write(ipc[i : i + 8192]) + + +async def fetch(table, requests, use_async): + result = table.fetch_blob_ranges("image", requests) + return await result if use_async else result + + +def api(db, use_async, version=None): + table = db.open_table("test", branch="experiment", version=version) + return table._table if use_async else table + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("version", [None, 3]) +async def test_range_sdk_order_snapshot_and_overwrite(use_async, version): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async, version) + requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)] + requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)] + result = await fetch(table, requests, use_async) + assert isinstance(result, pa.LargeBinaryArray) + assert result.to_pylist() == [ + None if row == 20 else payload(row, offset, length, version or 7) + for row, offset, length in requests + ] + assert [b["version"] for b in handler.fetches] == [version, version or 7] + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version or 8)] + assert handler.fetches[-1]["version"] == version + assert len(handler.fetches) == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_cached_reopen_negotiates_capability(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + for version in (7, 8): + table = api(db, use_async) + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version)] + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_large_single_and_aggregate_budget(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [ + (10, 3, 33 * MIB), + (30, 7, 33 * MIB), + (40, 11, 70 * MIB), + (20, 0, 2**64 - 1), + ] + # The loopback server advances latest after the first partition. + result = await fetch(table, requests, use_async) + assert len(result) == 4 + for i, (row, offset, length) in enumerate(requests[:3]): + expected = payload(row, offset, length, 7) + assert ( + hashlib.sha256(result[i].as_buffer()).digest() + == hashlib.sha256(expected).digest() + ) + assert len(result[i].as_buffer()) == length + assert result[3].as_py() is None + assert len(handler.fetches) == 3 + assert [b["version"] for b in handler.fetches] == [None, 7, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", + [ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ], +) +async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault): + handler = RangeServer(fault=fault) + with mock_lancedb_connection( + handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2} + ) as db: + table = api(db, use_async) + with pytest.raises(Exception) as exc: + await fetch(table, [(10, 0, 1)] * 1025, use_async) + if fault == 404: + assert isinstance(exc.value, TableNotFoundError) + assert isinstance(exc.value.__cause__, HttpError) + assert exc.value.__cause__.status_code == 404 + else: + assert not isinstance(exc.value, ValueError) + if isinstance(fault, int): + assert exc.value.status_code == fault + assert len(handler.fetches) == 2 + assert all( + path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE) + for _, path, _ in handler.calls + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_structured_400_preserves_value_error(use_async): + handler = RangeServer(fault="structured400") + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + with pytest.raises(ValueError, match="range exceeds blob size"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +async def test_range_sdk_async_cancel_releases_only_request_permit(): + handler = RangeServer(fault="stall") + with mock_lancedb_connection(handler, blob_request_concurrency=1) as db: + table = api(db, True) + pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True)) + try: + assert await asyncio.to_thread(handler.stalled.wait, 10) + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert len(handler.fetches) == 2 + result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5) + assert result.to_pylist() == [payload(10, 0, 1, 8)] + assert len(handler.fetches) == 3 + finally: + pending.cancel() + handler.release.set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_integer_validation_and_empty_zero_io(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + assert (await fetch(table, [], use_async)).to_pylist() == [] + for request in [ + (-1, 0, 1), + (2**64, 0, 1), + (10, -1, 1), + (10, 0, -1), + (10, 0, 2**64), + (10, 0.5, 1), + (20, 2**64 - 1, 1), + (10, 0), + ]: + with pytest.raises((ValueError, OverflowError, TypeError)): + await fetch(table, [request], use_async) + assert len(handler.calls) == before + + +def test_range_sdk_loaded_artifact_identity(): + artifact = Path(native.__file__).resolve() + digest = hashlib.sha256() + with artifact.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}") + assert artifact.is_file() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", ["missing-identity", "wrong-identity", "recreated", "gone"] +) +@pytest.mark.parametrize("huge", [False, True]) +async def test_range_sdk_original_identity_survives_every_partition( + use_async, fault, huge +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025 + error = ( + ValueError + if fault == "recreated" + else TableNotFoundError + if fault == "gone" + else NotImplementedError + ) + with pytest.raises( + error, match="snapshot identity" if fault != "gone" else None + ): + await fetch(table, requests, use_async) + assert handler.identities == [None, IDENTITY] + assert len(handler.fetches) == 2 + assert [body["version"] for body in handler.fetches] == [None, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"]) +async def test_range_sdk_bulk_requires_identity_before_payload_acceptance( + use_async, fault +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + with pytest.raises(NotImplementedError, match="snapshot identity"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 1 + assert len(handler.calls) == before + 1 diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 561a0f900..4f707f041 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5466,6 +5466,7 @@ def blob_remote_table( *, server_version=Version("0.5.0"), location=None, + range_capability=None, version_header="1", framing="file", requests=None, @@ -5487,6 +5488,8 @@ def blob_remote_table( request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) + if range_capability is not None: + request.send_header("x-lancedb-blob-ranges", range_capability) request.end_headers() response = dict(BLOB_DESCRIBE_RESPONSE) response["version"] = body.get("version") or state["version"] @@ -5594,6 +5597,42 @@ def blob_remote_table( writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream with writer_factory(request.wfile, response_table.schema) as writer: writer.write_table(response_table, max_chunksize=1) + elif ( + range_capability == "1" + and request.path == "/v1/table/test/fetch_blob_ranges/" + ): + size = int(request.headers["Content-Length"]) + body = json.loads(request.rfile.read(size)) + payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""} + values = [] + for item in body["ranges"]: + row, offset, length = ( + item[key] for key in ("row_id", "offset", "length") + ) + error = None + if row not in payloads: + error = "only 1 exist" + elif payloads[row] is not None and offset + length > len(payloads[row]): + error = "range exceeds blob size" + if error: + request.send_response(400) + request.end_headers() + request.wfile.write(error.encode()) + return + payload = payloads[row] + values.append( + None if payload is None else payload[offset : offset + length] + ) + response_table = pa.table( + {"value": pa.array(values, type=pa.large_binary())} + ) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", "1") + request.send_header("x-lancedb-query-snapshot", "v1:" + "a" * 64) + request.end_headers() + with pa.ipc.new_stream(request.wfile, response_table.schema) as writer: + writer.write_table(response_table) elif request.path == "/v1/table/test/fetch_blobs/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) @@ -5901,8 +5940,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access( @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) -async def test_remote_fetch_blob_ranges(use_async): - with blob_remote_table() as remote_table: +@pytest.mark.parametrize("range_capability", [None, "0", "2", "1"]) +async def test_remote_fetch_blob_ranges(use_async, range_capability): + with blob_remote_table( + server_version="1.13.0-beta.0", range_capability=range_capability + ) as remote_table: table = remote_table._table if use_async else remote_table requests = [ (30, 2, 3), diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index ead1f2410..82f502250 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -356,7 +356,7 @@ impl BlobFile { /// /// `row_id` is obtained from a query with row ids enabled. /// `offset` and `length` are relative to the beginning of the logical blob. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct BlobRangeRequest { /// Row id of the blob value to read. pub row_id: u64, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index b562f41df..578e3bbab 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1655,9 +1655,9 @@ impl Database for RemoteDatabase { 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?; + let rsp = self.client.check_response(&request_id, rsp).await?; - Ok(Arc::new(RemoteTable::new_with_sql_client( + let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), self.db_name.clone(), request.name, @@ -1665,7 +1665,9 @@ impl Database for RemoteDatabase { identifier, version, self.sql_client.clone(), - ))) + )); + table.seed_blob_ranges_capability(rsp.headers()); + Ok(table) } else { // Describe the table to confirm it exists before moving on. let req = self @@ -1676,6 +1678,7 @@ impl Database for RemoteDatabase { RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; let rsp = self.client.check_response(&request_id, rsp).await?; let version = parse_server_version(&request_id, &rsp)?; + let describe_headers = rsp.headers().clone(); let describe_body = rsp.text().await.ok(); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), @@ -1686,6 +1689,7 @@ impl Database for RemoteDatabase { version.clone(), self.sql_client.clone(), )); + table.seed_blob_ranges_capability(&describe_headers); // This describe already carries the schema, so hand it to the table // instead of making the first schema read fetch it again. A version or // branch pin applied after this invalidates the cache. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index d560a4802..fdb547afa 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -86,6 +86,7 @@ use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; use tokio::sync::RwLock; @@ -634,6 +635,8 @@ pub struct RemoteTable { version: Arc>>, location: RwLock>, schema_cache: BackgroundCache, + // Only a successful describe can opt into the batched range protocol. + blob_ranges_supported: Arc, // WAL-PK-FUSION: delete, with its initializers below. wal_pk_fusion: PkFusionMemory, freshness: Arc>, @@ -881,6 +884,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -888,6 +892,15 @@ impl RemoteTable { } } + pub(super) fn seed_blob_ranges_capability(&self, headers: &http::HeaderMap) { + self.blob_ranges_supported.store( + headers + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + /// Seed the schema cache from a `describe` body the caller already fetched. /// /// Best effort. `open_table` succeeds today without reading this body, so a @@ -918,6 +931,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: self.blob_ranges_supported.clone(), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, @@ -1067,6 +1081,7 @@ impl RemoteTable { }; let response = self.check_table_response(&request_id, response).await?; + self.seed_blob_ranges_capability(response.headers()); match response.text().await { Ok(body) => { @@ -1943,6 +1958,7 @@ async fn fetch_schema( read_snapshot: ReadSnapshot, branch: Option, freshness: Arc>, + blob_ranges_supported: Arc, ) -> Result { let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { @@ -1969,6 +1985,13 @@ async fn fetch_schema( let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); + blob_ranges_supported.store( + response + .headers() + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -2026,6 +2049,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2054,6 +2078,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2091,6 +2116,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2885,6 +2911,7 @@ impl BaseTable for RemoteTable { let table_name = self.name.clone(); let branch = self.branch.clone(); let freshness = self.freshness.clone(); + let blob_ranges_supported = self.blob_ranges_supported.clone(); match self .schema_cache @@ -2896,6 +2923,7 @@ impl BaseTable for RemoteTable { read_snapshot, branch, freshness, + blob_ranges_supported, ) .await }) diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index a0051c955..3367d2218 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -35,11 +35,13 @@ use crate::table::{AnyQuery, BaseTable}; use super::{ FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, + valid_query_snapshot_identity, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit // is handled by splitting a rejected request below. const MAX_FETCH_BLOBS_ROW_IDS: usize = 1024; +const MAX_FETCH_BLOB_RANGE_BYTES: u64 = 64 * 1024 * 1024; fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { matches!(error, Error::Http { @@ -599,7 +601,7 @@ impl RemoteTable { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut blobs = BlobAccumulator::new(row_ids.len()); + let mut blobs = BlobAccumulator::new(row_ids.len())?; while let Some(ids) = pending.pop() { match self .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) @@ -642,7 +644,7 @@ impl RemoteTable { } } - Ok(blobs.finish()) + Ok(blobs.finish()?) } async fn fetch_blobs_chunk( @@ -725,11 +727,88 @@ impl RemoteTable { Ok(()) } - /// Materialize ranges through version-pinned handles, preserving nulls and order. + /// Materialize ranges using the protocol advertised by a successful describe. pub(super) async fn fetch_blob_ranges_impl( &self, column: &str, requests: &[BlobRangeRequest], + ) -> Result { + let mut blobs = BlobAccumulator::new(requests.len())?; + if requests.is_empty() { + return Ok(blobs.finish()?); + } + for request in requests { + request + .offset + .checked_add(request.length) + .ok_or_else(|| Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + })?; + } + self.reject_list_blob_path_if_known(column).await?; + if !self.blob_ranges_supported.load(Ordering::Relaxed) { + return self.fetch_blob_ranges_legacy(column, requests).await; + } + // Select the protocol before issuing data requests. An advertised endpoint + // failing in a mixed deployment must fail truthfully, without fallback. + let mut snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + let mut index = 0; + let mut consumed = 0; + let mut ranges = Vec::new(); + ranges + .try_reserve_exact(MAX_FETCH_BLOBS_ROW_IDS) + .map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + while index < requests.len() { + ranges.clear(); + let continuation = consumed != 0; + let mut budget = MAX_FETCH_BLOB_RANGE_BYTES; + while index < requests.len() && ranges.len() < MAX_FETCH_BLOBS_ROW_IDS { + let request = requests[index]; + let remaining = request.length - consumed; + if budget == 0 && remaining != 0 { + break; + } + let length = remaining.min(budget); + // The full range was checked above; all subranges fit within it. + ranges.push(BlobRangeRequest::new( + request.row_id, + request.offset + consumed, + length, + )); + consumed += length; + budget -= length; + if consumed == request.length { + index += 1; + consumed = 0; + } else { + break; + } + } + let array = self + .fetch_blob_ranges_chunk(column, &ranges, &mut snapshot, &mut identity) + .await?; + // A null has no bytes to partition. Avoid sending arbitrarily many + // empty fragments for a null with a very large requested length. + if consumed != 0 && array.is_null(array.len() - 1) { + index += 1; + consumed = 0; + } + if continuation { + blobs.append_continuation(&array)?; + } else { + blobs.append(&array)?; + } + } + Ok(blobs.finish()?) + } + + async fn fetch_blob_ranges_legacy( + &self, + column: &str, + requests: &[BlobRangeRequest], ) -> Result { let row_ids = requests .iter() @@ -738,16 +817,12 @@ impl RemoteTable { let files = self.fetch_blob_files_impl(column, &row_ids).await?; let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); for (file, request) in files.into_iter().zip(requests) { - let end = - request - .offset - .checked_add(request.length) - .ok_or_else(|| Error::InvalidInput { - message: "blob range offset + length overflows u64".into(), - })?; match file { Some(file) => { - let bytes = file.read_range(request.offset..end).await?; + // Overflow was checked before selecting either protocol. + let bytes = file + .read_range(request.offset..request.offset + request.length) + .await?; builder.append_value(bytes); } None => builder.append_null(), @@ -756,6 +831,162 @@ impl RemoteTable { Ok(builder.finish()) } + async fn fetch_blob_ranges_chunk( + &self, + column: &str, + ranges: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result { + let _permit = self + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let body = serde_json::json!({ + "column": column, + "version": snapshot.version, + "branch": self.branch, + "ranges": ranges, + }); + let request = self + .client + .post(&format!("/v1/table/{}/fetch_blob_ranges/", self.identifier)) + .json(&body); + let request = if let Some(expected) = identity.as_deref() { + request.header(super::QUERY_SNAPSHOT_HEADER, expected) + } else { + request + }; + let (request_id, response) = self + .send_with_freshness(request, false, snapshot.freshness) + .await?; + // The range operation defines 400 as invalid input. Let the established + // checker decode structured/plain server errors before normalizing it. + let response = self + .check_table_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("fetch_blob_ranges (request {request_id}): {source}"), + } + } else { + error + } + })?; + let invalid = |message: String| Error::Http { + source: format!("fetch_blob_ranges: {message}").into(), + request_id: request_id.clone(), + status_code: None, + }; + let version = response.headers().get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| invalid("missing or invalid x-lancedb-version; a server supporting the batched range endpoint is required".into()))?; + if snapshot.version.is_some_and(|expected| expected != version) { + return Err(invalid(format!( + "response version {version} differs from requested version {:?}", + snapshot.version + ))); + } + // Do not decode or accept any payload before establishing/verifying the + // identity. A later partition can never replace the original expectation. + check_query_snapshot_response(identity.as_deref(), &response)?; + if identity.is_none() { + let actual = response.headers().get(super::QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .ok_or_else(|| Error::NotSupported { + message: "Batched Blob ranges require a snapshot identity; upgrade every serving node".into(), + })?; + *identity = Some(actual.to_owned()); + } + snapshot.version = Some(version); + // This endpoint's contract is stream framing. Keep the bounded, fallible + // IPC path from #4979 instead of buffering an Arrow file response. + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if !content_type + .split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case(crate::remote::ARROW_STREAM_CONTENT_TYPE) + { + return Err(invalid(format!( + "expected Arrow IPC stream, got '{content_type}'" + ))); + } + let mut stream = super::ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.clone(), + Some(version), + ) + .await?; + let schema = stream.schema(); + if !matches!( + schema + .field_with_name("value") + .map(|field| field.data_type()), + Ok(DataType::LargeBinary) + ) { + return Err(invalid( + "response requires a LargeBinary column named 'value'".into(), + )); + } + let mut blobs = BlobAccumulator::new(ranges.len())?; + let mut rows = 0usize; + let mut bytes = 0u64; + while let Some(batch) = stream.try_next().await? { + let array = batch + .column_by_name("value") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| { + invalid("response requires a LargeBinary column named 'value'".into()) + })?; + let end = rows + .checked_add(array.len()) + .filter(|end| *end <= ranges.len()) + .ok_or_else(|| invalid("response has more rows than requested".into()))?; + let offsets = array.value_offsets(); + bytes = bytes + .checked_add((offsets[array.len()] - offsets[0]) as u64) + .filter(|bytes| *bytes <= MAX_FETCH_BLOB_RANGE_BYTES) + .ok_or_else(|| invalid("response exceeds 64 MiB of range bytes".into()))?; + for (i, range) in ranges[rows..end].iter().enumerate() { + if array.is_valid(i) && array.value_length(i) as u64 != range.length { + return Err(invalid(format!( + "row {} returned {} bytes for requested length {}", + rows + i, + array.value_length(i), + range.length + ))); + } + } + blobs.append(array)?; + rows = end; + } + if rows != ranges.len() { + return Err(invalid(format!( + "returned {rows} rows for {} ranges", + ranges.len() + ))); + } + Ok(blobs.finish()?) + } + /// Open seekable handles for `row_ids`. /// /// Descriptors for the requested rows come from one `_rowid` take query per @@ -1666,10 +1897,155 @@ mod tests { let error = table.fetch_blob_ranges("image", &ranges).await.unwrap_err(); assert!(error.to_string().contains(message), "{error}"); // Missing rows and invalid ranges fail without reading any bytes. - assert_eq!(requests.lock().unwrap().len(), 1); + assert!(matches!(error, Error::InvalidInput { .. })); + assert_eq!( + requests.lock().unwrap().len(), + usize::from(!message.contains("overflows")) + ); } } + #[tokio::test] + async fn remote_blob_ranges_keep_producing_query_identity_from_first_request() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let calls = Arc::new(StdMutex::new(Vec::new())); + let captured = calls.clone(); + let table = RemoteTable::new_mock( + "my_table".into(), + move |request| { + assert_eq!( + request.url().path(), + "/v1/table/my_table/fetch_blob_ranges/" + ); + assert_eq!( + request.headers()[super::super::QUERY_SNAPSHOT_HEADER], + IDENTITY + ); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["version"], 42); + let rows = body["ranges"].as_array().unwrap().len(); + captured.lock().unwrap().push(rows); + let batch = RecordBatch::try_from_iter([( + "value", + Arc::new(LargeBinaryArray::from(vec![Some(b"A".as_slice()); rows])) + as Arc, + )]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "42") + .header(super::super::QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(bytes) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let snapshot = table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap(); + let ranges = snapshot + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(b"A".as_slice()); 1025]) + ); + assert_eq!(*calls.lock().unwrap(), [1024, 1]); + assert!(table.snapshot_read_state().await.version.is_none()); + } + + #[tokio::test] + async fn remote_blob_ranges_cancel_releases_the_only_request_permit() { + use std::sync::atomic::AtomicUsize; + let entered = Arc::new(tokio::sync::Notify::new()); + let started = entered.clone(); + let calls = Arc::new(AtomicUsize::new(0)); + let captured = calls.clone(); + let table = Arc::new(RemoteTable::new_mock_with_version_and_config( + "my_table".into(), + move |request| { + assert!(request.url().path().ends_with("/fetch_blob_ranges/")); + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + started.notify_one(); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header( + super::super::QUERY_SNAPSHOT_HEADER, + format!("v1:{}", "a".repeat(64)), + ) + .body(reqwest::Body::wrap_stream(futures::stream::pending::< + std::result::Result, + >())) + .unwrap() + } else { + http::Response::builder() + .status(400) + .header("x-lancedb-error-code", "invalid_input") + .body(reqwest::Body::from( + r#"{"error":"range exceeds blob size"}"#, + )) + .unwrap() + } + }, + Some(Version::new(1, 13, 0)), + crate::remote::ClientConfig { + blob_request_concurrency: Some(1), + ..Default::default() + }, + )); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let reader_table = table.clone(); + let reader = tokio::spawn(async move { + reader_table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + }); + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + let error = tokio::time::timeout( + Duration::from_secs(5), + table.fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1)]), + ) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds blob size")); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn remote_blob_ranges_reject_overflow_before_http() { + let (table, requests) = mock_take_blob_table(vec![], Some("7")); + let error = table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("overflows u64"), "{error}"); + assert!(requests.lock().unwrap().is_empty()); + } + #[tokio::test] async fn remote_blob_ranges_accept_empty_requests_without_http() { let (table, requests) = mock_take_blob_table(vec![], Some("7")); diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs index e8e794fa0..68bc20c88 100644 --- a/rust/lancedb/src/remote/table/blobs/aggregate.rs +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -6,75 +6,143 @@ use std::collections::VecDeque; use arrow_array::{Array, LargeBinaryArray}; -use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, OffsetBuffer}; +use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer}; use arrow_schema::ArrowError; +fn allocation_error(error: impl std::fmt::Display) -> ArrowError { + ArrowError::ComputeError(format!("cannot allocate blob result: {error}")) +} + pub(super) struct BlobAccumulator { offsets: Vec, - nulls: NullBufferBuilder, + validity: Vec, values: VecDeque, bytes: i64, + has_nulls: bool, } impl BlobAccumulator { - pub(super) fn new(rows: usize) -> Self { - let mut offsets = Vec::with_capacity(rows + 1); + pub(super) fn new(rows: usize) -> Result { + let capacity = rows + .checked_add(1) + .ok_or_else(|| allocation_error("row count overflow"))?; + let mut offsets = Vec::new(); + offsets + .try_reserve_exact(capacity) + .map_err(allocation_error)?; offsets.push(0); - Self { + let mut validity = Vec::new(); + let validity_bytes = rows / 8 + usize::from(!rows.is_multiple_of(8)); + validity + .try_reserve_exact(validity_bytes) + .map_err(allocation_error)?; + Ok(Self { offsets, - nulls: NullBufferBuilder::new(rows), + validity, values: VecDeque::new(), bytes: 0, - } + has_nulls: false, + }) } pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + self.append_inner(array, false) + } + + /// The first value continues the preceding response's final logical range. + pub(super) fn append_continuation( + &mut self, + array: &LargeBinaryArray, + ) -> Result<(), ArrowError> { + self.append_inner(array, true) + } + + fn append_inner( + &mut self, + array: &LargeBinaryArray, + continuation: bool, + ) -> Result<(), ArrowError> { + let rows = self.offsets.len() - 1; + if continuation + && (rows == 0 + || array.is_empty() + || (self.validity[(rows - 1) / 8] & (1 << ((rows - 1) % 8)) != 0) + != array.is_valid(0)) + { + return Err(ArrowError::ComputeError( + "inconsistent nulls in split blob range".into(), + )); + } let offsets = array.value_offsets(); let start = offsets[0]; let length = offsets[array.len()] - start; let total = self.bytes.checked_add(length).ok_or_else(|| { - ArrowError::ComputeError("fetch_blobs result exceeds i64 byte offsets".into()) + ArrowError::ComputeError("blob result exceeds i64 byte offsets".into()) })?; - self.offsets.extend( - offsets[1..] - .iter() - .map(|offset| self.bytes + (*offset - start)), - ); - if let Some(nulls) = array.nulls() { - self.nulls.append_buffer(nulls); - } else { - self.nulls.append_n_non_nulls(array.len()); - } + let skip = usize::from(continuation); + self.offsets + .try_reserve(array.len() - skip) + .map_err(allocation_error)?; + let new_rows = rows + .checked_add(array.len() - skip) + .ok_or_else(|| allocation_error("row count overflow"))?; + let validity_bytes = new_rows / 8 + usize::from(new_rows % 8 != 0); + self.validity + .try_reserve(validity_bytes - self.validity.len()) + .map_err(allocation_error)?; + self.validity.resize(validity_bytes, 0); if length != 0 { + self.values.try_reserve(1).map_err(allocation_error)?; self.values.push_back( array .values() .slice_with_length(start as usize, length as usize), ); } + if continuation { + *self.offsets.last_mut().unwrap() = self.bytes + (offsets[1] - start); + } + self.offsets.extend( + offsets[1 + skip..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + for i in skip..array.len() { + let row = rows + i - skip; + if array.is_valid(i) { + self.validity[row / 8] |= 1 << (row % 8); + } else { + self.has_nulls = true; + } + } self.bytes = total; Ok(()) } - pub(super) fn finish(mut self) -> LargeBinaryArray { + pub(super) fn finish(mut self) -> Result { let values = match self.values.len() { 0 => Buffer::default(), 1 => self.values.pop_front().unwrap(), _ => { - let mut values = MutableBuffer::new(self.bytes as usize); - // Do not retain all decoded batches alongside the final allocation. + let length = usize::try_from(self.bytes).map_err(allocation_error)?; + let mut values = Vec::new(); + values.try_reserve_exact(length).map_err(allocation_error)?; // Drop each source allocation immediately after copying its bytes. while let Some(chunk) = self.values.pop_front() { values.extend_from_slice(&chunk); } - values.into() + Buffer::from_vec(values) } }; - LargeBinaryArray::new( + let rows = self.offsets.len() - 1; + let nulls = self + .has_nulls + .then(|| NullBuffer::new(BooleanBuffer::new(Buffer::from_vec(self.validity), 0, rows))); + Ok(LargeBinaryArray::new( OffsetBuffer::new(self.offsets.into()), values, - self.nulls.finish(), - ) + nulls, + )) } } @@ -85,9 +153,9 @@ mod tests { #[test] fn single_buffer_is_not_copied() { let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); - let mut result = BlobAccumulator::new(3); + let mut result = BlobAccumulator::new(3).unwrap(); result.append(&array).unwrap(); - let output = result.finish(); + let output = result.finish().unwrap(); assert_eq!(output.values().as_ptr(), array.values().as_ptr()); assert_eq!(output, array); } @@ -101,21 +169,27 @@ mod tests { Some(b""), Some(b"beta"), ]); - let mut result = BlobAccumulator::new(6); + let mut result = BlobAccumulator::new(6).unwrap(); result.append(&array.slice(1, 3)).unwrap(); result.append(&array.slice(4, 1)).unwrap(); result.append(&array.slice(2, 2)).unwrap(); assert_eq!( - result.finish(), + result.finish().unwrap(), LargeBinaryArray::from(vec![ Some(b"alpha".as_slice()), None, Some(b""), Some(b"beta"), None, - Some(b""), + Some(b"") ]) ); - assert_eq!(BlobAccumulator::new(0).finish().len(), 0); + assert_eq!(BlobAccumulator::new(0).unwrap().finish().unwrap().len(), 0); + } + + #[test] + fn impossible_capacity_is_an_error() { + assert!(BlobAccumulator::new(usize::MAX).is_err()); + assert!(BlobAccumulator::new(usize::MAX / 2).is_err()); } } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index db68ab290..4959b2842 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1452,8 +1452,13 @@ 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. - /// LanceDB Enterprise tables read through version-pinned [`BlobFile`] handles using - /// HTTP byte-range requests. + /// LanceDB Enterprise uses the batched endpoint when the server advertises + /// support, splitting calls at 1024 ranges and 64 MiB of requested bytes. + /// Individual larger ranges are partitioned and reassembled into one result. + /// Older servers use descriptor queries and [`Self::fetch_blob_files`] range + /// reads. Both protocols read one exact branch and version without changing + /// this handle's checkout. The final materialized output still occupies memory. + /// Errors from an advertised endpoint propagate without switching protocols. /// /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no @@ -1486,10 +1491,14 @@ impl Table { column: impl AsRef, requests: impl IntoIterator, ) -> Result { - let requests = requests.into_iter().collect::>(); - self.inner - .fetch_blob_ranges(column.as_ref(), &requests) - .await + let mut ranges = Vec::new(); + for request in requests { + ranges.try_reserve(1).map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + ranges.push(request); + } + self.inner.fetch_blob_ranges(column.as_ref(), &ranges).await } /// Open lazy [`BlobFile`] handles for the given row ids. diff --git a/rust/lancedb/tests/remote_blob_ranges.rs b/rust/lancedb/tests/remote_blob_ranges.rs new file mode 100644 index 000000000..51c49fe09 --- /dev/null +++ b/rust/lancedb/tests/remote_blob_ranges.rs @@ -0,0 +1,634 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +#![cfg(feature = "remote")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{Array, ArrayRef, LargeBinaryArray, RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use lancedb::Table; +use lancedb::blob::BlobRangeRequest; +use lancedb::remote::{ClientConfig, RetryConfig, TimeoutConfig}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +const MIB: u64 = 1024 * 1024; +const IDENTITY: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const ROUTE: &str = "/v1/table/test/fetch_blob_ranges/"; + +struct Reply { + status: u16, + version: Option, + body: Vec, + declared_extra: usize, + identity: Option<&'static str>, +} + +fn ipc(column: &str, values: ArrayRef) -> Vec { + let batch = RecordBatch::try_from_iter([(column, values)]).unwrap(); + let mut body = Vec::new(); + let mut writer = StreamWriter::try_new(&mut body, &batch.schema()).unwrap(); + // Multiple batches exercise response assembly as well as HTTP partitions. + let mid = batch.num_rows() / 2; + writer.write(&batch.slice(0, mid)).unwrap(); + writer + .write(&batch.slice(mid, batch.num_rows() - mid)) + .unwrap(); + writer.finish().unwrap(); + drop(writer); + body +} + +fn legacy_reply(path: &str, body: &Value, takes: usize) -> Reply { + use arrow_array::{StructArray, UInt8Array, UInt32Array, UInt64Array}; + let version = body["version"] + .as_u64() + .unwrap_or(if takes == 1 { 7 } else { 8 }); + if path.ends_with("/query/") { + assert_eq!(body["branch"], "experiment"); + assert_eq!(body["columns"], json!(["image"])); + let filter = body["filter"].as_str().unwrap(); + let ids = filter + .split_once('(') + .unwrap() + .1 + .trim_end_matches(')') + .split(',') + .map(|id| id.trim().parse::().unwrap()) + .filter(|id| [10, 20, 30, 40].contains(id)) + .rev() + .collect::>(); + let fields = lance_core::datatypes::BLOB_V2_DESC_FIELDS.clone(); + let descriptors = StructArray::new( + fields, + vec![ + Arc::new(UInt8Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from( + ids.iter() + .map(|id| if *id == 40 { 0 } else { 5 }) + .collect::>(), + )), + Arc::new(UInt32Array::from(vec![0; ids.len()])), + Arc::new(StringArray::from(vec![""; ids.len()])), + ], + Some(ids.iter().map(|id| *id != 20).collect()), + ); + let batch = RecordBatch::try_from_iter([ + ("image", Arc::new(descriptors) as ArrayRef), + ("_rowid", Arc::new(UInt64Array::from(ids)) as ArrayRef), + ]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + Reply { + status: 200, + version: Some(version), + body: bytes, + declared_extra: 0, + identity: Some(IDENTITY), + } + } else { + assert!(path.contains("branch=experiment"), "{path}"); + let version = path + .split("version=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .parse::() + .unwrap(); + let range = body["range"] + .as_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap(); + let (start, end) = range.split_once('-').unwrap(); + let start = start.parse::().unwrap(); + let end = end.parse::().unwrap(); + let payload = if version == 8 { b"ALPHA" } else { b"alpha" }; + Reply { + status: 206, + version: Some(version), + body: payload[start..=end].to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + } + } +} + +fn reply(values: Vec>>, version: u64) -> Reply { + Reply { + status: 200, + version: Some(version), + body: ipc( + "value", + Arc::new(LargeBinaryArray::from_iter( + values.iter().map(|v| v.as_deref()), + )), + ), + declared_extra: 0, + identity: Some(IDENTITY), + } +} + +fn byte(row: u64, offset: u64, version: u64) -> u8 { + ((row * 17 + offset % 251 + version) % 251) as u8 +} + +fn serve_ranges(body: &Value, version: u64) -> Reply { + assert_eq!(body["column"], "image"); + let ranges = body["ranges"].as_array().unwrap(); + assert!(ranges.len() <= 1024); + assert!( + ranges + .iter() + .map(|r| r["length"].as_u64().unwrap()) + .sum::() + <= 64 * MIB + ); + let values = ranges + .iter() + .map(|r| { + let row = r["row_id"].as_u64().unwrap(); + let offset = r["offset"].as_u64().unwrap(); + let length = r["length"].as_u64().unwrap(); + (row != 20).then(|| { + (offset..offset + length) + .map(|i| byte(row, i, version)) + .collect() + }) + }) + .collect(); + reply(values, version) +} + +struct Server { + url: String, + calls: Arc>>, + task: tokio::task::JoinHandle<()>, + identities: Arc>>>, +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl Server { + async fn new(handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static) -> Self { + Self::with_capability(handler, Some("1")).await + } + + async fn with_capability( + handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static, + capability: Option<&'static str>, + ) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let calls = Arc::new(Mutex::new(Vec::new())); + let captured = calls.clone(); + let identities = Arc::new(Mutex::new(Vec::new())); + let captured_identities = identities.clone(); + let task = tokio::spawn(async move { + let mut fetches = 0; + let mut takes = 0; + loop { + let (socket, _) = listener.accept().await.unwrap(); + let captured = captured.clone(); + let result = tokio::time::timeout(Duration::from_secs(20), async { + let mut socket = BufReader::new(socket); + let mut line = String::new(); + socket.read_line(&mut line).await?; + let path = line.split_whitespace().nth(1).unwrap().to_string(); + let method = line.split_whitespace().next().unwrap().to_string(); + let mut range = String::new(); + let mut length = 0; + let mut identity = None; + loop { + line.clear(); + socket.read_line(&mut line).await?; + assert!(line.len() <= 16384); + if line == "\r\n" { break; } + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse::().unwrap(); + } + if name.eq_ignore_ascii_case("x-lancedb-query-snapshot") { identity = Some(value.trim().to_owned()); } + if name.eq_ignore_ascii_case("range") { range = value.trim().to_string(); } + } + } + assert!(length <= 256 * 1024); + let mut bytes = vec![0; length]; + socket.read_exact(&mut bytes).await?; + let body = if method == "GET" { json!({"range": range}) } else if bytes.is_empty() { json!({}) } else { serde_json::from_slice(&bytes).unwrap() }; + captured.lock().unwrap().push((path.clone(), body.clone())); + let response = if path == "/v1/table/test/describe/" { + Reply { status: 200, version: None, body: serde_json::to_vec(&json!({"version": 8, "schema": {"fields": []}})).unwrap(), declared_extra: 0, identity: None } + } else if path == "/v1/table/test/branches/list/" { + Reply { status: 200, version: None, body: br#"{"branches":{"experiment":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#.to_vec(), declared_extra: 0, identity: None } + } else if capability != Some("1") { + assert_ne!(path, ROUTE, "unknown capability must select old routes first"); + takes += usize::from(path.ends_with("/query/")); + legacy_reply(&path, &body, takes) + } else { + assert_eq!(path, ROUTE, "unexpected legacy or fallback request"); + fetches += 1; + captured_identities.lock().unwrap().push(identity); + handler(&body, fetches) + }; + if response.status == 0 { return Ok::<_, std::io::Error>(()); } + let version = response.version.map(|v| format!("x-lancedb-version: {v}\r\n")).unwrap_or_default(); + let capability = if path.ends_with("/describe/") { capability.map(|value| format!("x-lancedb-blob-ranges: {value}\r\n")).unwrap_or_default() } else { String::new() }; + let content_type = if path == ROUTE || path.ends_with("/query/") { "application/vnd.apache.arrow.stream" } else { "application/json" }; + let content_range = if method == "GET" { format!("Content-Range: {}/5\r\n", body["range"].as_str().unwrap().replace("bytes=", "bytes ")) } else { String::new() }; + let identity = if path == ROUTE { response.identity.map(|id| format!("x-lancedb-query-snapshot: {id}\r\n")).unwrap_or_default() } else { String::new() }; + let header = format!("HTTP/1.1 {} Response\r\nContent-Type: {content_type}\r\nphalanx-version: 1.13.0-beta.0\r\n{capability}{version}{identity}{content_range}Content-Length: {}\r\nConnection: close\r\n\r\n", response.status, response.body.len() + response.declared_extra); + socket.write_all(header.as_bytes()).await?; + for chunk in response.body.chunks(8192) { socket.write_all(chunk).await?; } + socket.shutdown().await?; + Ok(()) + }).await; + // A client rejecting a malformed schema may close the body early. + assert!(result.is_ok(), "loopback request timed out"); + } + }); + Self { + url, + calls, + task, + identities, + } + } + + async fn table(&self, version: Option) -> Table { + let db = lancedb::connect("db://dev") + .api_key("fake") + .region("us-east-1") + .host_override(&self.url) + .client_config(ClientConfig { + retry_config: RetryConfig { + retries: Some(2), + connect_retries: Some(2), + read_retries: Some(2), + ..Default::default() + }, + timeout_config: TimeoutConfig { + timeout: Some(Duration::from_secs(30)), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let mut open = db.open_table("test").branch("experiment"); + if let Some(version) = version { + open = open.version(version); + } + open.execute().await.unwrap() + } +} + +#[tokio::test] +async fn public_ranges_work_on_old_routes_only_servers() { + for capability in [None, Some("0"), Some("2")] { + for checkout in [None, Some(3)] { + let server = Server::with_capability( + |_, _| panic!("new endpoint must not be requested"), + capability, + ) + .await; + let table = server.table(checkout).await; + let cloned = table.clone(); + let ranges = [ + BlobRangeRequest::new(10, 1, 3), + BlobRangeRequest::new(20, 0, 1), + BlobRangeRequest::new(40, 0, 0), + BlobRangeRequest::new(10, 5, 0), + BlobRangeRequest::new(10, 1, 3), + ]; + let result = cloned.fetch_blob_ranges("image", ranges).await.unwrap(); + assert_eq!( + result, + LargeBinaryArray::from(vec![ + Some(b"lph".as_slice()), + None, + Some(b"".as_slice()), + Some(b"".as_slice()), + Some(b"lph".as_slice()) + ]) + ); + let result = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!( + result.value(0), + if checkout.is_none() { b"A" } else { b"a" } + ); + for ranges in [ + vec![BlobRangeRequest::new(10, 4, 2)], + vec![BlobRangeRequest::new(99, 0, 1)], + ] { + assert!(matches!( + table.fetch_blob_ranges("image", ranges).await.unwrap_err(), + lancedb::Error::InvalidInput { .. } + )); + } + assert!( + !server + .calls + .lock() + .unwrap() + .iter() + .any(|(path, _)| path == ROUTE) + ); + } + } +} + +#[tokio::test] +async fn public_ranges_keep_order_nulls_and_snapshot_without_pinning_live_handle() { + for checkout in [None, Some(3)] { + let server = Server::new(move |body, call| { + assert_eq!(body["branch"], "experiment"); + let expected = checkout.or((call > 1 && call < 3).then_some(7)); + assert_eq!(body["version"].as_u64(), expected); + serve_ranges( + body, + body["version"] + .as_u64() + .unwrap_or(if call == 1 { 7 } else { 8 }), + ) + }) + .await; + let table = server.table(checkout).await; + let mut requests = (0..1025) + .map(|i| BlobRangeRequest::new(if i % 9 == 0 { 20 } else { 10 + i % 7 }, i, i % 4)) + .collect::>(); + requests.extend([ + BlobRangeRequest::new(10, 0, 0), + BlobRangeRequest::new(10, 2, 3), + BlobRangeRequest::new(10, 2, 3), + ]); + let result = table + .fetch_blob_ranges("image", requests.clone()) + .await + .unwrap(); + assert_eq!(result.len(), requests.len()); + for (i, request) in requests.iter().enumerate() { + assert_eq!(result.is_null(i), request.row_id == 20); + if request.row_id != 20 { + let expected = (request.offset..request.offset + request.length) + .map(|j| byte(request.row_id, j, checkout.unwrap_or(7))) + .collect::>(); + assert_eq!(result.value(i), expected); + } + } + let next = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!(next.value(0), [byte(10, 0, checkout.unwrap_or(8))]); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); + } +} + +#[tokio::test] +async fn public_ranges_partition_bytes_and_reassemble_large_single_range() { + let server = Server::new(|body, call| { + assert_eq!(body["version"].as_u64(), (call > 1).then_some(7)); + serve_ranges(body, 7) + }) + .await; + let table = server.table(None).await; + let requests = [ + BlobRangeRequest::new(10, 3, 33 * MIB), + BlobRangeRequest::new(30, 7, 33 * MIB), + BlobRangeRequest::new(40, 11, 70 * MIB), + BlobRangeRequest::new(20, 0, u64::MAX), + ]; + let result = table.fetch_blob_ranges("image", requests).await.unwrap(); + assert_eq!(result.len(), 4); + for (i, request) in requests[..3].iter().enumerate() { + assert_eq!(result.value_length(i) as u64, request.length); + assert!( + result + .value(i) + .iter() + .enumerate() + .all(|(j, value)| *value == byte(request.row_id, request.offset + j as u64, 7)) + ); + } + assert!(result.is_null(3)); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); +} + +#[tokio::test] +async fn public_ranges_reject_malformed_responses_and_http_failures_without_fallback() { + for case in 0..16 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + // Fail after one successful partition to prove no partial success. + if call == 1 { + return response; + } + match case { + 0 => response.body = ipc("value", Arc::new(StringArray::from(vec!["bad"]))), + 1 => { + response.body = ipc( + "wrong", + Arc::new(LargeBinaryArray::from(vec![Some(b"a".as_slice())])), + ) + } + 2 => response = reply(vec![], 7), + 3 => response = reply(vec![Some(vec![1]), Some(vec![2])], 7), + 4 => response.body.truncate(response.body.len() - 8), + 5 => response.body.truncate(response.body.len() / 2), + 6 => response.declared_extra = 10, + 7 => response = reply(vec![Some(vec![])], 7), + 8 => response.version = None, + 9 => response.version = Some(8), + 10..=14 => { + response.status = [401, 403, 404, 429, 500][case - 10]; + response.body = b"ordinary failure".to_vec(); + } + 15 => response.status = 0, + _ => unreachable!(), + } + response + }) + .await; + let table = server.table(None).await; + let requests = vec![BlobRangeRequest::new(10, 0, 1); 1025]; + assert!( + table.fetch_blob_ranges("image", requests).await.is_err(), + "case {case}" + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2, + "case {case}" + ); + } +} + +#[tokio::test] +async fn public_ranges_validate_locally_and_propagate_server_range_errors() { + let server = Server::new(|_, _| Reply { + status: 400, + version: None, + body: b"range exceeds blob size or missing row".to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + assert_eq!(table.fetch_blob_ranges("image", []).await.unwrap().len(), 0); + assert!( + table + .fetch_blob_ranges("image", [BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err() + .to_string() + .contains("overflows u64") + ); + assert_eq!(server.calls.lock().unwrap().len(), before); + let error = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 9, 2)]) + .await + .unwrap_err(); + assert!(matches!(error, lancedb::Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds")); +} + +#[tokio::test] +async fn public_ranges_require_original_identity_on_every_partition() { + for huge in [false, true] { + for case in 0..5 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + if call == 2 { + response.identity = match case { + 0 => None, // Old serving node ignores the precondition. + 1 => Some("invalid"), + _ => Some( + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ), + }; + if case == 3 || case == 4 { + response.status = if case == 3 { 400 } else { 404 }; + response.body = + b"query snapshot identity mismatch: gone or replaced".to_vec(); + } else { + // Identity verification must win over malformed payload. + response.body = b"not Arrow".to_vec(); + } + } + response + }) + .await; + let table = server.table(None).await; + let requests = if huge { + vec![BlobRangeRequest::new(10, 0, 64 * MIB + 1)] + } else { + vec![BlobRangeRequest::new(10, 0, 1); 1025] + }; + let error = table + .fetch_blob_ranges("image", requests) + .await + .unwrap_err(); + if case < 3 { + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + } else if case == 3 { + assert!( + matches!(error, lancedb::Error::InvalidInput { .. }), + "{error}" + ); + } else { + assert!( + matches!(error, lancedb::Error::TableNotFound { .. }), + "{error}" + ); + } + assert_eq!( + *server.identities.lock().unwrap(), + [None, Some(IDENTITY.into())] + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2 + ); + } + } +} + +#[tokio::test] +async fn public_ranges_cannot_establish_identity_from_numeric_version_or_describe() { + for identity in [None, Some("invalid"), Some("v2:unsupported")] { + let server = Server::new(move |_, call| { + assert_eq!(call, 1, "no failure fallback, replay or second partition"); + let mut response = reply(vec![Some(b"A".to_vec()); 1024], 7); + response.identity = identity; + response.body = b"not Arrow".to_vec(); + response + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + let error = table + .fetch_blob_ranges("image", vec![BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap_err(); + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(server.calls.lock().unwrap().len(), before + 1); + } +} From cababaecf08a12bdd97a157cac16751c13350274 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 06:22:35 +0800 Subject: [PATCH 097/203] feat(remote): discover server builds and retain error provenance (#4999) Remote callers can use `db.server_info()` in Rust and Python, including synchronous and asynchronous Python connections, to identify the responding server without submitting a query or Job. Typed results describe the query-node build, component versions, Function protocol and configured images. Older servers without the endpoint return an explicit unsupported error. REST and Flight errors retain the reported build in diagnostic text and Rust `RemoteErrorMetadata.server`. Typed table/job-not-found errors preserve their HTTP source and classification, including the schema-cache path; masked REST errors can obtain provenance from the response header. Unknown build information stays absent. The matching native Python SDK was exercised against a real localhost server (`8829b074` client / `43920fa` server): sync/async discovery, both SQL version forms and actual REST/Flight error provenance passed. The product files match this branch; private validation drivers are excluded. Focused coverage includes typed 404 errors, masked errors, and the public schema-cache regression. Deployment and published-package acceptance remain separate. Server counterpart: https://github.com/lancedb/sophon/pull/10234. Related: ENT-3565. --- docs/src/python/python.md | 12 +++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/db.py | 23 +++++ python/python/lancedb/remote/db.py | 9 ++ python/python/lancedb/server_info.py | 33 +++++++ python/python/tests/test_remote_db.py | 87 +++++++++++++++++ python/src/connection.rs | 8 ++ rust/lancedb/src/connection.rs | 18 ++++ rust/lancedb/src/database.rs | 7 ++ rust/lancedb/src/error.rs | 77 ++++++++++++--- rust/lancedb/src/lib.rs | 1 + rust/lancedb/src/remote/db.rs | 133 +++++++++++++++++++++++++- rust/lancedb/src/remote/sql.rs | 13 ++- rust/lancedb/src/remote/sql_test.rs | 47 +++++++++ rust/lancedb/src/remote/table.rs | 60 +++++++++--- rust/lancedb/src/server_info.rs | 56 +++++++++++ 16 files changed, 553 insertions(+), 32 deletions(-) create mode 100644 python/python/lancedb/server_info.py create mode 100644 rust/lancedb/src/server_info.rs diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 0e7164c1a..058f2529a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -37,6 +37,18 @@ embedding_functions`. Prefer keyword arguments for optional parameters. ::: lancedb.db.DBConnection +Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection) +to include the responding server's release, Git revision, build date and Function +runtime information in a bug report. It returns a JSON-compatible dictionary and +does not submit a query or job. Configured images are distinct from the version +of an already running job. During a rolling upgrade, successive requests can +reach different query-node builds. Embedded connections and older servers without +the endpoint raise `NotImplementedError`. + +::: lancedb.server_info.ServerBuildInfo + +::: lancedb.server_info.ServerInfo + 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 diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 956806cde..ffdd68e5f 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -185,6 +185,7 @@ class Connection(object): limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead async def open_job(self, job_id: str) -> Job: ... + async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( self, request_json: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 59fa5b4c6..b4e5c6182 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -58,6 +58,7 @@ from lance_namespace import ( from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ +from .server_info import ServerInfo from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore from .functions import FunctionVersion, FunctionDefinition from .graph import ( @@ -1476,6 +1477,22 @@ class DBConnection(EnforceOverrides): ) ) + def server_info(self) -> ServerInfo: + """Return the responding server's build and Function runtime information. + + This call submits no query, Function, or job. The response is a + JSON-compatible dictionary, convenient to include in a bug report:: + + info = db.server_info() + print(info["query_node"]) # release, git_sha, build_date + + Requires System Usage permission. Embedded connections and older + servers without this endpoint raise ``NotImplementedError``. + Different calls can reach different builds during a rolling upgrade. + Configured images do not identify the version of a running job. + """ + raise NotImplementedError("Server build discovery requires a remote connection") + def list_gpu_classes(self) -> List[GpuClass]: """List the operator-configured Function GPU classes. @@ -3653,6 +3670,12 @@ class AsyncConnection(object): """ return _opened_job(await self._inner.open_job(job_id)) + async def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return json.loads(await self._inner.server_info()) + async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See [DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes]. diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index a06af5d62..911766674 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -4,6 +4,8 @@ from __future__ import annotations +from lancedb.server_info import ServerInfo + from dataclasses import replace from datetime import timedelta import json @@ -966,6 +968,13 @@ class RemoteDBConnection(DBConnection): """ return Job(LOOP.run(self._conn.open_job(job_id))) + @override + def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return LOOP.run(self._conn.server_info()) + @override def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/server_info.py b/python/python/lancedb/server_info.py new file mode 100644 index 000000000..d53c6c380 --- /dev/null +++ b/python/python/lancedb/server_info.py @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Remote server build information returned as JSON-compatible dictionaries.""" + +from typing import Optional, TypedDict + + +class ServerBuildInfo(TypedDict): + """Immutable identity compiled into a server executable.""" + + release: str + git_sha: str + build_date: Optional[str] + + +class ServerInfo(TypedDict): + """The responding query node and its configured Function runtime. + + ``query_node`` can be ``None`` when the executable has no build metadata. + ``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling + upgrade, separate requests can reach different query-node builds. + Configured images do not establish the version of a running job. + """ + + query_node: Optional[ServerBuildInfo] + lance_version: str + lancedb_version: str + function_worker_protocol_version: int + configured_query_node_image: Optional[str] + configured_job_worker_image: Optional[str] + configured_sql_job_image: Optional[str] + configured_gpu_worker_image: Optional[str] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 4f707f041..ca2516fda 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -6539,6 +6539,93 @@ def test_remote_job_handle_reports_its_own_detail(): } +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("known_build", [False, True]) +@pytest.mark.asyncio +async def test_remote_server_info(is_async, known_build): + requests = [] + expected = { + "query_node": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + } + if known_build + else None, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_query_node_image": "example.invalid/query:configured", + "configured_job_worker_image": "example.invalid/cpu:configured", + "configured_sql_job_image": "example.invalid/cli:configured", + "configured_gpu_worker_image": "example.invalid/worker:configured", + } + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(expected).encode()) + + if is_async: + async with mock_lancedb_connection_async(handler) as db: + actual = await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + actual = db.server_info() + + assert actual == expected + assert json.loads(json.dumps(actual)) == expected + assert requests == [("GET", "/v1/server/info")] + + +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("status", [404, 403]) +@pytest.mark.asyncio +async def test_remote_server_info_errors(is_async, status): + requests = [] + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "error": "discovery unavailable", + "server": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }, + } + ).encode() + ) + + expected_error = NotImplementedError if status == 404 else HttpError + with pytest.raises(expected_error) as caught: + if is_async: + async with mock_lancedb_connection_async(handler) as db: + await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + db.server_info() + + if status == 404: + assert "/v1/server/info" in str(caught.value) + else: + # Permission responses do not carry the input-error classifier header. + # The native HTTP error and Python conversion must retain provenance. + assert "discovery unavailable" in str(caught.value) + assert "1.2.3" in str(caught.value) + assert "0123456789ab" in str(caught.value) + assert "2024-01-01T00:00:00Z" in str(caught.value) + assert caught.value.status_code == 403 + assert requests == [("GET", "/v1/server/info")] + + @pytest.mark.parametrize("is_async", [False, True]) @pytest.mark.asyncio async def test_remote_list_gpu_classes(is_async): diff --git a/python/src/connection.rs b/python/src/connection.rs index 1a99c1372..2bf01a6f7 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1285,6 +1285,14 @@ impl Connection { )) } + pub fn server_info(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let info = inner.server_info().await.infer_error()?; + serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string())) + }) + } + pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index fa35dc459..cc398e32b 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -1303,6 +1303,24 @@ impl Connection { self.database().list_gpu_classes().await } + /// Read the responding server's build and Function runtime information. + /// + /// This request does not submit a query, Function, or job. It requires + /// System Usage permission. Embedded databases and older servers without + /// `GET /v1/server/info` return [`Error::NotSupported`]. During a rolling + /// upgrade, separate requests can report different query-node builds. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let info = db.server_info().await?; + /// println!("{:?}", info.query_node); + /// # Ok(()) + /// # } + /// ``` + pub async fn server_info(&self) -> Result { + self.database().server_info().await + } + /// List server-side jobs across the database's tables. /// /// Results are fetched lazily, one page at a time. See [`Listing`] diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 7b4859faa..23ed9fc3d 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -479,6 +479,13 @@ pub trait Database: async fn list_gpu_classes(&self) -> Result> { gpu_class_catalog_not_supported() } + + /// Read the responding remote server's build identity. + async fn server_info(&self) -> Result { + Err(crate::Error::NotSupported { + message: "Server build discovery requires a remote LanceDB connection".into(), + }) + } /// Create a materialized view through a remote catalog and return its /// initial-population job. Local connections use the native declaration /// path directly. diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 89ad7a229..6aed94d71 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -64,6 +64,8 @@ impl RemoteResourceIdentity { #[derive(Debug, Clone, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RemoteErrorMetadata { + /// Build of the executable that produced the error, when reported. + pub server: Option, /// Machine-readable input error code, when available. pub error_code: Option, /// SQL job that failed, when the request ran in an isolated job. @@ -84,6 +86,8 @@ impl RemoteErrorMetadata { .map(str::to_owned) }; Self { + server: header("x-lancedb-server-build") + .and_then(|value| serde_json::from_str(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header("x-lancedb-sql-job-id"), job_request_id: header("x-job-request-id"), @@ -119,7 +123,7 @@ pub(crate) fn parse_flight_resource_identity(value: &str) -> Option, @@ -131,17 +135,28 @@ impl HttpErrorSource { pub(crate) fn new( message: String, response_body: Option<&str>, - metadata: RemoteErrorMetadata, + mut metadata: RemoteErrorMetadata, ) -> Self { let details = response_body.and_then(parse_http_error_details); + let body = + response_body.and_then(|body| serde_json::from_str::(body).ok()); + if metadata.server.is_none() { + metadata.server = body + .as_ref() + .and_then(|body| body.get("server").cloned()) + .and_then(|server| serde_json::from_value(server).ok()); + } let message = if metadata.error_code.is_some() { - response_body - .and_then(|body| serde_json::from_str::(body).ok()) + body.as_ref() .and_then(|body| body.get("error")?.as_str().map(str::to_owned)) .unwrap_or(message) } else { message }; + let message = match &metadata.server { + Some(server) => format!("{message} [server: {server}]"), + None => message, + }; Self { message, details, @@ -317,6 +332,18 @@ impl Display for JobFailure { } } +fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static)) -> String { + #[cfg(feature = "remote")] + if let Some(server) = _source + .downcast_ref::() + .and_then(Error::remote_error_metadata) + .and_then(|metadata| metadata.server.as_ref()) + { + return format!(" [server: {server}]"); + } + String::new() +} + #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { @@ -324,7 +351,7 @@ pub enum Error { InvalidTableName { name: String, reason: String }, #[snafu(display("Invalid input, {message}"))] InvalidInput { message: String }, - #[snafu(display("Table '{name}' was not found"))] + #[snafu(display("Table '{name}' was not found{}", server_build_suffix(source.as_ref())))] TableNotFound { name: String, source: BoxError }, #[snafu(display( "Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}" @@ -385,8 +412,8 @@ pub enum Error { }, #[snafu(display("Job{} was cancelled", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobCancelled { job_id: Option }, - #[snafu(display("Job '{job_id}' was not found"))] - JobNotFound { job_id: String }, + #[snafu(display("Job '{job_id}' was not found{}", server_build_suffix(source.as_ref())))] + JobNotFound { job_id: String, source: BoxError }, // 3rd party / external errors #[snafu(display("object_store error: {source}"))] @@ -576,7 +603,7 @@ impl Error { match self { Self::Http { status_code, .. } => *status_code, Self::Retry { status_code, .. } => *status_code, - Self::TableNotFound { source, .. } => { + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => { source.downcast_ref::().and_then(Self::status_code) } Self::JobFailed { failure, .. } => { @@ -623,7 +650,7 @@ impl Error { Self::Retry { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), - Self::TableNotFound { source, .. } => source + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), Self::JobFailed { failure, .. } => failure @@ -635,9 +662,35 @@ impl Error { } } - /// A copy of an error that other partitions of a DataFusion plan still hold. - /// Only an interrupted response can be copied, because it shares its source. - fn clone_shared(&self) -> Option { + /// Copy supported errors without flattening sources retained by a shared plan + /// or schema cache. + pub(crate) fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + match self { + Self::Http { + source, + request_id, + status_code, + } => { + return source + .downcast_ref::() + .map(|source| Self::Http { + source: Box::new(source.clone()), + request_id: request_id.clone(), + status_code: *status_code, + }); + } + Self::TableNotFound { name, source } => { + return source + .downcast_ref::() + .and_then(Self::clone_shared) + .map(|source| Self::TableNotFound { + name: name.clone(), + source: Box::new(source), + }); + } + _ => {} + } #[cfg(feature = "remote")] if let Self::ResponseInterrupted { request_id, diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 0f02d90cf..9f800d593 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -216,6 +216,7 @@ pub mod query; pub mod remote; pub mod rerankers; pub mod secrets; +pub mod server_info; pub mod sql; pub mod storage_integration; pub mod table; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 578e3bbab..92523ec34 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1242,16 +1242,39 @@ impl Database for RemoteDatabase { let handle = super::job::RemoteJob::new(self.client.clone(), job_id.to_string()); match crate::job::JobHandle::describe(&handle).await { Ok(description) => Ok(Job::opened(Box::new(handle), description)), - Err(Error::Http { - status_code: Some(StatusCode::NOT_FOUND), - .. - }) => Err(Error::JobNotFound { + Err( + error @ Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }, + ) => Err(Error::JobNotFound { job_id: job_id.to_string(), + source: Box::new(error), }), Err(err) => Err(err), } } + async fn server_info(&self) -> Result { + let req = self.client.get("/v1/server/info"); + let (request_id, response) = self.client.send(req).await?; + let response = match self.client.check_response(&request_id, response).await { + Ok(response) => response, + Err(Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }) => { + return Err(Error::NotSupported { + message: "Server build discovery requires a newer LanceDB server; \ + GET /v1/server/info returned 404 Not Found" + .into(), + }); + } + Err(error) => return Err(error), + }; + response.json().await.err_to_http(request_id) + } + async fn list_gpu_classes(&self) -> Result> { #[derive(serde::Deserialize)] struct Response { @@ -4155,6 +4178,106 @@ mod tests { } } + #[tokio::test] + async fn test_server_info_preserves_remote_provenance() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/server/info"); + http::Response::builder().status(200).body(serde_json::json!({ + "query_node": { "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" }, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_gpu_worker_image": "example.invalid/worker:configured", + "future_component": "ignored" + }).to_string()).unwrap() + }); + let info = conn.server_info().await.unwrap(); + let build = info.query_node.unwrap(); + assert_eq!(build.release, "1.2.3"); + assert_eq!(build.git_sha, "0123456789ab"); + assert_eq!(build.build_date.as_deref(), Some("2024-01-01T00:00:00Z")); + assert_eq!(info.function_worker_protocol_version, 25); + assert_eq!( + info.configured_gpu_worker_image.as_deref(), + Some("example.invalid/worker:configured") + ); + } + + #[tokio::test] + async fn test_server_info_error_provenance_survives_classification() { + for target in ["table", "job", "masked"] { + let conn = Connection::new_with_handler(move |_| { + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + if target == "masked" { + http::Response::builder() + .status(500) + .header("x-lancedb-server-build", server.to_string()) + .body("Internal server error".to_string()) + .unwrap() + } else { + http::Response::builder() + .status(404) + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let error = match target { + "table" => conn.open_table("missing").execute().await.unwrap_err(), + "job" => conn.open_job("missing").await.unwrap_err(), + _ => conn.server_info().await.unwrap_err(), + }; + match target { + "table" => assert!(matches!(&error, Error::TableNotFound { .. })), + "job" => assert!(matches!(&error, Error::JobNotFound { .. })), + _ => assert_eq!( + error.status_code(), + Some(http::StatusCode::INTERNAL_SERVER_ERROR) + ), + } + let server = error + .remote_error_metadata() + .unwrap() + .server + .as_ref() + .unwrap(); + assert_eq!(server.git_sha, "0123456789ab"); + assert_eq!(server.release, "1.2.3"); + let message = error.to_string(); + assert!(message.contains("0123456789ab"), "{message}"); + assert!(message.contains("2024-01-01T00:00:00Z"), "{message}"); + } + } + + #[tokio::test] + async fn test_server_info_distinguishes_unsupported_from_denied() { + for status in [404, 403] { + let conn = Connection::new_with_handler(move |_| { + http::Response::builder() + .status(status) + .body("unavailable") + .unwrap() + }); + let error = conn.server_info().await.unwrap_err(); + if status == 404 { + assert!( + matches!(error, Error::NotSupported { message } if message.contains("/v1/server/info")) + ); + } else { + assert!(matches!( + error, + Error::Http { + status_code: Some(http::StatusCode::FORBIDDEN), + .. + } + )); + } + } + } + #[tokio::test] async fn test_list_gpu_classes_reports_configured_hardware() { let conn = Connection::new_with_handler(|request| { @@ -4368,7 +4491,7 @@ mod tests { }); let err = conn.open_job("nope").await.unwrap_err(); assert!( - matches!(&err, Error::JobNotFound { job_id } if job_id == "nope"), + matches!(&err, Error::JobNotFound { job_id, .. } if job_id == "nope"), "{err:?}" ); } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 949b078e3..9c34f8f90 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -1797,6 +1797,11 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .map(str::to_owned) }; let metadata = crate::error::RemoteErrorMetadata { + server: status + .metadata() + .get_bin("x-lancedb-server-build-bin") + .and_then(|value| value.to_bytes().ok()) + .and_then(|value| serde_json::from_slice(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header(SQL_JOB_ID_METADATA_KEY), job_request_id: header("x-job-request-id"), @@ -1805,8 +1810,12 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .and_then(crate::error::parse_flight_resource_identity), }; let sql_job_id = metadata.job_id.clone(); + let mut message = status.message().to_owned(); + if let Some(server) = &metadata.server { + message.push_str(&format!(" [server: {server}]")); + } let error = Error::Sql { - message: status.message().into(), + message: message.clone(), request_id: request_id.into(), grpc_code: status.code() as i32, metadata: Box::new(metadata), @@ -1816,7 +1825,7 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro job_id: Some(sql_job_id.clone()), failure: Box::new(JobFailure { phase: None, - message: Some(status.message().into()), + message: Some(message), traceback: None, retryable: None, sql_job_id: Some(sql_job_id), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d94defac4..eb994f7dd 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -33,6 +33,53 @@ use crate::remote::table::RemoteTable; use crate::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; use crate::table::BaseTable; +#[test] +fn server_info_survives_flight_error_and_job_wrapping() { + for with_job in [false, true] { + let mut status = tonic::Status::invalid_argument("invalid query"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "invalid_query".parse().unwrap()); + let build = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" + }) + .to_string(); + status.metadata_mut().insert_bin( + "x-lancedb-server-build-bin", + tonic::metadata::MetadataValue::from_bytes(build.as_bytes()), + ); + if with_job { + status + .metadata_mut() + .insert(SQL_JOB_ID_METADATA_KEY, "job-original".parse().unwrap()); + } + let error = sql_status_error("request-original", &status); + let text = error.to_string(); + assert!(text.contains("invalid query"), "{text}"); + assert!(text.contains("1.2.3"), "{text}"); + assert!(text.contains("0123456789ab"), "{text}"); + assert!(text.contains("2024-01-01T00:00:00Z"), "{text}"); + assert_eq!( + error.remote_error_metadata().unwrap().error_code.as_deref(), + Some("invalid_query") + ); + match error { + Error::JobFailed { job_id, .. } if with_job => { + assert_eq!(job_id.as_deref(), Some("job-original")) + } + Error::Sql { + grpc_code, + request_id, + .. + } if !with_job => { + assert_eq!(grpc_code, tonic::Code::InvalidArgument as i32); + assert_eq!(request_id, "request-original"); + } + other => panic!("unexpected error classification: {other}"), + } + } +} + #[derive(Debug, Default)] struct DelayedHeaderProvider { delay_next: AtomicBool, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index fdb547afa..dcceb4260 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1939,7 +1939,7 @@ fn base_media_type(content_type: &str) -> &str { fn unwrap_shared_error(arc: Arc) -> Error { match Arc::try_unwrap(arc) { Ok(err) => err, - Err(arc) => match &*arc { + Err(arc) => arc.clone_shared().unwrap_or_else(|| match &*arc { Error::TableNotFound { name, source } => Error::TableNotFound { name: name.clone(), source: source.to_string().into(), @@ -1947,7 +1947,7 @@ fn unwrap_shared_error(arc: Arc) -> Error { _ => Error::Runtime { message: arc.to_string(), }, - }, + }), } } @@ -1971,17 +1971,8 @@ async fn fetch_schema( let (request_id, response) = client.send_with_retry(request, None, true).await?; - if response.status() == StatusCode::NOT_FOUND { - let body = response.text().await.ok().unwrap_or_default(); - return Err(Error::TableNotFound { - name: table_name.to_string(), - source: Box::new(Error::Http { - source: body.into(), - request_id, - status_code: Some(StatusCode::NOT_FOUND), - }), - }); - } + let response = + RemoteTable::::handle_table_not_found(table_name, response, &request_id).await?; let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); @@ -4922,6 +4913,49 @@ mod tests { assert_eq!(schema, expected); } + #[tokio::test] + async fn test_server_info_survives_schema_cache_errors() { + let expected = crate::server_info::ServerBuildInfo { + release: "1.2.3".into(), + git_sha: "0123456789ab".into(), + build_date: Some("2024-01-01T00:00:00Z".into()), + }; + for header_only in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + let response = http::Response::builder().status(404); + if header_only { + response + .header("x-lancedb-server-build", server.to_string()) + .body("missing".to_string()) + .unwrap() + } else { + response + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let original = Arc::new(table.schema().await.unwrap_err()); + // Keep another reader's reference alive to exercise the shared result. + let shared = unwrap_shared_error(original.clone()); + for error in [original.as_ref(), &shared] { + assert!(matches!(error, Error::TableNotFound { name, .. } if name == "my_table")); + assert_eq!(error.status_code(), Some(StatusCode::NOT_FOUND)); + assert_eq!( + error + .remote_error_metadata() + .and_then(|metadata| metadata.server.as_ref()), + Some(&expected), + ); + assert!(error.to_string().contains("0123456789ab")); + } + } + } + #[tokio::test] async fn test_count_rows() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/server_info.rs b/rust/lancedb/src/server_info.rs new file mode 100644 index 000000000..48daf508b --- /dev/null +++ b/rust/lancedb/src/server_info.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Remote server provenance for diagnostics without submitting a query or job. + +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Immutable identity compiled into a server executable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerBuildInfo { + /// Release of this executable. + pub release: String, + /// Git revision used to build the executable. + pub git_sha: String, + /// UTC RFC 3339 build timestamp, when known. + pub build_date: Option, +} + +impl fmt::Display for ServerBuildInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} (git {}, built {})", + self.release, + self.git_sha, + self.build_date.as_deref().unwrap_or("unknown") + ) + } +} + +/// Identity of the query node that answered a discovery request. +/// +/// Different requests can reach different versions during a rolling upgrade. +/// Configured images do not establish which version a running job uses. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerInfo { + /// The responding executable; absent if its identity was not initialized. + pub query_node: Option, + /// Lance library linked into the responding server. + pub lance_version: String, + /// LanceDB library linked into the responding server. + pub lancedb_version: String, + /// Function worker protocol supported by this server build. + pub function_worker_protocol_version: u16, + /// Configured query-node image, not an independently observed digest. + pub configured_query_node_image: Option, + /// Default CPU/job worker image; existing jobs can retain earlier pins. + pub configured_job_worker_image: Option, + /// CLI image configured for newly launched SQL jobs. + pub configured_sql_job_image: Option, + /// Configured GPU worker image, not an observation of a running worker. + pub configured_gpu_worker_image: Option, +} From f863ea5e0858f7a081206488ee7e33ec4e34d88d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 06:34:38 +0800 Subject: [PATCH 098/203] feat(rust): support cross-table blob copies in DataFusion (#4976) `INSERT INTO target SELECT ... FROM source` currently cannot copy Blob v2 descriptors into an independent table. This enables copies from a single native source snapshot through projections, filters, sorting, and limits, while preserving descriptor queries such as `SELECT payload.size`. Source-owned payloads become target-owned data, so subsequent source mutation, compaction, or deletion does not invalidate the copy; nested fields retain their named identity across metadata differences, child reordering, scalar casts, and nullable parents. External blobs remain URI/range references under the destination's existing authorization policy: a destination that independently registers the matching external base accepts the copy, while an unregistered destination rejects it without committing. Source base registrations are not transferred, and `allow_external_blob_outside_bases` is not relaxed. JOIN, UNION, aggregation, and computed descriptors are rejected during planning. This addresses the DataFusion cross-table copy portion of OSS-696; remote/cloud execution and Realtime/MemWAL remain outside this support boundary. Local acceptance covers 15 passing DataFusion Blob integration cases, including byte reads after physical source-directory deletion, authorized and unauthorized External ranges, and a source-read failure after an earlier partition has written an uncommitted data file, with both the live destination and an independently reopened manifest unchanged. Existing regression evidence also includes 195 DataFusion unit tests and 59 Blob integration tests. Rust formatting and whitespace checks passed. Remote-feature builds, cloud/S3 execution, clippy, and the full workspace suite were not run. --- rust/lancedb/src/table/datafusion.rs | 99 ++- .../src/table/datafusion/blob_materialize.rs | 615 +++++++++++++++ rust/lancedb/src/table/datafusion/insert.rs | 4 + rust/lancedb/tests/datafusion_blob_schema.rs | 707 +++++++++++++++++- 4 files changed, 1380 insertions(+), 45 deletions(-) create mode 100644 rust/lancedb/src/table/datafusion/blob_materialize.rs diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 81df7d300..22ec5caeb 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_materialize; mod blob_nulls; pub mod cast; pub mod insert; @@ -31,7 +32,7 @@ use lance_core::{ datatypes::{Projection, Schema as LanceSchema}, }; -use super::{AnyQuery, BaseTable}; +use super::{AnyQuery, BaseTable, NativeTableExt}; use crate::{ Error, Result, query::{QueryExecutionOptions, QueryFilter, QueryRequest, Select}, @@ -199,7 +200,8 @@ impl ExecutionPlan for MetadataEraserExec { 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. + /// SQL INSERT SELECT materializes descriptors from a single native-table + /// snapshot; remote and Realtime/MemWAL sources are not supported. #[default] Read, /// Expose Blob v2 write inputs (`data`, `uri`, `position`, `size`) and legacy @@ -213,9 +215,33 @@ pub enum BlobSchema { /// /// 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. +/// SQL INSERT with logical blob inputs. In read mode, INSERT SELECT can copy +/// Blob v2 descriptors from a single native-table snapshot into target-owned +/// payloads, including projections, filters, sorting, and limits. JOIN, UNION, +/// aggregation, and computed descriptors fail during planning because their +/// source row addresses cannot be established safely. 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. +/// Descriptor copying requires a native source table; remote and Realtime/MemWAL +/// sources are not supported by this materialization path. +/// +/// With read adapters registered as `source` and `target`, copying blobs needs +/// no payload UDF or explicit system columns: +/// +/// ```sql +/// INSERT INTO target SELECT * FROM source WHERE id > 10; +/// ``` +/// +/// The target owns the copied payloads independently of subsequent source +/// compaction or deletion. External URI references retain their external +/// storage semantics and remain subject to the target's registered external +/// bases; copying a descriptor does not authorize a new external location. +/// +/// Materialization allocates payload bytes for each input batch outside the +/// DataFusion memory pool. For large blobs, configure a conservative +/// `SessionConfig::with_batch_size`; the pool limit alone does not bound these +/// allocations, and a single blob can still exceed that limit. #[derive(Debug)] pub struct BaseTableAdapter { table: Arc, @@ -440,13 +466,55 @@ impl TableProvider for BaseTableAdapter { ..Default::default() }; - let plan = self - .table - .create_plan(&AnyQuery::Query(query), options) + // The scan and any later INSERT rewrite must use the same snapshot, + // even if the live table advances between planning and execution. + let projects_descriptors = match projection { + Some(indices) => indices + .iter() + .any(|index| blob_nulls::has_descriptor(provider_schema.field(*index))), + None => provider_schema + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)), + }; + let snapshot = if self.blob_schema == BlobSchema::Read + && self.table.as_native().is_some() + && projects_descriptors + { + Some( + self.table + .query_snapshot() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?, + ) + } else { + None + }; + let source = snapshot.as_ref().unwrap_or(&self.table); + let plan = source + .create_plan(&AnyQuery::Query(query.clone()), options.clone()) .map_err(|err| DataFusionError::External(err.into())) .await?; let plan = blob_nulls::mask_plan(plan)?; - let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let mut plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + if let Some(snapshot) = snapshot + && plan + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + let dataset = snapshot + .as_native() + .unwrap() + .dataset + .get() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + plan = Arc::new(blob_materialize::BlobScanExec::new( + plan, snapshot, dataset, query, options, + )); + } if self.blob_schema == BlobSchema::Write { let schema = match projection { Some(projection) => Arc::new(provider_schema.project(projection)?), @@ -509,17 +577,30 @@ impl TableProvider for BaseTableAdapter { input: Arc, insert_op: InsertOp, ) -> DataFusionResult> { + let has_descriptors = input + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + || (blob_materialize::has_source_scan(&input) + && input + .schema() + .fields() + .iter() + .any(|field| blob_materialize::has_descriptor(field))); if self.blob_schema == BlobSchema::Read && self .schema .fields() .iter() .any(|field| blob_nulls::has_descriptor(field)) + && !has_descriptors { return Err(DataFusionError::NotImplemented( "SQL INSERT into Blob v2 tables requires BlobSchema::Write".into(), )); } + let input = blob_materialize::materialize(input, self.write_schema.as_ref()).await?; let mode = match insert_op { InsertOp::Append => WriteMode::Append, InsertOp::Overwrite => WriteMode::Overwrite, diff --git a/rust/lancedb/src/table/datafusion/blob_materialize.rs b/rust/lancedb/src/table/datafusion/blob_materialize.rs new file mode 100644 index 000000000..22d0a023d --- /dev/null +++ b/rust/lancedb/src/table/datafusion/blob_materialize.rs @@ -0,0 +1,615 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Preserve scan provenance until INSERT can materialize source-owned blobs. +//! +//! External descriptors remain references and must satisfy the destination's +//! existing external-base policy; source authorization grants no target trust. + +use std::fmt; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use datafusion_common::{DataFusionError, Result, tree_node::TreeNodeRecursion}; +use datafusion_execution::{SendableRecordBatchStream, TaskContext}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::{ + PhysicalExpr, ScalarFunctionExpr, + expressions::{CastExpr, Column, Literal}, +}; +use datafusion_physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, + coalesce_partitions::CoalescePartitionsExec, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + filter::FilterExec, + limit::{GlobalLimitExec, LocalLimitExec}, + projection::ProjectionExec, + repartition::RepartitionExec, + sorts::{sort::SortExec, sort_preserving_merge::SortPreservingMergeExec}, + stream::RecordBatchStreamAdapter, +}; +use futures::{FutureExt, TryStreamExt, future::BoxFuture}; +use lance::{Dataset, dataset::BlobV2BatchRewritePlan}; +use lance_core::{ + ROW_ADDR, + datatypes::{BlobV2Layout, Schema as LanceSchema}, +}; + +use super::{BaseTable, MetadataEraserExec, blob_nulls}; +use crate::{ + query::{QueryExecutionOptions, QueryRequest, Select}, + table::AnyQuery, +}; + +const HIDDEN_ROW_ADDR: &str = "__lancedb_blob_rowaddr"; + +// Expressions such as CASE can retain the descriptor layout while dropping +// extension metadata. They still require proven provenance before writing. +pub(super) fn has_descriptor(field: &Field) -> bool { + contains_layout(field.data_type(), BlobV2Layout::Descriptor) +} + +fn descriptor_for_target(input: &Field, target: &Field) -> bool { + if crate::blob::is_blob(target) { + return matches!(input.data_type(), DataType::Struct(fields) + if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)); + } + match (input.data_type(), target.data_type()) { + (DataType::Struct(input), DataType::Struct(target)) => target.iter().any(|target| { + input + .find(target.name()) + .is_some_and(|(_, input)| descriptor_for_target(input, target)) + }), + ( + DataType::List(input) | DataType::LargeList(input) | DataType::FixedSizeList(input, _), + DataType::List(target) + | DataType::LargeList(target) + | DataType::FixedSizeList(target, _), + ) => descriptor_for_target(input, target), + _ => false, + } +} + +fn contains_layout(data_type: &DataType, layout: BlobV2Layout) -> bool { + match data_type { + DataType::Struct(fields) => { + BlobV2Layout::classify(fields) == Some(layout) + || fields + .iter() + .any(|field| contains_layout(field.data_type(), layout)) + } + DataType::List(item) | DataType::LargeList(item) | DataType::FixedSizeList(item, _) => { + contains_layout(item.data_type(), layout) + } + _ => false, + } +} + +pub(super) fn has_source_scan(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.children().iter().any(|child| has_source_scan(child)) +} + +#[expect( + deprecated, + reason = "DataFusion 55 still accepts CoalesceBatchesExec plans" +)] +fn preserves_row_identity(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input + .downcast_ref::() + .is_some() + || input.downcast_ref::().is_some() +} + +fn provenance_error(detail: impl fmt::Display) -> DataFusionError { + DataFusionError::Plan(format!( + "Blob INSERT SELECT requires descriptors from one source table snapshot with an \ + unambiguous row address; {detail}. JOIN, UNION, aggregation, and computed blob \ + descriptors are not supported" + )) +} + +/// A transparent scan boundary. It retains the snapshot and scan request, rather +/// than exposing a system column to SELECT * or fetching any payloads on reads. +#[derive(Debug)] +pub(super) struct BlobScanExec { + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, +} + +impl BlobScanExec { + pub(super) fn new( + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, + ) -> Self { + Self { + input, + source, + dataset, + query, + options, + } + } + + async fn with_row_address(&self) -> Result { + let mut query = self.query.clone(); + let Select::Columns(columns) = &mut query.select else { + return Err(provenance_error( + "source scan has no explicit column projection", + )); + }; + if !columns.iter().any(|name| name == ROW_ADDR) { + columns.push(ROW_ADDR.to_owned()); + } + let plan = self + .source + .create_plan(&AnyQuery::Query(query), self.options.clone()) + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + let plan = blob_nulls::mask_plan(plan)?; + let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let schema = plan.schema(); + let mut projection: Vec<(Arc, String)> = self + .input + .schema() + .fields() + .iter() + .map(|field| { + Ok(( + Arc::new(Column::new(field.name(), schema.index_of(field.name())?)) as _, + field.name().clone(), + )) + }) + .collect::>()?; + projection.push(( + Arc::new(Column::new(ROW_ADDR, schema.index_of(ROW_ADDR)?)), + HIDDEN_ROW_ADDR.into(), + )); + Ok(Provenance { + plan: Arc::new(ProjectionExec::try_new(projection, plan)?), + dataset: self.dataset.clone(), + fields: self + .input + .schema() + .fields() + .iter() + .map(|field| Some(field.name().clone())) + .collect(), + }) + } +} + +impl DisplayAs for BlobScanExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "BlobScanExec: version={}", + self.dataset.version().version + ) + } +} + +impl ExecutionPlan for BlobScanExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "BlobScanExec" + } + fn properties(&self) -> &Arc { + self.input.properties() + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid scan children"))?; + Ok(Arc::new(Self::new( + input, + self.source.clone(), + self.dataset.clone(), + self.query.clone(), + self.options.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.input.execute(partition, context) + } +} + +struct Provenance { + plan: Arc, + dataset: Arc, + // Source field path for each output column, before the hidden address. + fields: Vec>, +} + +fn source_field(expr: &Arc, fields: &[Option]) -> Option { + if let Some(column) = expr.downcast_ref::() { + return fields.get(column.index()).cloned().flatten(); + } + let call = expr.downcast_ref::()?; + call.fun().inner().downcast_ref::()?; + let (root, path) = call.args().split_first()?; + let mut source = source_field(root, fields)?; + for component in path { + let name = component + .downcast_ref::()? + .value() + .try_as_str() + .flatten()?; + source.push('.'); + source.push_str(name); + } + Some(source) +} + +fn with_provenance(input: Arc) -> BoxFuture<'static, Result> { + async move { + if let Some(scan) = input.downcast_ref::() { + return scan.with_row_address().await; + } + let children = input.children(); + // An explicit allowlist keeps row identity from silently propagating + // through a future operator that changes cardinality or column meaning. + if children.len() != 1 || !preserves_row_identity(&input) { + return Err(provenance_error(format!( + "cannot establish provenance through {}", + input.name() + ))); + } + let mut provenance = with_provenance(children[0].clone()).await?; + if let Some(projection) = input.downcast_ref::() { + let fields = projection + .expr() + .iter() + .map(|expr| source_field(&expr.expr, &provenance.fields)) + .collect(); + let mut expressions: Vec<(Arc, String)> = projection + .expr() + .iter() + .map(|expr| (expr.expr.clone(), expr.alias.clone())) + .collect(); + expressions.push(( + Arc::new(Column::new( + HIDDEN_ROW_ADDR, + provenance.plan.schema().fields().len() - 1, + )), + HIDDEN_ROW_ADDR.into(), + )); + provenance.plan = Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + provenance.fields = fields; + } else { + if input.schema() != children[0].schema() { + return Err(provenance_error(format!( + "{} changes the source schema", + input.name() + ))); + } + provenance.plan = input.replace_children( + vec![provenance.plan], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + } + Ok(provenance) + } + .boxed() +} + +/// Defer only a container coercion whose Blob leaves retain their named paths. +/// Descriptor leaves are atomic: casting their members is never provenance. +fn can_defer_blob_cast(source: &Field, cast_type: &DataType, target: &Field) -> bool { + if crate::blob::is_blob(target) { + let (DataType::Struct(source), DataType::Struct(cast)) = (source.data_type(), cast_type) + else { + return false; + }; + return BlobV2Layout::classify(source) == Some(BlobV2Layout::Descriptor) + && (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Logical) + || (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Descriptor) + && source.len() == cast.len() + && source.iter().zip(cast).all(|(source, cast)| { + source.name() == cast.name() && source.data_type() == cast.data_type() + }))); + } + match (source.data_type(), cast_type, target.data_type()) { + (DataType::Struct(source), DataType::Struct(cast), DataType::Struct(target)) => { + source.len() == cast.len() + && source.len() == target.len() + && target.iter().all(|target| { + source + .find(target.name()) + .zip(cast.find(target.name())) + .is_some_and(|((_, source), (_, cast))| { + can_defer_blob_cast(source, cast.data_type(), target) + }) + }) + } + (DataType::List(source), DataType::List(cast), DataType::List(target)) + | (DataType::LargeList(source), DataType::LargeList(cast), DataType::LargeList(target)) => { + can_defer_blob_cast(source, cast.data_type(), target) + } + ( + DataType::FixedSizeList(source, source_len), + DataType::FixedSizeList(cast, cast_len), + DataType::FixedSizeList(target, target_len), + ) => { + source_len == cast_len + && source_len == target_len + && can_defer_blob_cast(source, cast.data_type(), target) + } + _ => !has_descriptor(source) && cast_type == target.data_type(), + } +} + +pub(super) async fn materialize( + input: Arc, + target_schema: &Schema, +) -> Result> { + if !target_schema + .fields() + .iter() + .any(|field| crate::blob::field_tree_has_blob_v2(field)) + { + return Ok(input); + } + // INSERT may cast containers for metadata, field order, scalar siblings, + // or a Write adapter's logical layout. Bind the original Blob leaves and + // materialize before applying the target coercion. Other expressions still + // have to pass the Column/GetField provenance checks below. + let input = if let Some(projection) = input.downcast_ref::() { + let mut changed = false; + let expressions = projection + .expr() + .iter() + .map(|projected| { + let mut expr = projected.expr.clone(); + if let Some(cast) = expr.downcast_ref::() + && let Ok(target) = target_schema.field_with_name(&projected.alias) + && crate::blob::field_tree_has_blob_v2(target) + && let source = cast + .expr() + .return_field(projection.input().schema().as_ref())? + && has_descriptor(&source) + { + if !can_defer_blob_cast( + &source, + &cast.data_type(projection.input().schema().as_ref())?, + target, + ) { + return Err(provenance_error(format!( + "cast of column '{}' does not preserve Blob leaf identity", + projected.alias + ))); + } + expr = cast.expr().clone(); + changed = true; + } + Ok((expr, projected.alias.clone())) + }) + .collect::>>()?; + if changed { + Arc::new(ProjectionExec::try_new( + expressions, + projection.input().clone(), + )?) as Arc + } else { + input + } + } else { + input + }; + let rewrite_columns: Vec = input + .schema() + .fields() + .iter() + .map(|field| { + target_schema + .field_with_name(field.name()) + .is_ok_and(|target| descriptor_for_target(field, target)) + }) + .collect(); + if !rewrite_columns.iter().any(|rewrite| *rewrite) { + return Ok(input); + } + let provenance = with_provenance(input.clone()).await?; + let mut source_schema = LanceSchema::default(); + let mut expressions: Vec<(Arc, String)> = Vec::new(); + for (index, (field, source)) in input + .schema() + .fields() + .iter() + .zip(&provenance.fields) + .enumerate() + { + let name = format!("__lancedb_blob_column_{index}"); + if rewrite_columns[index] { + let source = source.as_ref().ok_or_else(|| { + provenance_error(format!("column '{}' has no source", field.name())) + })?; + let mut source_field = provenance + .dataset + .schema() + .field(source) + .ok_or_else(|| provenance_error(format!("source field '{source}' is missing")))? + .clone(); + if !crate::blob::field_tree_has_blob_v2(&Field::from(&source_field)) { + return Err(provenance_error(format!( + "source field '{source}' is not a Blob v2 column" + ))); + } + source_field.name = name.clone(); + source_schema.fields.push(source_field); + } + expressions.push((Arc::new(Column::new(field.name(), index)), name)); + } + expressions.push(( + Arc::new(Column::new(HIDDEN_ROW_ADDR, provenance.fields.len())), + ROW_ADDR.into(), + )); + let plan: Arc = + Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + // preserve_managed=false forces even managed source payloads to become + // target-owned bytes instead of retaining source storage references. + let rewrite = Arc::new(BlobV2BatchRewritePlan::try_new( + &source_schema, + plan.schema().as_ref(), + false, + false, + )?); + let schema = Arc::new(Schema::new( + rewrite + .output_schema() + .fields() + .iter() + .zip(input.schema().fields()) + .map(|(rewritten, original)| rewritten.as_ref().clone().with_name(original.name())) + .collect::>(), + )); + let plan = Arc::new(MaterializeBlobsExec::new( + plan, + provenance.dataset, + rewrite, + schema, + )); + super::cast::cast_to_table_schema(plan, target_schema) + .map_err(|error| DataFusionError::External(Box::new(error))) +} + +struct MaterializeBlobsExec { + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + properties: Arc, +} + +impl fmt::Debug for MaterializeBlobsExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MaterializeBlobsExec") + .field("input", &self.input) + .finish_non_exhaustive() + } +} + +impl MaterializeBlobsExec { + fn new( + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + ) -> Self { + // Rewriting changes column types; descriptor equivalences/orderings do + // not describe the resulting payload structs. + let properties = Arc::new(PlanProperties::new( + datafusion_physical_expr::EquivalenceProperties::new(schema.clone()), + datafusion_physical_expr::Partitioning::UnknownPartitioning( + input.output_partitioning().partition_count(), + ), + input.properties().emission_type, + input.properties().boundedness, + )); + Self { + input, + dataset, + rewrite, + schema, + properties, + } + } +} + +impl DisplayAs for MaterializeBlobsExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MaterializeBlobsExec") + } +} + +impl ExecutionPlan for MaterializeBlobsExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "MaterializeBlobsExec" + } + fn properties(&self) -> &Arc { + &self.properties + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid rewrite children"))?; + Ok(Arc::new(Self::new( + input, + self.dataset.clone(), + self.rewrite.clone(), + self.schema.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + let dataset = self.dataset.clone(); + let rewrite = self.rewrite.clone(); + let schema = self.schema.clone(); + let stream = self + .input + .execute(partition, context)? + .and_then(move |batch| { + let dataset = dataset.clone(); + let rewrite = rewrite.clone(); + let schema = schema.clone(); + async move { + let batch = rewrite.transform_batch(&dataset, batch).await?; + Ok(RecordBatch::try_new(schema, batch.columns().to_vec())?) + } + }); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema.clone(), + stream, + ))) + } +} diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index ec1e603d2..a2d5f34c9 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -195,6 +195,7 @@ impl ExecutionPlan for InsertExec { context: Arc, ) -> DataFusionResult { let input_stream = self.input.execute(partition, context)?; + let input_plan = self.input.clone(); let dataset = self.dataset.clone(); let mut write_params = self.write_params.clone(); let partial_transactions = self.partial_transactions.clone(); @@ -227,6 +228,9 @@ impl ExecutionPlan for InsertExec { )); let stream = futures::stream::once(async move { + // Source blob snapshots must outlive the final target commit, not + // only the consumption of the input stream. + let _input_plan = input_plan; if let Some(tracker) = tracker && write_params.write_progress.is_none() { diff --git a/rust/lancedb/tests/datafusion_blob_schema.rs b/rust/lancedb/tests/datafusion_blob_schema.rs index d51c182f6..5af3122ab 100644 --- a/rust/lancedb/tests/datafusion_blob_schema.rs +++ b/rust/lancedb/tests/datafusion_blob_schema.rs @@ -571,66 +571,701 @@ async fn legacy_blob_write_mode_rejects_descriptor_scans_and_keeps_scalar_scans( } #[tokio::test] -async fn copying_non_null_descriptors_between_tables_commits_no_rows() { +async fn copying_descriptors_materializes_payloads_and_preserves_snapshot() { + use std::collections::HashMap; + use std::num::NonZeroUsize; + + use lancedb::blob::{BlobOptions, blob_with_options}; + use lancedb::table::OptimizeAction; + + for managed in [false, true] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let payload = blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(8), + dedicated_size_threshold: NonZeroUsize::new(32), + }, + ); + let values: Vec> = vec![ + Some(b"hi"), + Some(&[2; 16]), + Some(&[3; 64]), + None, + Some(b""), + Some(b"skip"), + ]; + let schema = Arc::new(Schema::new_with_metadata( + vec![Field::new("id", DataType::Int64, false), payload], + HashMap::from([("lance.blob.managed".into(), managed.to_string())]), + )); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2, 3, 4, 5, 6])), + blob_inputs(values.clone()), + ], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_batch_size(2) + .with_target_partitions(2), + ); + register(&ctx, &source, BlobSchema::Read).await; + // Descriptor queries and SELECT * retain their original read schema. + let sizes = sql(&ctx, "SELECT payload.size FROM docs ORDER BY id").await; + assert_eq!( + sizes + .column(0) + .as_primitive::() + .value(2), + 64 + ); + assert_eq!(sql(&ctx, "SELECT * FROM docs").await.num_columns(), 2); + let kinds = sql(&ctx, "SELECT payload.kind FROM docs ORDER BY id").await; + let kinds = kinds + .column(0) + .as_primitive::(); + if !managed { + assert_eq!( + kinds.value(0), + lance_core::datatypes::BlobKind::Inline as u8 + ); + assert_eq!( + kinds.value(1), + lance_core::datatypes::BlobKind::Packed as u8 + ); + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Dedicated as u8 + ); + } else { + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Managed as u8 + ); + } + let (_destination_tmp, destination) = empty_table(vec![ + blob("copied", true), + Field::new("id", DataType::Int64, false), + ]) + .await; + let writer = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode); + ctx.register_table("destination", Arc::new(writer)).unwrap(); + let plan = ctx.sql("INSERT INTO destination (id, copied) SELECT id + 10, payload AS copied FROM docs WHERE id > 0 AND (payload.size IS NULL OR payload.size < 100) ORDER BY id DESC LIMIT 5 OFFSET 1") + .await.unwrap().create_physical_plan().await.unwrap(); + // A live-table change after planning must not change the source + // version used to decode the descriptors in this insert. + source.delete("id = 1").await.unwrap(); + datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(destination.count_rows(None).await.unwrap(), 5); + source.optimize(OptimizeAction::All).await.unwrap(); + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let reader = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID]) + .unwrap(); + ctx.register_table("copied_rows", Arc::new(reader)).unwrap(); + let ids = sql(&ctx, "SELECT _rowid FROM copied_rows ORDER BY id").await; + let ids = ids + .column(0) + .as_primitive::() + .values(); + assert_eq!( + destination.fetch_blobs("copied", ids).await.unwrap(), + LargeBinaryArray::from(values[..5].to_vec()) + ); + } + } +} + +#[tokio::test] +async fn copying_nested_descriptors_preserves_parent_nulls_and_field_identity() { + use arrow_array::Int32Array; + use lancedb::blob::{BlobOptions, blob_with_options}; + + for difference in ["metadata", "order", "scalar"] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let children = vec![ + Arc::new(Field::new("note", DataType::Utf8, true)), + Arc::new(Field::new("rank", DataType::Int32, true)), + Arc::new(blob_with_options( + "clip", + true, + BlobOptions { + inline_size_threshold: Some(8), + ..Default::default() + }, + )), + ]; + let extra_field = Field::new("extra", DataType::Struct(children.clone().into()), true); + let extra = StructArray::new( + children.into(), + vec![ + Arc::new(StringArray::from(vec![ + Some("a"), + Some("hidden"), + Some("c"), + ])), + Arc::new(Int32Array::from(vec![1, 2, 3])), + blob_inputs(vec![Some(b"hi"), Some(b"hidden"), Some(b"")]), + ], + Some(NullBuffer::from(vec![true, false, true])), + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + extra_field, + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let mut target_children = vec![ + Field::new("note", DataType::Utf8, true), + Field::new( + "rank", + if difference == "scalar" { + DataType::Int64 + } else { + DataType::Int32 + }, + true, + ), + blob("clip", true), + ]; + if difference == "order" { + target_children.swap(0, 2); + } + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + Field::new("extra", DataType::Struct(target_children.into()), true), + blob("flattened", true), + ]) + .await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + for expression in [ + "CASE WHEN id = 1 THEN extra ELSE NULL END", + "named_struct('note', extra.note, 'rank', extra.rank, 'clip', extra.clip)", + ] { + let query = format!( + "INSERT INTO destination SELECT id, {expression} AS extra, extra.clip AS flattened FROM docs" + ); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{difference}, {mode:?}: {error}" + ); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } + sql(&ctx, "INSERT INTO destination SELECT id, extra, extra.clip AS flattened FROM docs ORDER BY id DESC").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let ids = row_ids(&ctx, &destination).await; + let expected = + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, Some(b"".as_slice())]); + assert_eq!( + destination.fetch_blobs("extra.clip", &ids).await.unwrap(), + expected, + "{difference}, {mode:?}" + ); + assert_eq!( + destination.fetch_blobs("flattened", &ids).await.unwrap(), + expected + ); + let nested = sql(&ctx, "SELECT extra FROM read_docs ORDER BY id").await; + let extra = nested.column(0).as_struct(); + assert!(extra.is_null(1)); + assert_eq!( + extra + .column_by_name("note") + .unwrap() + .as_string::() + .value(2), + "c" + ); + let rank = extra.column_by_name("rank").unwrap(); + if difference == "scalar" { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } else { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } + } + } +} + +#[tokio::test] +async fn ordinary_descriptor_shaped_structs_remain_plain_data() { + let fields = vec![ + Field::new("id", DataType::Int64, false), + Field::new( + "raw", + DataType::Struct( + vec![ + Field::new("kind", DataType::UInt8, true), + Field::new("position", DataType::UInt64, true), + Field::new("size", DataType::UInt64, true), + Field::new("blob_id", DataType::UInt32, true), + Field::new("blob_uri", DataType::Utf8, true), + ] + .into(), + ), + true, + ), + ]; + let (source_tmp, source) = empty_table(fields.clone()).await; + let (_destination_tmp, destination) = empty_table(fields).await; + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + sql(&ctx, "INSERT INTO docs VALUES (1, named_struct('kind', 1, 'position', 2, 'size', 3, 'blob_id', 4, 'blob_uri', 'plain data'))").await; + let expected = sql(&ctx, "SELECT * FROM docs").await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + sql(&ctx, "INSERT INTO destination SELECT * FROM docs").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let actual = sql(&ctx, "SELECT * FROM destination").await; + assert_eq!(actual.columns(), expected.columns()); +} + +#[tokio::test] +async fn ambiguous_descriptor_sources_fail_during_planning_without_writing() { 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), - ); + let ctx = SessionContext::new(); 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(), - ) + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) .await; let writer = BaseTableAdapter::try_new(destination.base_table().clone()) .await - .unwrap() - .with_blob_schema(BlobSchema::Write); + .unwrap(); 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") + for select in [ + "SELECT a.id, a.payload FROM docs a JOIN docs b ON a.id = b.id", + "SELECT id, payload FROM docs UNION ALL SELECT id, payload FROM docs", + "SELECT id, payload FROM docs GROUP BY id, payload", + "SELECT id, CASE WHEN id = 1 THEN payload ELSE NULL END AS payload FROM docs", + ] { + let query = format!("INSERT INTO destination {select}"); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{query}: {error}" + ); + } + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + assert_eq!(destination.version().await.unwrap(), version); +} + +#[tokio::test] +async fn external_descriptor_copy_obeys_destination_bases_and_preserves_ranges() { + use lance::dataset::WriteParams; + use lance_core::datatypes::BlobKind; + use lance_table::format::BasePath; + use lancedb::table::WriteOptions; + + let external_tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let path = external_tmp.path().join("payload.bin"); + std::fs::write(&path, payload).unwrap(); + let uri = url::Url::from_file_path(&path).unwrap().to_string(); + let base_uri = url::Url::from_directory_path(external_tmp.path()) + .unwrap() + .to_string(); + let base = |id| BasePath { + id, + name: Some("external".into()), + path: base_uri.clone(), + is_dataset_root: false, + }; + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ])); + let DataType::Struct(children) = schema.field(1).data_type().clone() else { + unreachable!() + }; + let input = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + Arc::new(StructArray::new( + children, + vec![ + Arc::new(LargeBinaryArray::from(vec![ + None, + Some(b"inline".as_slice()), + ])), + Arc::new(StringArray::from(vec![Some(uri.as_str()), None])), + Arc::new(UInt64Array::from(vec![Some(4), None])), + Arc::new(UInt64Array::from(vec![Some(6), None])), + ], + None, + )), + ], + ) + .unwrap(); + for source_registered in [false, true] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let source = db + .create_empty_table("source", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: source_registered.then(|| vec![base(7)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + source + .add(input.clone()) + .allow_external_blob_outside_bases(!source_registered) + .execute() + .await + .unwrap(); + for mode in [BlobSchema::Read, BlobSchema::Write] { + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let descriptor = sql(&ctx, "SELECT payload.blob_id FROM docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + if source_registered { 7 } else { 0 } + ); + for authorized in [false, true] { + let destination_tmp = tempdir().unwrap(); + let destination_db = connect(destination_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let destination = destination_db + .create_empty_table("destination", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: authorized.then(|| vec![base(11)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + ctx.deregister_table("destination").unwrap(); + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let result = ctx + .sql("INSERT INTO destination SELECT * FROM docs ORDER BY id") + .await + .unwrap() + .collect() + .await; + if !authorized { + let error = result.unwrap_err().to_string(); + assert!( + error.contains("outside registered external bases"), + "{error}" + ); + let reopened = destination_db + .open_table("destination") + .execute() + .await + .unwrap(); + assert_eq!(reopened.version().await.unwrap(), version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); + // A logical URI input has the same destination authorization boundary. + ctx.register_table( + "logical_target", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write), + ), + ) + .unwrap(); + let error = ctx.sql(&format!("INSERT INTO logical_target SELECT 3, named_struct('data', NULL, 'uri', '{uri}')")).await.unwrap().collect().await.unwrap_err().to_string(); + assert!( + error.contains("allow_external_blob_outside_bases"), + "{error}" + ); + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } else { + result.unwrap(); + let ids = row_ids(&ctx, &destination).await; + let descriptor = sql(&ctx, "SELECT payload.kind, payload.blob_id, payload.blob_uri, payload.position, payload.size FROM read_docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + BlobKind::External as u8 + ); + assert_eq!( + descriptor + .column(1) + .as_primitive::() + .value(0), + 11 + ); + assert_eq!( + descriptor.column(2).as_string::().value(0), + "payload.bin" + ); + assert_eq!( + descriptor + .column(3) + .as_primitive::() + .value(0), + 4 + ); + assert_eq!( + descriptor + .column(4) + .as_primitive::() + .value(0), + 6 + ); + assert_eq!( + destination.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![ + Some(&payload[4..10]), + Some(b"inline".as_slice()) + ]) + ); + let files = destination.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.uri(), Some("payload.bin")); + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let registered = &dataset.manifest().base_paths[&11]; + let resolved = + url::Url::parse(&format!("{}/", registered.path.trim_end_matches('/'))) + .unwrap() + .join(file.uri().unwrap()) + .unwrap(); + assert_eq!(resolved.as_str(), uri); + assert_eq!(file.position(), Some(4)); + assert_eq!(file.size(), 6); + } + } + } + } +} + +#[tokio::test] +async fn source_payload_failure_after_written_partition_does_not_commit() { + use datafusion_physical_plan::{ + ExecutionPlanProperties, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + union::UnionExec, + }; + use futures::TryStreamExt; + use lancedb::blob::{BlobOptions, blob_with_options}; + use std::num::NonZeroUsize; + + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(0), + dedicated_size_threshold: NonZeroUsize::new(1), + }, + ), + ])); + let source = db + .create_table( + "docs", + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + blob_inputs(vec![Some(&[1; 64]), Some(&[2; 64])]), + ], + ) + .unwrap(), + ) + .execute() + .await + .unwrap(); + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_target_partitions(1) + .with_batch_size(1), + ); + register(&ctx, &source, BlobSchema::Read).await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + let first = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 1") .await .unwrap() .create_physical_plan() .await .unwrap(); - let error = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + let second = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 2") .await - .unwrap_err(); - assert!(error.to_string().contains("blob"), "{error}"); + .unwrap() + .create_physical_plan() + .await + .unwrap(); + assert_eq!(first.name(), "InsertExec"); + assert_eq!(second.name(), "InsertExec"); + // Combine already validated SQL inputs only to control partition scheduling: + // finish one real uncommitted write before faulting the next payload read. + let input = UnionExec::try_new(vec![ + first.children()[0].clone(), + second.children()[0].clone(), + ]) + .unwrap(); + assert_eq!(input.output_partitioning().partition_count(), 2); + let insert = first + .replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let batches: Vec = insert + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 1 + ); 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]>]) + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let data_dir = _destination_tmp.path().join("docs.lance").join("data"); + assert!( + std::fs::read_dir(data_dir).unwrap().next().is_some(), + "first partition must have written a data file" ); + let ids = row_ids(&ctx, &source).await; + let files = source.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[1].as_ref().unwrap(); + assert_eq!( + file.kind(), + Some(lance_core::datatypes::BlobKind::Dedicated) + ); + let missing_path = std::path::Path::new("/").join(file.data_path().unwrap().as_ref()); + drop(files); + std::fs::remove_file(&missing_path).unwrap(); + let error = insert + .execute(1, ctx.task_ctx()) + .unwrap() + .try_collect::>() + .await + .unwrap_err() + .to_string(); + assert!( + error.contains(missing_path.file_name().unwrap().to_str().unwrap()), + "{error}" + ); + // Check both the live handle and an independently reopened manifest. + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + let reopened = lance::Dataset::open(dataset.uri()).await.unwrap(); + assert_eq!(reopened.version().version, version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); } From 9302287bed205bc017979681fa31b9b8e6ae450f Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 14:57:00 -0800 Subject: [PATCH 099/203] fix: accept defining queries in Python materialized views (#4980) Python materialized-view creation now accepts a complete defining SQL query across sync, async, remote, and namespace connections, including creation jobs: ```python view = db.create_materialized_view( "events_by_kind", query="SELECT kind, count(*) AS n FROM events GROUP BY kind", ) ``` `query` is mutually exclusive with `source`, `select`, `where`, and `limit`. Existing source-based calls remain supported. Adds Rust `Connection::create_materialized_view_from_query`: embedded connections plan through `MaterializedViewDefinition::from_sql`, while remote connections submit the full query for server-side parsing. Includes regression coverage for grouping, UNNEST, query forwarding, creation jobs, and argument validation. --- docs/src/python/python.md | 14 ++ .../materialized-views.mdx | 28 +-- python/python/lancedb/_lancedb.pyi | 8 +- python/python/lancedb/db.py | 60 ++++-- python/python/lancedb/materialized_view.py | 10 + python/python/lancedb/namespace.py | 16 +- python/python/lancedb/remote/db.py | 8 +- .../python/tests/test_materialized_views.py | 175 +++++++++++++-- python/src/connection.rs | 50 ++++- rust/lancedb/src/materialized_view.rs | 199 +++++++++++++++--- rust/lancedb/src/remote/sql_test.rs | 55 +++++ 11 files changed, 536 insertions(+), 87 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 058f2529a..4ce325b2f 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -627,6 +627,20 @@ remain available, as do LanceDB Enterprise operations. The same feature requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary eager `add_columns` transforms remain available. +Pass a complete defining SQL query with `query=` to use grouping, Functions +in `FROM`, or `UNNEST`: + +```python +view = db.create_materialized_view( + "events_by_kind", + query="SELECT kind, count(*) AS n FROM events GROUP BY kind", +) +``` + +`query` is mutually exclusive with `source`, `select`, `where`, and `limit`. +It is also accepted by asynchronous connections and `create_materialized_view_async`. +The backend SQL parser determines which query shapes are supported. + In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and `auto_refresh_interval_seconds`: diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 0f9494c9f..617eb7525 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -20,19 +20,19 @@ In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create). ## Create a view {#create} A materialized view is defined by a SQL query, so it is created with one. -From Python, run the statement on an [Enterprise connection](/basics/catalog#enterprise) -with [`execute_query`](/basics/sql#sql-from-python); the SQL is the same -either way: +From Python, pass the defining query to `create_materialized_view` on an +[Enterprise connection](/basics/catalog#enterprise): ```python Python icon="python" -db.execute_query(""" - CREATE MATERIALIZED VIEW frames_captioned AS - SELECT frame_id, video_id, ts, caption - FROM frames - WHERE selected = true -""").read_all() -view = db.open_materialized_view("frames_captioned") +view = db.create_materialized_view( + "frames_captioned", + query=""" + SELECT frame_id, video_id, ts, caption + FROM frames + WHERE selected = true + """, +) ``` ```sql SQL icon="database" @@ -43,9 +43,11 @@ WHERE selected = true ``` -`execute_query` returns once the result stream is readable, not once the -statement has finished, so `.read_all()` waits out the full creation before -the next line opens it. +`create_materialized_view` waits for creation and initial population, then +returns the view handle. Use `create_materialized_view_async` to submit a job +and wait for it separately. Both methods accept `query=` on synchronous and +asynchronous connections. `query` cannot be combined with `source`, `select`, +`where`, or `limit`; put those clauses in the query itself. The query defines the view: here, the `frames` table's `frame_id`, `video_id`, `ts` and `caption` columns, filtered to the frames selected for diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index ffdd68e5f..5897ddd0c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -349,24 +349,28 @@ class Connection(object): async def create_materialized_view( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, 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, + *, + query: Optional[str] = None, ) -> Table: ... async def create_materialized_view_async( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, 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, + *, + query: Optional[str] = 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 b4e5c6182..7d690abe3 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -79,6 +79,7 @@ from .materialized_view import ( MaterializedViewSource, SelectArg, normalize_select, + _validate_create_materialized_view, ) from .secrets import ( EnvVarSecret, @@ -698,8 +699,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -722,8 +724,12 @@ class DBConnection(EnforceOverrides): ---------- name: str The name of the view. - source: str - The name of the source table. + source: str, optional + The name of the source table. Required when ``query`` is omitted. + query: str, optional + The complete defining SQL query, including any GROUP BY or FROM + Function. Mutually exclusive with ``source``, ``select``, ``where`` + and ``limit``. Supported query shapes depend on the backend. select: list or dict, optional The view's columns: column names, ``(alias, SQL expression)`` pairs, or a dict of the same. Omitting it selects every source @@ -745,6 +751,13 @@ class DBConnection(EnforceOverrides): Returns ------- MaterializedView + + Examples + -------- + >>> view = db.create_materialized_view( # doctest: +SKIP + ... "events_by_kind", + ... query="SELECT kind, count(*) AS n FROM events GROUP BY kind", + ... ) """ raise NotImplementedError( _append_doc_url( @@ -756,8 +769,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2108,8 +2122,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2144,6 +2159,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -2158,8 +2174,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2171,6 +2188,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -3390,8 +3408,9 @@ class AsyncConnection(object): async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3407,9 +3426,15 @@ class AsyncConnection(object): See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ - source, native_options = await self._materialized_view_source( - source, select, where, limit - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view( name, source, @@ -3426,8 +3451,9 @@ class AsyncConnection(object): async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3441,9 +3467,15 @@ class AsyncConnection(object): Enterprise, 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 - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view_async( name, source, diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 7b8c8c6a4..dc04f89f8 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -134,6 +134,16 @@ def _quote_identifier(name: str) -> str: return f"`{escaped}`" +def _validate_create_materialized_view(source, query, select, where, limit): + if query is not None: + if any(value is not None for value in (source, select, where, limit)): + raise ValueError( + "query cannot be combined with source, select, where or limit" + ) + elif source is None: + raise ValueError("either source or query must be provided") + + def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]: """``select`` items may be a column name, an ``(alias, expression)`` pair, or a dict of the same. A bare name projects itself and is quoted, so any diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index aa9025641..72dc78c8b 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -696,8 +696,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -715,6 +716,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -730,8 +732,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -743,6 +746,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -1339,8 +1343,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1352,6 +1357,7 @@ class AsyncLanceNamespaceDBConnection: view = await self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -1366,8 +1372,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1379,6 +1386,7 @@ class AsyncLanceNamespaceDBConnection: return await self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 911766674..db3ab554c 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -792,8 +792,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -807,6 +808,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -828,8 +830,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -841,6 +844,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index bf964102b..1ea0c1cb9 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -10,6 +10,7 @@ import lancedb import pytest import pyarrow as pa from lancedb.db import AsyncConnection +from lancedb.exceptions import JobFailedError from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection from utils import start_server_thread @@ -175,7 +176,8 @@ async def test_remote_refresh_reports_unknown_metrics( assert not any("count_rows" in path for path in requests) -def test_sync_remote_create_uses_public_async_connection(): +@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"]) +def test_sync_remote_create_uses_public_async_connection(query): calls = [] class StubAsyncTable: @@ -190,6 +192,7 @@ def test_sync_remote_create_uses_public_async_connection(): name, source, *, + query=None, select=None, where=None, limit=None, @@ -201,6 +204,7 @@ def test_sync_remote_create_uses_public_async_connection(): ( name, source, + query, select, where, limit, @@ -219,18 +223,24 @@ def test_sync_remote_create_uses_public_async_connection(): db.db_name = "example" db.serialize = lambda: "{}" - view = db.create_materialized_view( - "adults", - "people", - select=["name"], - where="age >= 18", - limit=10, - with_no_data=True, - auto_refresh_enabled=True, - auto_refresh_interval_seconds=0.5, - ) + if query is None: + view = db.create_materialized_view( + "adults", + "people", + select=["name"], + where="age >= 18", + limit=10, + with_no_data=True, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=0.5, + ) + assert calls == [ + ("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5) + ] + else: + view = db.create_materialized_view("adults", query=query) + assert calls == [("adults", None, query, None, None, None, False, None, None)] assert view.name == "adults" - 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"]) @@ -790,3 +800,144 @@ 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 + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "query, expected", + [ + ( + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + [{"kind": "a", "n": 2}, {"kind": "b", "n": 1}], + ), + ( + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + [{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}], + ), + ], +) +async def test_query_defined_materialized_view( + tmp_path, sync, namespace, background, query, expected +): + if namespace: + connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async + db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS) + elif sync: + db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) + else: + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + rows = [ + {"id": 1, "kind": "a", "tags": ["x", "y"]}, + {"id": 2, "kind": "a", "tags": []}, + {"id": 3, "kind": "b", "tags": ["z"]}, + ] + if sync: + db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + db.create_materialized_view_async("result", query=query).wait() + view = db.open_materialized_view("result") + else: + view = db.create_materialized_view("result", query=query) + actual = view.table.to_arrow().to_pylist() + assert view.definition.query == query + view.refresh() + refreshed = view.table.to_arrow().to_pylist() + else: + await db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + view = await db.open_materialized_view("result") + else: + view = await db.create_materialized_view("result", query=query) + actual = (await view.table.to_arrow()).to_pylist() + assert (await view.definition()).query == query + await view.refresh() + refreshed = (await view.table.to_arrow()).to_pylist() + assert sorted(actual, key=str) == sorted(expected, key=str) + assert sorted(refreshed, key=str) == sorted(expected, key=str) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "clauses", + [{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}], +) +async def test_query_rejects_source_clauses_before_submission( + sync, background, clauses +): + connect = lancedb.connect if sync else lancedb.connect_async + db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1") + if not sync: + db = await db + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + with pytest.raises(ValueError, match="query cannot be combined"): + if sync: + create("invalid", query="SELECT * FROM people", **clauses) + else: + await create("invalid", query="SELECT * FROM people", **clauses) + with pytest.raises(ValueError, match="either source or query"): + if sync: + create("missing") + else: + await create("missing") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "query", + [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ], +) +async def test_remote_create_forwards_defining_query(sync, query): + native = CapturingCreateConnection() + db = AsyncConnection(native) + if sync: + remote = RemoteDBConnection.__new__(RemoteDBConnection) + remote._conn = db + job = remote.create_materialized_view_async("result", query=query) + job.wait() + else: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + assert native.calls[0][0:2] == ("result", None) + assert native.calls[0][2]["query"] == query + + +@pytest.mark.experimental_functions +@pytest.mark.parametrize("background", [False, True]) +def test_query_with_no_data_and_invalid_query(tmp_path, background): + db = make_db(tmp_path) + query = "SELECT name FROM people WHERE age >= 18" + if background: + db.create_materialized_view_async( + "adults", query=query, with_no_data=True + ).wait() + view = db.open_materialized_view("adults") + else: + view = db.create_materialized_view("adults", query=query, with_no_data=True) + assert view.table.count_rows() == 0 + view.refresh() + assert view.table.count_rows() == 2 + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + error = JobFailedError if background else ValueError + with pytest.raises(error, match="unsupported clause"): + result = create("invalid", query="SELECT * FROM people ORDER BY age") + if background: + result.wait() + assert "invalid" not in db.table_names() diff --git a/python/src/connection.rs b/python/src/connection.rs index 2bf01a6f7..a32c00be1 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -26,6 +26,7 @@ use lancedb::{ database::{CreateTableMode, Database, ReadConsistency}, function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, + materialized_view::CreateMaterializedViewBuilder, }; use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, @@ -34,6 +35,27 @@ use pyo3::{ types::{PyAnyMethods, PyDict, PyDictMethods, PyList}, }; +fn materialized_view_builder( + connection: &LanceConnection, + name: String, + source: Option, + query: Option, + has_clauses: bool, +) -> PyResult { + match (source, query) { + (None, Some(query)) if !has_clauses => { + Ok(connection.create_materialized_view_from_query(name, query)) + } + (Some(source), None) => Ok(connection.create_materialized_view(name, source)), + (None, None) => Err(PyValueError::new_err( + "either source or query must be provided", + )), + _ => Err(PyValueError::new_err( + "query cannot be combined with source, select, where or limit", + )), + } +} + #[pyclass] pub struct Connection { inner: Option, @@ -483,21 +505,29 @@ impl Connection { } #[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))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -520,21 +550,29 @@ impl Connection { } #[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))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index bd7fbb942..9920cd893 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1574,14 +1574,15 @@ async fn prepare_with( } /// Builds a materialized view. Created by -/// [`Connection::create_materialized_view`]. +/// [`Connection::create_materialized_view`] or +/// [`Connection::create_materialized_view_from_query`]. pub struct CreateMaterializedViewBuilder { connection: Connection, name: String, namespace: Vec, - source: String, + input: MaterializedViewInput, source_namespace: Vec, - projections: Vec<(String, String)>, + projections: Option>, filter: Option, limit: Option, with_no_data: bool, @@ -1589,6 +1590,11 @@ pub struct CreateMaterializedViewBuilder { auto_refresh_interval_seconds: Option, } +enum MaterializedViewInput { + Source(String), + Query(String), +} + fn source_sql_identifier( namespace_path: &[String], source: &str, @@ -1609,14 +1615,14 @@ fn source_sql_identifier( } impl CreateMaterializedViewBuilder { - pub(crate) fn new(connection: Connection, name: String, source: String) -> Self { + fn new(connection: Connection, name: String, input: MaterializedViewInput) -> Self { Self { connection, name, namespace: Vec::new(), - source, + input, source_namespace: Vec::new(), - projections: Vec::new(), + projections: None, filter: None, limit: None, with_no_data: false, @@ -1644,10 +1650,12 @@ impl CreateMaterializedViewBuilder { mut self, columns: impl IntoIterator, impl Into)>, ) -> Self { - self.projections = columns - .into_iter() - .map(|(output, expression)| (output.into(), expression.into())) - .collect(); + self.projections = Some( + columns + .into_iter() + .map(|(output, expression)| (output.into(), expression.into())) + .collect(), + ); self } @@ -1697,22 +1705,38 @@ impl CreateMaterializedViewBuilder { } fn query(&self) -> Result { + if let MaterializedViewInput::Query(query) = &self.input { + if !self.source_namespace.is_empty() + || self.projections.is_some() + || self.filter.is_some() + || self.limit.is_some() + { + return Err(Error::InvalidInput { + message: "a defining query cannot be combined with source_namespace, select, only_if or limit".into(), + }); + } + return Ok(query.clone()); + } + let MaterializedViewInput::Source(source) = &self.input else { + unreachable!() + }; fn quote(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) } - let projection = if self.projections.is_empty() { - "*".to_string() - } else { - self.projections - .iter() - .map(|(output, expression)| format!("{expression} AS {}", quote(output))) - .collect::>() - .join(", ") - }; + let projection = + if let Some(projections) = self.projections.as_ref().filter(|p| !p.is_empty()) { + projections + .iter() + .map(|(output, expression)| format!("{expression} AS {}", quote(output))) + .collect::>() + .join(", ") + } else { + "*".to_string() + }; let source = source_sql_identifier( &self.source_namespace, - &self.source, + source, self.connection.uri().starts_with("db://"), ); let mut query = format!("SELECT {projection} FROM {source}"); @@ -1775,19 +1799,33 @@ impl CreateMaterializedViewBuilder { .to_string(), }); } - let source = self - .connection - .open_table(&self.source) - .namespace(self.source_namespace.clone()) - .execute() - .await?; - let prepared = prepare_declaration( - &source, - (!self.projections.is_empty()).then_some(self.projections.as_slice()), - self.filter.as_deref(), - self.limit, - ) - .await?; + let prepared = match &self.input { + MaterializedViewInput::Source(name) => { + let source = self + .connection + .open_table(name) + .namespace(self.source_namespace.clone()) + .execute() + .await?; + prepare_declaration( + &source, + self.projections.as_deref().filter(|p| !p.is_empty()), + self.filter.as_deref(), + self.limit, + ) + .await? + } + MaterializedViewInput::Query(_) => { + let definition = MaterializedViewDefinition::from_sql(&self.query()?)?; + let source = self + .connection + .open_table(&definition.source_table) + .namespace(definition.source_namespace.clone()) + .execute() + .await?; + prepare_definition(&source, definition).await? + } + }; let view = prepared.create_in(&self.namespace, &self.name).await?; if !self.with_no_data { view.refresh().execute().await?; @@ -2067,7 +2105,41 @@ impl Connection { name: impl Into, source: impl Into, ) -> CreateMaterializedViewBuilder { - CreateMaterializedViewBuilder::new(self.clone(), name.into(), source.into()) + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Source(source.into()), + ) + } + + /// Define a materialized view using a complete SQL query. + /// + /// Embedded connections parse the query with + /// [`MaterializedViewDefinition::from_sql`]. Remote connections send the + /// query to the server, which determines the supported SQL syntax. + /// Put projections, predicates and limits in the query rather than using + /// the builder's source-specific methods. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn create(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let view = db.create_materialized_view_from_query( + /// "events_by_kind", + /// "SELECT kind, count(*) AS n FROM events GROUP BY kind", + /// ).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_materialized_view_from_query( + &self, + name: impl Into, + query: impl Into, + ) -> CreateMaterializedViewBuilder { + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Query(query.into()), + ) } /// Open the materialized view named `name`. @@ -2229,6 +2301,65 @@ mod tests { ); } + #[tokio::test] + async fn query_builder_rejects_source_clauses() { + let conn = connect("memory://").execute().await.unwrap(); + let builder = || conn.create_materialized_view_from_query("mv", "SELECT * FROM src"); + for invalid in [ + builder().select([("x", "x")]), + builder().select(Vec::<(String, String)>::new()), + builder().only_if("x > 0"), + builder().limit(0), + builder().source_namespace(vec!["ns".into()]), + ] { + assert!(matches!(invalid.query(), Err(Error::InvalidInput { .. }))); + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn create_from_query_supports_grouping_and_background_population() { + let conn = connect("memory://").execute().await.unwrap(); + conn.create_table( + "src", + record_batch!(("kind", Utf8, ["a", "a", "b"])).unwrap(), + ) + .execute() + .await + .unwrap(); + let query = "SELECT kind, count(*) AS n FROM src GROUP BY kind"; + let view = conn + .create_materialized_view_from_query("groups", query) + .with_no_data(true) + .execute() + .await + .unwrap(); + assert_eq!(view.definition_sql(), query); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + view.refresh().execute().await.unwrap(); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); + conn.create_materialized_view_from_query("background", query) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + conn.open_materialized_view("background") + .await + .unwrap() + .table() + .count_rows(None) + .await + .unwrap(), + 2 + ); + } + #[test] fn sql_definition_defaults_share_one_metadata_value() { let metadata = HashMap::from([( diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index eb994f7dd..d25c72830 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1137,6 +1137,61 @@ async fn catalog_connections_use_explicit_sql_endpoint_and_database_scope() { server.await.unwrap().unwrap(); } +#[tokio::test] +async fn remote_query_builder_sends_the_complete_query() { + 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 { + let (socket, _) = listener.accept().await?; + Ok::<_, std::io::Error>(Some((socket, listener))) + }); + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(FlightServiceServer::new(service)) + .serve_with_incoming_shutdown(incoming, async { + let _ = shutdown_rx.await; + }), + ); + let connection = crate::connect("db://analytics") + .region("us-east-1") + .api_key("test-key") + .host_override("http://127.0.0.1:1") + .sql_host_override(&format!("grpc://{address}")) + .execute() + .await + .unwrap(); + for query in [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ] { + connection + .create_materialized_view_from_query("result", query) + .auto_refresh_enabled(false) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + statements.lock().unwrap().last().unwrap(), + &format!( + "CREATE MATERIALIZED VIEW \"result\" WITH (auto_refresh_enabled = false) AS {query}" + ) + ); + } + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + #[tokio::test] async fn remote_create_uses_sql_and_preserves_options_and_namespace() { for defer in [false, true] { From db098ba812ff9cf47e7c8ba5c1a2d58485b6d510 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 13 Nov 2026 12:34:31 +0800 Subject: [PATCH 100/203] fix(ci): support Cargo 1.100 artifact layout in cleanup fixture (#5010) Cargo 1.100 moves intermediate compiler artifacts into per-unit build directories and emits `build_script_build` instead of `build-script-build`. The unlocked-build fixture currently fails on its old rlib path before the SDK build starts, even though the library survives cleanup. Discover compiler inputs recursively and accept both build-script names while preserving the library, generated-input, ordinary-executable, discarded-test, linker-failure and outside-target assertions. The standalone fixture reproduces the failure before this change and passes afterward on Rust/Cargo 1.100.0; it also passes on 1.97.0. Fault injection confirms missing libraries and other retained inputs still fail their assertions. Production cleanup and normal workflow coverage are unchanged. --- ci/tests/test_build_no_lock.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ci/tests/test_build_no_lock.py b/ci/tests/test_build_no_lock.py index 634e8d333..f760d2bfc 100644 --- a/ci/tests/test_build_no_lock.py +++ b/ci/tests/test_build_no_lock.py @@ -88,9 +88,11 @@ class BuildNoLockTest(unittest.TestCase): self.assertTrue((target / "fixture_cli").is_file()) # Cargo guarantees this binary for test execution, not compile-time reads. subprocess.run([str(target / "fixture_cli")], check=True) - self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib"))) - self.assertTrue(list((target / "build").glob("*/build-script-build"))) - self.assertTrue(list((target / "build").glob("*/out/generated.rs"))) + # Cargo 1.100 nests compiler inputs in per-unit build directories and + # names the build-script executable build_script_build. + self.assertTrue(list(target.rglob("libartifact_fixture*.rlib"))) + self.assertTrue(list((target / "build").rglob("build[-_]script[-_]build"))) + self.assertTrue(list((target / "build").rglob("out/generated.rs"))) def test_link_failure_preserves_cargo_status_and_diagnostic(self): with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp: From bab22a3fbd0f120b6d9e23cd4f3ee37621bb9bb5 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 00:21:58 -0800 Subject: [PATCH 101/203] feat(python): bundle Function package resources (#4987) A package shipped through `code=` currently loses its non-Python files. This breaks vendored packages that read JSON configuration, manifests, prompts, or binary resources after deployment. Include regular package resources in a separate base64-encoded `python_bundle.resources` map, preserving exact bytes and relative paths. Both source and resources contribute to the artifact digest. UTF-8 Python source bytes retain their original line endings as well, so manifests that hash vendor code continue to match. For example, `@function(code=[my_package])` can use `importlib.resources.files("my_package").joinpath("models.json").read_text()` on the worker. Hidden files and caches are excluded; symlinks and unsafe paths warn instead of following files outside the package. Source-only bundles retain their existing wire form. Resource bundles require matching server support. Adds an isolated-import regression with a vendored subpackage, JSON metadata, binary data, SHA256 verification, preserved CRLF bytes, and resource-only version changes. Local builds and tests are disabled by request. Ruff formatting and linting run locally; CI runs the tests. --- docs/src/python/python.md | 12 ++ docs/web/management/function.mdx | 21 ++- python/python/lancedb/functions.py | 92 ++++++++------ .../python/tests/test_function_packaging.py | 120 ++++++++++++++++-- 4 files changed, 187 insertions(+), 58 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 4ce325b2f..36f47c8f0 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1420,3 +1420,15 @@ name; omitting it allows matching reads of any revision. Prefixes must be concre paths without wildcards or traversal. This integration does not make Hugging Face a writable database location for `ATTACH DATABASE`. Dataset SQL sources select a matching integration automatically, with no integration argument in the query. + + +### Function package resources + +`@function(code=[my_package])` includes the package’s Python modules and data +files, including vendored subpackages. Resource paths and bytes are preserved, +so `importlib.resources` and package integrity checks work after deployment. +Changing a resource changes the Function artifact digest. This requires a server +that accepts `python_bundle.resources`. + +Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or +`conda=` for platform-specific dependencies and `models=` for large model snapshots. diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index bebbe1169..04c146bb1 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -499,13 +499,20 @@ def caption(jpeg: bytes) -> str: Each module in `code` is captured and shipped the same way the function -itself is: as source, snapshotted at registration. Only `.py` source files are -included; package data such as JSON, YAML, prompt, or tokenizer files is not -copied. `@function` warns before registration when it skips such files from a -package in `code`, naming the affected paths. To use a package that includes -the required resources, install it with `pip=` or `conda=` and remove that -package from `code`; otherwise the Python-only copied package shadows the -installed distribution. +itself is: as source, snapshotted at registration. Packages also include regular +data files such as JSON, YAML, prompts, and tokenizer files, including resources +inside vendored subpackages. Resource paths and bytes are preserved for +`importlib.resources` and package integrity checks. Changing a resource changes +the Function artifact's identity. Caches, hidden paths, symlinks, and unsafe +paths are excluded. + +Package resources require matching SDK and server support. Upgrade query nodes +and Function image-building workers before registering resource bundles; older +servers reject them. Older SDKs ship only Python source and warn when excluding +package data. On deployments without resource-bundle support, install the +package with `pip=` or `conda=` and omit it from `code` so the copied package does +not shadow the installed distribution. Use environment dependencies for +platform-specific packages and `models=` for large model snapshots. ## Drop it {#drop} diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 92be658a8..f04d3d481 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -22,6 +22,7 @@ import symtable import json import linecache import math +import os import re import sys import textwrap @@ -29,6 +30,7 @@ import types import warnings from collections.abc import Mapping, Sequence from datetime import date, datetime +from pathlib import Path from typing import ( Annotated, Any, @@ -2104,18 +2106,12 @@ class _SourcePackager: self._require_importable(node.module) -def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]: - """The Python source files of the modules and packages in ``code=``, - keyed by their path on the Function's import path. - - Package resources are not part of the source artifact. Warn about files - and excluded directories that the walk leaves behind instead of silently - producing a Function that will fail later on the worker. - """ - import os - from pathlib import Path - +def _code_files( + modules: Sequence[Any], +) -> tuple[dict[str, str], dict[str, str], frozenset[str]]: + """Source and byte-preserving package resources on the Function import path.""" files: dict[str, str] = {} + resources: dict[str, str] = {} names: set[str] = set() for module in modules: if not isinstance(module, types.ModuleType): @@ -2149,35 +2145,50 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]] sources = [] skipped = set() for directory, subdirectories, filenames in os.walk(root): - # Only importable modules travel: data files, caches, and - # directories that are not identifiers cannot be imported. kept = [] for child in sorted(subdirectories): - if child == "__pycache__": + path = Path(directory) / child + if child == "__pycache__" or child.startswith("."): continue - if _SOURCE_PATH_COMPONENT.fullmatch(child): + if not path.is_symlink() and re.fullmatch( + r"[A-Za-z0-9_][A-Za-z0-9_.-]*", child + ): kept.append(child) else: - relative = (Path(directory) / child).relative_to(root) + relative = path.relative_to(root) skipped.add(f"{name}/{relative.as_posix()}/") subdirectories[:] = kept for filename in sorted(filenames): + path = Path(directory) / filename stem, suffix = os.path.splitext(filename) - if suffix in {".pyc", ".pyo"}: + if suffix in {".pyc", ".pyo"} or filename.startswith("."): continue - if suffix == ".py" and _SOURCE_PATH_COMPONENT.fullmatch(stem): - sources.append(Path(directory) / filename) + relative = path.relative_to(root) + key = f"{name}/{relative.as_posix()}" + if ( + path.is_symlink() + or not path.is_file() + or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", filename) + ): + skipped.add(key) + elif suffix == ".py": + if all( + _SOURCE_PATH_COMPONENT.fullmatch(part) + for part in relative.with_suffix("").parts + ): + sources.append(path) + else: + skipped.add(key) else: - relative = (Path(directory) / filename).relative_to(root) - skipped.add(f"{name}/{relative.as_posix()}") + resources[key] = base64.b64encode(path.read_bytes()).decode( + "ascii" + ) if skipped: - skipped_paths = ", ".join(sorted(skipped)) warnings.warn( - f"code= ships Python .py modules only; package {name!r} " - f"will not include: {skipped_paths}. Install a package that " - "includes the required resources with pip= or conda=, and " - f"remove {name!r} from code= so the copied package cannot " - "shadow the installed distribution.", + "code= cannot ship these package paths: " + f"{', '.join(sorted(skipped))}. " + "Use regular files with safe relative names and importable " + "Python module names.", UserWarning, ) for path in sources: @@ -2188,12 +2199,12 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]] if not file or not file.endswith(".py"): raise ValueError(f"code= ships Python source; module {name!r} has none") files[f"{name}.py"] = _source_text(Path(file)) - return files, frozenset(names) + return files, resources, frozenset(names) def _source_text(path) -> str: try: - return path.read_text(encoding="utf-8") + return path.read_bytes().decode("utf-8") except UnicodeDecodeError as error: raise ValueError(f"code= ships UTF-8 source; {path} is not UTF-8") from error @@ -2449,14 +2460,17 @@ class FunctionDefinition: UserWarning, stacklevel=3, ) - code_files, code_modules = _code_files(code) + code_files, code_resources, code_modules = _code_files(code) entry_source = _SourcePackager( code_modules, frozenset(_requirement_name(package) for package in packages) ).package(function, signature) if code_files: kind = _PYTHON_BUNDLE_ARTIFACT + bundle = {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}} + if code_resources: + bundle["resources"] = code_resources source = json.dumps( - {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}}, + bundle, ensure_ascii=False, sort_keys=True, separators=(",", ":"), @@ -2802,13 +2816,15 @@ def function( immutable Function version; per-refresh aggregate GPU budgets are selected through ``refresh_column`` instead of registration. code : sequence of module, optional - Top-level modules or packages whose importable ``.py`` files ship - with the Function and are importable by their own names. Package data - files are not copied. To use a package that includes required data - resources, install it with ``pip=`` or ``conda=`` and remove that - package from ``code=`` so the copied Python package cannot shadow the - installed distribution. ``@function`` warns when it skips files from a - package in ``code=``. + Top-level modules or packages shipped with the Function and importable + by their own names. Package resources, including binary data and + vendored subpackages, retain their relative paths and exact bytes. + Source and resource changes both create a new Function version. + Caches and hidden paths are excluded. Symlinks and unsafe paths are + skipped with a warning. Compiled dependencies must match the remote + runtime; use ``pip=`` or ``conda=`` for platform-specific distributions + and ``models=`` for large model snapshots. Resource bundles require + server support for the ``python_bundle.resources`` field. models : sequence of HuggingFaceModel, optional Immutable Hugging Face repository snapshots prepared in the worker node cache before user code starts. A Function may declare a diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 2e285aa33..fcefc9110 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -7,6 +7,7 @@ from __future__ import annotations import base64 import importlib +import hashlib import json import subprocess import sys @@ -628,6 +629,102 @@ def test_binding_passes_initialization_as_constants(): version(text=col("body"), model=object()) +def test_vendored_package_resources_survive_an_isolated_import( + tmp_path, helper_package +): + package = helper_package( + "fx_vendor", + { + "__init__.py": "from .vendor.model import predict", + "vendor/__init__.py": "", + "vendor/model.py": """ + import hashlib + import json + from importlib.resources import files + + def predict(value): + root = files("fx_vendor") + payload = root.joinpath("label-maps/payload.bin").read_bytes() + metadata = json.loads(root.joinpath("models.json").read_text()) + source = root.joinpath("vendor/model.py").read_bytes() + source_digest = hashlib.sha256(source).hexdigest() + assert source_digest == metadata["source_sha256"] + assert hashlib.sha256(payload).hexdigest() == metadata["sha256"] + return value + metadata["offset"] + """, + "models.json": "{}", + }, + ) + payload = b"\x00\xff\r\nvendored model data" + package_root = Path(package.__file__).parent + (package_root / "label-maps").mkdir() + (package_root / "label-maps/payload.bin").write_bytes(payload) + module_path = package_root / "vendor/model.py" + module_bytes = ( + module_path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") + ) + module_path.write_bytes(module_bytes) + (package_root / "models.json").write_bytes( + json.dumps( + { + "sha256": hashlib.sha256(payload).hexdigest(), + "source_sha256": hashlib.sha256(module_bytes).hexdigest(), + "offset": 7, + } + ).encode() + + b"\r\n" + ) + + entry = helper_package( + "fx_vendor_entry", + { + "__init__.py": """ + import fx_vendor + from lancedb import function + + @function(code=[fx_vendor]) + def vendored(value: int) -> int: + return fx_vendor.predict(value) + """ + }, + ) + vendored = entry.vendored + + first_digest = vendored.registration_request.artifact.digest + bundle = json.loads(artifact(vendored)) + isolated = tmp_path / "isolated" + isolated.mkdir() + for name, content in bundle["files"].items(): + target = isolated / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content.encode("utf-8")) + for name, content in bundle["resources"].items(): + target = isolated / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(base64.b64decode(content)) + assert (isolated / "fx_vendor/models.json").read_bytes().endswith(b"\r\n") + result = subprocess.run( + [ + sys.executable, + "-I", + "-c", + "import sys; sys.path.insert(0, sys.argv[1]); " + "from user_function import vendored; assert vendored(3) == 10", + str(isolated), + ], + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr + (package_root / "models.json").write_text('{"offset": 8}') + assert ( + function(code=[package])( + vendored._function + ).registration_request.artifact.digest + != first_digest + ) + + def test_code_packages_ship_as_a_bundle_and_version_with_their_source( tmp_path, helper_package ): @@ -672,14 +769,13 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source( first = define() assert len(caught) == 1 warning = str(caught[0].message) - assert "fx_helpers/fixtures/data.json" in warning + assert "fx_helpers/fixtures/data.json" not in warning assert "fx_helpers/not-a-module.py" in warning - assert warning.index("fx_helpers/fixtures/data.json") < warning.index( - "fx_helpers/not-a-module.py" - ) - assert "remove 'fx_helpers' from code=" in warning - assert "pip=" in warning - assert "conda=" in warning + + assert "safe relative names" in warning + assert "importable Python module names" in warning + resources = json.loads(artifact(first))["resources"] + assert base64.b64decode(resources["fx_helpers/fixtures/data.json"]) == b"{}" assert "__pycache__" not in warning assert ".pyc" not in warning shipped = bundle_files(first) @@ -732,7 +828,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package): ] -def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package): +def test_code_package_resources_keep_nonidentifier_directories(helper_package): resources = helper_package( "fx_resources", { @@ -748,11 +844,9 @@ def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_packag def resource_boundary(value: int) -> int: return value - assert len(caught) == 1 - warning = str(caught[0].message) - assert "fx_resources/label-maps/" in warning - assert "remove 'fx_resources' from code=" in warning - assert "labels.json" not in warning + assert not caught + resources = json.loads(artifact(resource_boundary))["resources"] + assert base64.b64decode(resources["fx_resources/label-maps/labels.json"]) == b"{}" assert sorted(bundle_files(resource_boundary)) == [ "fx_resources/__init__.py", "user_function.py", From 927b24394866c835b7f7c3e27a3ee10845a9bf46 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Fri, 13 Nov 2026 09:38:50 -0800 Subject: [PATCH 102/203] fix(remote): preserve branches in cache prewarm requests (#5012) Calling `prewarm_data` or `prewarm_index` on a checked-out remote branch currently targets main. Both methods omit the branch context, which can warm the wrong snapshot, miss a branch-only index, or fail when the branch's minimum read version is ahead of main. This PR carries the table handle's branch through the existing request helpers. Main requests retain their existing format, with no public API changes. --- rust/lancedb/src/remote/table.rs | 71 ++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index dcceb4260..9b64ab56d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4548,10 +4548,10 @@ impl BaseTable for RemoteTable { async fn prewarm_index(&self, index_name: &str) -> Result<()> { let encoded_name = urlencoding::encode(index_name); - let request = self.client.post(&format!( + let request = self.apply_branch_query(self.client.post(&format!( "/v1/table/{}/index/{encoded_name}/prewarm/", self.identifier - )); + ))); let (request_id, response) = self.send(request, true).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::IndexNotFound { @@ -4567,9 +4567,10 @@ impl BaseTable for RemoteTable { "/v1/table/{}/page_cache/prewarm/", self.identifier )); - let body = serde_json::json!({ + let mut body = serde_json::json!({ "columns": columns.unwrap_or_default(), }); + self.apply_branch_body(&mut body); request = request.json(&body); let (request_id, response) = self.send(request, true).await?; self.check_table_response(&request_id, response).await?; @@ -13018,6 +13019,70 @@ mod tests { .unwrap(); } + #[tokio::test] + async fn test_prewarm_data_sends_the_checked_out_branch() { + use lance::dataset::refs::Ref; + + let table = + Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { + match request.url().path() { + "/v1/table/my_table/branches/create/" => { + http::Response::builder().status(200).body("{}").unwrap() + } + "/v1/table/my_table/page_cache/prewarm/" => { + let body = request_body_json(&request); + assert_eq!(body["branch"], "dev"); + assert_eq!(body["columns"], json!(["payload"])); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"prewarm-job"}"#) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let branch = table + .create_branch("dev", Ref::Version(None, None)) + .await + .unwrap(); + branch + .prewarm_data(Some(vec!["payload".into()])) + .await + .unwrap(); + } + + #[tokio::test] + async fn test_prewarm_index_sends_the_checked_out_branch() { + use lance::dataset::refs::Ref; + + let table = + Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { + match request.url().path() { + "/v1/table/my_table/branches/create/" => { + http::Response::builder().status(200).body("{}").unwrap() + } + "/v1/table/my_table/index/my_index/prewarm/" => { + let branch = request + .url() + .query_pairs() + .find(|(key, _)| key == "branch") + .map(|(_, value)| value.into_owned()); + assert_eq!(branch.as_deref(), Some("feature/dev")); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"prewarm-job"}"#) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let branch = table + .create_branch("feature/dev", Ref::Version(None, None)) + .await + .unwrap(); + branch.prewarm_index("my_index").await.unwrap(); + } + #[tokio::test] async fn test_drop_index() { let table = Table::new_with_handler("my_table", |request| { From 1765747f916d6eb7f3fbbcc105591e5835ea3684 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 11:02:07 -0800 Subject: [PATCH 103/203] fix: allow updates to Function input columns (#4985) Updating an input column on a table with a Function binding currently fails before the write, although the write path already preserves freshness for bindings whose inputs are unchanged. Allow input updates through the normal update builder while retaining supported binding-metadata validation and the guard against writing computed or internal assignment outputs directly. Lance rewrites only the matched rows. Their affected Function outputs keep their previous values and their changed input signatures make them eligible for refresh; unchanged fragments retain their freshness. Rewrites affecting only unrelated inputs keep the existing freshness-preservation path. For a table whose Function reads `title`, this update now succeeds while retaining the previous computed values until refresh: ```python table.update(where="id = 7", values={"title": "revised"}) ``` Server consumers need this crate update before remote input updates gain the behavior. Adds regressions for a one-row input update, retained output values, freshness scope, independent binding preservation, and atomic rejection of mixed input/output writes. Local builds and tests are disabled by request; CI runs the regressions. --- rust/lancedb/src/table/computed_columns.rs | 54 ++++++++- rust/lancedb/src/table/freshness.rs | 122 +++++++++++++++++++++ rust/lancedb/src/table/update.rs | 33 +++--- 3 files changed, 192 insertions(+), 17 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index d09a790a3..64e90b246 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -1757,10 +1757,20 @@ pub(crate) fn ensure_not_written<'a>( schema: &ArrowSchema, written: impl IntoIterator, ) -> Result<()> { - let declared: Vec = computed_columns(schema) + ensure_supported_function_metadata(schema)?; + let mut declared: Vec = computed_columns(schema) .into_iter() .map(|declaration| declaration.name) .collect(); + declared.extend( + function_bindings(schema)? + .into_iter() + .filter_map(|binding| { + binding + .assignment() + .map(|assignment| assignment.output_name.clone()) + }), + ); for name in written { if declared.iter().any(|declared| *declared == root(name)) { return Err(Error::InvalidInput { @@ -2532,10 +2542,15 @@ pub(crate) mod test_support { )]) .await .unwrap(); - let inputs = ["title".to_string(), "body".to_string()]; + let schema = dataset.schema(); let outputs = bindings .iter() .flat_map(|binding| { + let inputs = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); let assignment = binding.assignment().map(|assignment| { ( assignment.output_name.clone(), @@ -2547,9 +2562,9 @@ pub(crate) mod test_support { .iter() .map(|output| (output.output_name.clone(), output.output_ordinal)) .chain(assignment) - .map(|(name, ordinal)| { + .map(move |(name, ordinal)| { ( - dataset.schema().field(&name).unwrap().id as u32, + schema.field(&name).unwrap().id as u32, function_computed_column_metadata( binding.binding_id(), ordinal, @@ -4144,6 +4159,37 @@ mod tests { ArrowSchema::new(fields) } + #[test] + fn input_writes_preserve_the_assignment_column_guard() { + let mut raw: Value = serde_json::to_value(test_support::text_features_binding("")).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": "__function_assignment_fb_01K3TEXT", "output_field_id": -1, + }); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["outputs"][1]["nullable"] = Value::Bool(true); + raw["output_schema"]["fields"].as_array_mut().unwrap().push(serde_json::json!({ + "name": "__function_assignment_fb_01K3TEXT", "nullable": true, "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let schema = ArrowSchema::new_with_metadata( + valid_function_binding_schema(true, true, &binding) + .fields() + .to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.into(), + function_bindings_metadata(&[binding]).unwrap(), + )]), + ); + ensure_not_written(&schema, ["title", "body"]).unwrap(); + for output in [ + "search_text", + "search_token_count", + "__function_assignment_fb_01K3TEXT", + ] { + assert!(ensure_not_written(&schema, [output]).is_err(), "{output}"); + } + } + #[test] fn test_non_nullable_function_inputs_can_bind_to_nullable_parameters() { let binding = FunctionBinding::from_json(include_str!( diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 645653a46..563a2a4e5 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -2646,6 +2646,8 @@ mod tests { use lance_file::version::ConcreteFileVersion; use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + use crate::table::computed_columns::test_support::{stamp_bindings, text_features_binding}; + const COLUMN: &str = "doubled"; const EXPRESSION: &str = "value * 2"; @@ -3126,6 +3128,126 @@ mod tests { } } + #[tokio::test] + async fn input_update_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let result = table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + assert_eq!(result.rows_updated, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_update_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_functions", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + table + .update() + .only_if("title = 'a'") + .column("body", "'changed'") + .execute() + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 55980c5ff..93e8a08ea 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -103,11 +103,6 @@ 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_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()), update.columns.iter().map(|(name, _)| name.as_str()), @@ -473,26 +468,38 @@ mod tests { 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() { + async fn update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table().await; - let result = table.update().column("spare", "7").execute().await.unwrap(); + let result = table + .update() + .column("title", "'changed'") + .execute() + .await + .unwrap(); assert_eq!(result.rows_updated, 1); - for column in ["title", "search_text"] { + assert_eq!( + table + .count_rows(Some("title = 'changed' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 + ); + for column in ["search_text", "search_token_count"] { + let version = table.version().await.unwrap(); let err = table .update() - .column(column, "'x'") + .column("title", "'must not commit'") + .column(column, "NULL") .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")), + if message.contains("is computed") && message.contains("cannot be written directly")), "{column}: {err:?}" ); + assert_eq!(table.version().await.unwrap(), version); } } } From 3a980054a19dc51f53979a04142468f57478d156 Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:24:55 -0800 Subject: [PATCH 104/203] docs: standardize Realtime Engine naming (#4969) The Enterprise feature name was inconsistently written as "Real Time Engine" and "real time engine". Standardize it to **Realtime Engine** in eight website guides, including page and sidebar titles, descriptions, prose, link labels, cards, and search keywords. The remaining MemWAL references describe Lance's open source format or literal API/job identifiers, including `memwal_compaction` and `memwal_catchup_`, and are preserved. Only `docs/web/*.mdx` pages change; SDK source, generated API reference, code examples, URL destinations, and section anchors are unchanged. Validation: - `git diff --check` passes. - Reviewed all MemWAL and Realtime Engine references under `docs/`. - Verified each changed file differs only by the intended naming substitutions and preserves code blocks, inline code, links, anchors, and MemWAL identifiers. - Confirmed no split or hyphenated "real time engine" names remain in website guides. - No snippets needed regeneration because code examples are unchanged. Vale and Mintlify are not installed locally, so their checks were not run locally. --- docs/web/basics/sdk.mdx | 2 +- docs/web/enterprise/distributed-real-time-read.mdx | 2 +- docs/web/enterprise/distributed-real-time-write.mdx | 4 ++-- docs/web/enterprise/realtime-engine-compaction.mdx | 12 ++++++------ docs/web/ingestion/realtime-write.mdx | 8 ++++---- docs/web/search/realtime-read.mdx | 8 ++++---- docs/web/sql/ddl/table.mdx | 2 +- docs/web/tables/realtime-engine.mdx | 10 +++++----- 8 files changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/web/basics/sdk.mdx b/docs/web/basics/sdk.mdx index 2ff1a4ba7..0274c039a 100644 --- a/docs/web/basics/sdk.mdx +++ b/docs/web/basics/sdk.mdx @@ -53,7 +53,7 @@ without a LanceDB SDK. For SQL queries, connect through 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 Namespace endpoint. -The [real time engine](/tables/realtime-engine) is the one area with its own, +The [Realtime 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 Client SDK Specification. diff --git a/docs/web/enterprise/distributed-real-time-read.mdx b/docs/web/enterprise/distributed-real-time-read.mdx index 1b6a582c4..7442474ec 100644 --- a/docs/web/enterprise/distributed-real-time-read.mdx +++ b/docs/web/enterprise/distributed-real-time-read.mdx @@ -1,7 +1,7 @@ --- title: "Distributed RTE Read" sidebarTitle: "Distributed RTE Read" -description: "How a query combines the real time engine's fresh tier with the ordinary distributed query-serving path, machine to machine." +description: "How a query combines the Realtime Engine's fresh tier with the ordinary distributed query-serving path, machine to machine." icon: "network-wired" availability: embedded: unavailable diff --git a/docs/web/enterprise/distributed-real-time-write.mdx b/docs/web/enterprise/distributed-real-time-write.mdx index ac91e2d0d..e75497360 100644 --- a/docs/web/enterprise/distributed-real-time-write.mdx +++ b/docs/web/enterprise/distributed-real-time-write.mdx @@ -3,7 +3,7 @@ title: "Distributed RTE Write" sidebarTitle: "Distributed RTE Write" description: "How Enterprise scales RTE writes horizontally across a dedicated serving tier, and the throughput limits that come with it." icon: "bolt" -keywords: ["rte", "real time engine", "shard", "sharding", "horizontal scaling", "write throughput"] +keywords: ["rte", "realtime engine", "shard", "sharding", "horizontal scaling", "write throughput"] availability: embedded: unavailable enterprise: available @@ -128,7 +128,7 @@ throughput than this provides. Enable RTE and write to a table; the same call on Embedded or Enterprise. - + MemWAL, shards, memtables and SSTables -- the shared architecture. diff --git a/docs/web/enterprise/realtime-engine-compaction.mdx b/docs/web/enterprise/realtime-engine-compaction.mdx index e04429ab8..fb1a68481 100644 --- a/docs/web/enterprise/realtime-engine-compaction.mdx +++ b/docs/web/enterprise/realtime-engine-compaction.mdx @@ -1,7 +1,7 @@ --- -title: "Real Time Engine compaction" +title: "Realtime Engine compaction" sidebarTitle: "RTE Compaction" -description: "How Enterprise automatically folds a Real Time Engine shard's SSTables into the base table and catches its indexes up." +description: "How Enterprise automatically folds a Realtime Engine shard's SSTables into the base table and catches its indexes up." icon: "compress" availability: embedded: unavailable @@ -11,7 +11,7 @@ availability: [Distributed Compaction](/enterprise/distributed-compaction) merges small base-table fragments and reclaims deleted rows -- the same operation [Compaction](/maintenance/compaction) describes for LanceDB Embedded. A -table with the [real time engine](/tables/realtime-engine) enabled has a +table with the [Realtime Engine](/tables/realtime-engine) enabled has a second, unrelated compaction: folding a shard's accumulated SSTables into the base table and catching the base table's indexes up over the rows that just landed. This produces two job types, `memwal_compaction` and @@ -176,9 +176,9 @@ manifest update in step 6 is the single point where a row's SSTable copy stops being listed, and it only commits after `merge_insert` has already written that row into the base table. -A table queried *without* the real time engine's live path only sees data +A table queried *without* the Realtime Engine's live path only sees data once it has been folded into the base table, so its staleness bound tracks -whichever trigger fires -- wider either way than the real time engine's +whichever trigger fires -- wider either way than the Realtime Engine's own millisecond-scale freshness. A shard under steady write pressure compacts on the count or bytes trigger, within `WAL_COMPACTION_INTERVAL_SECS` plus the compaction job's own runtime. A shard that never gathers enough @@ -197,7 +197,7 @@ for what a live RTE read sees instead. ## What to read next {#next} - + The MemWAL format, shards, and WAL nodes this page assumes. diff --git a/docs/web/ingestion/realtime-write.mdx b/docs/web/ingestion/realtime-write.mdx index 5b61e67bc..21b6eb2fa 100644 --- a/docs/web/ingestion/realtime-write.mdx +++ b/docs/web/ingestion/realtime-write.mdx @@ -1,15 +1,15 @@ --- title: "RTE Write (Upsert)" sidebarTitle: "RTE Write (Upsert)" -description: "Enable the real time engine on a table and absorb small, frequent writes cheaply, each one committed in milliseconds." +description: "Enable the Realtime 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"] +keywords: ["rte", "realtime engine", "wal", "memwal", "lsm", "write-ahead log", "streaming writes", "upsert"] availability: embedded: available enterprise: available --- -The [real time engine](/tables/realtime-engine) puts an LSM-style write tier in +The [Realtime 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 [RTE reads](/search/realtime-read). @@ -239,6 +239,6 @@ for the numbers. - [RTE reads](/search/realtime-read) — query an RTE table - [Distributed RTE Write](/enterprise/distributed-real-time-write) — how Enterprise shards and scales this -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Merge insert](/ingestion/merge-insert) - [`ALTER TABLE ... SET RTE`](/sql/ddl/table#properties) diff --git a/docs/web/search/realtime-read.mdx b/docs/web/search/realtime-read.mdx index 19c5bc2ab..d87d98c81 100644 --- a/docs/web/search/realtime-read.mdx +++ b/docs/web/search/realtime-read.mdx @@ -1,15 +1,15 @@ --- title: "RTE reads" sidebarTitle: "RTE 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." +description: "Query a table with the Realtime 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"] +keywords: ["rte", "realtime engine", "real time search", "real time query", "fresh reads", "memwal", "upsert"] availability: embedded: available enterprise: available --- -A table with the [real time engine](/tables/realtime-engine) enabled queries +A table with the [Realtime 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; for enabling RTE and writing to a table, see [RTE writes](/ingestion/realtime-write). For how Enterprise @@ -79,6 +79,6 @@ available. - [RTE writes](/ingestion/realtime-write) — enable RTE and write to a table - [Distributed RTE Read](/enterprise/distributed-real-time-read) — combining results across machines in Enterprise -- [How the real time engine works](/tables/realtime-engine#memwal-format) +- [How the Realtime Engine works](/tables/realtime-engine#memwal-format) - [Hybrid search](/search/hybrid-search) - [Vector search](/search/vector-search) diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index 6e751667e..ab0ff64bf 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -176,7 +176,7 @@ ALTER TABLE t UNSET RTE ``` -The [real time engine](/tables/realtime-engine) puts a write-ahead log in front +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 diff --git a/docs/web/tables/realtime-engine.mdx b/docs/web/tables/realtime-engine.mdx index 5c6983cc5..09e933894 100644 --- a/docs/web/tables/realtime-engine.mdx +++ b/docs/web/tables/realtime-engine.mdx @@ -1,21 +1,21 @@ --- -title: "Real Time engine (RTE)" -sidebarTitle: "Real Time Engine (RTE)" +title: "Realtime Engine (RTE)" +sidebarTitle: "Realtime Engine (RTE)" description: "Absorb small, frequent writes cheaply and make them queryable within milliseconds." icon: "bolt" -keywords: ["rte", "real time engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] +keywords: ["rte", "realtime engine", "wal", "memwal", "wal node", "lsm", "write-ahead log", "streaming writes", "upsert", "sharding"] availability: embedded: available enterprise: available --- -## What is the real time engine? {#what-is-rte} +## 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 real time engine (RTE) puts an LSM-style write tier in front of the table. +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. From 7d50d2d28f84559672d15f8d91e06bf55cc2fa3d Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 13 Nov 2026 11:44:40 -0800 Subject: [PATCH 105/203] chore(deps): bump Rust deps flagged by security scans (#5035) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Bumps the Rust dependencies flagged by Aikido that have a semver-compatible fix available. Supersedes #5009 (rustls in the docs lockfile is included here). Root `Cargo.lock`: | Crate | From | To | | --- | --- | --- | | mio | 1.2.0 | 1.2.5 | | smallvec | 1.15.1 | 1.16.5 | | thread_local | 1.1.9 | 1.1.10 | | tinyvec | 1.11.0 | 1.13.3 | | zerocopy / zerocopy-derive | 0.8.48 | 0.8.63 | | event-listener | 5.4.1 | 5.4.2 | | arrayvec | 0.7.6 | 0.7.8 | | wasm-bindgen (+ js-sys, web-sys) | 0.2.121 | 0.2.130 | | getrandom 0.4 | 0.4.2 | 0.4.3 (drops wasip3 → wasmparser 0.244) | | brotli | 3.5.0 | 9.1.1 (via `random_word` dev-dep 0.4.3 → 1.0.0) | `docs/web-tests/rs/Cargo.lock` gets the same crates plus rustls, hyper, h2, moka, bytes, crossbeam-epoch and anyhow. That crate is not a workspace member, so cargo refused to resolve it; it now has an empty `[workspace]` table. Still open, blocked upstream: quick-xml 0.41 (lance-io), rand 0.9 (datafusion/lance/candle), heapless 0.8 (rstar via geo), paste, unsafe-libyaml (rattler_conda_types, lindera), fast-float/smartstring (polars 0.39), number_prefix (needs hf-hub 1.0 migration), zstd 0.13 (arrow-ipc). ## Merge Risk **Door:** two-way. Lockfile patch/minor bumps and a dev-only dependency. **Blast Radius:** none expected; no source changes. The docs crate is not built in CI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 282 +++++++------------------------- docs/web-tests/rs/Cargo.lock | 301 ++++++++--------------------------- docs/web-tests/rs/Cargo.toml | 4 + rust/lancedb/Cargo.toml | 2 +- 4 files changed, 127 insertions(+), 462 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index efe0338cd..22b0f1e6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,15 +63,15 @@ dependencies = [ [[package]] name = "alloc-no-stdlib" -version = "2.0.4" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" [[package]] name = "alloc-stdlib" -version = "0.2.2" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ "alloc-no-stdlib", ] @@ -221,9 +221,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" @@ -1474,9 +1474,9 @@ dependencies = [ [[package]] name = "brotli" -version = "3.5.0" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1485,9 +1485,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.5.1" +version = "6.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -2261,7 +2261,7 @@ checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ "cpubits", "ctutils", - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "num-traits", "rand_core 0.10.1", @@ -2285,7 +2285,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "hybrid-array", "rand_core 0.10.1", ] @@ -3504,11 +3504,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", ] @@ -4248,17 +4247,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", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -4939,12 +4936,6 @@ version = "2.2.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" - [[package]] name = "ident_case" version = "1.0.1" @@ -5275,13 +5266,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.98" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if 1.0.4", "futures-util", - "once_cell", "wasm-bindgen", ] @@ -6243,12 +6233,6 @@ 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" @@ -6704,9 +6688,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.0" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -8550,16 +8534,6 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.117", -] - [[package]] name = "primefield" version = "0.14.0" @@ -8870,7 +8844,7 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.1", "rand_pcg", @@ -8973,7 +8947,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -9061,15 +9035,13 @@ dependencies = [ [[package]] name = "random_word" -version = "0.4.3" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07eed67a16dde2cc3c7f65c072acd8d5b2e53d4aab95067c320db851c7651f29" +checksum = "5d9299243acac3cb4f35c9f78d5ad29c87e70cd916a70f293d8526e54049c340" dependencies = [ "ahash", "brotli", - "once_cell", - "paste", - "rand 0.8.6", + "rand 0.10.1", "unicase", ] @@ -10528,9 +10500,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -11014,7 +10986,7 @@ 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 1.1.4", "windows-sys 0.61.2", @@ -11113,9 +11085,9 @@ 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", ] @@ -11183,18 +11155,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" @@ -11744,12 +11707,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" -[[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" @@ -11836,7 +11793,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", @@ -11919,16 +11876,7 @@ version = "1.0.3+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" 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]] @@ -11942,12 +11890,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if 1.0.4", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -11955,19 +11902,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.71" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -11975,48 +11923,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.121" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" 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" @@ -12043,23 +11969,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.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -12579,100 +12493,12 @@ 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" 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" @@ -12775,7 +12601,7 @@ dependencies = [ "countio", "futures", "futures-util", - "getrandom 0.4.2", + "getrandom 0.4.3", "heapify", "itertools 0.14.0", "lz4_flex 0.13.1", @@ -12912,18 +12738,18 @@ dependencies = [ [[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", @@ -12999,7 +12825,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e408c6cc4699dd017d53dc080cd51c2cea2b5354af57a1479bd265ed42911487" dependencies = [ "crc32fast", - "getrandom 0.4.2", + "getrandom 0.4.3", "indexmap 2.14.0", "libc", "memchr", diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock index 6e288950e..85384c8af 100644 --- a/docs/web-tests/rs/Cargo.lock +++ b/docs/web-tests/rs/Cargo.lock @@ -87,9 +87,9 @@ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "ar_archive_writer" @@ -129,9 +129,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" @@ -683,9 +683,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cast" @@ -1019,9 +1019,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] @@ -1904,7 +1904,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1993,7 +1993,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2004,11 +2004,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", ] @@ -2289,17 +2288,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", "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", "wasm-bindgen", ] @@ -2317,9 +2314,9 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "h2" -version = "0.4.12" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2475,9 +2472,9 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" [[package]] name = "hyper" -version = "1.8.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -2490,7 +2487,6 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -2699,12 +2695,6 @@ version = "2.2.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" - [[package]] name = "ident_case" version = "1.0.1" @@ -2808,7 +2798,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2876,7 +2866,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2917,11 +2907,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] @@ -3607,12 +3598,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[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" @@ -3925,9 +3910,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -3936,9 +3921,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.12.11" +version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8261cd88c312e0004c1d51baad2980c66528dfdb2bee62003e643a4d8f86b077" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" dependencies = [ "async-lock", "crossbeam-channel", @@ -3949,7 +3934,6 @@ dependencies = [ "futures-util", "parking_lot", "portable-atomic", - "rustc_version", "smallvec", "tagptr", "uuid", @@ -4062,7 +4046,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4919,7 +4903,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "itertools 0.14.0", "log", "multimap", @@ -5020,7 +5004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", - "getrandom 0.4.2", + "getrandom 0.4.3", "lru-slab", "rand 0.10.3", "rand_pcg", @@ -5046,7 +5030,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -5113,7 +5097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", - "getrandom 0.4.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -5520,14 +5504,14 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.11.0", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -5861,9 +5845,9 @@ checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "smartstring" @@ -5900,7 +5884,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -5912,7 +5896,7 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f103c50866b8743da9429b8a581d81a27c2d3a9c4ac7df8f8571c1dd7896eda" dependencies = [ - "heck 0.5.0", + "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.117", @@ -6247,7 +6231,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.1.2", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6301,9 +6285,9 @@ 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", ] @@ -6371,18 +6355,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -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 = "tokio" @@ -6646,12 +6621,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 = "unsafe-libyaml" version = "0.2.11" @@ -6700,7 +6669,7 @@ version = "1.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "serde_core", "sha1_smol", @@ -6731,9 +6700,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", ] @@ -6750,26 +6719,16 @@ version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wit-bindgen 0.46.0", -] - -[[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]] name = "wasm-bindgen" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -6777,22 +6736,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.56" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ - "cfg-if", "js-sys", - "once_cell", + "tokio", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6800,48 +6757,26 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.6", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.106" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" 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" @@ -6855,23 +6790,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.10.0", - "hashbrown 0.15.5", - "indexmap 2.14.0", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.83" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -6909,7 +6832,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7254,94 +7177,6 @@ version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" -[[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-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.10.0", - "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 = "writeable" version = "0.6.2" @@ -7388,18 +7223,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.31" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", diff --git a/docs/web-tests/rs/Cargo.toml b/docs/web-tests/rs/Cargo.toml index 8bc594c3c..1e1de2e45 100644 --- a/docs/web-tests/rs/Cargo.toml +++ b/docs/web-tests/rs/Cargo.toml @@ -1,3 +1,7 @@ +# Standalone crate pinned to a published lancedb release, not part of the root +# workspace. Without this, cargo commands here fail to resolve the workspace. +[workspace] + [package] name = "rs" version = "0.1.0" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 737c385c1..ef5da44c5 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -118,7 +118,7 @@ lance-testing = { workspace = true } # production remote feature so Python wheels do not resolve its Axum 0.7 stack. lance-namespace-impls = { workspace = true, features = ["rest-adapter"] } tempfile = { workspace = true } -random_word = { version = "0.4.3", features = ["en"] } +random_word = { version = "1.0.0", features = ["en"] } tokio = { workspace = true, features = ["io-util", "macros", "net", "test-util"] } uuid = { workspace = true } walkdir = "2" From b061c3627c46ec3d310cddb0aa45f022f8c4aad2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:52 -0800 Subject: [PATCH 106/203] feat(python): support exist_ok when creating views (#4984) Add `exist_ok=False` to synchronous and asynchronous Python view creation. Passing `True` sends `CREATE VIEW IF NOT EXISTS` and returns the existing view's stored query and schema unchanged; the default continues to fail on an existing name. ```python view = db.create_view("recent_orders", query, exist_ok=True) view = await async_db.create_view("recent_orders", query, exist_ok=True) ``` Requires a SQL server supporting `CREATE VIEW IF NOT EXISTS`. Rust gains an awaitable builder with `.exist_ok(true)`. Existing `.create_view(...).await` calls continue to work; callers requiring `Future` must convert the builder, and custom `Database` implementations must accept the new `exist_ok` argument. Includes Python round-trip coverage and Rust coverage for direct/deferred results and metadata preservation. --- docs/web/sql/ddl/view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 7 ++- python/python/lancedb/db.py | 36 ++++++++--- python/python/lancedb/remote/db.py | 11 +++- python/python/tests/test_view_creation.py | 71 ++++++++++++++++++++++ python/src/connection.rs | 4 +- rust/lancedb/src/connection.rs | 24 +++++--- rust/lancedb/src/connection/create_view.rs | 62 +++++++++++++++++++ rust/lancedb/src/database.rs | 1 + rust/lancedb/src/remote/db.rs | 3 +- rust/lancedb/src/remote/sql/view.rs | 7 ++- rust/lancedb/src/remote/sql_test.rs | 28 ++++++++- 12 files changed, 239 insertions(+), 25 deletions(-) create mode 100644 python/python/tests/test_view_creation.py create mode 100644 rust/lancedb/src/connection/create_view.rs diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index e039fc43a..3d94292ab 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -23,6 +23,16 @@ catalog removal; physical cleanup can continue afterward. ## CREATE VIEW {#create} +{/* Draft for the view exist_ok release. + +`CREATE VIEW IF NOT EXISTS` creates a missing view and returns an existing +view's stored query and schema unchanged. Without `IF NOT EXISTS`, an existing +name is an error. In Python, use `db.create_view(name, query, exist_ok=True)`; +in Rust, use `db.create_view(name, query, &namespace).exist_ok(true).await?`. +Returning an existing view requires `SELECT` on that view. + +*/} + ```sql SQL icon="database" CREATE VIEW "recent_matches" AS diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5897ddd0c..56b644abb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -253,7 +253,12 @@ class Connection(object): self, name: str, namespace_path: Optional[List[str]] = None ) -> Tuple[str, int, int]: ... async def create_view( - self, name: str, query: str, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ... async def describe_view( self, name: str, namespace_path: Optional[List[str]] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 7d690abe3..020c79be0 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1273,7 +1273,12 @@ class DBConnection(EnforceOverrides): ) def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -1281,9 +1286,10 @@ class DBConnection(EnforceOverrides): is refused now rather than at the first read. A view holds no rows, and 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. LanceDB Embedded connections raise - ``NotImplementedError``. + A name already taken is an error unless ``exist_ok=True``, which returns + the existing view's stored query and schema without changing them. + Changing a view is a drop followed by a create. LanceDB Embedded + connections raise ``NotImplementedError``. >>> import lancedb >>> db = lancedb.connect("db://my_database") # doctest: +SKIP @@ -2592,10 +2598,17 @@ class LanceDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override @@ -4107,7 +4120,12 @@ class AsyncConnection(object): ) async def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: """Create a view: a named query the database plans on every read. @@ -4115,7 +4133,9 @@ class AsyncConnection(object): [DBConnection.create_view][lancedb.DBConnection.create_view]. """ return _view_description( - await self._inner.create_view(name, query, list(namespace_path or [])) + await self._inner.create_view( + name, query, list(namespace_path or []), exist_ok=exist_ok + ) ) async def describe_view( diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index db3ab554c..ea9468331 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1197,10 +1197,17 @@ class RemoteDBConnection(DBConnection): @override def create_view( - self, name: str, query: str, *, namespace_path: Optional[List[str]] = None + self, + name: str, + query: str, + *, + exist_ok: bool = False, + namespace_path: Optional[List[str]] = None, ) -> ViewDescription: return LOOP.run( - self._conn.create_view(name, query, namespace_path=namespace_path) + self._conn.create_view( + name, query, exist_ok=exist_ok, namespace_path=namespace_path + ) ) @override diff --git a/python/python/tests/test_view_creation.py b/python/python/tests/test_view_creation.py new file mode 100644 index 000000000..410356da0 --- /dev/null +++ b/python/python/tests/test_view_creation.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_create_view_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + original_query = "SELECT 'original' AS original" + submitted_query = ( + "SELECT 'replacement' AS replacement" if existing else original_query + ) + schema = { + "fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}], + "metadata": { + "lancedb::view::default_db": "analytics", + "lancedb::view::default_namespace": "team", + }, + } + result = pa.table( + {"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]} + ) + + class ViewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with ViewServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + if asynchronous: + db = await lancedb.connect_async("db://analytics", **connection_options) + view = await db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + else: + db = lancedb.connect("db://analytics", **connection_options) + view = db.create_view( + "saved", submitted_query, namespace_path=["team"], **kwargs + ) + (request,) = server.requests + + prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW" + assert f'{prefix} "saved" AS {submitted_query}'.encode() in request + assert view.name == "saved" + assert view.namespace_path == ["team"] + assert view.default_namespace_path == ["team"] + assert view.query == original_query + assert view.schema.names == ["original"] diff --git a/python/src/connection.rs b/python/src/connection.rs index a32c00be1..ffa59fd02 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -1158,18 +1158,20 @@ impl Connection { }) } - #[pyo3(signature = (name, query, namespace_path=None))] + #[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))] pub fn create_view( self_: PyRef<'_, Self>, name: String, query: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { let view = inner .create_view(name, query, &namespace_path) + .exist_ok(exist_ok) .await .infer_error()?; view_description_to_py(view) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index cc398e32b..c7a058502 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -53,6 +53,9 @@ use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; mod create_secret; mod create_table; +mod create_view; + +pub use create_view::CreateViewBuilder; pub use create_secret::CreateSecretBuilder; @@ -976,9 +979,10 @@ impl Connection { /// refused now rather than at the first read. A view holds no rows, and /// 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, each authorized against what it - /// actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. + /// A name already taken is an error unless [`CreateViewBuilder::exist_ok`] is + /// true, which returns the stored definition and schema without changing them. + /// Changing a view is a drop followed by a create, each authorized against what + /// it actually touches. LanceDB Embedded databases return [`Error::NotSupported`]. /// /// # Example /// @@ -1011,16 +1015,18 @@ impl Connection { /// # Ok(()) /// # } /// ``` - pub async fn create_view( + pub fn create_view( &self, name: impl AsRef, query: impl AsRef, namespace_path: &[String], - ) -> Result { - validate_view_reference(name.as_ref(), namespace_path)?; - self.internal - .create_view(name.as_ref(), query.as_ref(), namespace_path) - .await + ) -> CreateViewBuilder { + CreateViewBuilder::new( + self.internal.clone(), + name.as_ref().to_owned(), + query.as_ref().to_owned(), + namespace_path.to_vec(), + ) } /// What this database records about one view: its defining query and the diff --git a/rust/lancedb/src/connection/create_view.rs b/rust/lancedb/src/connection/create_view.rs new file mode 100644 index 000000000..bd80ca6e7 --- /dev/null +++ b/rust/lancedb/src/connection/create_view.rs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::future::{Future, IntoFuture}; +use std::pin::Pin; +use std::sync::Arc; + +use crate::Result; +use crate::database::Database; +use crate::utils::validate_view_reference; +use crate::view::ViewDescription; + +/// Configure creation of a view with [`super::Connection::create_view`]. +#[must_use] +pub struct CreateViewBuilder { + database: Arc, + name: String, + query: String, + namespace_path: Vec, + exist_ok: bool, +} + +impl CreateViewBuilder { + pub(super) fn new( + database: Arc, + name: String, + query: String, + namespace_path: Vec, + ) -> Self { + Self { + database, + name, + query, + namespace_path, + exist_ok: false, + } + } + + /// Return the existing view without changing its definition if it exists. + /// Defaults to false, which reports an error for an existing name. + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + /// Create the view or return the existing view when `exist_ok` is true. + pub async fn execute(self) -> Result { + validate_view_reference(&self.name, &self.namespace_path)?; + self.database + .create_view(&self.name, &self.query, &self.namespace_path, self.exist_ok) + .await + } +} + +impl IntoFuture for CreateViewBuilder { + type Output = Result; + type IntoFuture = Pin + Send>>; + + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.execute()) + } +} diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 23ed9fc3d..39e361a39 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -693,6 +693,7 @@ pub trait Database: _name: &str, _query: &str, _namespace_path: &[String], + _exist_ok: bool, ) -> Result { view_ops_not_supported() } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 92523ec34..a05bb07b7 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1099,11 +1099,12 @@ impl Database for RemoteDatabase { name: &str, query: &str, namespace_path: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace_path)?; self.sql_client()? - .create_view(name, query, namespace_path) + .create_view(name, query, namespace_path, exist_ok) .await } async fn describe_view( diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 0c2229684..513113187 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -99,13 +99,18 @@ impl SqlClient { name: &str, query: &str, namespace: &[String], + exist_ok: bool, ) -> Result { validate_view_name(name)?; validate_namespace(namespace)?; let namespace_path = namespace.to_vec(); + let if_not_exists = if exist_ok { " IF NOT EXISTS" } else { "" }; self.object_job( ExecuteQueryRequest { - query: format!("CREATE VIEW {} AS {query}", quote_identifier(name)), + query: format!( + "CREATE VIEW{if_not_exists} {} AS {query}", + quote_identifier(name) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d25c72830..6a3f30390 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -24,6 +24,7 @@ use super::stream::{PROTOCOL_HEADER, PROTOCOL_VERSION, QueryResponse}; use super::*; use crate::Connection; use crate::database::Database; +use crate::embeddings::MemoryRegistry; use crate::materialized_view::CreateMaterializedViewRequest; use crate::remote::RemoteCatalogOptions; use crate::remote::client::HeaderProvider; @@ -3710,26 +3711,49 @@ async fn view_create_and_describe_return_metadata_through_sql() { ..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(|_| -> http::Response { panic!("unexpected REST request"); }) .with_sql_client(client); - let created = db + let connection = Connection::new(Arc::new(db), Arc::new(MemoryRegistry::new())); + let created = connection .create_view("adults", "SELECT name FROM people", &["team".into()]) .await .unwrap(); - let described = db.describe_view("adults", &["team".into()]).await.unwrap(); + let existing = connection + .create_view( + "adults", + "SELECT replacement FROM other_people", + &["team".into()], + ) + .exist_ok(true) + .await + .unwrap(); + let described = connection + .describe_view("adults", &["team".into()]) + .await + .unwrap(); assert_eq!(created, described); + assert_eq!(existing, described); assert_eq!(created.schema.fields()[0].name(), "name"); assert_eq!(created.default_namespace_path, ["team"]); assert_eq!( statements.lock().unwrap().as_slice(), [ "CREATE VIEW \"adults\" AS SELECT name FROM people", + "CREATE VIEW IF NOT EXISTS \"adults\" AS SELECT replacement FROM other_people", "DESCRIBE VIEW \"adults\"" ] ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|header| header.namespace_path == "team") + ); shutdown.send(()).unwrap(); } } From 2c3c30dbdf02a4dc9f725b00701b995954e228b1 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:35:54 -0800 Subject: [PATCH 107/203] feat(python): support exist_ok for Function creation (#4992) Adds `exist_ok=False` to Python Function creation and job submission. `exist_ok=True` sends `CREATE FUNCTION IF NOT EXISTS` and returns the stored immutable version, preserving its code, credentials and execution settings. The default retains the current version-creation behavior. ```python version = db.create_function(analyze_caption, exist_ok=True) ``` The option also exists on the Rust registration request and is kept out of the canonical Function definition payload. Includes sync/async/background protocol and stored-version coverage. Requires matching SQL server support. BREAKING CHANGE: Rust `FunctionRegistrationRequest` struct literals must initialize `exist_ok`; legacy serialized requests default to false. No local builds or tests were run, as requested. --- docs/web/management/function.mdx | 13 ++++ docs/web/sql/ddl/function.mdx | 9 +++ python/python/lancedb/_lancedb.pyi | 6 +- python/python/lancedb/db.py | 25 +++++++- python/python/lancedb/remote/db.py | 6 +- python/python/tests/test_function_creation.py | 63 +++++++++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/function.rs | 7 +++ rust/lancedb/src/remote/sql/function.rs | 11 +++- rust/lancedb/src/remote/sql_test.rs | 20 +++++- 10 files changed, 155 insertions(+), 11 deletions(-) create mode 100644 python/python/tests/test_function_creation.py diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 04c146bb1..aae67ceb9 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -111,6 +111,19 @@ with `db.get_function(name, version=...)`. The version may be an integer or its string form. Omit `version` to resolve and return the latest currently visible revision. +{/* Draft for the function exist_ok release. + +Use `exist_ok=True` on `create_function` or `create_function_async` to return +the existing named version without changing its code, credentials or settings. +This requires a deployment that supports the option. The default retains the +current behavior of registering a new version. + +```python +version = db.create_function(embed, exist_ok=True) +``` + +*/} + The SQL command submits an internal `create_function` image-build job and waits for publication. The SDK returns the SQL query handle. Query handles diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 95c2d4d6e..55e2d6fe7 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -16,6 +16,15 @@ availability: ## CREATE FUNCTION {#create} +{/* Draft for the function exist_ok release. + +`CREATE FUNCTION IF NOT EXISTS` preserves an existing named Function version, +including its code, credentials and execution settings. In Python, pass +`exist_ok=True` to `create_function` or `create_function_async`. The default +retains the existing version-creation behavior. + +*/} + ```sql SQL icon="database" CREATE FUNCTION f(x int64) RETURNS int64 diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 56b644abb..44523fd42 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -188,7 +188,11 @@ class Connection(object): async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( - self, request_json: str, namespace_path: Optional[List[str]] = None + self, + request_json: str, + namespace_path: Optional[List[str]] = None, + *, + exist_ok: bool = False, ) -> Job: ... async def get_function( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 020c79be0..050b20727 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1004,10 +1004,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. + ``exist_ok=True`` returns the existing named Function version unchanged. + By default, registration retains its existing version-creation behavior. + The server builds the OCI image and registers the completed artifact. This is the blocking counterpart of :meth:`create_function_async`. LanceDB Embedded connections raise ``NotImplementedError``. @@ -1040,7 +1044,10 @@ class DBConnection(EnforceOverrides): ``` """ return self.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ).wait() def create_function_async( @@ -1048,10 +1055,14 @@ class DBConnection(EnforceOverrides): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -2396,11 +2407,15 @@ class LanceDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) @@ -3732,10 +3747,14 @@ class AsyncConnection(object): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> AsyncJob[FunctionVersion]: """Submit a scalar Python function for building and registration. + ``exist_ok=True`` preserves an existing named version and its metadata. + The default retains the existing version-creation behavior. + The server-side job builds the OCI image, then registers the completed artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. @@ -3749,7 +3768,7 @@ class AsyncConnection(object): raise TypeError("create_function_async requires a @function definition") request = definition.bind_secrets(secrets) inner = await self._inner.create_function_async( - request.to_canonical_json(), namespace_path + request.to_canonical_json(), namespace_path, exist_ok=exist_ok ) return _typed_job(inner, FunctionVersion.from_json) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ea9468331..870b85b1e 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -992,11 +992,15 @@ class RemoteDBConnection(DBConnection): definition: FunctionDefinition, *, secrets: Optional[Sequence[EnvVarSecret]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( - definition, secrets=secrets, namespace_path=namespace_path + definition, + secrets=secrets, + exist_ok=exist_ok, + namespace_path=namespace_path, ) ) return Job(job) diff --git a/python/python/tests/test_function_creation.py b/python/python/tests/test_function_creation.py new file mode 100644 index 000000000..823dba7b9 --- /dev/null +++ b/python/python/tests/test_function_creation.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb +from lancedb.functions import function + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"]) +@pytest.mark.parametrize("exist_ok", [None, False, True]) +async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/first_class_functions/v1" + / "remote_function_version.canonical.json" + ) + stored = json.loads(fixture.read_text()) + result = pa.table({"definition": [json.dumps(stored)]}) + + @function(name=stored["name"]) + def replacement(value: float) -> float: + return value * 2 + + class FunctionServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with FunctionServer() as server: + options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs["namespace_path"] = ["team"] + if entry == "async_job": + db = await lancedb.connect_async("db://analytics", **options) + job = await db.create_function_async(replacement, **kwargs) + version = await job.wait() + else: + db = lancedb.connect("db://analytics", **options) + if entry == "sync_job": + version = db.create_function_async(replacement, **kwargs).wait() + else: + version = db.create_function(replacement, **kwargs) + (request,) = server.requests + + prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION" + assert f'{prefix} "{stored["name"]}" FROM '.encode() in request + assert b'"exist_ok"' not in request + assert json.loads(version.to_canonical_json()) == stored diff --git a/python/src/connection.rs b/python/src/connection.rs index ffa59fd02..dabecc048 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -903,15 +903,17 @@ impl Connection { }) } - #[pyo3(signature = (request_json, namespace_path=None))] + #[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))] pub fn create_function_async( self_: PyRef<'_, Self>, request_json: String, namespace_path: Option>, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); - let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) + let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) .infer_error()?; + request.exist_ok = exist_ok; let namespace_path = namespace_path.unwrap_or_default(); future_into_py(self_.py(), async move { inner diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index e3d47948e..d1b63f2ad 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -834,6 +834,9 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s /// database already holds, which Sophon resolves inside the remote runtime. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { + /// Preserve an existing named Function version instead of registering a new one. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, /// Default retries of failed user-code calls. Enterprise only. #[serde(default, skip_serializing_if = "Option::is_none")] pub retry_policy: Option, @@ -876,6 +879,10 @@ pub struct FunctionRegistrationRequest { pub models: Vec, } +fn is_false(value: &bool) -> bool { + !*value +} + impl FunctionRegistrationRequest { /// Decode a registration request supplied by an SDK language binding. pub fn from_json(json: &str) -> Result { diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index c2b5aba06..19a1a6cbc 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -34,13 +34,22 @@ impl SqlClient { validate_function_name(&request.name)?; validate_namespace(namespace)?; let name = quote_identifier(&request.name); + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let mut body = serde_json::to_value(request).map_err(|error| Error::Runtime { message: error.to_string(), })?; body.as_object_mut().unwrap().remove("name"); + body.as_object_mut().unwrap().remove("exist_ok"); self.object_job( ExecuteQueryRequest { - query: format!("CREATE FUNCTION {name} FROM {}", literal(&body.to_string())), + query: format!( + "CREATE FUNCTION{if_not_exists} {name} FROM {}", + literal(&body.to_string()) + ), default_namespace_path: namespace.to_vec(), parameters: None, }, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 6a3f30390..e1780f118 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3087,7 +3087,16 @@ async fn function_creation_and_description_use_sql_query_handles() { const REQUEST: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" ); - for (defer, with_models) in [(false, false), (false, true), (true, false), (true, true)] { + for (defer, with_models, exist_ok) in [ + (false, false, false), + (false, true, false), + (true, false, false), + (true, true, false), + (false, false, true), + (false, true, true), + (true, false, true), + (true, true, true), + ] { let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); request_json["batch_size"] = serde_json::json!(2); request_json["max_concurrency"] = serde_json::json!(4); @@ -3113,9 +3122,11 @@ async fn function_creation_and_description_use_sql_query_handles() { let expected_models = version_json["image"].get("models"); let mut expected_request = request_json.clone(); expected_request.as_object_mut().unwrap().remove("name"); - let request = + let mut request = crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) .unwrap(); + assert!(!request.exist_ok); + request.exist_ok = exist_ok; let result = RecordBatch::try_from_iter(vec![( "definition", Arc::new(StringArray::from(vec![version_json.to_string()])) as ArrayRef, @@ -3151,7 +3162,10 @@ async fn function_creation_and_description_use_sql_query_handles() { { let seen = statements.lock().unwrap(); let encoded = seen[0] - .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .strip_prefix(&format!( + "CREATE FUNCTION{} \"normalize_score\" FROM '", + if exist_ok { " IF NOT EXISTS" } else { "" } + )) .unwrap() .strip_suffix('\'') .unwrap(); From a0eb6b4b71d7b59a5047387a32563b098e349418 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:37:08 -0800 Subject: [PATCH 108/203] feat(python): support exist_ok for storage integrations (#4986) Adds `exist_ok=False` to sync and async Python storage integration creation. `exist_ok=True` sends `CREATE STORAGE INTEGRATION IF NOT EXISTS` and returns the server's stored configuration, preserving the prefix, credentials and external ID. ```python integration = db.create_storage_integration( "raw", storage_provider="S3", storage_prefix="s3://customer-bucket/raw/", aws_role_arn="arn:aws:iam::123456789012:role/access", exist_ok=True, ) ``` The non-exhaustive Rust request also supports `.exist_ok(true)` for every provider. Requires a SQL server supporting this syntax. Includes protocol and provider SQL coverage. No local builds or tests were run, as requested. --- docs/web/sql/ddl/storage-integration.mdx | 10 +++ python/python/lancedb/db.py | 13 +++ python/python/lancedb/remote/db.py | 2 + .../test_storage_integration_creation.py | 85 +++++++++++++++++++ .../lancedb/src/remote/storage_integration.rs | 53 +++++++++++- rust/lancedb/src/storage_integration.rs | 26 ++++++ 6 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 python/python/tests/test_storage_integration_creation.py diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx index 37351f971..9444824ac 100644 --- a/docs/web/sql/ddl/storage-integration.mdx +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -28,6 +28,16 @@ CREATE STORAGE INTEGRATION ``` +{/* Draft for the storage-integration exist_ok release. + +`IF NOT EXISTS` returns an existing integration unchanged, including its provider, +storage prefix, credential references and external ID. In the Python SDK, pass +`exist_ok=True` to `create_storage_integration`. The default reports an error when +the name already exists. +Returning an existing integration requires `USAGE` on that integration. + +*/} + `STORAGE_PROVIDER` and `STORAGE_PREFIX` are required for every provider. `STORAGE_PREFIX` is the URI prefix the integration covers -- a query only matches an integration whose prefix is a prefix of the URI it reads. diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 050b20727..39c9eb1d5 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -432,8 +432,12 @@ class DBConnection(EnforceOverrides): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: + """Register storage access, preserving existing configuration with + ``exist_ok=True``. Existing names are errors by default. + """ raise NotImplementedError def describe_storage_integration( @@ -2503,6 +2507,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -2520,6 +2525,7 @@ class LanceDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) @@ -3888,6 +3894,7 @@ class AsyncConnection(object): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: """Register cloud storage access using database-owned credential Secrets. @@ -3902,6 +3909,10 @@ class AsyncConnection(object): optionally set ``huggingface_token_secret`` to a Secret containing the token; omitting it selects anonymous access at the default rate limits. Registration returns setup instructions without verifying storage access. + + ``exist_ok=True`` returns the stored configuration unchanged when the + integration exists, preserving its provider, prefix and credential + bindings. Existing names are errors by default. """ azure_options = ( azure_tenant_id_secret, @@ -4010,6 +4021,8 @@ class AsyncConnection(object): "aws_access_key_id_secret": reference(aws_access_key_id_secret), "aws_secret_access_key_secret": reference(aws_secret_access_key_secret), } + if exist_ok: + request["exist_ok"] = True info = await self._inner.create_storage_integration( validate_secret_name(name), json.dumps(request), diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 870b85b1e..9221c7ceb 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1091,6 +1091,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret: Optional[Union[str, SecretReference]] = None, gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None, huggingface_token_secret: Optional[Union[str, SecretReference]] = None, + exist_ok: bool = False, namespace_path: Optional[List[str]] = None, ) -> StorageIntegrationInfo: return LOOP.run( @@ -1108,6 +1109,7 @@ class RemoteDBConnection(DBConnection): azure_client_secret_secret=azure_client_secret_secret, gcp_credentials_json_secret=gcp_credentials_json_secret, huggingface_token_secret=huggingface_token_secret, + exist_ok=exist_ok, namespace_path=namespace_path, ) ) diff --git a/python/python/tests/test_storage_integration_creation.py b/python/python/tests/test_storage_integration_creation.py new file mode 100644 index 000000000..13b94d741 --- /dev/null +++ b/python/python/tests/test_storage_integration_creation.py @@ -0,0 +1,85 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + ("exist_ok", "existing"), + [(None, False), (False, False), (True, False), (True, True)], +) +async def test_storage_integration_exist_ok_preserves_server_metadata( + asynchronous, exist_ok, existing +): + flight = pytest.importorskip("pyarrow.flight") + fixture = ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/storage_integration.json" + ) + stored = json.loads(fixture.read_text()) + stored["namespace_path"] = ["team"] + columns = {} + for key, value in stored.items(): + if isinstance(value, (dict, list)): + value = json.dumps(value) + columns[key] = pa.array([None], type=pa.string()) if value is None else [value] + result = pa.table(columns) + prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"] + role = ( + "arn:aws:iam::999999999999:role/replacement" + if existing + else stored["aws_role_arn"] + ) + + class IntegrationServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.requests = [] + + def do_get(self, context, ticket): + self.requests.append(ticket.ticket) + return flight.RecordBatchStream(result) + + with IntegrationServer() as server: + connection_options = { + "api_key": "test-key", + "host_override": "http://localhost:10024", + "sql_host_override": f"grpc://127.0.0.1:{server.port}", + } + kwargs = {} if exist_ok is None else {"exist_ok": exist_ok} + kwargs.update( + storage_provider="S3", + storage_prefix=prefix, + aws_role_arn=role, + namespace_path=["team"], + ) + uri = f"db://{stored['database']}" + if asynchronous: + db = await lancedb.connect_async(uri, **connection_options) + info = await db.create_storage_integration(stored["name"], **kwargs) + else: + db = lancedb.connect(uri, **connection_options) + info = db.create_storage_integration(stored["name"], **kwargs) + (request,) = server.requests + + command = ( + "CREATE STORAGE INTEGRATION IF NOT EXISTS" + if exist_ok + else "CREATE STORAGE INTEGRATION" + ) + assert f'{command} "raw"'.encode() in request + assert prefix.encode() in request + assert role.encode() in request + assert info.storage_prefix == stored["storage_prefix"] + assert info.aws_role_arn == stored["aws_role_arn"] + assert info.aws_external_id == stored["aws_external_id"] + assert info.created_at_millis == stored["created_at_millis"] + assert info.namespace_path == ["team"] diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index bdba4f1df..48dab4c6a 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -54,6 +54,11 @@ pub(super) fn create_sql( namespace: &[String], request: &CreateStorageIntegrationRequest, ) -> Result { + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; if request.storage_provider != StorageProvider::HuggingFace && request.huggingface_token_secret.is_some() { @@ -77,7 +82,7 @@ pub(super) fn create_sql( )); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'HUGGINGFACE' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -115,7 +120,7 @@ pub(super) fn create_sql( .as_ref() .ok_or_else(|| invalid("GCP integrations require gcp_credentials_json_secret"))?; return Ok(format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'GCP' STORAGE_PREFIX = {} GCP_CREDENTIALS_JSON_SECRET = {}", object_name(name, namespace)?, literal(&request.storage_prefix), secret_name(reference)? @@ -135,7 +140,7 @@ pub(super) fn create_sql( .filter(|account| !account.is_empty()) .ok_or_else(|| invalid("Azure integrations require azure_storage_account"))?; let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'AZURE' STORAGE_PREFIX = {} STORAGE_AZURE_STORAGE_ACCOUNT = {}", object_name(name, namespace)?, literal(&request.storage_prefix), literal(account) @@ -169,7 +174,7 @@ pub(super) fn create_sql( return Err(invalid("S3 integrations cannot contain Azure options")); } let mut sql = format!( - "CREATE STORAGE INTEGRATION {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", + "CREATE STORAGE INTEGRATION{if_not_exists} {} STORAGE_PROVIDER = 'S3' STORAGE_PREFIX = {}", object_name(name, namespace)?, literal(&request.storage_prefix) ); @@ -283,6 +288,46 @@ mod tests { use super::*; + #[test] + fn create_if_not_exists_preserves_provider_options() { + let secret = SecretReference::new("credential"); + let requests = [ + CreateStorageIntegrationRequest::s3("s3://bucket/", "role"), + CreateStorageIntegrationRequest::s3_with_secrets( + "s3://bucket/", + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::azure( + "az://container/", + "account", + secret.clone(), + secret.clone(), + secret.clone(), + ), + CreateStorageIntegrationRequest::gcp("gs://bucket/", secret), + CreateStorageIntegrationRequest::huggingface("hf://datasets/acme/data/"), + ]; + for request in requests { + let legacy_json = serde_json::to_value(&request).unwrap(); + assert!(legacy_json.get("exist_ok").is_none()); + let decoded: CreateStorageIntegrationRequest = + serde_json::from_value(legacy_json).unwrap(); + assert!(!decoded.exist_ok); + let strict = create_sql("raw", &[], &request).unwrap(); + let guarded = request.exist_ok(true); + assert_eq!(serde_json::to_value(&guarded).unwrap()["exist_ok"], true); + assert_eq!( + create_sql("raw", &[], &guarded).unwrap(), + strict.replacen( + "CREATE STORAGE INTEGRATION ", + "CREATE STORAGE INTEGRATION IF NOT EXISTS ", + 1, + ) + ); + } + } + #[test] fn sql_quotes_values_and_keeps_secret_root_namespace_explicit() { let role = CreateStorageIntegrationRequest::s3("s3://bucket/it's/", "role'value"); diff --git a/rust/lancedb/src/storage_integration.rs b/rust/lancedb/src/storage_integration.rs index 50bfc0aca..587528037 100644 --- a/rust/lancedb/src/storage_integration.rs +++ b/rust/lancedb/src/storage_integration.rs @@ -40,6 +40,9 @@ impl SecretReference { #[derive(Debug, Clone, Serialize, Deserialize)] #[non_exhaustive] pub struct CreateStorageIntegrationRequest { + /// Return the stored configuration unchanged when the integration already exists. + #[serde(default, skip_serializing_if = "is_false")] + pub exist_ok: bool, pub storage_provider: StorageProvider, pub storage_prefix: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -77,12 +80,31 @@ pub enum StorageProvider { HuggingFace, } +fn is_false(value: &bool) -> bool { + !*value +} + impl CreateStorageIntegrationRequest { + /// Return an existing integration without changing its configuration. + /// Defaults to false, which reports an error for an existing name. + /// + /// ``` + /// use lancedb::storage_integration::CreateStorageIntegrationRequest; + /// let config = CreateStorageIntegrationRequest::huggingface( + /// "hf://datasets/acme/data/", + /// ).exist_ok(true); + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Register a prefix and the customer-owned IAM role authorized to access it. pub fn s3(storage_prefix: impl Into, aws_role_arn: impl Into) -> Self { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: Some(aws_role_arn.into()), aws_access_key_id_secret: None, aws_secret_access_key_secret: None, @@ -105,6 +127,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::S3, storage_prefix: storage_prefix.into(), + exist_ok: false, aws_role_arn: None, aws_access_key_id_secret: Some(access_key), aws_secret_access_key_secret: Some(secret_key), @@ -138,6 +161,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Azure, storage_prefix: storage_prefix.into(), + exist_ok: false, azure_storage_account: Some(storage_account.into()), azure_tenant_id_secret: Some(tenant_id), azure_client_id_secret: Some(client_id), @@ -163,6 +187,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::Gcp, storage_prefix: storage_prefix.into(), + exist_ok: false, gcp_credentials_json_secret: Some(credentials_json), huggingface_token_secret: None, aws_role_arn: None, @@ -189,6 +214,7 @@ impl CreateStorageIntegrationRequest { Self { storage_provider: StorageProvider::HuggingFace, storage_prefix: storage_prefix.into(), + exist_ok: false, huggingface_token_secret: None, gcp_credentials_json_secret: None, aws_role_arn: None, From 4db0d5c7f50a61d1c01a9ef409c11e3ba09d04eb Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 18:48:26 -0800 Subject: [PATCH 109/203] feat(python): support exist_ok when cloning tables (#4990) Adds `exist_ok=False` to Python table cloning and `.exist_ok(true)` to the Rust clone builder. An existing target is returned with its data and version history unchanged; strict duplicate errors remain the default. ```python snapshot = db.clone_table("snapshot", source_uri, exist_ok=True) ``` Embedded cloning skips source reads for an existing target and handles typed creation conflicts. Remote cloning forwards the option to the server. Includes sync/async preservation and remote request coverage, plus SQL syntax documentation for `CREATE TABLE IF NOT EXISTS target CLONE source`. Requires a server supporting the option for remote clones. BREAKING CHANGE: Rust `CloneTableRequest` struct literals must initialize the new `exist_ok` field; `CloneTableRequest::new` remains compatible. No local builds or tests were run, as requested. --- docs/web/management/table.mdx | 12 ++++ docs/web/sql/ddl/table.mdx | 10 ++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 8 +++ python/python/lancedb/remote/db.py | 4 ++ python/python/tests/test_clone_creation.py | 36 ++++++++++++ python/src/connection.rs | 6 +- rust/lancedb/src/connection.rs | 30 +++++++++- rust/lancedb/src/database.rs | 3 + rust/lancedb/src/database/listing.rs | 65 ++++++++++++++-------- rust/lancedb/src/remote/db.rs | 16 +++++- 11 files changed, 162 insertions(+), 30 deletions(-) create mode 100644 python/python/tests/test_clone_creation.py diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index bf6bf3edd..8031a4c49 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -270,6 +270,18 @@ Renaming is not supported on a local directory connection. In LanceDB Enterprise whether a table can be renamed or cloned at all depends on how the deployment stores its catalog. +{/* Draft for the table-clone exist_ok release. + +Pass `exist_ok=True` to keep an existing target table, including its data and +version history, instead of reporting a duplicate. The source is used only when +the target is missing. Remote use requires a deployment that supports this option. + +```python +db.clone_table("docs_snapshot", source_uri="s3://bucket/db/documents.lance", exist_ok=True) +``` + +*/} + A **shallow** clone (the default) references the source's data files rather than copying them, so it is fast and cheap regardless of table size. It is the practical way to branch an experiment off a known version, or to pin a training diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index ab0ff64bf..c8c42d4e0 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -205,6 +205,16 @@ Dropping, renaming, or retyping a column is an SDK operation ## CLONE {#clone} +{/* Draft for the table-clone exist_ok release. + +Use `CREATE TABLE IF NOT EXISTS target CLONE source` to preserve an existing +target unchanged. The Python equivalent is +`db.clone_table("target", source_uri, exist_ok=True)`. Omitting the option reports +an error for an existing target. A skipped clone does not copy rows or change +the target's version history. + +*/} + ```sql SQL icon="database" CREATE TABLE docs_snapshot CLONE documents diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 44523fd42..d5c024959 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -347,6 +347,8 @@ class Connection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + *, + exist_ok: bool = False, ) -> Table: ... async def rename_table( self, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 39c9eb1d5..18ca9cf6f 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -2271,6 +2271,7 @@ class LanceDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> LanceTable: """Clone a table from a source table. @@ -2295,6 +2296,8 @@ class LanceDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -2310,6 +2313,7 @@ class LanceDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return LanceTable.open( @@ -3595,6 +3599,7 @@ class AsyncConnection(object): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> AsyncTable: """Clone a table from a source table. @@ -3619,6 +3624,8 @@ class AsyncConnection(object): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -3633,6 +3640,7 @@ class AsyncConnection(object): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) return AsyncTable(table) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 9221c7ceb..69b691004 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -576,6 +576,7 @@ class RemoteDBConnection(DBConnection): source_version: Optional[int] = None, source_tag: Optional[str] = None, is_shallow: bool = True, + exist_ok: bool = False, ) -> Table: """Clone a table from a source table. @@ -595,6 +596,8 @@ class RemoteDBConnection(DBConnection): is_shallow: bool, default True Whether to perform a shallow clone (True) or deep clone (False). Currently only shallow clone is supported. + exist_ok: bool, default False + Return the existing target unchanged instead of cloning over it. Returns ------- @@ -612,6 +615,7 @@ class RemoteDBConnection(DBConnection): source_version=source_version, source_tag=source_tag, is_shallow=is_shallow, + exist_ok=exist_ok, ) ) return RemoteTable( diff --git a/python/python/tests/test_clone_creation.py b/python/python/tests/test_clone_creation.py new file mode 100644 index 000000000..6c12420c5 --- /dev/null +++ b/python/python/tests/test_clone_creation.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous): + source_uri = str(tmp_path / "source.lance") + if asynchronous: + db = await lancedb.connect_async(tmp_path) + await db.create_table("source", [{"id": 1}]) + table = await db.clone_table("target", source_uri, exist_ok=True) + assert (await table.to_arrow()).to_pylist() == [{"id": 1}] + await table.add([{"id": 2}]) + version = await table.version() + with pytest.raises(ValueError, match="already exists"): + await db.clone_table("target", source_uri) + kept = await db.clone_table("target", "missing.lance", exist_ok=True) + assert await kept.version() == version + assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}] + else: + db = lancedb.connect(tmp_path) + db.create_table("source", [{"id": 1}]) + table = db.clone_table("target", source_uri, exist_ok=True) + assert table.to_arrow().to_pylist() == [{"id": 1}] + table.add([{"id": 2}]) + version = table.version + with pytest.raises(ValueError, match="already exists"): + db.clone_table("target", source_uri) + kept = db.clone_table("target", "missing.lance", exist_ok=True) + assert kept.version == version + assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}] diff --git a/python/src/connection.rs b/python/src/connection.rs index dabecc048..8763822cc 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -457,7 +457,8 @@ impl Connection { }) } - #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))] pub fn clone_table( self_: PyRef<'_, Self>, target_table_name: String, @@ -466,6 +467,7 @@ impl Connection { source_version: Option, source_tag: Option, is_shallow: bool, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); @@ -477,7 +479,7 @@ impl Connection { if let Some(tag) = source_tag { builder = builder.source_tag(tag); } - builder = builder.is_shallow(is_shallow); + builder = builder.is_shallow(is_shallow).exist_ok(exist_ok); future_into_py(self_.py(), async move { let table = builder.execute().await.infer_error()?; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index c7a058502..6dacbbbea 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -433,6 +433,21 @@ impl CloneTableBuilder { } } + /// Preserve an existing target without reading or cloning the source. + /// Defaults to false, which reports a duplicate-name error. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let table = db.clone_table("snapshot", "s3://bucket/source.lance") + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.request.exist_ok = exist_ok; + self + } + /// Set the source version to clone from pub fn source_version(mut self, version: u64) -> Self { self.request.source_version = Some(version); @@ -633,7 +648,8 @@ impl Connection { /// Creates a new table by cloning from an existing source table. /// By default, this performs a shallow clone where the new table shares /// the underlying data files with the source table. - /// The target table name must be unused. An existing table is left unchanged. + /// The target table name must be unused by default. Use + /// [`CloneTableBuilder::exist_ok`] to open an existing target unchanged. /// /// # Parameters /// - `target_table_name`: The name of the new table to create @@ -2787,6 +2803,14 @@ mod tests { "unexpected clone error: {err:?}" ); + let preserved = db + .clone_table(target, "missing-source.lance") + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(preserved.name(), target); + // Reopen both tables to verify that the failed clone left their data and versions intact. for (name, expected_data) in [("source", source_data), ("target", target_data)] { let table = db.open_table(name).execute().await.unwrap(); @@ -2804,8 +2828,9 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { let tmp_dir = tempdir().unwrap(); let uri = tmp_dir.path().to_str().unwrap(); let db = connect(uri).execute().await.unwrap(); @@ -2830,6 +2855,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table("cloned_table", source_uri) + .exist_ok(exist_ok) .execute() .await .unwrap(); diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 39e361a39..638ae0dd5 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -163,6 +163,8 @@ impl CreateTableRequest { /// sharing the same data, deletion, and index files. #[derive(Clone, Debug)] pub struct CloneTableRequest { + /// Preserve an existing target rather than returning a duplicate-name error. + pub exist_ok: bool, /// The name of the target table to create pub target_table_name: String, /// The namespace path for the target table. Empty list represents root namespace. @@ -184,6 +186,7 @@ pub struct CloneTableRequest { impl CloneTableRequest { pub fn new(target_table_name: String, source_uri: String) -> Self { Self { + exist_ok: false, target_table_name, target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index d5749f974..765c8af3d 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1119,40 +1119,47 @@ impl Database for ListingDatabase { }; let target_uri = self.table_uri(&request.target_table_name)?; - match DatasetBuilder::from_uri(&target_uri) + let exists = match DatasetBuilder::from_uri(&target_uri) .with_read_params(read_params.clone()) .load() .await { - Ok(_) => { + Ok(_) if !request.exist_ok => { return Err(Error::TableAlreadyExists { name: request.target_table_name, }); } - Err(lance::Error::DatasetNotFound { .. }) => {} + Ok(_) => true, + Err(lance::Error::DatasetNotFound { .. }) => false, Err(err) => return Err(err.into()), + }; + + if !exists { + let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) + .with_read_params(read_params.clone()) + .load() + .await + .map_err(|e| -> Error { e.into() })?; + + let version_ref = match (request.source_version, request.source_tag) { + (Some(v), None) => Ok(Ref::Version(None, Some(v))), + (None, Some(tag)) => Ok(Ref::Tag(tag)), + (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), + _ => Err(Error::InvalidInput { + message: "Cannot specify both source_version and source_tag".to_string(), + }), + }?; + + match source_dataset + .shallow_clone(&target_uri, version_ref, Some(storage_params)) + .await + { + Ok(_) => {} + Err(lance::Error::DatasetAlreadyExists { .. }) if request.exist_ok => {} + Err(error) => return Err(error.into()), + } } - let mut source_dataset = DatasetBuilder::from_uri(&request.source_uri) - .with_read_params(read_params.clone()) - .load() - .await - .map_err(|e| -> Error { e.into() })?; - - let version_ref = match (request.source_version, request.source_tag) { - (Some(v), None) => Ok(Ref::Version(None, Some(v))), - (None, Some(tag)) => Ok(Ref::Tag(tag)), - (None, None) => Ok(Ref::Version(None, Some(source_dataset.version().version))), - _ => Err(Error::InvalidInput { - message: "Cannot specify both source_version and source_tag".to_string(), - }), - }?; - - source_dataset - .shallow_clone(&target_uri, version_ref, Some(storage_params)) - .await - .map_err(|e| -> Error { e.into() })?; - let cloned_table = NativeTable::open_with_params( &target_uri, &request.target_table_name, @@ -2252,6 +2259,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_table".to_string(), target_namespace_path: vec![], source_uri: source_uri.clone(), @@ -2313,6 +2321,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_with_data".to_string(), target_namespace_path: vec![], source_uri, @@ -2375,6 +2384,7 @@ mod tests { // Clone should work with storage options let cloned = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2412,6 +2422,7 @@ mod tests { // Try deep clone (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2453,6 +2464,7 @@ mod tests { // Try clone with namespace (should fail for listing database) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec!["namespace".to_string()], // Non-empty namespace source_uri, @@ -2494,6 +2506,7 @@ mod tests { // Try clone with invalid target name let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "invalid/name".to_string(), // Invalid name with slash target_namespace_path: vec![], source_uri, @@ -2514,6 +2527,7 @@ mod tests { // Try to clone from non-existent source let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri: "/nonexistent/table.lance".to_string(), @@ -2551,6 +2565,7 @@ mod tests { // Try clone with both version and tag (should fail) let result = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned".to_string(), target_namespace_path: vec![], source_uri, @@ -2625,6 +2640,7 @@ mod tests { // Clone from the initial version (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_version".to_string(), target_namespace_path: vec![], source_uri, @@ -2704,6 +2720,7 @@ mod tests { // Clone from the tag (should have only 2 rows) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_from_tag".to_string(), target_namespace_path: vec![], source_uri, @@ -2756,6 +2773,7 @@ mod tests { // Clone the table let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "independent_clone".to_string(), target_namespace_path: vec![], source_uri, @@ -2849,6 +2867,7 @@ mod tests { // Clone without specifying version or tag (should get latest) let cloned_table = db .clone_table(CloneTableRequest { + exist_ok: false, target_table_name: "cloned_latest".to_string(), target_namespace_path: vec![], source_uri, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a05bb07b7..300cd6b09 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1612,10 +1612,13 @@ impl Database for RemoteDatabase { is_shallow: Some(request.is_shallow), }; - let req = self + let mut req = self .client .post(&format!("/v1/table/{}/clone", table_identifier.clone())) .json(&remote_request); + if request.exist_ok { + req = req.query(&[("exist_ok", true)]); + } let (request_id, rsp) = self.client.send(req).await?; @@ -3651,9 +3654,10 @@ mod tests { } } + #[rstest::rstest] #[tokio::test] - async fn test_clone_table() { - let conn = Connection::new_with_handler(|request| { + async fn test_clone_table(#[values(false, true)] exist_ok: bool) { + let conn = Connection::new_with_handler(move |request| { assert_eq!(request.method(), &reqwest::Method::POST); assert_eq!(request.url().path(), "/v1/table/cloned_table/clone"); assert_eq!( @@ -3665,12 +3669,18 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(body).unwrap(); assert_eq!(body["source_location"], "s3://bucket/source_table"); assert_eq!(body["is_shallow"], true); + if exist_ok { + assert_eq!(request.url().query(), Some("exist_ok=true")); + } else { + assert!(request.url().query().is_none()); + } http::Response::builder().status(200).body("").unwrap() }); let table = conn .clone_table("cloned_table", "s3://bucket/source_table") + .exist_ok(exist_ok) .execute() .await .unwrap(); From 81d04b8c361b596b29f4f7988aab7df0eb9f84ca Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:29 -0800 Subject: [PATCH 110/203] feat(python): support exist_ok for materialized views (#4991) --- docs/web/sql/ddl/materialized-view.mdx | 10 +++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 25 ++++++ python/python/lancedb/namespace.py | 8 ++ python/python/lancedb/remote/db.py | 4 + .../tests/test_materialized_view_creation.py | 84 +++++++++++++++++++ .../python/tests/test_materialized_views.py | 2 + python/src/connection.rs | 10 ++- rust/lancedb/src/materialized_view.rs | 49 ++++++++++- rust/lancedb/src/remote/db.rs | 11 ++- .../src/remote/sql/materialized_view.rs | 15 ++++ rust/lancedb/src/remote/sql_test.rs | 60 +++++++++++++ rust/lancedb/src/remote/table.rs | 7 ++ 13 files changed, 281 insertions(+), 6 deletions(-) create mode 100644 python/python/tests/test_materialized_view_creation.py diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index 2f9173ecd..a2453ba01 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -27,6 +27,16 @@ CREATE MATERIALIZED VIEW AS SELECT ... ``` +{/* Draft for the materialized-view exist_ok release. + +`IF NOT EXISTS` preserves an existing materialized view's definition, data and +refresh settings without refreshing it. The Python equivalent is +`db.create_materialized_view("saved", "source", exist_ok=True)`. A skipped +asynchronous creation returns a completed job without submitting a refresh job. +Existing names are errors by default. + +*/} + 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). diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index d5c024959..e3f00557c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -369,6 +369,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> Table: ... async def create_materialized_view_async( self, @@ -382,6 +383,7 @@ class Connection(object): auto_refresh_interval_seconds: Optional[float] = None, *, query: Optional[str] = None, + exist_ok: bool = False, ) -> 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 18ca9cf6f..b84e4d581 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -710,11 +710,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: 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``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -780,11 +784,15 @@ class DBConnection(EnforceOverrides): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: 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. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + The job may already be complete in LanceDB Embedded. In LanceDB Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL server and the returned ``id`` is the registry job ID. That ID can be @@ -2150,11 +2158,15 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: 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``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -2185,6 +2197,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -2202,6 +2215,7 @@ class LanceDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -2214,6 +2228,7 @@ class LanceDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -3453,11 +3468,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: 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``. + ``exist_ok=True`` preserves an existing view's definition, data and + refresh settings without refreshing it. Existing names error by default. + LanceDB Embedded creation and refresh require a source build with the ``experimental-functions`` Cargo feature. Published packages leave it disabled; LanceDB Enterprise operations remain available. @@ -3480,6 +3499,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, @@ -3496,11 +3516,15 @@ class AsyncConnection(object): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: 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. + ``exist_ok=True`` preserves an existing view without refreshing it. + A skipped creation returns a completed job without a registry job ID. + Wait for the returned job before opening or querying the view. In LanceDB Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. @@ -3521,6 +3545,7 @@ class AsyncConnection(object): filter=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, **native_options, diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 72dc78c8b..67fcc61f7 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -705,6 +705,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "MaterializedView": """Define a materialized view over a table in the root namespace. See @@ -723,6 +724,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ).name ) @@ -741,6 +743,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> Job[None]: job = LOOP.run( self._inner.create_materialized_view_async( @@ -753,6 +756,7 @@ class LanceNamespaceDBConnection(DBConnection): with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) ) return Job(job) @@ -1352,6 +1356,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> "AsyncMaterializedView": """Define a materialized view over a table in the root namespace.""" view = await self._inner.create_materialized_view( @@ -1364,6 +1369,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) # Reopen through the namespace so the view's table carries the # namespace client and pushdown configuration a bare inner table lacks. @@ -1381,6 +1387,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + exist_ok: bool = False, ) -> AsyncJob[None]: """Submit materialized-view creation and return its job.""" return await self._inner.create_materialized_view_async( @@ -1393,6 +1400,7 @@ class AsyncLanceNamespaceDBConnection: with_no_data=with_no_data, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, + exist_ok=exist_ok, ) 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 69b691004..b9928d278 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -803,6 +803,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> MaterializedView: @@ -817,6 +818,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) @@ -841,6 +843,7 @@ class RemoteDBConnection(DBConnection): where: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, + exist_ok: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, ) -> Job[None]: @@ -853,6 +856,7 @@ class RemoteDBConnection(DBConnection): where=where, limit=limit, with_no_data=with_no_data, + exist_ok=exist_ok, auto_refresh_enabled=auto_refresh_enabled, auto_refresh_interval_seconds=auto_refresh_interval_seconds, ) diff --git a/python/python/tests/test_materialized_view_creation.py b/python/python/tests/test_materialized_view_creation.py new file mode 100644 index 000000000..0d9a4c2b4 --- /dev/null +++ b/python/python/tests/test_materialized_view_creation.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +import lancedb + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("defining_query", [False, True]) +async def test_exist_ok_preserves_materialized_data( + tmp_path, asynchronous, background, namespace, defining_query +): + source_args = ( + {"query": "SELECT * FROM source"} if defining_query else {"source": "source"} + ) + replacement_args = { + **( + {"query": "SELECT * FROM missing"} + if defining_query + else {"source": "missing"} + ), + "auto_refresh_enabled": True, + "auto_refresh_interval_seconds": 1, + } + options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}} + if asynchronous: + db = ( + lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options) + if namespace + else await lancedb.connect_async(tmp_path, **options) + ) + source = await db.create_table("source", [{"id": 1}]) + original = await db.create_materialized_view( + "saved", **source_args, exist_ok=True + ) + definition = await original.definition() + version = await original.table.version() + await source.add([{"id": 2}]) + if background: + job = await db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + await job.wait() + kept = await db.open_materialized_view("saved") + else: + kept = await db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert (await kept.definition()).query == definition.query + assert await kept.table.version() == version + assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + await db.create_materialized_view("saved", **source_args) + else: + db = ( + lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options) + if namespace + else lancedb.connect(tmp_path, **options) + ) + source = db.create_table("source", [{"id": 1}]) + original = db.create_materialized_view("saved", **source_args, exist_ok=True) + definition = original.definition + version = original.table.version + source.add([{"id": 2}]) + if background: + job = db.create_materialized_view_async( + "saved", **replacement_args, exist_ok=True + ) + job.wait() + kept = db.open_materialized_view("saved") + else: + kept = db.create_materialized_view( + "saved", **replacement_args, exist_ok=True + ) + assert kept.definition.query == definition.query + assert kept.table.version == version + assert kept.table.to_arrow().to_pylist() == [{"id": 1}] + with pytest.raises(ValueError, match="already exists"): + db.create_materialized_view("saved", **source_args) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 1ea0c1cb9..13950a39c 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -197,6 +197,7 @@ def test_sync_remote_create_uses_public_async_connection(query): where=None, limit=None, with_no_data=False, + exist_ok=False, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, ): @@ -729,6 +730,7 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options "filter": None, "limit": None, "with_no_data": False, + "exist_ok": False, "auto_refresh_enabled": options.get("auto_refresh_enabled"), "auto_refresh_interval_seconds": options.get( "auto_refresh_interval_seconds" diff --git a/python/src/connection.rs b/python/src/connection.rs index 8763822cc..1a171032c 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -507,7 +507,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, @@ -519,6 +519,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -529,7 +530,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -552,7 +553,7 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, @@ -564,6 +565,7 @@ impl Connection { auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, query: Option, + exist_ok: bool, ) -> PyResult> { let inner = self_.get_inner()?.clone(); let builder = materialized_view_builder( @@ -574,7 +576,7 @@ impl Connection { projections.is_some() || filter.is_some() || limit.is_some(), )?; future_into_py(self_.py(), async move { - let mut builder = builder; + let mut builder = builder.exist_ok(exist_ok); if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 9920cd893..4b2a61f2c 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -287,6 +287,8 @@ pub struct MaterializedViewInfo { #[doc(hidden)] #[derive(Debug, Clone, PartialEq)] pub struct CreateMaterializedViewRequest { + /// Preserve an existing materialized view without refreshing it. + pub exist_ok: bool, /// Name of the new view. pub name: String, /// Namespace in which to create the view. @@ -1586,6 +1588,7 @@ pub struct CreateMaterializedViewBuilder { filter: Option, limit: Option, with_no_data: bool, + exist_ok: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, } @@ -1626,6 +1629,7 @@ impl CreateMaterializedViewBuilder { filter: None, limit: None, with_no_data: false, + exist_ok: false, auto_refresh_enabled: None, auto_refresh_interval_seconds: None, } @@ -1678,6 +1682,35 @@ impl CreateMaterializedViewBuilder { self } + /// Preserve an existing view's definition, data and refresh settings. + /// Defaults to false. A skipped creation does not refresh the view. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// db.create_materialized_view("saved", "source").exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + + async fn existing_view(&self) -> Result> { + match self + .connection + .open_table(&self.name) + .namespace(self.namespace.clone()) + .execute() + .await + { + Ok(table) => MaterializedView::from_table(table).await.map(Some), + Err(Error::TableNotFound { .. }) => Ok(None), + Err(error) => Err(error), + } + } + /// Enable or disable automatic refresh in LanceDB Enterprise. /// When omitted, the server determines whether automatic refresh is enabled. /// LanceDB Embedded does not support automatic refresh. @@ -1759,6 +1792,7 @@ impl CreateMaterializedViewBuilder { .connection .database() .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: self.exist_ok, name: self.name.clone(), namespace_path: self.namespace.clone(), query: self.query()?, @@ -1793,6 +1827,11 @@ impl CreateMaterializedViewBuilder { async fn execute_native(self) -> Result { crate::require_experimental_functions()?; + if self.exist_ok + && let Some(view) = self.existing_view().await? + { + return Ok(view); + } if self.auto_refresh_enabled == Some(true) || self.auto_refresh_interval_seconds.is_some() { return Err(Error::NotSupported { message: "automatic materialized-view refresh requires LanceDB Enterprise" @@ -1826,7 +1865,15 @@ impl CreateMaterializedViewBuilder { prepare_definition(&source, definition).await? } }; - let view = prepared.create_in(&self.namespace, &self.name).await?; + let view = match prepared.create_in(&self.namespace, &self.name).await { + Ok(view) => view, + Err(Error::TableAlreadyExists { .. }) if self.exist_ok => { + return self.existing_view().await?.ok_or_else(|| Error::Runtime { + message: "materialized view disappeared after concurrent creation".into(), + }); + } + Err(error) => return Err(error), + }; if !self.with_no_data { view.refresh().execute().await?; } diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 300cd6b09..7100e1b04 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -803,16 +803,24 @@ impl Database for RemoteDatabase { } else { format!(" WITH ({})", options.join(", ")) }; + let if_not_exists = if request.exist_ok { + " IF NOT EXISTS" + } else { + "" + }; let submission = client .submit_materialized_view_job( format!( - "CREATE MATERIALIZED VIEW \"{name}\"{options} AS {}", + "CREATE MATERIALIZED VIEW{if_not_exists} \"{name}\"{options} AS {}", request.query ), request.namespace_path, ) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Ok(Job::new_done()) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new(Box::new(RemoteJob::new( @@ -4865,6 +4873,7 @@ mod tests { for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] { let result = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec![], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index 4eaad5156..e982afac7 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -39,6 +39,7 @@ fn strings(batch: &RecordBatch, name: &str) -> Result> { } pub(in crate::remote) enum MaterializedViewJobSubmission { + AlreadyExists, Registry { job_id: String }, Query(Arc), } @@ -66,6 +67,7 @@ impl SqlClient { let mut reader: SendableRecordBatchStream = query.reader().await?; let mut rows = 0; let mut registry_job_id = None; + let mut already_exists = false; while let Some(batch) = reader.try_next().await? { rows += batch.num_rows(); if rows > 1 { @@ -74,6 +76,16 @@ impl SqlClient { .into(), }); } + if let Some(column) = batch.column_by_name("status") { + let values = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission status is not UTF-8".into(), + })?; + already_exists = + values.len() == 1 && !values.is_null(0) && values.value(0) == "already_exists"; + } if let Some(column) = batch.column_by_name("job_id") { let values = column .as_any() @@ -100,6 +112,9 @@ impl SqlClient { message: "materialized-view submission must return exactly one status row".into(), }); } + if already_exists && registry_job_id.is_none() { + return Ok(MaterializedViewJobSubmission::AlreadyExists); + } let job_id = registry_job_id.ok_or_else(|| Error::Runtime { message: "server acknowledged an early materialized-view handle but returned no job_id" .into(), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index e1780f118..1c39eda19 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -1220,6 +1220,7 @@ async fn remote_create_uses_sql_and_preserves_options_and_namespace() { ] { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1302,6 +1303,7 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), @@ -1329,6 +1331,63 @@ async fn remote_create_returns_the_registry_job_from_the_early_status_row() { shutdown.send(()).unwrap(); } +#[tokio::test] +async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry_job() { + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + materialized_view_job_handle_supported: true, + ..Default::default() + }; + let statement = "CREATE MATERIALIZED VIEW IF NOT EXISTS \"adults\" AS SELECT * FROM people"; + service.result_overrides.lock().unwrap().insert( + statement.into(), + RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec!["already_exists"])) as arrow_array::ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![""])) as arrow_array::ArrayRef, + ), + ]) + .unwrap(), + ); + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!( + "a skipped creation must not poll a registry job: {}", + request.url() + ); + }) + .with_sql_client(client); + let job = db + .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: true, + name: "adults".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + }) + .await + .unwrap(); + if defer { + assert!(job.id().is_none()); + } else { + assert_eq!(job.job_type().as_deref(), Some("query")); + } + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert_eq!(*statements.lock().unwrap(), [statement]); + shutdown.send(()).unwrap(); + } +} + #[tokio::test] async fn remote_create_registry_handle_reopens_describes_and_cancels() { let service = TestSqlService { @@ -1394,6 +1453,7 @@ async fn remote_create_registry_handle_reopens_describes_and_cancels() { let job = db .create_materialized_view_async(CreateMaterializedViewRequest { + exist_ok: false, name: "adults".into(), namespace_path: vec!["team".into(), "reports".into()], query: "SELECT * FROM people".into(), diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 9b64ab56d..f4e5c1e4a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2658,6 +2658,13 @@ impl BaseTable for RemoteTable { .submit_materialized_view_job(statement, self.namespace.clone()) .await?; match submission { + crate::remote::sql::materialized_view::MaterializedViewJobSubmission::AlreadyExists => { + Err(Error::Runtime { + message: + "REFRESH MATERIALIZED VIEW returned a create-only already_exists status" + .into(), + }) + } crate::remote::sql::materialized_view::MaterializedViewJobSubmission::Registry { job_id, } => Ok(Job::new_typed(Box::new(MaterializedViewRefreshJob { From f6311ae7e9c34ab8fc5067282fec864bd9f3a558 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 13 Nov 2026 19:21:50 -0800 Subject: [PATCH 111/203] feat: support exist_ok for index creation (#4993) --- docs/web/sql/ddl/index.mdx | 40 +++++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/remote/table.py | 10 ++ python/python/lancedb/table.py | 71 ++++++++- python/python/tests/test_index.py | 42 ++++++ python/python/tests/test_remote_db.py | 52 +++++++ python/python/tests/test_table.py | 96 ++++++++++++ python/python/tests/test_table_signatures.py | 6 +- python/src/table.rs | 10 +- rust/lancedb/src/index.rs | 17 +++ rust/lancedb/src/remote/table.rs | 42 +++++- rust/lancedb/src/table.rs | 8 +- rust/lancedb/src/table/create_index.rs | 146 ++++++++++++++++++- 13 files changed, 525 insertions(+), 17 deletions(-) diff --git a/docs/web/sql/ddl/index.mdx b/docs/web/sql/ddl/index.mdx index 425af7376..035424b5f 100644 --- a/docs/web/sql/ddl/index.mdx +++ b/docs/web/sql/ddl/index.mdx @@ -38,6 +38,46 @@ runs as `create_` followed by the algorithm instead. See [Incremental Indexing](/indexing/incremental-indexing). +{/* Draft for the index exist_ok release. + +```sql +CREATE INDEX IF NOT EXISTS text_search ON documents USING fts (text) +``` + +Use `IF NOT EXISTS` to preserve the existing index with the same name. Without an +explicit name, the name is derived from the column (`title_idx`, or +`title_list_element_idx` for list-element FTS). Existing definitions and builds +are kept, even when the new request specifies different settings. + +The Python SDK exposes the same behavior through `exist_ok=True` on +`create_index` and `create_index_async`, including scalar and FTS wrappers. +This option takes precedence over `replace`, whose default behavior is unchanged. + +```python +from lancedb.index import BTree + +table.create_index("title", config=BTree(), name="title_idx", exist_ok=True) +``` + +```rust +use lancedb::index::Index; + +table.create_index(&["title"], Index::BTree(Default::default())) + .name("title_idx".to_string()) + .exist_ok(true) + .execute() + .await?; +``` + +The SDK option is available in Python and Rust. TypeScript support is a separate +follow-up. Remote use requires a server that supports the option. + +An existing background build continues running. A completed submission handle +for a skipped creation does not wait for that build; use `wait_for_index` when +its completion is required. + +*/} + ## DROP INDEX {#drop} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index e3f00557c..cbc62f772 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -591,6 +591,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ): ... async def create_index_async( self, @@ -615,6 +616,7 @@ class Table: *, name: Optional[str], train: Optional[bool], + exist_ok: bool = False, ) -> Job: ... async def list_versions(self) -> List[Dict[str, Any]]: ... async def version(self) -> int: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 6730e6694..dbfd127ee 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -369,6 +369,7 @@ class RemoteTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -395,6 +396,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -433,6 +435,7 @@ class RemoteTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -492,6 +495,7 @@ class RemoteTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -516,6 +520,7 @@ class RemoteTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -541,6 +546,7 @@ class RemoteTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -572,6 +578,7 @@ class RemoteTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -675,6 +682,7 @@ class RemoteTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -690,6 +698,7 @@ class RemoteTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -702,6 +711,7 @@ class RemoteTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 5f0af7a66..e0b96e476 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -168,6 +168,36 @@ def _validate_index_accelerator(accelerator: Any) -> None: raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err +def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options): + if exist_ok: + parts = _parse_field_path(options["column"]) + default_name = ".".join(parts) + if any("." in part for part in parts): + default_name = ".".join( + "`" + part.replace("`", "``") + "`" + if any( + not character.isalnum() and character != "_" for character in part + ) + else part + for part in parts + ) + name = name or f"{default_name}_idx" + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + options["replace"] = False + options["name"] = name + _validate_index_accelerator(options.get("accelerator")) + try: + dataset.create_index(**options) + except Exception: + if exist_ok: + dataset.checkout_latest() + if any(index["name"] == name for index in dataset.list_indices()): + return + raise + + def _polars_predicate_pushdown_barrier(frame: Any) -> Any: """Return a Polars frame unchanged while blocking predicate pushdown.""" return frame @@ -1834,6 +1864,7 @@ class Table(ABC): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -1859,6 +1890,7 @@ class Table(ABC): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -1890,6 +1922,7 @@ class Table(ABC): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -1913,6 +1946,9 @@ class Table(ABC): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional LanceDB Enterprise only: how long to wait for the index build to finish. If not set, the call returns once the build is scheduled. @@ -1968,6 +2004,7 @@ class Table(ABC): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -2060,6 +2097,7 @@ class Table(ABC): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -2144,6 +2182,7 @@ class Table(ABC): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on the table. @@ -4318,6 +4357,7 @@ class LanceTable(Table): replace: bool = ..., wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., ) -> None: ... @@ -4343,6 +4383,7 @@ class LanceTable(Table): *, wait_timeout: Optional[timedelta] = ..., name: Optional[str] = ..., + exist_ok: bool = ..., train: bool = ..., target_partition_size: Optional[int] = ..., ) -> None: ... @@ -4374,6 +4415,7 @@ class LanceTable(Table): config: Optional[IndexConfigType] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, target_partition_size: Optional[int] = None, ): @@ -4397,6 +4439,9 @@ class LanceTable(Table): BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS. replace : bool, default True Whether to replace an existing index on this column. + exist_ok : bool, default False + Preserve the existing index with the requested or derived name. + Takes precedence over replace and keeps its definition and build. wait_timeout : timedelta, optional Timeout to wait for async indexing to complete. name : str, optional @@ -4465,8 +4510,10 @@ class LanceTable(Table): # Handle accelerator through pylance if accelerator is not None: dataset = self.to_lance() - _validate_index_accelerator(accelerator) - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=index_type, metric=metric, @@ -4492,7 +4539,6 @@ class LanceTable(Table): 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", @@ -4509,7 +4555,10 @@ class LanceTable(Table): if num_bits is not None: quantization_kwargs["num_bits"] = num_bits - dataset.create_index( + _create_accelerated_index( + dataset, + exist_ok=exist_ok, + name=name, column=column, index_type=lance_index_type, metric=getattr(config, "distance_type", "l2"), @@ -4531,6 +4580,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4546,6 +4596,7 @@ class LanceTable(Table): replace: Optional[bool] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> Job: """Create an index, returning a handle to the indexing job. @@ -4564,6 +4615,7 @@ class LanceTable(Table): self._table.create_index_async( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4684,6 +4736,7 @@ class LanceTable(Table): index_type: ScalarIndexType = "BTREE", wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a scalar index on a column. @@ -4710,6 +4763,7 @@ class LanceTable(Table): self._table.create_index( column, replace=replace, + exist_ok=exist_ok, config=config, wait_timeout=wait_timeout, name=name, @@ -4747,6 +4801,7 @@ class LanceTable(Table): document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, ): """Create a full-text search index on a column. @@ -4808,6 +4863,7 @@ class LanceTable(Table): self._table.create_index( field_names, replace=replace, + exist_ok=exist_ok, config=config, name=name, wait_timeout=wait_timeout, @@ -6806,6 +6862,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ): """Create an index to speed up queries @@ -6836,6 +6893,9 @@ class AsyncTable: If not set, the call returns once the build is scheduled. name: str, optional The name of the index. If not provided, a default name will be generated. + exist_ok: bool, default False + Preserve an existing index with the requested or derived name. This + takes precedence over replace and keeps its definition and build. train: bool, default True Whether to train the index with existing data. Vector indices always train with existing data. @@ -6891,6 +6951,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, @@ -6928,6 +6989,7 @@ class AsyncTable: ] = None, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, + exist_ok: bool = False, train: bool = True, ) -> AsyncJob: """Create an index, returning a handle to the indexing job. @@ -6946,6 +7008,7 @@ class AsyncTable: column, index=config, replace=replace, + exist_ok=exist_ok, wait_timeout=wait_timeout, name=name, train=train, diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 738a791ad..e658d18e1 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -621,3 +621,45 @@ def test_index_statistics_index_type_lists_all_supported_values(): set(get_args(get_type_hints(IndexStatistics)["index_type"])) == expected_index_types ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))] +) +async def test_index_exist_ok_preserves_existing_index( + some_table, background, column, config +): + await some_table.create_index(column, config=config, exist_ok=True) + version = await some_table.version() + original = await some_table.list_indices() + if background: + job = await some_table.create_index_async( + column, config=config, replace=True, exist_ok=True + ) + await job.wait() + else: + await some_table.create_index( + column, config=config, replace=True, exist_ok=True + ) + assert await some_table.version() == version + assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [ + (i.name, i.index_type) for i in original + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("background", [False, True]) +async def test_named_index_exist_ok_checks_before_column_validation( + some_table, background +): + await some_table.create_index("id", config=BTree(), name="kept") + version = await some_table.version() + method = some_table.create_index_async if background else some_table.create_index + result = await method("missing", config=BTree(), name="kept", exist_ok=True) + if background: + assert result.id is None + await result.wait() + assert await some_table.version() == version + assert [index.name for index in await some_table.list_indices()] == ["kept"] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ca2516fda..ea7f73c71 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -45,6 +45,7 @@ from lancedb.query import ( LanceVectorQueryBuilder, MatchQuery, ) +from lancedb.index import BTree from lancedb.remote import ClientConfig from lancedb.remote.errors import ( AlreadyExistsError, @@ -7420,3 +7421,54 @@ async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnati if use_async: await result assert not any(path == "fetch_blobs" for path, _ in requests) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize("kwargs", [{}, {"exist_ok": False}, {"exist_ok": True}]) +async def test_remote_index_exist_ok_wire(is_async, background, kwargs): + received = [] + + def handler(request): + parsed = urlparse(request.path) + body = request.rfile.read(int(request.headers.get("Content-Length", 0))) + if parsed.path.endswith("/create_index/"): + received.append((parse_qs(parsed.query), json.loads(body))) + payload = {} + elif parsed.path.endswith("/describe/"): + payload = dict( + version=1, + schema=dict( + fields=[dict(name="id", type={"type": "int64"}, nullable=False)] + ), + ) + elif parsed.path.endswith("/create/"): + payload = {} + else: + raise AssertionError(request.path) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + + method = "create_index_async" if background else "create_index" + if is_async: + async with mock_lancedb_connection_async(handler) as db: + table = await db.create_table("test", [{"id": 1}]) + result = await getattr(table, method)("id", config=BTree(), **kwargs) + if background: + await result.wait() + else: + with mock_lancedb_connection(handler) as db: + table = db.create_table("test", [{"id": 1}]) + result = getattr(table, method)("id", config=BTree(), **kwargs) + if background: + result.wait() + query, body = received[0] + assert query == ({"exist_ok": ["true"]} if kwargs.get("exist_ok") else {}) + assert "exist_ok" not in body + if kwargs.get("exist_ok"): + assert body["replace"] is False + else: + assert "replace" not in body diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e3b69ced1..604d6afb3 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1837,6 +1837,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Test with target_partition_size @@ -1862,6 +1863,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # target_partition_size has a default value, @@ -1886,6 +1888,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1902,6 +1905,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1922,6 +1926,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) table.create_index( @@ -1942,6 +1947,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -2073,6 +2079,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_custom_index", train=True, + exist_ok=False, ) # Test with train=False @@ -2084,6 +2091,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name=None, train=False, + exist_ok=False, ) # Test with both name and train @@ -2095,6 +2103,7 @@ def test_create_index_name_and_train_parameters( wait_timeout=None, name="my_index_name", train=True, + exist_ok=False, ) @@ -2132,6 +2141,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # Scalar index via new API @@ -2143,6 +2153,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) # FTS index via new API @@ -2154,6 +2165,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection): wait_timeout=None, name=None, train=True, + exist_ok=False, ) @@ -6292,3 +6304,87 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path): 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 + + +@pytest.mark.parametrize( + "method", + ["create_index", "create_index_async", "create_scalar_index", "create_fts_index"], +) +@pytest.mark.parametrize("name", [None, "kept_index"]) +def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name): + table = mem_db.create_table( + "keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)] + ) + column = "text" if method == "create_fts_index" else "id" + config = FTS() if column == "text" else BTree() + table.create_index(column, config=config, name=name, exist_ok=True) + before = table.version + original = table.list_indices() + kwargs = dict(name=name, exist_ok=True) + if method in ("create_index", "create_index_async"): + kwargs["config"] = config + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + result = getattr(table, method)(column, **kwargs) + if method == "create_index_async": + result.wait() + assert table.version == before + assert [(index.name, index.index_type) for index in table.list_indices()] == [ + (index.name, index.index_type) for index in original + ] + with pytest.raises((ValueError, RuntimeError), match="already exists"): + table.create_index(column, config=config, name=name, replace=False) + table.create_index(column, config=config, name=name) + assert table.version > before + + +@pytest.mark.parametrize( + "column,name,existing", + [ + ("vector", "kept", "kept"), + ("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"), + ], +) +def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing): + dataset = MagicMock() + dataset.list_indices.return_value = [{"name": existing}] + with patch("lancedb.table._validate_index_accelerator") as validate: + table_module._create_accelerated_index( + dataset, column=column, accelerator="cuda", name=name, exist_ok=True + ) + validate.assert_not_called() + dataset.create_index.assert_not_called() + + +def test_accelerated_index_exist_ok_preserves_concurrent_winner(): + dataset = MagicMock() + dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]] + dataset.create_index.side_effect = RuntimeError("concurrent create") + with patch("lancedb.table._validate_index_accelerator"): + table_module._create_accelerated_index( + dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True + ) + assert dataset.create_index.call_args.kwargs["replace"] is False + assert dataset.create_index.call_args.kwargs["name"] == "vector_idx" + + +@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"]) +def test_index_exist_ok_matches_lance_default_name(mem_db, column): + table = mem_db.create_table( + "quoted_index", + [{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}], + ) + table.create_index(column, config=BTree()) + before = table.version + table.create_index(column, config=BTree(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 + + +def test_fts_exist_ok_matches_quoted_default_name(mem_db): + table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}]) + table.create_index("`body-text`", config=FTS()) + before = table.version + table.create_index("`body-text`", config=FTS(), exist_ok=True) + assert table.version == before + assert len(table.list_indices()) == 1 diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py index 387a89f31..41a688068 100644 --- a/python/python/tests/test_table_signatures.py +++ b/python/python/tests/test_table_signatures.py @@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table): }.items(): assert getattr(config, name) == value assert kwargs == dict( - wait_timeout=timeout, name="custom_idx", replace=False, train=False + wait_timeout=timeout, + name="custom_idx", + replace=False, + train=False, + exist_ok=False, ) diff --git a/python/src/table.rs b/python/src/table.rs index 31cf8d25c..f77ff5a7f 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1628,7 +1628,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index<'a>( self_: PyRef<'a, Self>, column: String, @@ -1637,6 +1638,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1645,6 +1647,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } @@ -1661,7 +1664,8 @@ impl Table { }) } - #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))] pub fn create_index_async<'a>( self_: PyRef<'a, Self>, column: String, @@ -1670,6 +1674,7 @@ impl Table { wait_timeout: Option>, name: Option, train: Option, + exist_ok: bool, ) -> PyResult> { let index = extract_index_params(&index)?; let timeout = wait_timeout @@ -1678,6 +1683,7 @@ impl Table { let mut op = self_ .inner_ref()? .create_index_with_timeout(&[column], index, timeout); + op = op.exist_ok(exist_ok); if let Some(replace) = replace { op = op.replace(replace); } diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 87eff864d..91c941154 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -220,6 +220,7 @@ pub struct IndexBuilder { pub(crate) index: Index, pub(crate) columns: Vec, pub(crate) replace: bool, + pub(crate) exist_ok: bool, pub(crate) wait_timeout: Option, pub(crate) train: bool, pub(crate) name: Option, @@ -232,6 +233,7 @@ impl IndexBuilder { index, columns, replace: true, + exist_ok: false, train: true, wait_timeout: None, name: None, @@ -324,6 +326,21 @@ impl IndexBuilder { self } + /// Preserve an existing index with the requested name. Defaults to false. + /// This takes precedence over `replace`; a skipped creation does not rebuild. + /// + /// ```no_run + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// table.create_index(&["id"], lancedb::index::Index::Auto) + /// .exist_ok(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn exist_ok(mut self, exist_ok: bool) -> Self { + self.exist_ok = exist_ok; + self + } + /// Duration of time to wait for asynchronous indexing to complete. If not set, /// `create_index()` will not wait. /// diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f4e5c1e4a..a7cf3f80d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -701,9 +701,13 @@ impl RemoteTable { async fn submit_create_index(&self, mut index: IndexBuilder) -> Result> { self.check_mutable().await?; - let request = self + let mut request = self .client .post(&format!("/v1/table/{}/create_index/", self.identifier)); + if index.exist_ok { + request = request.query(&[("exist_ok", true)]); + index.replace = false; + } let column = match index.columns.len() { 0 => { @@ -18101,6 +18105,42 @@ mod tests { branch.restore().await.unwrap(); } + #[tokio::test] + async fn test_index_exist_ok_query_and_replacement_policy() { + for exist_ok in [false, true] { + for background in [false, true] { + 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/create_index/" => { + assert_eq!(request.url().query(), exist_ok.then_some("exist_ok=true")); + let body = request_body_json(&request); + assert_eq!( + body.get("replace"), + exist_ok.then_some(&serde_json::Value::Bool(false)) + ); + assert!(body.get("exist_ok").is_none()); + http::Response::builder() + .status(200) + .body("{}".into()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + let builder = table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(exist_ok); + if background { + builder.execute_async().await.unwrap().wait().await.unwrap(); + } else { + builder.execute().await.unwrap(); + } + } + } + } + #[tokio::test] async fn test_branch_create_index_carries_branch_in_body() { use lance::dataset::refs::Ref; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4959b2842..ff0ab8b94 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4145,14 +4145,18 @@ impl BaseTable for NativeTable { } async fn create_index(&self, opts: IndexBuilder) -> Result<()> { - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(()); + }; self.build_index(opts, prepared).await } async fn create_index_async(&self, opts: IndexBuilder) -> Result { // Prepare before spawning so bad input is reported by this call rather // than only by the job. - let prepared = self.prepare_index(&opts).await?; + let Some(prepared) = self.prepare_index(&opts).await? else { + return Ok(Job::new_done()); + }; let table = self.clone(); Ok(Job::spawned(tokio::spawn(async move { table.build_index(opts, prepared).await diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 5f9ae13b4..e0da64029 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -115,14 +115,24 @@ impl NativeTable { pub(super) async fn prepare_index( &self, opts: &crate::index::IndexBuilder, - ) -> Result { + ) -> Result> { + self.dataset.ensure_mutable()?; + let dataset = self.dataset.get().await?; + if opts.exist_ok + && let Some(name) = &opts.name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(None); + } if opts.columns.len() != 1 { return Err(Error::Schema { message: "Multi-column (composite) indices are not yet supported".to_string(), }); } - self.dataset.ensure_mutable()?; - let dataset = self.dataset.get().await?; let (column, field) = if let Index::FTS(params) = &opts.index { let resolved = resolve_lance_fts_field_path(dataset.schema(), &opts.columns[0])?; if params.get_document_granularity().is_list_element() && resolved.list_depth == 0 { @@ -137,9 +147,48 @@ impl NativeTable { } else { Self::resolve_index_field(dataset.schema(), &opts.columns[0])? }; + if let Some(name) = Self::guarded_index_name(opts, &column)? + && dataset + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(None); + } let params = self.make_index_params(&field, opts.index.clone()).await?; let index_type = self.get_index_type_for_field(&field, &opts.index); - Ok((column, params, index_type)) + Ok(Some((column, params, index_type))) + } + + fn guarded_index_name( + opts: &crate::index::IndexBuilder, + column: &str, + ) -> Result> { + let name = if opts.exist_ok { + Some(if let Some(name) = &opts.name { + name.clone() + } else { + let names = lance_core::datatypes::parse_field_path(column)?; + let default_name = if matches!(&opts.index, Index::FTS(_)) + || names.iter().any(|name| name.contains('.')) + { + column.to_string() + } else { + names.join(".") + }; + let suffix = if matches!(&opts.index, Index::FTS(params) if params.get_document_granularity().is_list_element()) + { + "_list_element_idx" + } else { + "_idx" + }; + format!("{default_name}{suffix}") + }) + } else { + None + }; + Ok(name) } /// Builds a prepared index and publishes the new dataset version. @@ -150,16 +199,42 @@ impl NativeTable { ) -> Result<()> { let (column, lance_idx_params, index_type) = prepared; let mut dataset = (*self.dataset.get().await?).clone(); + let guarded_name = Self::guarded_index_name(&opts, &column)?; + if let Some(name) = &guarded_name + && dataset + .load_indices() + .await? + .iter() + .any(|index| &index.name == name) + { + return Ok(()); + } let columns = [column.as_str()]; let mut builder = dataset .create_index_builder(&columns, index_type, lance_idx_params.as_ref()) .train(opts.train) - .replace(opts.replace); + .replace(opts.replace && !opts.exist_ok); - if let Some(name) = opts.name { + if let Some(name) = guarded_name.clone().or(opts.name) { builder = builder.name(name); } - builder.await?; + if let Err(error) = builder.await { + if let Some(name) = guarded_name { + self.dataset.reload().await?; + if self + .dataset + .get() + .await? + .load_indices() + .await? + .iter() + .any(|index| index.name == name) + { + return Ok(()); + } + } + return Err(error.into()); + } // A writer already open was built before this index existed, so it has // to pick it up here or a read needing it is refused until it reopens. self.dataset @@ -568,6 +643,63 @@ mod tests { Ok(FixedSizeListArray::from(data)) } + #[tokio::test] + async fn test_concurrent_index_exist_ok_preserves_single_identity() { + let dir = tempdir().unwrap(); + let db = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("id", Int32, (0..512).collect::>())).unwrap(); + let table = db.create_table("t", batch).execute().await.unwrap(); + let second = db.open_table("t").execute().await.unwrap(); + let (left, right) = tokio::join!( + table + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute(), + second + .create_index(&["id"], Index::BTree(Default::default())) + .exist_ok(true) + .execute() + ); + left.unwrap(); + right.unwrap(); + table.checkout_latest().await.unwrap(); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices.len(), 1); + let original_uuid = indices[0].uuid; + let version = table.version().await.unwrap(); + table + .create_index(&["id"], Index::BTree(Default::default())) + .replace(true) + .exist_ok(true) + .execute() + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), version); + let indices = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .load_indices() + .await + .unwrap(); + assert_eq!(indices[0].uuid, original_uuid); + } + #[tokio::test] async fn test_create_index() { use std::iter::repeat_with; From d67ec47921ba0b761405b898703725864adb15a2 Mon Sep 17 00:00:00 2001 From: Taylor <28880387+tsmithv11@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:23:41 -0800 Subject: [PATCH 112/203] docs: make the landing page concise (#4898) Shortens the docs landing page and organizes its overview around database features, with the multimodal data model, ML workflow, SDKs, and PyTorch loader explained in prose. Keeps versioning visible, branching in draft, and the existing `{#architecture}` anchor. Validation: added documentation links and anchors verified; `git diff --check` passes. `mint validate` reports the same four pre-existing missing snippet-export warnings in the reranking and vector-search pages, also reproduced on the unchanged revision. Closes https://linear.app/lancedb/issue/DOC-80/strengthen-what-is-lancedb --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brendan Clement --- docs/web/basics/lance.mdx | 2 +- docs/web/docs.json | 2 +- docs/web/enterprise/deployment/kubernetes.mdx | 2 +- docs/web/enterprise/security.mdx | 2 +- docs/web/index.mdx | 157 +++++------------- docs/web/quickstart.mdx | 6 +- 6 files changed, 51 insertions(+), 120 deletions(-) diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index 84996ffe9..341d36cde 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -76,4 +76,4 @@ boundaries). - [Multimodal data and blobs](/management/table#multimodal): declare `lancedb.blob()` columns and read blobs on demand. - [Table versioning](/management/table#versioning): read and manage table versions. - [Computed columns](/feature-engineering/add-computed-column): add derived features to your data. -- [Architecture](/index#architecture): how LanceDB Embedded and Enterprise build on Lance. +- [Embedded vs Enterprise](/basics/embedded-vs-enterprise): how LanceDB Embedded and Enterprise build on Lance. diff --git a/docs/web/docs.json b/docs/web/docs.json index c20341793..3414fd121 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -81,7 +81,7 @@ }, { "source": "/basics/offerings", - "destination": "/#architecture" + "destination": "/basics/embedded-vs-enterprise" }, { "source": "/enterprise/deployment", diff --git a/docs/web/enterprise/deployment/kubernetes.mdx b/docs/web/enterprise/deployment/kubernetes.mdx index 0133cf065..0c09d7f90 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](/index#architecture) for what differs between the two. +[Embedded vs Enterprise](/basics/embedded-vs-enterprise) 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/security.mdx b/docs/web/enterprise/security.mdx index 367e71b51..25af04656 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](/index#architecture) for what differs between the two. +[Embedded vs Enterprise](/basics/embedded-vs-enterprise) 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/index.mdx b/docs/web/index.mdx index 7b6bc6eed..1d451c246 100644 --- a/docs/web/index.mdx +++ b/docs/web/index.mdx @@ -6,130 +6,59 @@ icon: "/static/assets/logo/lancedb-icon-gray.svg" keywords: ["multimodal lakehouse", "training", "feature engineering", "search", "open source", "oss"] --- -**LanceDB** is a [multimodal lakehouse](https://lancedb.com/blog/multimodal-lakehouse/) for AI teams that need -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. +LanceDB Enterprise is a distributed multimodal lakehouse for AI. It gives you one data layer for search and +retrieval, curation, feature engineering, and model training. It is built on [Lance](/basics/lance), an open-source +columnar format for multimodal AI data. For the open-source retrieval library that runs inside your application, +see [LanceDB Embedded](/basics/lancedb-embedded). -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. +LanceDB Enterprise depends only on object storage for its primary state, and NVMe/memory for caching in the serving +layer, giving it the latency profile of an in-memory database with the petabyte scalability and cost profile of S3. +It brings these workloads into one system, giving your team one system to become expert in and removing the need +for multiple database systems and synchronization pipelines between them. -## Train on the right data faster {#train-on-the-right-data-faster} +Core features include: -Search, curate, and train at petabyte scale, with all your multimodal data in one table. +- [**SQL**](/basics/sql) powered by Apache DataFusion +- [**Secondary indexes**](/indexing) for vector search, full-text search, and scalar filters +- [**Computed columns**](/feature-engineering/add-computed-column) with on-demand or scheduled refresh +- [**Materialized views**](/feature-engineering/materialized-views) with on-demand or scheduled refresh +- [**Time travel and versioning**](/management/table#versioning) to pin and revisit datasets +- **Search**: [vector](/search/vector-search), [full-text](/search/full-text-search), and + [hybrid](/search/hybrid-search), with [filters](/search/filtering) and [reranking](/reranking) +- [**Functions**](/curation/create-function) for custom transformations and model inference (early access) +- [**Row-level random access**](/basics/lance#capabilities) for retrieval and training +- [**Column additions**](/management/table#schema-add-new-columns) without rewriting existing columns -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. +{/* +Draft until branching reaches early access. Add this item to the list above, after Time travel and versioning: +- [**Copy-on-write branching**](/tables/branching) that gives each experiment or agent a writable fork of a table to review before it reaches `main` +*/} -## Accelerate the data flywheel for model research {#accelerate-the-data-flywheel-for-model-research} +LanceDB Enterprise stores images, video, audio, text, embeddings, and metadata in +[schema-enforced tables](/management/table#multimodal). These features let you build +declarative ML data pipelines: ingest raw data and metadata, enrich it incrementally with computed columns and +Functions, and organize it into [curated datasets](/curation) with materialized views. Add features without +rewriting existing columns, then train from those datasets using row-level random access and sampling. -Keep your AI data in one table.{/* Draft until branching reaches early access: restore ", and give each agent-driven experiment its own isolated branch" before the period. */} -Find the failure, fix the data, and retrain. +Connect through [SDKs](/basics/sdk) for Python, TypeScript, and Rust, and use the +[PyTorch data loader](/training/data-loading) for reproducible shuffling and streaming batches. - - - 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. - - {/* - Draft until branching reaches early access. +## Architecture {#architecture} - - 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). - - */} - - 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. - - +Queries and feature engineering run across a cluster, with background indexing and maintenance. Deploy +LanceDB Enterprise in your cloud or use a LanceDB-managed deployment. -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: Embedded and Enterprise {#architecture} - -LanceDB ships as two offerings on the same [Lance](/basics/lance) format and table model, which stores table data, -versions, and indexes in open, columnar files. What changes between them is how storage and compute are organized -around that format: 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. - - - - An open-source, embedded retrieval library that runs inside your application process, with no separate - database server to deploy. - - - A distributed multimodal lakehouse service for production workloads that need managed infrastructure and - higher-throughput workflows. - - - -See [Embedded vs Enterprise](/basics/embedded-vs-enterprise) for a feature-by-feature comparison, including -architecture, latency, throughput, and day-to-day usage differences. +Your application connects to the service through an SDK or [SQL client](/basics/sql). The cluster executes queries, +refreshes derived data, and maintains tables and indexes outside your application. ## 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 HuggingFace - 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} - - - - 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. - - +Teams use LanceDB for world-model and robotics training, as in +[stable-worldmodel](https://github.com/galilai-group/stable-worldmodel) and +[lerobot-lancedb](https://github.com/lancedb/lerobot-lancedb), and for agent memory, as in +[CrewAI](https://www.lancedb.com/blog/crewai-rebuilt-agent-memory-on-lancedb), +[Cognee](https://github.com/topoteretes/cognee), and +[OpenClaw](https://docs.openclaw.ai/plugins/memory-lancedb). +Try out LanceDB using our [quickstart](/quickstart). For help planning an Enterprise deployment +that meets your scale and performance needs, [contact the LanceDB team](https://www.lancedb.com/contact). diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index ef462cbf7..12c9f87ca 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -7,8 +7,10 @@ icon: rocket import { PyConnect, TsConnect, RsConnect, PyConnectObjectStorage, TsConnectObjectStorage, RsConnectObjectStorage, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartCurateSample, PyQuickstartCurateDedupeSetup, PyQuickstartCurateDedupe, PyQuickstartCurateDedupeQuery, PyQuickstartFlattenStats, PyQuickstartAddFeature, PyQuickstartAddFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, 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. +This quickstart walks you through creating a table, searching your data, and preparing it for training. +By default, it uses LanceDB Embedded with a local database, so no account or API key is required. +To follow along with an existing LanceDB Enterprise deployment, use the +[Enterprise connection instructions](#connect-to-lancedb-enterprise). ## 1\. Install LanceDB {#1-install-lancedb} From 97e62dc11b561db29df24260d158ec9dba1f9a0d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 15:41:33 +0800 Subject: [PATCH 113/203] feat(remote): expose canonical job statistics reports (#5016) Expose `Job::stats()` in Rust and synchronous/asynchronous Python jobs. It reads `POST /v1/jobs/stats` and returns the canonical server-rendered report verbatim, or `None` for a running job or one without a readable durable profile. It does not wait for completion or recompute measurements. On `cc25005525671756b5cf5ebd96492b792e9aa1cb`, all three Rust transport tests and six Python tests passed against the matching rebuilt native extension; strict SDK Clippy also passed. These tests cover optional reports, exact text preservation, fresh reads, errors, and the HTTP boundary with a controlled server. Against the actual Phalanx HTTP route from [Sophon #10247](https://github.com/lancedb/sophon/pull/10247) (`5be3236`), the same native extension also completed two sync and two async reads after durable registry archival, preserving the exact canonical report. This is an HTTP/registry integration fixture, not a Function workload or shared-cluster acceptance. The private runner's JSON field-order collector failed after the successful probe; all raw evidence was retained and hash-verified, and the original receipt was recovered with the corrected parser without rerunning the probe. The follow-up `ad36f66` only corrects the synchronous Python API-reference link to the asynchronous method. Ruff checks and formatting passed; runtime evidence above remains applicable. The actual Phalanx/native-SDK probe covers archived reports; running-job null availability is covered by separate backend and SDK transport tests, not that end-to-end probe. Part of ENT-3501. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/job.py | 41 +++++++++++ python/python/tests/test_job.py | 40 +++++++++++ python/python/tests/test_remote_db.py | 44 ++++++++++++ python/src/job.rs | 5 ++ rust/lancedb/src/job.rs | 28 ++++++++ rust/lancedb/src/remote/job.rs | 97 +++++++++++++++++++++++++++ 7 files changed, 256 insertions(+) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index cbc62f772..1e811d865 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -437,6 +437,7 @@ class Job: async def cancel(self) -> None: ... async def refresh(self) -> None: ... async def timeline(self) -> str: ... + async def stats(self) -> Optional[str]: ... async def events( self, *, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index bf9605567..9195e01ae 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -425,6 +425,32 @@ class AsyncJob(Generic[T]): description = self._inner._description if self._inner is not None else None return getattr(description, name) if description is not None else None + async def stats(self) -> Optional[str]: + """Return a printable run report for this Function job. + + The report includes recorded phase timings, finishing-supervisor slot + occupancy, all-attempt split execution and batch latency, and accepted-row + throughput. Each call reads the current server report. + Returns ``None`` while the job is running or if no recorded profile is + available, without waiting for completion. Missing measurements remain + unavailable rather than becoming zero. The server formats the report; + the SDK returns it verbatim. + + Requires a server-side Function job and a server supporting run reports. + Local operations and SQL query handles do not support this operation. + Unsupported operations raise ``NotImplementedError`` or a server error. + This method returns text; use ``print`` to display it. + + Examples + -------- + >>> print(await job.stats()) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job statistics require a server-side Function job" + ) + return await self._inner.stats() + async def export_timeline(self, path: str | PathLike[str]) -> None: """Write a fresh recorded Function job timeline as Chrome trace JSON. @@ -649,6 +675,21 @@ class Job(Generic[T]): def _field(self, name: str) -> Optional[Any]: return getattr(self._inner, name) if self._inner is not None else None + def stats(self) -> Optional[str]: + """Return a printable Function job run report. + + See [AsyncJob.stats][lancedb.job.AsyncJob.stats] for metrics and availability. + + Examples + -------- + >>> print(job.stats()) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "job statistics require a server-side Function job" + ) + return LOOP.run(self._inner.stats()) + def export_timeline(self, path: str | PathLike[str]) -> None: """Write Chrome trace JSON for this Function job. diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 690f6414b..9897d97b5 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -754,6 +754,46 @@ async def test_query_wait_timeout_requires_keeping_original_handle(): assert "db.open_job" not in message +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys): + reports = [ + None, + "Function job: finished\nWorker utilization: unavailable\n", + "Function job: finished\nWorker utilization: 25.0%\n", + ] + inner = SimpleNamespace( + stats=AsyncMock(side_effect=reports), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + for expected in reports: + actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats() + assert actual == expected + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + assert capsys.readouterr().out == "" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync): + error = RuntimeError("run reports are unavailable on this server") + job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error))) + with pytest.raises(RuntimeError) as exc: + if sync: + await asyncio.to_thread(Job(job).stats) + else: + await job.stats() + assert exc.value is error + with pytest.raises(NotImplementedError, match="server-side Function job"): + if sync: + Job(None).stats() + else: + await AsyncJob(None).stats() + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ea7f73c71..b38ae4a5b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2732,6 +2732,50 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): assert exc.value.__cause__.is_transport_error is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_remote_job_stats_returns_native_optional_report(sync): + report = "Function job: finished\nWorker utilization: unavailable\n" + paths = [] + + def handler(request): + payload = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert payload == {"job_id": "refresh-1"} + paths.append(request.path) + if request.path == "/v1/jobs/describe": + response = { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "IN_PROGRESS", + "creation_ms": 1000, + } + elif request.path == "/v1/jobs/stats": + available = paths.count("/v1/jobs/stats") > 1 + response = { + "job_id": "refresh-1", + "profile": {"future_field": True} if available else None, + "report": report if available else None, + } + else: + raise AssertionError(f"unexpected request: {request.path}") + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + assert job.stats() is None + assert job.stats() == report + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + assert await job.stats() is None + assert await job.stats() == report + assert paths == ["/v1/jobs/describe", "/v1/jobs/stats", "/v1/jobs/stats"] + + @pytest.mark.asyncio @pytest.mark.parametrize("sync", [False, True]) @pytest.mark.parametrize( diff --git a/python/src/job.rs b/python/src/job.rs index 0d411072f..08f6440ab 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -159,6 +159,11 @@ impl Job { }) } + pub fn stats(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) + } + #[pyo3(signature = (*, limit=None, filter=None))] pub fn events( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 092ece8b5..b1e3c1bbf 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -90,6 +90,11 @@ pub(crate) trait JobHandle: Send + Sync { job_detail_not_supported("job timeline export") } + /// A printable report of recorded Function job metrics. + async fn stats(&self) -> Result> { + job_detail_not_supported("job statistics") + } + /// The job's recorded lifecycle events. async fn events(&self, _request: JobEventsRequest) -> Result> { job_detail_not_supported("job event history") @@ -531,6 +536,29 @@ where } } + /// Fetch a printable run report for a server-side Function job. + /// + /// The server report includes recorded phase timings, finishing-supervisor + /// slot occupancy, all-attempt split execution and batch latency, and + /// accepted-row throughput. Returns `None` for running jobs or when no recorded + /// profile is available, without waiting for completion. Requires server + /// support; local operations and SQL query handles do not support reports. + /// + /// ```no_run + /// # async fn report(job: &lancedb::job::Job) -> Result<(), Box> { + /// if let Some(report) = job.stats().await? { + /// println!("{report}"); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn stats(&self) -> Result> { + match &self.inner { + JobInner::Handle { handle, .. } => handle.stats().await, + JobInner::Completed(_) => job_detail_not_supported("job statistics"), + } + } + /// Waits until the operation reaches a terminal state. /// /// Returns the endpoint's typed result. Unit-result jobs return `()`. diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 5a0afa7e8..c546ce4d1 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -261,6 +261,35 @@ impl JobHandle for RemoteJob { Ok(trace) } + async fn stats(&self) -> Result> { + let request = self + .client + .post("/v1/jobs/stats") + .json(&serde_json::json!({"job_id": self.job_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let response: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse job statistics: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if response.get("job_id").and_then(serde_json::Value::as_str) == Some(self.job_id.as_str()) + { + match response.get("report") { + Some(serde_json::Value::Null) => return Ok(None), + Some(serde_json::Value::String(report)) => return Ok(Some(report.clone())), + _ => {} + } + } + Err(Error::Http { + source: "server response is not a Function job run report; job statistics require server support".into(), + request_id, + status_code: None, + }) + } + async fn events(&self, request: JobEventsRequest) -> Result> { let mut body = serde_json::json!({ "job_id": self.job_id }); if let Some(limit) = request.limit { @@ -354,6 +383,74 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test] + async fn stats_reads_report_verbatim_and_preserves_unavailable_without_waiting() { + let requests = Arc::new(AtomicUsize::new(0)); + let seen = requests.clone(); + let report = "Function job: finished\nWorker utilization: unavailable\n"; + let client = client_with_handler(move |request| { + assert_eq!(request.method(), reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/jobs/stats"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body, serde_json::json!({"job_id":"job-1"})); + let response = if seen.fetch_add(1, Ordering::SeqCst) == 0 { + serde_json::json!({"job_id":"job-1","profile":null,"report":null}) + } else { + serde_json::json!({"job_id":"job-1","profile":{"future_field":17},"report":report}) + }; + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".to_string()))); + assert_eq!(job.stats().await.unwrap(), None); + assert_eq!(requests.load(Ordering::SeqCst), 1); + assert_eq!(job.stats().await.unwrap().as_deref(), Some(report)); + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn stats_rejects_malformed_or_unrelated_responses() { + for body in [ + "{", + r#"{"job_id":"job-1"}"#, + r#"{"job_id":"job-1","report":7}"#, + r#"{"job_id":"another-job","report":"a report"}"#, + ] { + let client = client_with_handler(move |_| { + http::Response::builder().status(200).body(body).unwrap() + }); + let error = RemoteJob::new(client, "job-1".to_string()) + .stats() + .await + .unwrap_err(); + assert!(matches!(error, crate::Error::Http { .. })); + assert!(error.to_string().contains("job statistics")); + } + } + + #[tokio::test] + async fn stats_preserves_not_found_errors() { + let client = client_with_handler(|_| { + http::Response::builder() + .status(404) + .body("job not found") + .unwrap() + }); + let error = RemoteJob::new(client, "missing".to_string()) + .stats() + .await + .unwrap_err(); + match error { + crate::Error::Http { status_code, .. } => { + assert_eq!(status_code, Some(reqwest::StatusCode::NOT_FOUND)); + } + other => panic!("expected HTTP 404, got {other:?}"), + } + } + struct FixtureRemoteJob(&'static str); #[async_trait] From dd449978d9c43a286ae7bf739301be34827125c4 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 14 Nov 2026 01:09:40 -0800 Subject: [PATCH 114/203] docs: clarify Function workflows and search contracts Clarify Function signatures, refresh and recovery workflows, job snapshots, FTS operators, and IVF deduplication limits. --- .agents/skills/lancedb-vector-dedup/SKILL.md | 63 ++++++++ docs/web/basics/jobs.mdx | 73 +++++++++ docs/web/curation/create-function.mdx | 61 ++++++- docs/web/curation/dedupe.mdx | 58 ++++++- docs/web/docs.json | 1 + .../add-computed-column.mdx | 7 + .../materialized-views.mdx | 24 +++ .../feature-engineering/refresh-column.mdx | 119 ++++++++++++++ docs/web/management/function-failures.mdx | 151 ++++++++++++++++++ docs/web/management/function.mdx | 44 +++++ docs/web/search/full-text-search.mdx | 57 +++++++ docs/web/sql/dql/dedupe.mdx | 9 ++ docs/web/sql/dql/duplicate-pairs.mdx | 6 + docs/web/sql/dql/fts.mdx | 63 +++++++- 14 files changed, 725 insertions(+), 11 deletions(-) create mode 100644 .agents/skills/lancedb-vector-dedup/SKILL.md create mode 100644 docs/web/management/function-failures.mdx diff --git a/.agents/skills/lancedb-vector-dedup/SKILL.md b/.agents/skills/lancedb-vector-dedup/SKILL.md new file mode 100644 index 000000000..1221e4061 --- /dev/null +++ b/.agents/skills/lancedb-vector-dedup/SKILL.md @@ -0,0 +1,63 @@ +--- +name: lancedb-vector-dedup +description: Plan and run Enterprise IVF vector deduplication with dedupe and duplicate_pairs, including sampling, index coverage, recall and resource limits. Use for near-duplicate embedding or perceptual-hash records; use MinHash guidance for text shingles. +--- + +# Vector deduplication + +Read the maintained [workflow](../../../docs/web/curation/dedupe.mdx), +[DEDUPE reference](../../../docs/web/sql/dql/dedupe.mdx) and +[DUPLICATE_PAIRS reference](../../../docs/web/sql/dql/duplicate-pairs.mdx) +before constructing SQL. In a source checkout these paths are relative to this +skill directory. When using an installed copy without the docs, read +`https://docs.lancedb.com/curation/dedupe` and the linked SQL references. + +## Establish the comparison contract + +- Confirm an Enterprise deployment that supports these table functions. Use + `dedupe` and `duplicate_pairs`; legacy `vector_dedup` names are rejected. +- Inspect the vector type, metric, compatible index, indexed fragments and + source version. Wait for index coverage after writes. Do not run a full + scan over unindexed fragments or silently change the index to make it run. +- Explain that candidates are compared only within physical IVF partitions + and segments. Encoded/quantized distances are not an exact raw-vector + comparison. L2 thresholds are squared distances; Hamming counts bits. +- Use `id_column` on pair queries for business IDs. Retain `dataset_version`, + segment and partition identities. Do not decode internal row IDs or assume + that representatives stay the same after later data/index changes. + +## Bound the first experiment + +Use a reproducible partition sample before a full scan: + +```sql +SELECT id_a, id_b, distance, dataset_version, segment_id, partition_id +FROM duplicate_pairs( + 'frames', 'embedding', + distance_threshold => 0.02, + id_column => 'frame_id', + selection => 'random', count => 10, seed => 42 +) +``` + +Adapt the threshold and sample size to the metric and actual partition count. +Sampling partitions is not uniform sampling of rows. Inspect known duplicate +and distinct examples, pair density, partition skew, memory, spill space and +elapsed time. Do not infer global recall or ten-billion-row qualification +from a small or unversioned benchmark. Pair work and output can be quadratic +within a partition; an outer SQL `LIMIT` is not an upstream work budget. + +## Choose the result + +`dedupe` returns original representative rows and always scans all partitions. +Use its default `connected_components` for transitive groups; choose +`direct_representative` when chains should not merge transitively. It does not +accept `id_column`, `selection`, `count` or `seed`; `duplicate_pairs` does not +accept `resolution`. + +Keep pair data on the server when possible; avoid collecting an unbounded +edge set in client memory. Persist a new table/view only within the user's +authorized scope, preserving source rows unless deletion was requested. +Do not register a Python Function or fetch/rewrite Blob payloads to invoke +these built-in table functions. For MinHash/text deduplication, follow the +separate `https://docs.lancedb.com/enterprise/sql-minhash` workflow. diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 47285f5d0..264acd728 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -33,6 +33,46 @@ print(job.status()) ``` +## Cached properties and live calls {#snapshots} + +Python job properties describe the last observation; reading them does not +contact the server. Submission need not fetch the full registry record, so +some properties can initially be `None`. + +| Surface | Contract | +| --- | --- | +| `state` | Last observed lifecycle state. It does not update on its own. | +| `job_type`, `creation_ms` | Cached job kind and creation time in epoch milliseconds. | +| `spec` | Complete, job-specific submitted specification. Read this separately from the bounded `repr(job)` display. | +| `result` | Cached, job-specific reported data; it is not necessarily the typed object returned by `wait()`. | +| `failure` | Cached `JobFailureInfo`, when the server reports a terminal failure. | +| `status()` | Live lifecycle request. For registry jobs it also caches the full record. A failed state is returned without raising a job-failure exception; request errors can still raise. | +| `refresh()` | Fetch and cache the current record without waiting for completion. | +| `events(...)` | Separate live request returning a `pyarrow.Table` of recorded events; it does not refresh the properties. | +| `wait(...)` | Poll until completion and return the operation's typed result, or raise on failure/cancellation. Refresh afterward when you need the complete final registry record. | + +For example, poll a registry handle and then retrieve its final details: + +```python +import time + +state = job.status() +while state == "running": + print(job.state) + time.sleep(2) + state = job.status() + +result = job.wait() +job.refresh() +print(result) +print(job.spec) +``` + +The four lifecycle strings below are the usual SDK contract; newer server +states may pass through an older client. Do not infer execution progress from +`state` alone. Structured progress methods and queue fields require matching +SDK/server support; see [refresh admission](/feature-engineering/refresh-column#admission). + ## Submit and wait for a job {#waiting} 1. **Submit the operation.** Keep the returned job handle. For an Enterprise @@ -133,6 +173,39 @@ for info in db.list_jobs(page_limit=50): ``` +`list_jobs` yields `JobInfo` summaries, newest creation time first, rather than +live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds +each server request, not the total yielded items, and `page_token` resumes a +listing. It is a lazy iterator: iteration performs requests and can raise +request errors. To materialize it, use `list(db.list_jobs(...))`; it does not +support list indexing, `len()`, or a `.to_list()` method. + +`Listing.num_page_results()` reports cached items remaining in the current +page and `Listing.page_token()` reports the next request's token. Drain the +cached items before saving that token, or resuming can skip them. A `None` +token after the final page can coexist with unread cached items. A resumed +listing is not a transactionally frozen view of jobs submitted in the meantime. + +`events.schema` describes the Arrow response. Use `events.to_pylist()` for +Python row dictionaries. Common event columns are `event_seq` (int64), `state` +(string), `updated_at_millis` (int64), `updated_by` (string), and nullable +`emitted_from`, `emitted_by` and `claim_entity` strings. Optional uint64 work +counters such as `rows_processed` and diagnostic details depend on job type +and server version. If a `payload` column is returned, its value is a nullable +JSON string, not an already decoded Python dictionary. +Empty results retain their schema. Events are newest first and belong to the +requested job; child events are separate. An event count is not a completed-row +count, and a running job can have no terminal `result` while producing events. + +For a Function refresh, `wait()` returns a `RefreshColumnResult` such as +`rows_assigned`, `rows_failed`, `rows_remaining`, `source_version` and optional +`published_version`. Other job types have different results. Do not parse the +printed representation to recover a spec, result or progress measurement. +For object-shaped registry data, `job.spec` and `job.result` are decoded Python +dictionaries: access fields with keys, such as `job.result.get("summary")` +after refreshing a successful Function job. The separate typed object from +`wait()` uses attributes, such as `result.rows_assigned`. + 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. diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 111eaf13f..9ee7d572a 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -44,6 +44,58 @@ table.add_columns({"doubled": version(value=col("value"))}) immutable version, so changing one produces a new version rather than altering rows a previous version already filled. +## Supported Function signatures {#signature-types} + +A table's [Arrow schema](/sql/data-types#supported) can contain types that a +Function cannot accept or return. The matrix below describes the Python SDK +`0.42.0-beta.12` source contract. Nested schemas and list-Blob outputs require +a matching Enterprise server; an SDK upgrade alone does not enable them. + +| Arrow type | Function input/output support | +| --- | --- | +| Boolean; signed/unsigned 8, 16, 32, 64-bit integers; float16/32/64 | Supported. Ordinary `int` and `float` annotations infer int64 and float64. | +| utf8 / large_utf8; binary / large_binary | Supported. `str` and `bytes` infer utf8 and binary. Plain binary does not carry Blob semantics. | +| date32 / date64 | Supported; Python `date` infers date32. | +| timestamp, with or without timezone; time32/64; duration; interval | Unsupported by the Function signature grammar. A Python `datetime` annotation can resolve to an Arrow timestamp but registration still rejects it. | +| decimal; map; dictionary; union; fixed-size binary | Unsupported. Decode dictionary values and use supported scalar/list/struct representations. | +| struct; list / large_list; positive-length fixed-size list | Supported with supported children. Explicit schemas preserve child nullability; annotation-only `list[T]` uses non-nullable elements. Struct fields must be nonempty and uniquely named. | +| Blob v2 at top level or in a struct | Supported in inputs and outputs; use `lancedb.blob(...)` in the schema. | +| Blob v2 under list / large_list | Output only on supporting SDK/server versions. Inputs are rejected. | +| Blob v2 under fixed-size list or map | Unsupported in both directions. | + +For times, pass an int64 epoch value with an explicit unit such as microseconds, +or a UTF-8 ISO 8601 string with its timezone. Convert inside the Function and +cast the result in SQL if needed. Use scaled integers with a declared scale +when exact decimal values matter; converting to float can lose precision. +Represent a map as a list of key/value structs when that fits the calculation. + +A scalar output is non-nullable because physical NULL represents an unfilled +computed output. For an optional value, return a named struct with a nullable +field, for example: + +```python +import pyarrow as pa +from lancedb import function + +@function( + input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]), + output_schema=pa.schema([pa.field("score", pa.float64(), nullable=True)]), +) +def optional_score(text: str): + return {"score": float(len(text)) if text else None} +``` + +Return a dictionary by field name. A successfully computed nullable field can +be NULL; `score IS NULL` alone cannot distinguish it from pending work or a +skipped failure. Use the job result and error diagnostics. Do not assume an +explicit assignment-state flag is available on every deployment. + +List-nested Blob outputs are queryable as descriptors, but row-ID blob fetch +APIs and `blob_mode="bytes"` do not fetch payloads inside lists. Prefer a +separate row per media item when you need independent reads, retries or +re-scoring. A plain struct shaped like a Blob without its extension metadata +is not a substitute for `lancedb.blob`. + ## Batch: once per call, many rows at a time {#batch} A function is called once per batch instead of once per row when its @@ -170,9 +222,12 @@ in the function's source. A Secret is a database-scoped named credential: 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. 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__`. +around it -- is built once, not reopened on every row. Configure HTTP timeouts +inside `__call__`. Refresh-level `error_policy='skip'` can record row failures; +see [handling failures](/management/function#failures). Native retry policies +need matching SDK, server and Function-image support; on other deployments, +handle bounded retries inside the Function only when repeating the request is +safe. See [Vend a Secret to a Function](/curation/vend-secret#specify) for the full worked example, how the bound value actually reaches a running diff --git a/docs/web/curation/dedupe.mdx b/docs/web/curation/dedupe.mdx index 470e170c2..2e90bc231 100644 --- a/docs/web/curation/dedupe.mdx +++ b/docs/web/curation/dedupe.mdx @@ -136,12 +136,60 @@ SELECT * FROM dedupe( 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} +## Index, snapshot and recall limits {#limits} -[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. +These are Enterprise SQL table functions, not standard SQL or a registered +Python Function. They require one compatible current vector index covering +the scanned snapshot. Wait for indexing to finish after ingestion and inspect +index coverage before running a full scan. Unindexed fragments are rejected; +deleted rows are excluded at the pinned dataset version. + +The scan compares candidates **within each physical IVF partition and index +segment**. It does not compare across partitions or segments. Scanning every +partition therefore does not establish global all-pairs recall. Quantized +indexes compare their encoded vector representations; `IVF_FLAT` compares the +stored vectors. Thresholds must match the index's metric: L2 is squared L2, +cosine is `1 - cosine`, dot distance is `1 - dot`, and Hamming counts differing +bits. Inspect close examples and known duplicates before choosing a threshold. + +`duplicate_pairs` reports `dataset_version`, `segment_id` and `partition_id`. +Retain those with the index configuration and source version when comparing +runs. Pass `id_column` for application IDs, rather than treating physical row +addresses as durable identifiers. A new append, index change or bridge between +components can change groups and representatives. + +## Efficient use and scale qualification {#production} + +Start with [`duplicate_pairs` partition sampling](/sql/dql/duplicate-pairs#sampling), +using a recorded seed and a bounded partition count. Inspect pair density and +threshold quality before running `dedupe`, which always scans every partition. +Sampling partitions is not uniform row sampling and can miss rare groups. +`resolution='connected_components'` merges transitive chains; +`direct_representative` uses direct representative relationships instead. + +Pair work grows quadratically within dense partitions, and a loose threshold +can emit a quadratic number of edges. An outer `LIMIT` is not a resource +budget for upstream pair finding or group resolution. Avoid repeatedly +materializing all pairs in a Python list; select needed columns, aggregate on +the server, and persist a reviewed result when repeated reads justify it. +Measure peak memory, spill storage, elapsed time and pair count on +representative partitions before increasing scope. + +The [LeRobotDataset integration](/integrations/lerobotdataset) illustrates a +27.6-million-row data workflow. Its timings are not a versioned qualification +of this deduplication path on arbitrary indexes or hardware. A 10-billion-row +run is not qualified by that example. Qualify source/index versions, partition +sizes, metric, threshold, worker resources, spill limits and correctness on your +deployment before extrapolating. There is no universal row-count or latency +guarantee in this guide. + +For text shingles and MinHash signatures, use the distinct +[MinHash workflow](/enterprise/sql-minhash). Vector distance deduplication and +MinHash/Jaccard text deduplication have different indexes and thresholds. + +Agents can follow the repository's +[vector deduplication skill](https://github.com/lancedb/lancedb/blob/main/.agents/skills/lancedb-vector-dedup/SKILL.md) +to apply these checks without inventing Function options or scale guarantees. ## Continue with the curated data {#next} diff --git a/docs/web/docs.json b/docs/web/docs.json index 3414fd121..c586d4f62 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -496,6 +496,7 @@ "management/materialized-view", "management/secret", "management/function", + "management/function-failures", "management/storage-integration" ] }, diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 851b37d9b..7cc9f6988 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -13,6 +13,13 @@ import { PySchemaAddSetup, } from '/snippets/tables.mdx'; + +Declare computed columns on ordinary tables. A materialized view derives its +schema from its query; include the calculation in the view's `SELECT` instead +of attaching a Function with `add_columns`. See +[materialized-view schema changes](/feature-engineering/materialized-views#schema-changes). + + 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 diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 617eb7525..ccfd8429d 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -176,6 +176,30 @@ definition is read with `await view.definition()`. Creation, refresh and drop also have async, job-returning SDK methods; see [Materialized view](/management/materialized-view#manage). +## Add derived values to a view {#schema-changes} + +A materialized view's output schema belongs to its defining `SELECT`. Do not +use `view.table.add_columns(...)` to attach another computed or Function column +to that output. In particular, adding a Function binding is rejected: the +column would not be produced by the next view refresh. + +Choose where the calculation belongs: + +- Include the expression or Function call in the view's `SELECT`, as in the + [caption example](#functions). To change an existing definition, create a + replacement view under a new name, check its results, indexes and grants, + and move readers to it before dropping the old view. +- Add a Function column to the ordinary source table, refresh it, then select + that stored column in a view. This lets you manage column refresh separately + from view refresh. +- Create an ordinary table from a query when you need independently editable + outputs. That table is a snapshot; it does not inherit the view's refresh + relationship to the source. + +Opening the underlying table gives access to reads and indexes; it does not +make independent schema changes part of the materialized-view definition. +Changing automatic-refresh settings also does not change that definition. + ## Related guides {#next} diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index 1b809b91d..d82fb1eef 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -77,6 +77,11 @@ catch-up works when it's re-enabled after being off. ## Refreshing part of a table {#partial} +Python `where=` requires a supporting SDK, such as `0.42.0b9`, and an +Enterprise server with filtered refresh support. Stable `0.41.0` does not +accept this argument. The SQL form is available independently of that Python +argument on supporting servers. + Enterprise A refresh can be scoped to a predicate, with `where=` in Python or `WHERE` in SQL, which is useful for filling a slice first and checking it before committing to the whole table: @@ -123,6 +128,89 @@ to let LanceDB track which outputs need updating. `function_refresh` for one filled by a registered [function](/management/function). +### Re-score selected list elements {#list-elements} + +`WHERE` selects **rows**, not elements within a list. Refreshing a row that +contains ten answers passes the whole list to the Function. A mask can control +which elements your code computes, but the Function still returns one complete +list for that row. There is no element-level refresh or partial-list write API. + +This example keeps `sample_id` as the link to an existing `samples` table with +a Blob column named `media`. It creates only answer metadata and scores; it +neither reads nor copies Blob payloads. Run it on a deployment supporting +`@function`, list signatures and Python `where=`, with `samples` already +containing sample IDs `s1` and `s2`. + +```python +from lancedb import col, function + +media_before = db.execute_query( + "SELECT sample_id, media FROM samples " + "WHERE sample_id IN ('s1', 's2') ORDER BY sample_id" +).read_all().to_pylist() + +answers = db.create_table("answer_rescore_demo", [ + {"group_id": "g1", "sample_id": "s1", + "answers": ["yes", "maybe", "no"], + "selected": [False, True, False], "previous": [0.1, 0.2, 0.3]}, + {"group_id": "g1", "sample_id": "s2", + "answers": ["other"], "selected": [False], "previous": [0.4]}, +]) + +@function +def rescore_masked( + answers: list[str], selected: list[bool], previous: list[float] +) -> list[float]: + if not (len(answers) == len(selected) == len(previous)): + raise ValueError("answers, selected and previous must have equal lengths") + return [ + float(len(answer)) if choose else old + for answer, choose, old in zip(answers, selected, previous) + ] + +version = db.create_function(rescore_masked) +answers.add_columns( + {"rescored": version( + answers=col("answers"), selected=col("selected"), previous=col("previous") + )}, + auto_refresh_enabled=False, +) +job = answers.refresh_column_async("rescored", where="sample_id = 's1'") +job.wait() + +rows = answers.search().select( + ["group_id", "sample_id", "previous", "rescored"] +).to_list() +by_sample = {row["sample_id"]: row for row in rows} +assert by_sample["s1"]["group_id"] == "g1" +assert by_sample["s1"]["rescored"] == [0.1, 5.0, 0.3] +assert by_sample["s1"]["previous"] == [0.1, 0.2, 0.3] +assert by_sample["s2"]["rescored"] is None +assert by_sample["s2"]["previous"] == [0.4] + +media_after = db.execute_query( + "SELECT sample_id, media FROM samples " + "WHERE sample_id IN ('s1', 's2') ORDER BY sample_id" +).read_all().to_pylist() +assert media_after == media_before +``` + +Here length is a deterministic stand-in for a scorer. Only `"maybe"` is scored; +the other scores are copied from `previous`. The final equality checks Blob +descriptors on an otherwise unchanged source table, without fetching payloads. +Keep the source table unchanged during this comparison. Use the same model, +normalization and score type as the original computation in a real re-scoring +pass. For another pass, explicitly supply the intended prior scores and mask; +refresh does not merge the previous output into your Function's inputs. + +If answers need independent retries or versions, prefer one ordinary table row +per answer, with `group_id`, `sample_id`, a stable application `answer_id`, +answer text and score. Keep media in `samples` and join by `sample_id` when +needed. A row predicate can then select exact answer IDs, and Blob storage +stays in the source table. Do not use `UNNEST` to assume that nested Blob values +become supported Function inputs; see the +[nested-Blob limits](/curation/create-function#signature-types). + ## Run a refresh on Enterprise {#async} Enterprise @@ -212,6 +300,31 @@ The wait helpers do not submit or cancel a refresh. They retry only the typed finalization-pending response and propagate other errors. */} +### Admission and waiting {#admission} + +Submission does not reserve a supervisor or GPU immediately. A refresh can wait +for source preparation/compaction, an earlier refresh, executor admission or +worker capacity. A lifecycle `running` value from `status()` alone does not +prove that Python code has begun executing. + +Use [`SHOW JOBS`](/sql/ddl/job#show) and the Console's job detail to inspect +available phase and row progress. On SDK/server versions with `job.progress()`, +the snapshot can also include `phase`, `queue_reason`, timestamps and row +counters. These optional fields are version-dependent; missing values are +unknown, not zero progress or an ETA. `creation_ms` is submission time, not +worker start time. `DESCRIBE JOB` provides the finished run report, rather than +a live queue-position API. + +Limits are deployment settings: the Agent dispatcher concurrency, executor +capacity, per-table automatic-refresh limit and Function-call +`max_concurrency` control different things. There is no universal five-refresh +limit per database. Ask your administrator for the effective settings and use +the [Enterprise operations guide](/enterprise/function-operations#admission) +for their configuration names. Repeated cancellation and resubmission does not +bypass those limits. Cancellation requests a stop, including while queued; +observe a terminal state before submitting replacement work. Committed work +is not rolled back. + ### Configure workers and resources {#resources} SQL exposes the worker budget directly, which is the lever when a backfill is @@ -229,6 +342,12 @@ up to 8 CPUs, 16 GiB of memory, and 2 GPUs across the fleet. They are not per-worker allocations or a guaranteed worker count. `num_workers` is only accepted for SQL-expression columns; registered Function columns reject it. +In particular, `gpu_count = 2` does not request two devices inside one Python +process or enable tensor parallelism. Inspect configured GPU classes and their +per-worker limits with `db.list_gpu_classes()` or `SHOW GPU CLASSES`. Choose a +model that fits the worker shape supported by your deployment; see +[GPU placement and budgets](/enterprise/function-operations#gpu). + The SDKs accept the same nested budget. CPU and memory are required; the GPU count inside the budget defaults to zero, so a CPU-only Function can omit it: diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx new file mode 100644 index 000000000..4546129fa --- /dev/null +++ b/docs/web/management/function-failures.mdx @@ -0,0 +1,151 @@ +--- +title: "Handle Function failures" +sidebarTitle: "Function Failures" +description: "Keep usable outputs, inspect row errors, retry by stable identity and isolate inputs that need attention." +tag: "Early access" +availability: + embedded: unavailable + enterprise: available +--- + +A Function refresh can encounter a bad row, fail to initialize a model, lose +a worker, or fail while publishing results. These need different remedies. +This guide uses the existing [refresh error policy](/sql/dml/refresh-column#options) +and Python error records; it does not require a new retry or quarantine API. + +## Choose a row-error policy {#policy} + +The default `fail` stops the job on a row error. `skip` writes null outputs for +failed rows and records errors, subject to the refresh's failure limits: + +```python +job = table.refresh_column_async( + "embedding", + error_policy="skip", + max_failed_rows=100, + max_failed_fraction=0.1, +) +result = job.wait() +print(result.rows_assigned, result.rows_failed, result.rows_remaining) +``` + +Choose limits for your workload; these example limits stop work when more +than 100 rows or more than 10% fail. `skip` does not make initialization, +infrastructure or publication failures successful. If `wait()` raises, +[refresh the job record](/basics/jobs#snapshots), inspect `job.failure`, and +inspect any recorded row errors. A failed/cancelled job can have committed +some output, but retention of every successful call is not guaranteed. +External effects are not rolled back and can be repeated during recovery. + +## Inspect and group recorded errors {#inspect} + +Scope diagnostics to the job you are investigating: + +```python +from collections import Counter + +errors = table.function_errors(job_id=job.id, column="embedding", limit=10000) +groups = Counter((r.error_type, r.error_message) for r in errors.records) +for cause, count in groups.most_common(): + print(count, cause) +for fragment in errors.fragments: + print(fragment.fragment_id, fragment.rows_skipped, fragment.rows_recorded) +print("listing truncated:", errors.truncated) +``` + +Each record includes the Function name/version, table version, error type and +message, creation time, and available row identities. `attempts` and traceback +details depend on the server/image version. This client-side grouping counts +only returned detail records. `truncated=True` or fragment summaries with +more skipped than recorded rows mean it is incomplete; do not label it a full +error census. See [`SHOW ERRORS`](/sql/ddl/job#errors) for SQL and its limits. + +Records are historical observations, not a deduplicated list of currently +failed rows. Reading errors without `job_id` can include older attempts that +have since succeeded. A null output can mean unfilled, skipped, or a computed +nullable field; output nullness alone is not a current-error test. + +## Retry exactly identified rows {#retry} + +On tables with stable row IDs, supporting server/SDK versions return +`record.row_id` from the refresh's pinned source version. Keep that table and +branch identity with the records. Compaction can move physical addresses, so +do not derive a row ID from fragment numbers or offsets. + +The following deliberately refuses incomplete or unidentified error sets. +Review historical records against the current inputs before using them as a +retry selection. Keep this selection small enough for a SQL predicate. + +```python +if errors.truncated or any(f.rows_skipped > f.rows_recorded for f in errors.fragments): + raise RuntimeError("Inspect a narrower job/error set before selecting retries") +if any(r.row_id is None for r in errors.records): + raise RuntimeError("This workflow requires stable row IDs in every error record") + +row_ids = sorted({int(r.row_id) for r in errors.records}) +if row_ids: + predicate = "_rowid IN (" + ", ".join(map(str, row_ids)) + ")" + retry_job = table.refresh_column_async("embedding", where=predicate) + retry_job.wait() +``` + +This recomputes every selected live row with the existing binding. It can +repeat a row already repaired since the error was recorded. Inspect the retry +job and its errors afterward; an older record need not disappear. On tables +without stable row IDs, resolve errors to application keys at the recorded +snapshot before retrying. Do not substitute `_rowaddr` after a rewrite. +Python `where=` requires a supporting SDK such as `0.42.0b9`, not stable +`0.41.0`, plus a matching server. + +## Repair with a newer Function {#new-version} + +Registering a new version does not change an existing column's immutable +binding. To evaluate a fix while retaining old outputs, register the corrected +callable and declare a separate output column. For example, with a corrected +`embed_fixed` callable already defined and a `text` input column: + +```python +from lancedb import col + +fixed = db.create_function(embed_fixed) +table.add_columns( + {"embedding_repaired": fixed(text=col("text"))}, + auto_refresh_enabled=False, +) +if row_ids: + repair_job = table.refresh_column_async("embedding_repaired", where=predicate) + repair_job.wait() +``` + +Only the reviewed failed-row selection is populated in the new column; other +rows remain unfilled. Compare those outputs before deciding how readers +should use them. This does not promise an in-place upgrade/retry operation or +per-row producing-version lookup for a column containing mixed executions. +Error records' Function versions describe failures, not the provenance of +every successful row. + +## Quarantine inputs for review {#quarantine} + +Use an application-owned table of source table/branch, recorded table version, +stable row ID or business key, Function version, cause and review disposition. +Keep Blob payloads in the source table; a quarantine entry can refer to their +source identity. Choose an ordinary table name such as `function_quarantine`, +and explicitly exclude its reviewed IDs in subsequent input selections. + +Quarantine is an application workflow here: there is no implied built-in +quarantine lifecycle, automatic current-error clearing or exactly-once retry. +Do not delete source rows merely to hide an error. For very large failure sets, +bounded error listings cannot select every row; use a smaller reviewed scope +or wait for a deployment with the required complete selection support. + +Native retry policies, full current-error summaries, in-place version upgrades +and materialized-view row-error handling have separate server/SDK prerequisites. +Do not apply `REFRESH COLUMN` options to a materialized view and assume the +same policy; consult the [MV refresh reference](/sql/dml/refresh-materialized-view) +for your deployment's accepted options. + +## Continue {#next} + +- [Function lifecycle and failures](/management/function#failures) +- [Conditional and list-element refresh](/feature-engineering/refresh-column#partial) +- [Job results and events](/basics/jobs#snapshots) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index aae67ceb9..27f45cb6a 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -420,6 +420,9 @@ full worked example. ## Failure handling {#failures} +For the full skip, inspect, grouped-error, stable-row-ID retry and quarantine +workflow, see [Handle Function failures](/management/function-failures). + By default, a Function that raises fails the refresh job. Choose how the refresh handles row errors with its error policy: @@ -495,6 +498,47 @@ 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. +### Supported global captures {#captures} + +The Python SDK's source packager captures only these literal values: + +| Module-level value | Packaging behavior | +| --- | --- | +| `None`, exact `bool`, `int`, `str`, `bytes`, finite `float` | Inlined as a snapshot at registration. | +| Tuples containing only those values, including nested tuples | Recursively inlined. | +| Imported modules, importable functions/classes | Reconstructed as imports; declare their packages in `pip` or `conda`, or ship local source with `code`. | +| Arrow types/schemas, lists, dictionaries, sets, NumPy arrays, non-finite floats, other objects | Not captured as literals. Construct them inside the Function or class. | + +For example, a module-level `OUT_TYPE = pa.list_(pa.float32(), 3)` referenced +from the Function body is unsupported. Construct the type where it is used: + +```python +import pyarrow as pa +from lancedb import function + +@function( + input_schema=pa.schema([pa.field("value", pa.float32(), nullable=False)]), + output_schema=pa.list_(pa.float32(), 3), +) +def make_vector(value: pa.Array) -> pa.Array: + out_type = pa.list_(pa.float32(), 3) + return pa.array([[v, v, v] for v in value.to_pylist()], type=out_type) +``` + +Decorator schema arguments are serialized as the signature; this restriction +concerns values referenced by the packaged body. For an expensive constant or +model, build it in a class Function's `__init__` and keep it on `self`. + +Later mutations of a client global do not update a registered version. Register +a new version to change captured literals or source. The diagnostic fix in +[SDK #4938](https://github.com/lancedb/lancedb/pull/4938) names the unsupported +global and its type; it does not add Arrow/container capture support. There is +no supported arbitrary-object serialization or documented container-size limit +to rely on for those rejected types. + +See the [Function type matrix](/curation/create-function#signature-types) for +what can travel as row inputs and outputs rather than captured globals. + 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. diff --git a/docs/web/search/full-text-search.mdx b/docs/web/search/full-text-search.mdx index 9c17fc50b..b7ceb15ad 100644 --- a/docs/web/search/full-text-search.mdx +++ b/docs/web/search/full-text-search.mdx @@ -182,6 +182,56 @@ BM25 scores depend on the indexed corpus and its term statistics. Compare rankings on the dataset you will search; treat scores as relative relevance values rather than probabilities. +### Match any word or every word {#term-operators} + +A multi-word string such as `"happy puppy"` uses **OR**: a row can match either +term. Writing `"happy AND puppy"` does not select an AND operator; the string +is analyzed as search text. To require both terms, construct a match query: + + +```python Python icon="python" +from lancedb.query import FullTextOperator, MatchQuery + +query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND) +results = table.search(query, query_type="fts").limit(10).to_list() +``` + +```typescript TypeScript icon="square-js" +import { MatchQuery, Operator } from "@lancedb/lancedb"; + +const query = new MatchQuery("happy puppy", "text", { operator: Operator.And }); +const results = await tbl.query().fullTextSearch(query).limit(10).toArray(); +``` + +```rust Rust icon="rust" +use lance_index::scalar::{ + FullTextSearchQuery, + inverted::query::{MatchQuery, Operator}, +}; +use lancedb::query::{ExecutableQuery, QueryBase}; + +let query = MatchQuery::new("happy puppy".to_owned()) + .with_column(Some("text".to_owned())) + .with_operator(Operator::And); +let results = tbl + .query() + .full_text_search(FullTextSearchQuery::new_query(query.into())) + .limit(10) + .execute() + .await?; +``` + + +AND requires all analyzed terms, without requiring adjacency or order. Use +[`PhraseQuery`](#phrase-vs-terms-queries) for an ordered phrase, or combine +separate queries with [`&` and `|`](#boolean-queries). Python `and` and `or` +do not build queries. + +On Enterprise, the existing [`fts()` SQL reference](/sql/dql/fts#term-operators) +shows the equivalent JSON (`"operator":"And"`), `_score`, and a +[`COUNT(*)` workaround](/sql/dql/fts#count) for counting matches without a +top-k limit. `len(results)` counts only the returned result page. + ### Keeping the index up to date {#keeping-the-index-up-to-date} In LanceDB Embedded, new rows can remain outside the FTS index until you optimize the table. @@ -395,6 +445,13 @@ table.create_index("text", config=FTS(with_position=True, remove_stop_words=Fals Storing token positions increases the index size and adds indexing work. +On Enterprise, wait for the replacement index to finish before issuing the +phrase query, using `table.wait_for_index(["text_idx"])` with your actual +index name. An existing index without positions must be rebuilt; changing the +query does not add positions. A phrase query against such an index is rejected +with an error asking you to recreate it with positions, rather than returning +an empty match set. See [FTS index options](/indexing/fts-index#fts-parameters) +and the [SQL phrase reference](/sql/dql/fts#phrase). ### Fuzzy Search {#fuzzy-search} diff --git a/docs/web/sql/dql/dedupe.mdx b/docs/web/sql/dql/dedupe.mdx index dbb6717b4..452638ea3 100644 --- a/docs/web/sql/dql/dedupe.mdx +++ b/docs/web/sql/dql/dedupe.mdx @@ -55,6 +55,15 @@ current deployments. a subset of partitions and `id_column` are pair-query-only options, accepted by [`duplicate_pairs`](/sql/dql/duplicate-pairs#input) but refused here. +## Index and snapshot requirements {#requirements} + +Use one compatible, current vector index covering the source snapshot. +Full scans reject unindexed fragments. Comparisons stay within physical IVF +partitions and index segments; this does not enumerate cross-partition or +cross-segment duplicates. Quantized-index distances use encoded vector +representations. See [recall and scale limits](/curation/dedupe#limits) before +treating the result as globally exact deduplication. + ## Output {#output} One row per duplicate group, **in the table's own schema** -- every column of diff --git a/docs/web/sql/dql/duplicate-pairs.mdx b/docs/web/sql/dql/duplicate-pairs.mdx index daa078955..dc93d5180 100644 --- a/docs/web/sql/dql/duplicate-pairs.mdx +++ b/docs/web/sql/dql/duplicate-pairs.mdx @@ -60,6 +60,12 @@ only [`dedupe`](/sql/dql/dedupe#input) accepts it. ## Output {#output} +See [`dedupe` index prerequisites](/sql/dql/dedupe#requirements) and the +[recall limits](/curation/dedupe#limits). Pairs are found within each physical +partition and index segment, not across them. A full scan requires complete +index coverage; sampling is a diagnostic view of the selected indexed +partitions and does not prove coverage or recall for the rest of the table. + One row per close pair found, in a fixed schema independent of the source table: diff --git a/docs/web/sql/dql/fts.mdx b/docs/web/sql/dql/fts.mdx index 7b52f5e17..667d92cd6 100644 --- a/docs/web/sql/dql/fts.mdx +++ b/docs/web/sql/dql/fts.mdx @@ -30,14 +30,16 @@ INSERT INTO my_docs VALUES (3, 'The puppy catches a ball with great enthusiasm', 'sports', 'Alice'), (5, 'Puppy training requires patience and dedication', 'training', 'Alice'); -CREATE INDEX ON my_docs USING fts (text); +CREATE INDEX ON my_docs USING fts (text) WITH (with_position = true); ``` Phrase queries need position information, which costs extra index size. -Add `WITH (with_position = true)` to `CREATE INDEX`. Without it, -[phrase queries](#phrase) find nothing. See +The setup above enables it with `WITH (with_position = true)`. An existing +index without positions must be rebuilt before running a phrase query; the +server rejects the query and asks you to recreate the index with positions. +It does not silently return no matches. See [FTS parameters](/indexing/fts-index#fts-parameters). @@ -86,6 +88,44 @@ LIMIT 5 it behaves like any other column, but exists only in a relation that came from `fts()`. See [Data types](/sql/data-types#pseudo-columns). +## Match any term or every term {#term-operators} + +The default match operator is OR. `"happy puppy"` matches either analyzed +term. SQL JSON uses `"Or"` and `"And"`, with this casing; Python uses the +`FullTextOperator.OR` and `FullTextOperator.AND` enum members: + +```python +from lancedb.query import FullTextOperator, MatchQuery + +query = MatchQuery("happy puppy", "text", operator=FullTextOperator.AND) +json_query = query.to_json() +``` + +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +ORDER BY _score DESC +``` + +Both terms must occur, but they need not be adjacent. Do not embed `AND` or +`OR` in `terms` to select an operator. + +## Count matches {#count} + +Count the `fts()` relation before applying a top-k limit: + +```sql +SELECT COUNT(*) AS matching_rows +FROM fts('my_docs', '{"match":{"column":"text","terms":"happy puppy","operator":"And"}}') +``` + +This is an Enterprise SQL workaround when the SDK's FTS query builder does +not expose a match-count operation. `table.count_rows()` without an FTS +relation counts table rows, and taking the length of a limited search counts +only that result page. For list-element indexes, multiple matching elements +can produce multiple rows; use `COUNT(DISTINCT id)` when you need unique +application records. + ## Fuzzy {#fuzzy} Tolerates typos, up to a character-edit budget: @@ -109,6 +149,12 @@ PhraseQuery("puppy park", "text", slop=2) # up to 2 words between them ``` +```sql +SELECT id, text, _score +FROM fts('my_docs', '{"phrase":{"column":"text","terms":"happy puppy","slop":0}}') +ORDER BY _score DESC +``` + ## Boolean {#boolean} Combine queries with `&` (AND) or `|` (OR): @@ -120,6 +166,17 @@ MatchQuery("puppy", "text") | MatchQuery("kitten", "text") ``` +For SQL, serialize the composed query rather than writing occurrence enums +by hand: + +```python +query = MatchQuery("puppy", "text") & MatchQuery("happy", "text") +json_query = query.to_json() +``` + +Use that string as the second `fts()` argument. `.to_json()` supplies the +serialized Boolean field names for the SDK version you use. + ## Boost {#boost} Weight a query up or down relative to another: From e1a10eaa66c68aa87d40056f73f0bf97c95091c3 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Sat, 14 Nov 2026 20:22:13 +0800 Subject: [PATCH 115/203] chore(deps): upgrade Lance to v15.0.0-beta.21 (#5046) Upgrade the Rust Lance family from beta.18 to the published v15.0.0-beta.21 tag, and align Python test wheels and Java artifacts. This includes the explicit-empty-segment FTS fix in lance-format/lance#11063 needed by lancedb/sophon#10314. Enable Windows Git long paths so Cargo can check out Lance fixtures in the Rust, NPM and Python wheel builds. Beta.21 also contains lance-format/lance#9858: new NGram, RTree and MinHash LSH indexes use row addresses. Legacy row-ID segments remain readable, but index maintenance on stable-row-ID tables can require a rebuild. The NGram documentation now explains the consolidation requirement; NGram/RTree tables without stable row IDs retain their earlier format. The Python lock revision and unrelated dependency entries are unchanged. Validation: - The official Lance release and internal mirror match 80bc45a195279befdec42853dac8d15a37e0504d. The seven official Fury wheels and Maven POM/JAR were verified. - Exact executable/dependency state 7846a15e completed the full Rust, Python, Node, Java and CLI CI, including platform builds and package publication dry runs. Xuanwo approved that head; Gatekeeper recommended approve with a non-blocking qualification risk. - Follow-up a289cb2c only adds the requested seven-line NGram upgrade note. Static whitespace checks passed; new-head CI is running. No local correctness tests or test builds were run by this task owner. - Broader IVF/encoding/Blob/cache workload performance and the beta.21 Sophon composition remain separately qualified. Earlier Blob cancellation and DynamoDB failures on #4967 are retained in their original evidence; this PR does not count those historical failures as fixed. Current-head CI, full feedback and required review still gate merge. SDK publication is a separate action. Sophon adoption follows a published SDK release and mirror through its own dependency PR; its distributed performance acceptance remains in #10314. --- .../workflows/build_windows_wheel/action.yml | 3 + .github/workflows/npm-publish.yml | 4 + .github/workflows/rust.yml | 4 + Cargo.lock | 97 ++++++++++--------- Cargo.toml | 30 +++--- docs/web/indexing/scalar-index.mdx | 7 ++ java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 17 ++-- 9 files changed, 93 insertions(+), 73 deletions(-) diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 954ee7d35..3d92d818a 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -12,6 +12,9 @@ inputs: runs: using: "composite" steps: + - name: Enable long paths for Lance dependencies + shell: bash + run: git config --global core.longpaths true - uses: ./.github/actions/setup-protoc - name: Build wheel uses: PyO3/maturin-action@v1 diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 1b7d3dcbc..ac95b5a47 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -162,6 +162,10 @@ jobs: working-directory: nodejs steps: - uses: actions/checkout@v6 + - name: Enable long paths for Windows dependencies + if: runner.os == 'Windows' + # Cargo also checks out Lance test fixtures below its git cache path. + run: git config --global core.longpaths true - name: Setup pnpm uses: pnpm/action-setup@v6 with: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a5e5c9c30..4c275240f 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -349,6 +349,8 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add ${{ matrix.target }} - uses: Swatinem/rust-cache@v2 @@ -386,6 +388,8 @@ jobs: working-directory: rust/lancedb steps: - uses: actions/checkout@v6 + - name: Enable long paths for Lance dependencies + run: git config --global core.longpaths true - name: Set target run: rustup target add aarch64-pc-windows-msvc - uses: Swatinem/rust-cache@v2 diff --git a/Cargo.lock b/Cargo.lock index 22b0f1e6f..d1624f941 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3824,8 +3824,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5303,8 +5303,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5379,8 +5379,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5416,7 +5416,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5425,8 +5425,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrayref", "crunchy", @@ -5436,8 +5436,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5475,8 +5475,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5507,8 +5507,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5533,8 +5533,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5551,8 +5551,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "proc-macro2", "quote", @@ -5561,8 +5561,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-arith", "arrow-array", @@ -5595,8 +5595,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-arith", "arrow-array", @@ -5627,8 +5627,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5659,8 +5659,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5696,6 +5696,7 @@ dependencies = [ "lance-arrow-stats", "lance-bitpacking", "lance-core", + "lance-datafusion", "lance-datafusion-exec", "lance-encoding", "lance-file", @@ -5732,8 +5733,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5756,8 +5757,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5802,8 +5803,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "byteorder", "ethnum", @@ -5820,8 +5821,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5836,8 +5837,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "async-trait", @@ -5851,8 +5852,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arc-swap", "arrow", @@ -5906,8 +5907,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-buffer", @@ -5921,8 +5922,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow", "arrow-array", @@ -5963,8 +5964,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "arrow-array", "arrow-schema", @@ -5977,8 +5978,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" +version = "15.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index c45eef6da..bc9d85c72 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index f674a988d..fbd818b64 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -210,6 +210,13 @@ table.search().where("contains(text, 'needle')").limit(10).to_pandas() `list_indices()` reports the index type as `"NGram"`. + +Lance 15.0.0-beta.21 writes new NGram indexes using physical row addresses. On +tables with stable row IDs, rebuild legacy NGram indexes that store row IDs +before consolidating their segments. Consolidation rejects these legacy +row-ID segments. Tables without stable row IDs retain the earlier index format. + + ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. diff --git a/java/pom.xml b/java/pom.xml index fc89ebe4c..196e6db9a 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.18 + 15.0.0-beta.21 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 6940dce4f..d464424c7 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b18", + "pylance==15.0.0b21", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 369d558d2..31ac68b4d 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b18" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b21" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b18" +version = "15.0.0b21" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" }, - { url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" }, - { url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" }, + { url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" }, + { url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" }, ] [[package]] From 5de76bd8edebb1aae915591683bdcfa642807032 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sat, 14 Nov 2026 12:33:00 +0000 Subject: [PATCH 116/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.12=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index e4989d1eb..04ce71470 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.12" +current_version = "0.42.0-beta.13" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index d1624f941..a84f1d6fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5992,7 +5992,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "ahash", "anyhow", @@ -6103,7 +6103,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "anyhow", "arrow-array", @@ -6146,7 +6146,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "arrow-array", "arrow-buffer", @@ -6171,7 +6171,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index ca77b251c..1aadbe68f 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.42.0-beta.12 + 0.42.0-beta.13 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 792b434a1..e8a9a76ec 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.12 + 0.42.0-beta.13 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 196e6db9a..9b062f4e8 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.12 + 0.42.0-beta.13 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 22cfe6ecc..7f8468eb5 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.12" +version = "0.42.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 283a32fdc..0fb6fde09 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.42.0-beta.12", + "version": "0.42.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 5fd392245..24e779721 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.42.0-beta.12", + "version": "0.42.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 ec5103284..8ee7bd66b 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.42.0-beta.12", + "version": "0.42.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 1d45a2ed2..3c7c63b86 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.42.0-beta.12", + "version": "0.42.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 d17a3b4e7..75e68cacd 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.42.0-beta.12", + "version": "0.42.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 a7c4a74b6..3422e095c 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.42.0-beta.12", + "version": "0.42.0-beta.13", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0e3a4a626..e9ceb4dfb 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.42.0-beta.12", + "version": "0.42.0-beta.13", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index b0d99fb60..512e390aa 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.12", + "version": "0.42.0-beta.13", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 5a2923216..0f7667320 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.12" +version = "0.42.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 ef5da44c5..2dac7bda3 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index b22a3b8d8..581504423 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.12" +version = "0.42.0-beta.13" edition = "2021" license.workspace = true repository.workspace = true From 2f496322ef23bdb27d57e7aea9d151336ab570a4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:51:25 +0800 Subject: [PATCH 117/203] fix: report multipart rows only after part acknowledgement (#5020) Remote multipart progress currently counts every scanned row before the corresponding IPC part is acknowledged. A rejected first part can therefore report uploaded rows, even though its acknowledged byte count remains zero. Count both rows and IPC bytes only after each part succeeds, including parts assembled from multiple batches or split from one batch. Retried parts count once. Native and single-request writes retain their existing accounting; acknowledged multipart progress describes staged data, not a successful commit. Validation follows the actual TCP upload path: one scanned batch becomes six decoded IPC parts, the sixth response is lost, and each request/retry observes only previously acknowledged rows and bytes. Rejection and complete-outcome cases preserve the same accounting boundary. This validation covers local HTTP behavior; deployed service throughput and the original disconnect investigation remain outside its scope. Frozen candidate validation: 839 remote tests and 7 progress tests passed. Scoped Clippy (`lancedb`, remote feature, lib/tests/examples, warnings denied) passed with unchanged source. Python/Node bindings were unchanged and were not rebuilt for this patch. --- docs/web/ingestion/insert.mdx | 7 ++- rust/lancedb/src/remote/table.rs | 2 +- rust/lancedb/src/remote/table/insert.rs | 19 ++++-- rust/lancedb/src/remote/table/write_tests.rs | 63 ++++++++++++++++++-- rust/lancedb/src/table/write_progress.rs | 38 ++++++++---- 5 files changed, 103 insertions(+), 26 deletions(-) diff --git a/docs/web/ingestion/insert.mdx b/docs/web/ingestion/insert.mdx index 923a71b0e..7633584c6 100644 --- a/docs/web/ingestion/insert.mdx +++ b/docs/web/ingestion/insert.mdx @@ -150,9 +150,10 @@ Python and TypeScript report elapsed time in seconds; Rust returns a `Duration`. The expected row count may be unknown for streaming input. On the final update, it falls back to the number of rows written. -For remote multipart writes, rows count input scanning, while bytes count -acknowledged IPC parts. Bytes start at zero and a retried part is counted once, -after acknowledgement. Scanned rows and staged bytes do not imply a commit. +For remote multipart writes, both rows and IPC bytes count acknowledged parts. +Both start at zero; a retried part is counted once, after acknowledgement. +Scanning input or sending a rejected part does not advance these counts. +Acknowledged parts are staged and do not imply a successful commit. Keep callbacks short and use the write operation's result to determine success. The final `done` update means progress reporting has ended; it can also occur diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index a7cf3f80d..5c00232f7 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2262,7 +2262,7 @@ impl RemoteTable { num_partitions: usize, ) -> Result { if let Some(tracker) = &output.tracker { - tracker.use_wire_bytes(); + tracker.use_acknowledged_parts(); } let freshness_request = self.snapshot_freshness_headers(); let upload_id = self.create_multipart_write(output.retries).await?; diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index 0de1c21cc..0801880f2 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -480,6 +480,7 @@ impl PartRequestCtx<'_, S> { let started = Instant::now(); let mut pending = Some(first); let mut has_batch = false; + let mut part_rows = 0; let mut input_ended = false; loop { let batch = match pending.take().or_else(|| queued.pop_front()) { @@ -520,6 +521,7 @@ impl PartRequestCtx<'_, S> { // A single row and its schema cannot be split further. } has_batch = true; + part_rows += batch.num_rows(); if writer.get_ref().len() as u64 >= max_bytes || max_duration.is_some_and(|limit| started.elapsed() >= limit) { @@ -536,7 +538,7 @@ impl PartRequestCtx<'_, S> { match self.send_part_request(request, freshness).await { Ok(()) => { if let Some(tracker) = tracker { - tracker.record_bytes(body.len()); + tracker.record_acknowledged_part(part_rows, body.len()); } return Ok(input_ended); } @@ -1648,7 +1650,7 @@ mod tests { } #[tokio::test] - async fn test_multipart_records_acknowledged_bytes() { + async fn test_multipart_records_acknowledged_rows_and_bytes() { use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use futures::StreamExt; @@ -1667,14 +1669,18 @@ mod tests { ]; let input = input_plan_from_batches(schema, batches).await; - let observed = Arc::new(Mutex::new(Vec::::new())); + let observed = Arc::new(Mutex::new(Vec::<(usize, usize)>::new())); let observed_cb = observed.clone(); let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { - observed_cb.lock().unwrap().push(p.output_bytes()); + observed_cb + .lock() + .unwrap() + .push((p.output_rows(), p.output_bytes())); })); let tracker = Arc::new(WriteProgressTracker::new(callback, None)); - // Count encoded bytes once when the part is acknowledged. + tracker.use_acknowledged_parts(); + // Count rows from all encoded batches once when the part is acknowledged. let exec = RemoteWriteExec::new_multipart( "my_table".to_string(), "my_table".to_string(), @@ -1697,6 +1703,7 @@ mod tests { "batches should all land in a single part" ); let observed = observed.lock().unwrap(); + assert_eq!(observed.last().unwrap().0, 6); assert!( observed.len() == 1, "expected one progress update per acknowledged part: {observed:?}" @@ -1706,7 +1713,7 @@ mod tests { "progress bytes should be monotonic: {observed:?}" ); assert!( - *observed.last().unwrap() > 0, + observed.last().unwrap().1 > 0, "final progress should report bytes: {observed:?}" ); } diff --git a/rust/lancedb/src/remote/table/write_tests.rs b/rust/lancedb/src/remote/table/write_tests.rs index c97619af1..2e0ca1d45 100644 --- a/rust/lancedb/src/remote/table/write_tests.rs +++ b/rust/lancedb/src/remote/table/write_tests.rs @@ -267,17 +267,44 @@ async fn multipart_http_faults_preserve_committed_blob_payloads() { #[tokio::test] async fn multipart_retries_sixth_part_after_reused_connection_closes() { + use crate::table::write_progress::{ProgressCallback, WriteProgress, WriteProgressTracker}; use datafusion_execution::TaskContext; use datafusion_physical_plan::ExecutionPlan; use futures::TryStreamExt; + let progress = Arc::new(Mutex::new(Vec::new())); + let observed = progress.clone(); + let callback: ProgressCallback = Arc::new(Mutex::new(move |p: &WriteProgress| { + observed + .lock() + .unwrap() + .push((p.output_rows(), p.output_bytes())); + })); + let tracker = Arc::new(WriteProgressTracker::new(callback, Some(6))); + tracker.use_acknowledged_parts(); + let during_request = progress.clone(); 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 attempts = Vec::new(); + let mut acknowledged_bytes = 0; let (mut socket, _) = listener.accept().await.unwrap(); for n in 0..6 { let (path, body) = read_request(&mut socket).await; + let rows = StreamReader::try_new(body.as_slice(), None) + .unwrap() + .map(|batch| batch.unwrap().num_rows()) + .sum::(); + assert_eq!(rows, 1, "one scanned batch must split into six parts"); + let reported = *during_request.lock().unwrap().last().unwrap(); + assert_eq!( + reported, + (n, acknowledged_bytes), + "progress must exclude the unacknowledged part" + ); + if n < 5 { + acknowledged_bytes += body.len(); + } attempts.push((path, body)); if n == 5 { break; @@ -291,9 +318,17 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { // The sixth part was staged, but the peer closes before response headers. drop(socket); let (mut socket, _) = listener.accept().await.unwrap(); - attempts.push(read_request(&mut socket).await); + let (path, body) = read_request(&mut socket).await; + let reported = *during_request.lock().unwrap().last().unwrap(); + assert_eq!( + reported, + (5, acknowledged_bytes), + "retry must not report the lost acknowledgement" + ); + acknowledged_bytes += body.len(); + attempts.push((path, body)); respond(&mut socket, 200, "{}").await; - attempts + (attempts, acknowledged_bytes) }); let client = RestfulLanceDbClient::try_new( &crate::remote::client::parse_db_url("db://test").unwrap(), @@ -316,7 +351,10 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { .unwrap(); let input = arrow_array::record_batch!(("id", Int32, [1, 2, 3, 4, 5, 6])).unwrap(); let plan = Arc::new( - crate::table::datafusion::scannable_exec::ScannableExec::new(Box::new(input), None), + crate::table::datafusion::scannable_exec::ScannableExec::new( + Box::new(input), + Some(tracker.clone()), + ), ); let exec = super::insert::RemoteWriteExec::new_multipart( "test".into(), @@ -325,7 +363,7 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { plan, false, "upload-1".into(), - None, + Some(tracker), None, Some(1), None, @@ -335,7 +373,15 @@ async fn multipart_retries_sixth_part_after_reused_connection_closes() { .try_collect::>() .await .unwrap(); - let attempts = server.await.unwrap(); + let (attempts, acknowledged_bytes) = server.await.unwrap(); + let progress = progress.lock().unwrap(); + assert_eq!(*progress.first().unwrap(), (0, 0)); + assert_eq!(*progress.last().unwrap(), (6, acknowledged_bytes)); + assert!( + progress + .windows(2) + .all(|pair| pair[0].0 <= pair[1].0 && pair[0].1 <= pair[1].1) + ); assert_eq!(attempts.len(), 7); assert_eq!( attempts[5], attempts[6], @@ -424,7 +470,12 @@ async fn multipart_rejections_preserve_progress_and_cleanup_boundaries() { let progress = progress.lock().unwrap(); let last = progress.last().unwrap(); assert!(last.2); - assert_eq!(last.0, 2); + assert_eq!( + progress.first().unwrap().0, + 0, + "scan is not an acknowledgement" + ); + assert_eq!(last.0, if stage_status == 200 { 2 } else { 0 }); if stage_status != 200 { assert!( progress.iter().all(|p| p.1 == 0), diff --git a/rust/lancedb/src/table/write_progress.rs b/rust/lancedb/src/table/write_progress.rs index 12e4dd62c..efea4586c 100644 --- a/rust/lancedb/src/table/write_progress.rs +++ b/rust/lancedb/src/table/write_progress.rs @@ -30,9 +30,11 @@ impl WriteProgress { self.elapsed } - /// Number of rows processed by the input scan. + /// Number of rows processed by the writer. /// - /// This does not indicate that the rows have been committed. + /// Remote multipart writes count rows in acknowledged IPC parts, starting + /// at zero and counting retransmissions once. Other writers report rows + /// processed by the input scan. Neither indicates a successful commit. pub fn output_rows(&self) -> usize { self.output_rows } @@ -101,8 +103,8 @@ pub(crate) struct WriteProgressTracker { /// Wire bytes tracked separately by the insert layer. When set (> 0), /// this takes precedence over the in-memory bytes from `rows_and_bytes`. wire_bytes: AtomicUsize, - /// Multipart writes select this before scanning, including zero acknowledgements. - wire_bytes_enabled: AtomicBool, + /// Multipart progress excludes input scanning and counts only acknowledged parts. + acknowledged_parts: AtomicBool, active_tasks: Arc, total_tasks: AtomicUsize, start: Instant, @@ -116,7 +118,7 @@ impl WriteProgressTracker { Self { rows_and_bytes: std::sync::Mutex::new((0, 0)), wire_bytes: AtomicUsize::new(0), - wire_bytes_enabled: AtomicBool::new(false), + acknowledged_parts: AtomicBool::new(false), active_tasks: Arc::new(AtomicUsize::new(0)), total_tasks: AtomicUsize::new(1), start: Instant::now(), @@ -125,9 +127,9 @@ impl WriteProgressTracker { } } - /// Select wire-byte progress, including zero, before polling the input plan. - pub fn use_wire_bytes(&self) { - self.wire_bytes_enabled.store(true, Ordering::Relaxed); + /// Select acknowledged rows and wire bytes before polling the input plan. + pub fn use_acknowledged_parts(&self) { + self.acknowledged_parts.store(true, Ordering::Relaxed); } /// Set the total number of parallel write tasks (the write parallelism). @@ -145,13 +147,29 @@ impl WriteProgressTracker { pub fn record_batch(&self, rows: usize, bytes: usize) { // Lock order: callback first, then rows_and_bytes. This is the only // order used anywhere, so deadlocks cannot occur. + let mut cb = self.callback.lock().unwrap_or_else(|e| e.into_inner()); + let mut guard = self + .rows_and_bytes + .lock() + .unwrap_or_else(|e| e.into_inner()); + if !self.acknowledged_parts.load(Ordering::Relaxed) { + guard.0 += rows; + guard.1 += bytes; + } + let progress = self.snapshot(guard.0, guard.1, false); + drop(guard); + cb(&progress); + } + + /// Record one successfully staged part, after any retries have finished. + pub fn record_acknowledged_part(&self, rows: usize, bytes: usize) { let mut cb = self.callback.lock().unwrap_or_else(|e| e.into_inner()); let mut guard = self .rows_and_bytes .lock() .unwrap_or_else(|e| e.into_inner()); guard.0 += rows; - guard.1 += bytes; + self.wire_bytes.fetch_add(bytes, Ordering::Relaxed); let progress = self.snapshot(guard.0, guard.1, false); drop(guard); cb(&progress); @@ -194,7 +212,7 @@ impl WriteProgressTracker { let wire = self.wire_bytes.load(Ordering::Relaxed); // Prefer wire bytes (actual I/O size) when the insert layer is // tracking them; fall back to in-memory Arrow size otherwise. - let output_bytes = if self.wire_bytes_enabled.load(Ordering::Relaxed) || wire > 0 { + let output_bytes = if self.acknowledged_parts.load(Ordering::Relaxed) || wire > 0 { wire } else { in_memory_bytes From beda423318a33ec70515b6baf4ae92e95918c2d5 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:52:50 +0800 Subject: [PATCH 118/203] fix(node): bind blob byte queries to their response snapshot (#5019) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TypeScript remote `toArrow` and `toArray` could combine scalar values from query snapshot A with Blob payloads from a later snapshot B. Cached table schemas and native descriptor layouts could also leave descriptors in a `blobMode: "bytes"` result. Discover Blob fields and snapshot provenance from the executed query stream, recognizing canonical native v2 descriptors as well as extension-marked fields. Fetch payloads through an independent Rust snapshot handle bound to the query version and immutable dataset identity, without changing the live table. Preserve aliases, nested fields, NULL/empty values, explicit row IDs, and scalar-only results. Hybrid byte queries require matching provenance from both actual responses. Missing or mismatched server provenance fails explicitly; logical-input validation and local materialization remain unchanged. Manual integration validation at `4daf354df`: all five real SDK/NAPI → Sophon REST scenarios passed. Both `toArrow` and `toArray` retain A bytes across overwrite and reject same-name/same-URI recreation even when version and row IDs are reused. A previously cached handle discovers a subsequently added Blob field. Ten actual payload fetches include the two expected identity rejections; later queries on the same live handle read B. The canonical-descriptor and Blob regression suites pass 119 tests, with independent source and wire-evidence review. Earlier broader SDK and hybrid evidence is retained within its unchanged-source scope. This is local REST interoperability evidence, not deployed Cloud/header-forwarding acceptance. Remote bytes require the authoritative server version/identity and fetch-echo contract. CI and formal review remain merge requirements; this follow-up does not close ENT-3556 or Blob V2 GA. --- .../js/interfaces/QueryExecutionOptions.md | 6 +- docs/web/management/table.mdx | 19 + nodejs/__test__/remote_blob_snapshot.test.ts | 642 ++++++++++++++++++ nodejs/lancedb/blob.ts | 42 +- nodejs/lancedb/query.ts | 71 +- nodejs/src/table.rs | 25 + rust/lancedb/src/query.rs | 36 +- 7 files changed, 828 insertions(+), 13 deletions(-) create mode 100644 nodejs/__test__/remote_blob_snapshot.test.ts diff --git a/docs/src/js/interfaces/QueryExecutionOptions.md b/docs/src/js/interfaces/QueryExecutionOptions.md index fb9bada29..cd36343b8 100644 --- a/docs/src/js/interfaces/QueryExecutionOptions.md +++ b/docs/src/js/interfaces/QueryExecutionOptions.md @@ -29,8 +29,10 @@ 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. +The rows and bytes come from the same snapshot. Remote queries require +authoritative query version and snapshot identity headers, verified again +by the blob response. Older servers can still return `"descriptions"`. +Local queries retry up to three times if the table changes while they run. #### Example diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 8031a4c49..facb9bdfe 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -720,6 +720,25 @@ table changes while the query runs, the query runs again, up to three times: +{/* Draft for the Enterprise TypeScript bytes release. Replace the retry guidance above only after SDK and serving-node rollout. + +Local queries retry up to three times if the table changes while they run. +Remote queries instead bind payload fetches to the version and immutable +snapshot identity from the executed query response. They do not rerun the query +against a newer version to recover missing payloads. Both `toArray()` and +`toArrow()` discover Blob fields from that response, including fields added +after the table handle was opened. + +Every serving node must support `x-lancedb-query-version` and +`x-lancedb-query-snapshot`, enforce the requested identity when fetching bytes, +and echo it in the fetch response. Proxies must forward these headers. Missing +or mismatched provenance fails explicitly; use `blobMode: "descriptions"` until +the rollout is complete. Keep queried versions available for deferred reads: +snapshot identities do not prevent version deletion. Dropping and recreating a +table cannot substitute the replacement's bytes, even if its version is reused. +Hybrid byte queries require matching snapshot provenance from both responses. +*/} + #### Read blobs on demand {#multimodal-read-blobs} Query the rows you want and pass their `_rowid` values to a fetch method. diff --git a/nodejs/__test__/remote_blob_snapshot.test.ts b/nodejs/__test__/remote_blob_snapshot.test.ts new file mode 100644 index 000000000..908dfa9de --- /dev/null +++ b/nodejs/__test__/remote_blob_snapshot.test.ts @@ -0,0 +1,642 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { type Table, connect } from "../lancedb"; +import { + Table as ArrowTable, + DataType, + Field, + Float32, + LargeBinary, + RecordBatch, + Schema, + Struct, + Uint8, + Uint32, + Uint64, + Utf8, + makeArrowTable, + tableToIPC, + vectorFromArray, +} from "../lancedb/arrow"; + +const IDENTITY_A = `v1:${"a".repeat(64)}`; +const IDENTITY_B = `v1:${"b".repeat(64)}`; +const image = new Field( + "image", + new Struct([ + new Field("kind", new Uint8(), false), + new Field("position", new Uint64(), true), + new Field("size", new Uint64(), true), + new Field("blob_id", new Uint32(), false), + new Field("blob_uri", new Utf8(), false), + ]), + true, + // Native descriptor scans replace the logical extension metadata. + new Map([ + ["lance-encoding:blob", "true"], + ["lance-encoding:packed", "true"], + ]), +); +const schema = new Schema([new Field("label", new Utf8(), false), image]); +const description = { + fields: [ + { name: "label", type: { type: "string" }, nullable: false }, + { + name: "image", + nullable: true, + metadata: { "ARROW:extension:name": "lance.blob.v2" }, + type: { + type: "struct", + fields: ["position", "size"].map((name) => ({ + name, + type: { type: "uint64" }, + nullable: true, + })), + }, + }, + ], +}; + +type Request = { + path: string; + body: Record; + raw: string; + identity: string | string[] | undefined; +}; + +interface ServerOptions { + queryBlob?: Field; + describeBlobName?: string | null; + nestedBlob?: boolean; + queryVersion?: string | null; + queryIdentity?: string | null; + echo?: string | null; + empty?: boolean; + values?: boolean; + advanceQueries?: boolean; + otherLegIdentity?: string | null; + otherLegVersion?: string; +} + +// A real HTTP service: the query finishes on A, then the logical table changes +// before the deferred blob request. Recreating B reuses both version and row IDs. +async function withSnapshotServer( + change: "recreate" | "overwrite", + run: (table: Table, requests: Request[]) => Promise, + options: ServerOptions = {}, +) { + const requests: Request[] = []; + let changed = false; + const queryBlob = options.queryBlob ?? image; + const queryOutputSchema = options.nestedBlob + ? new Schema([ + schema.fields[0], + new Field("extra", new Struct([queryBlob]), true), + ]) + : new Schema([schema.fields[0], queryBlob]); + const server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + try { + const raw = Buffer.concat(chunks).toString() || "{}"; + const body = JSON.parse(raw); + const path = req.url ?? ""; + const identity = req.headers["x-lancedb-query-snapshot"]; + requests.push({ path, body, raw, identity }); + res.setHeader("phalanx-version", "0.5.0"); + if (path.endsWith("/describe/")) { + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + version: changed && change === "overwrite" ? 2 : 1, + schema: { + fields: description.fields.flatMap((field) => { + if (field.name !== "image") return [field]; + if (options.describeBlobName === null) return []; + return [ + { ...field, name: options.describeBlobName ?? "image" }, + ]; + }), + }, + }), + ); + } else if (path.endsWith("/query/")) { + const vector = (body.vector?.length ?? 0) > 0; + const advanced = options.advanceQueries === true && changed; + const label = advanced ? "B" : "A"; + const columns: [string, string][] = + body.columns === undefined + ? queryOutputSchema.fields.map((field) => [ + field.name, + field.name, + ]) + : Array.isArray(body.columns) + ? body.columns.map((name: string) => [name, name]) + : Object.entries(body.columns); + const queryFields = columns.map(([output, source]) => + queryOutputSchema.fields + .find((field) => field.name === source)! + .clone({ name: output }), + ); + if (body.with_row_id) { + queryFields.push(new Field("_rowid", new Uint64(), false)); + } + if (vector || body.full_text_query) { + queryFields.push( + new Field(vector ? "_distance" : "_score", new Float32(), false), + ); + } + // Forged IPC metadata must never substitute for authoritative headers. + const querySchema = new Schema( + queryFields, + new Map([ + ["lancedb:query_version", "999"], + ["lancedb:query_snapshot", IDENTITY_B], + ]), + ); + const values = options.empty + ? [] + : options.values + ? ["A", null, ""] + : [label]; + const rows = values.map((value, index) => { + const row: Record = {}; + for (const [output, source] of columns) { + const descriptor = + value === null + ? null + : { + kind: 0, + position: 0n, + size: BigInt(value.length), + // biome-ignore lint/style/useNamingConvention: Native Arrow field name. + blob_id: 0, + // biome-ignore lint/style/useNamingConvention: Native Arrow field name. + blob_uri: "", + }; + row[output] = + source === "image" + ? descriptor + : source === "extra" + ? descriptor === null + ? null + : { image: descriptor } + : label; + } + if (body.with_row_id) row._rowid = BigInt(index); + if (vector || body.full_text_query) { + row[vector ? "_distance" : "_score"] = 0.5; + } + return row; + }); + const result = + rows.length === 0 + ? new ArrowTable(querySchema) + : new ArrowTable( + querySchema, + Object.fromEntries( + queryFields.map((field) => [ + field.name, + vectorFromArray( + rows.map((row) => row[field.name]), + field.type, + ), + ]), + ), + ); + res.setHeader("content-type", "application/vnd.apache.arrow.stream"); + const version = + vector && options.otherLegVersion !== undefined + ? options.otherLegVersion + : options.queryVersion; + const snapshot = + vector && options.otherLegIdentity !== undefined + ? options.otherLegIdentity + : options.queryIdentity; + res.setHeader("x-lancedb-version", "1"); + if (version !== null) { + res.setHeader( + "x-lancedb-query-version", + version ?? (advanced ? "2" : "1"), + ); + } + if (snapshot !== null) { + res.setHeader( + "x-lancedb-query-snapshot", + snapshot ?? (advanced ? IDENTITY_B : IDENTITY_A), + ); + } + changed = true; + res.end(tableToIPC(result, "stream")); + } else if (path.endsWith("/fetch_blobs/")) { + const requestedVersion = /"version":([0-9]+)/.exec(raw)?.[1]; + const readsOriginal = + change === "overwrite" && + requestedVersion === (options.queryVersion ?? "1"); + const actualIdentity = readsOriginal ? IDENTITY_A : IDENTITY_B; + // An older serving node may ignore the guard and answer successfully; + // its echo must still be verified before the client uses any bytes. + if (options.echo !== null) { + res.setHeader( + "x-lancedb-query-snapshot", + options.echo ?? actualIdentity, + ); + } + res.setHeader("content-type", "application/vnd.apache.arrow.stream"); + const payloads = options.values + ? ["A", null, ""] + : [readsOriginal ? "A" : "B"]; + res.end( + tableToIPC( + makeArrowTable( + (body.row_ids as number[]).map((id) => ({ + [String(body.column)]: + payloads[id] === null ? null : Buffer.from(payloads[id]!), + })), + { + schema: new Schema([ + new Field(String(body.column), new LargeBinary(), true), + ]), + }, + ), + "stream", + ), + ); + } else { + res.writeHead(404).end(path); + } + } catch (error) { + res.writeHead(500).end(String(error)); + } + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${ + (server.address() as AddressInfo).port + }`, + }); + await run(await db.openTable("test"), requests); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } +} + +const fetchRequests = (requests: Request[]) => + requests.filter((request) => request.path.endsWith("/fetch_blobs/")); +const queryRequests = (requests: Request[]) => + requests.filter((request) => request.path.endsWith("/query/")); + +const keepFtsReranker = { + async rerankHybrid(_query: string, _vector: RecordBatch, fts: RecordBatch) { + const fields = fts.schema.fields.map((field) => + field.name === "_score" + ? field.clone({ name: "_relevance_score" }) + : field, + ); + return new RecordBatch( + new Schema(fields, fts.schema.metadata), + fts.data.clone(new Struct(fields)), + ); + }, +}; + +describe("remote blob query snapshot", () => { + it.each([ + image.clone({ metadata: new Map() }), + new Field( + "image", + new Struct(image.type.children.slice(1, 3)), + true, + image.metadata, + ), + ])( + "leaves plain structs and v1 descriptors unchanged: %s", + async (queryBlob) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const result = await table.query().toArrow({ blobMode: "bytes" }); + expect(DataType.isStruct(result.getChild("image")!.type)).toBe(true); + expect(result.toArray()[0].image.size).toBe(1n); + expect(fetchRequests(requests)).toHaveLength(0); + }, + { queryBlob }, + ); + }, + ); + + it("still recognizes extension-marked Blob results", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const rows = await table.query().toArray({ blobMode: "bytes" }); + expect(Buffer.from(rows[0].image).toString()).toBe("A"); + expect(fetchRequests(requests)).toHaveLength(1); + }, + { + queryBlob: image.clone({ + metadata: new Map([["ARROW:extension:name", "lance.blob.v2"]]), + }), + }, + ); + }); + + it.each([ + [null, false], + [null, true], + ["old_image", false], + ["old_image", true], + ] as const)( + "uses the query schema after cached blob %s changes (alias: %s)", + async (describeBlobName, alias) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + expect(await table.blobColumns()).toEqual( + describeBlobName === null ? [] : [describeBlobName], + ); + const query = table.query(); + if (alias) query.select({ "photo.image": "image" }); + const output = alias ? "photo.image" : "image"; + const result = await query.toArrow({ blobMode: "bytes" }); + expect(DataType.isLargeBinary(result.getChild(output)!.type)).toBe( + true, + ); + expect( + result + .toArray() + .map((row) => + row[output] === null + ? null + : Buffer.from(row[output]).toString(), + ), + ).toEqual(["A", null, ""]); + expect( + result.schema.fields.some((field) => field.name === "_rowid"), + ).toBe(false); + expect(queryRequests(requests)).toHaveLength(1); + expect(fetchRequests(requests)).toHaveLength(1); + expect(fetchRequests(requests)[0].body.column).toBe("image"); + expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A); + }, + { describeBlobName, values: true }, + ); + }, + ); + + it("maps nested query fields through literal aliases despite a stale schema", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + expect(await table.blobColumns()).toEqual([]); + const rows = await table + .query() + .select({ "container.alias": "extra" }) + .toArray({ blobMode: "bytes" }); + expect( + rows.map((row) => + row["container.alias"] === null + ? null + : Buffer.from(row["container.alias"].image).toString(), + ), + ).toEqual(["A", null, ""]); + expect(queryRequests(requests)).toHaveLength(1); + expect(fetchRequests(requests)[0].body.column).toBe("extra.image"); + expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A); + }, + { nestedBlob: true, describeBlobName: null, values: true }, + ); + }); + + it.each(["toArrow", "toArray"] as const)( + "%s rejects payloads from a recreated table with reused version and row IDs", + async (terminal) => { + await withSnapshotServer("recreate", async (table, requests) => { + await expect( + table.query()[terminal]({ blobMode: "bytes" }), + ).rejects.toThrow(/snapshot identity/); + const [fetch] = fetchRequests(requests); + expect(fetch.body.version).toBe(1); + expect(fetch.body.row_ids).toEqual([0]); + expect(fetch.body.column).toBe("image"); + expect(fetch.identity).toBe(IDENTITY_A); + }); + }, + ); + + it("keeps the producing snapshot after an overwrite without rerunning the query", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const rows = await table.query().toArray({ blobMode: "bytes" }); + expect(rows[0].label).toBe("A"); + expect(Buffer.from(rows[0].image).toString()).toBe("A"); + expect(queryRequests(requests)).toHaveLength(1); + const [fetch] = fetchRequests(requests); + expect(fetch.body.version).toBe(1); + expect(fetch.identity).toBe(IDENTITY_A); + expect(await table.version()).toBe(2); + const [latest] = await table.query().toArray({ blobMode: "bytes" }); + expect(latest.label).toBe("B"); + expect(Buffer.from(latest.image).toString()).toBe("B"); + expect(fetchRequests(requests)[1].identity).toBe(IDENTITY_B); + }, + { advanceQueries: true }, + ); + }); + + it.each([ + { queryVersion: null }, + { queryVersion: "0" }, + { queryVersion: "18446744073709551616" }, + { queryVersion: "invalid" }, + { queryIdentity: null }, + { queryIdentity: "v2:unsupported" }, + ])("refuses bytes without authoritative capability %j", async (options) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const [descriptor] = await table.query().toArray(); + expect(descriptor.image.size).toBe(1n); + await expect( + table.query().toArray({ blobMode: "bytes" }), + ).rejects.toThrow(/blobMode.*bytes.*requires.*snapshot/); + expect(fetchRequests(requests)).toHaveLength(0); + }, + options, + ); + }); + + it("rejects a serving node without the snapshot echo", async () => { + await withSnapshotServer( + "overwrite", + async (table) => { + await expect( + table.query().toArray({ blobMode: "bytes" }), + ).rejects.toThrow(/snapshot identity/); + }, + { echo: null }, + ); + }); + + it("keeps aliases, NULL, empty bytes, and explicit row IDs", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const query = table + .query() + .select({ caption: "label", "photo.image": "image" }); + const rows = await query.withRowId().toArray({ blobMode: "bytes" }); + expect(rows.map((row) => row._rowid)).toEqual([0n, 1n, 2n]); + expect( + rows.map((row) => + row["photo.image"] === null + ? null + : Buffer.from(row["photo.image"]).toString(), + ), + ).toEqual(["A", null, ""]); + expect(rows[0].caption).toBe("A"); + expect(fetchRequests(requests)[0].body.column).toBe("image"); + const [descriptor] = await query.toArray(); + expect(descriptor["photo.image"].size).toBe(1n); + }, + { values: true }, + ); + }); + + it("preserves an empty bytes schema without fetching payloads", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const result = await table.query().toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(0); + expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe( + true, + ); + expect(result.schema.fields.map((field) => field.name)).toEqual([ + "label", + "image", + ]); + expect(fetchRequests(requests)).toHaveLength(0); + }, + { empty: true }, + ); + }); + + it("passes the query version without rounding through a JS number", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + await table.query().toArray({ blobMode: "bytes" }); + expect(fetchRequests(requests)[0].raw).toContain( + '"version":9007199254740993', + ); + }, + { queryVersion: "9007199254740993" }, + ); + }); + + it.each(["vector", "hybrid"])( + "materializes the actual %s query entry point", + async (kind) => { + await withSnapshotServer("overwrite", async (table, requests) => { + const query = table.query().nearestTo([0.1, 0.2]); + if (kind === "hybrid") query.fullTextSearch("A"); + const rows = await query.toArray({ blobMode: "bytes" }); + expect(Buffer.from(rows[0].image).toString()).toBe("A"); + expect(fetchRequests(requests)[0].identity).toBe(IDENTITY_A); + expect(queryRequests(requests)).toHaveLength(kind === "hybrid" ? 2 : 1); + }); + }, + ); + + it("allows scalar-only bytes queries on older servers", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const [row] = await table + .query() + .select(["label"]) + .toArray({ blobMode: "bytes" }); + expect(row.label).toBe("A"); + expect(Object.keys(row)).toEqual(["label"]); + expect(fetchRequests(requests)).toHaveLength(0); + // Row IDs are requested before the executed output schema is known, + // then hidden from scalar-only results without requiring capability. + expect(queryRequests(requests)[0].body.with_row_id).toBe(true); + }, + { queryIdentity: null, queryVersion: null }, + ); + }); + + it.each([false, true])( + "preserves snapshot proof across a custom reranker (empty: %s)", + async (empty) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const result = await table + .query() + .nearestTo([0.1, 0.2]) + .fullTextSearch("A") + .rerank(keepFtsReranker) + .toArrow({ blobMode: "bytes" }); + expect(result.numRows).toBe(empty ? 0 : 1); + expect(DataType.isLargeBinary(result.getChild("image")!.type)).toBe( + true, + ); + expect(fetchRequests(requests)).toHaveLength(empty ? 0 : 1); + }, + { empty }, + ); + }, + ); + + it("does not trust a custom reranker's first-leg snapshot when the legs disagree", async () => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const query = table + .query() + .nearestTo([0.1, 0.2]) + .fullTextSearch("A") + .rerank(keepFtsReranker); + await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow( + /snapshot/, + ); + expect(fetchRequests(requests)).toHaveLength(0); + }, + { otherLegIdentity: IDENTITY_B }, + ); + }); + + it.each([ + { otherLegIdentity: IDENTITY_B }, + { otherLegIdentity: null }, + { otherLegVersion: "2" }, + ])( + "refuses hybrid bytes when its actual query legs disagree %j", + async (options) => { + await withSnapshotServer( + "overwrite", + async (table, requests) => { + const query = table.query().nearestTo([0.1, 0.2]).fullTextSearch("A"); + await expect(query.toArray({ blobMode: "bytes" })).rejects.toThrow( + /snapshot/, + ); + expect(fetchRequests(requests)).toHaveLength(0); + expect(await query.toArray()).toHaveLength(1); + }, + options, + ); + }, + ); +}); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index a46484314..be26f6121 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -1,7 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -import { Field, LargeBinary, Struct, Uint64, Utf8 } from "apache-arrow"; +import { + DataType, + Field, + LargeBinary, + Struct, + Uint64, + Utf8, +} from "apache-arrow"; import { BlobFile as NativeBlobFile } from "./native"; const BLOB_V2_EXTENSION_NAME = "lance.blob.v2"; @@ -178,6 +185,39 @@ export function isBlobField(field: Field): boolean { return field.metadata?.get("ARROW:extension:name") === BLOB_V2_EXTENSION_NAME; } +/** @ignore */ +export function isBlobDescriptorField(field: Field): boolean { + // Native descriptor scans replace the logical extension metadata. Require + // both the encoding marker and the v2 layout to exclude v1 and plain structs. + if ( + field.metadata?.get("lance-encoding:blob") !== "true" || + !DataType.isStruct(field.type) + ) { + return false; + } + const children = field.type.children; + const integers = [ + ["kind", 8], + ["position", 64], + ["size", 64], + ["blob_id", 32], + ] as const; + return ( + children.length === 5 && + integers.every(([name, width], index) => { + const child = children[index]; + return ( + child.name === name && + DataType.isInt(child.type) && + !child.type.isSigned && + child.type.bitWidth === width + ); + }) && + children[4].name === "blob_uri" && + DataType.isUtf8(children[4].type) + ); +} + /** * A lazy handle to blob bytes. Create one with {@link Table.fetchBlobFiles}. * diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index bb845276f..6b72f19fd 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -17,6 +17,7 @@ import { tableFromIPC, vectorFromArray, } from "./arrow"; +import { isBlobDescriptorField, isBlobField } from "./blob"; import { Expr } from "./expr"; import { type IvfPqOptions } from "./indices"; import { @@ -148,6 +149,34 @@ async function readBlobBytes( ); } +// Discover descriptors from the executed query, not the live table's cached +// schema. Projection names are literal aliases; only source paths use dots. +function projectedBlobSources( + schema: Schema, + projection: [string, string][] | undefined, +): BlobSource[] { + const sources: BlobSource[] = []; + for (const field of schema.fields) { + const source = + projection?.find(([output]) => output === field.name)?.[1] ?? field.name; + const visit = (child: Field, path: string[]) => { + if (isBlobField(child) || isBlobDescriptorField(child)) { + sources.push({ + output: field.name, + path, + source: [source, ...path].join("."), + }); + } else if (DataType.isStruct(child.type)) { + for (const nested of child.type.children) { + visit(nested, [...path, nested.name]); + } + } + }; + visit(field, []); + } + return sources; +} + function withBinaryColumns( table: ArrowTable, replacements: Map, @@ -257,8 +286,10 @@ export interface QueryExecutionOptions { * 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. + * The rows and bytes come from the same snapshot. Remote queries require + * authoritative query version and snapshot identity headers, verified again + * by the blob response. Older servers can still return `"descriptions"`. + * Local queries retry up to three times if the table changes while they run. * * @example * ```ts @@ -499,6 +530,34 @@ export class QueryBase< if (context === undefined) { return this.collect(options, false); } + if (!context.table.isNative()) { + // Request row IDs in the same query so newly added Blob columns can be + // fetched without rerunning the query against a different snapshot. + const addRowId = !context.withRowId; + const table = await this.collect(options, addRowId); + const sources = projectedBlobSources(table.schema, context.projection); + if (sources.length === 0) { + return addRowId + ? table.select( + table.schema.fields + .map((field) => field.name) + .filter((name) => name !== "_rowid"), + ) + : table; + } + const version = table.schema.metadata.get("lancedb:query_version"); + const identity = table.schema.metadata.get("lancedb:query_snapshot"); + if (version === undefined || identity === undefined) { + throw new Error( + 'blobMode "bytes" requires a trustworthy query snapshot: missing, invalid, or inconsistent x-lancedb-query-version or x-lancedb-query-snapshot. Upgrade every serving node, or use blobMode "descriptions".', + ); + } + const snapshot = await context.table.querySnapshotWithIdentity( + version, + identity, + ); + return readBlobBytes(table, sources, snapshot, addRowId); + } for (let attempt = 1; ; attempt++) { // The snapshot pins the bytes. The query runs on the live table, so an // unchanged version afterwards proves it read the snapshot's version. @@ -533,10 +592,10 @@ export class QueryBase< for await (const batch of RecordBatchIterator(iterator)) { batches.push(batch); } - if (batches.length === 0) { - return tableFromIPC((await iterator).schema()); - } - return new ArrowTable(batches); + // Read metadata from the executed stream, including empty results and + // query types whose individual batches do not carry the stream metadata. + const schema = tableFromIPC((await iterator).schema()).schema; + return new ArrowTable(schema, batches); } private blobBytesContext( diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index f6abeb553..c82c2cd93 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -349,6 +349,31 @@ impl Table { Ok(Query::new(self.inner_ref()?.query())) } + /// Whether this handle reads an in-process dataset. + #[napi] + pub fn is_native(&self) -> napi::Result { + Ok(self.inner_ref()?.as_native().is_some()) + } + + /// Constrain deferred blob reads by the producing query response. + #[napi(catch_unwind)] + pub async fn query_snapshot_with_identity( + &self, + version: String, + identity: String, + ) -> napi::Result { + // Keep u64 query versions exact across the JavaScript boundary. + let version = version + .parse::() + .map_err(|_| napi::Error::from_reason("Invalid query snapshot version"))?; + let snapshot = self + .inner_ref()? + .query_snapshot_with_identity(version, &identity) + .await + .default_error()?; + Ok(Self::new(snapshot)) + } + /// Return a read-only table handle pinned to the current query revision. #[napi(catch_unwind)] pub async fn query_snapshot(&self) -> napi::Result { diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index f96e84e96..157440910 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -42,7 +42,7 @@ use lance_index::vector::DIST_COL; use crate::error::{Error, Result}; use crate::rerankers::rrf::RRFReranker; use crate::rerankers::{NormalizeMethod, Reranker, check_reranker_result}; -use crate::table::BaseTable; +use crate::table::{BaseTable, NativeTableExt}; use crate::utils::{MaxBatchLengthStream, TimeoutStream}; use crate::{ApproxMode, DistanceType}; use crate::{ @@ -1564,14 +1564,32 @@ impl VectorQuery { vector_query.inner_execute_with_options(internal_options) )?; + // A reranker can replace schema metadata. Only the two producing + // streams can establish the snapshot of a remote hybrid result. + let snapshot = |schema: SchemaRef| { + schema + .metadata() + .get("lancedb:query_version") + .zip(schema.metadata().get("lancedb:query_snapshot")) + .map(|(version, identity)| (version.clone(), identity.clone())) + }; + let stream_schemas = (fts_results.schema(), vec_results.schema()); + let fts_snapshot = snapshot(stream_schemas.0.clone()); + let vec_snapshot = snapshot(stream_schemas.1.clone()); + let query_snapshot = fts_snapshot.filter(|value| Some(value) == vec_snapshot.as_ref()); + let (fts_results, vec_results) = try_join!( fts_results.try_collect::>(), vec_results.try_collect::>() )?; - // try to get the schema to use when combining batches. - // if either - let (fts_schema, vec_schema) = hybrid::query_schemas(&fts_results, &vec_results); + // Preserve remote output schemas even when a leg has no batches. + // The WAL primary-key fallback retains its synthesized score schema. + let (fts_schema, vec_schema) = if self.parent.as_native().is_none() && pk_fusion.is_none() { + stream_schemas + } else { + hybrid::query_schemas(&fts_results, &vec_results) + }; // concatenate all the batches together let mut fts_results = concat_batches(&fts_schema, fts_results.iter())?; @@ -1612,6 +1630,16 @@ impl VectorQuery { check_reranker_result(&results)?; + if self.parent.as_native().is_none() { + let metadata = results.schema_metadata_mut(); + metadata.remove("lancedb:query_version"); + metadata.remove("lancedb:query_snapshot"); + if let Some((version, identity)) = query_snapshot { + metadata.insert("lancedb:query_version".into(), version); + metadata.insert("lancedb:query_snapshot".into(), identity); + } + } + let limit = self.request.base.limit.unwrap_or(DEFAULT_TOP_K); if results.num_rows() > limit { results = results.slice(0, limit); From 193f203b720e6825299e9cf72f9d9695c5d4c72d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:54:19 +0800 Subject: [PATCH 119/203] ci: run remote Functions gate only in the full test suite (#5022) The remote job runs the default local Functions gate twice: once before building the remaining test targets, and again in the full remote suite. Run it only through the existing full suite, removing the serial Cargo invocation barrier while retaining the same features, authentication wrapper, targets, and 30-minute deadline. The [hosted remote job](https://github.com/lancedb/lancedb/actions/runs/43302507952/job/131477104217) at `7886d79e` completed successfully in 25m36s within the unchanged 30-minute limit. Its full suite passed 2,164 unit, 114 integration, and 120 doctests, including the three default gate tests. This single run establishes completion for that workload, not a general timing improvement or cold-build guarantee. The branch now includes main's Cargo artifact fixture repair (#5010). The workflow, full-suite command, authentication wrapper, three default Functions gate tests, and 30-minute deadline are unchanged from that hosted run. The 2,398-test result remains evidence for `7886d79e`. On the updated head `810d6558`, the [hosted remote job](https://github.com/lancedb/lancedb/actions/runs/43382023177/job/131741745645) completed in 17m58s with 2,171 unit tests, 119 integration tests, and 122 doctests passing (82 ignored), including all three default Functions gate tests. This is current-head execution evidence, not a controlled speedup comparison. --- .github/workflows/rust.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 4c275240f..9bbc4d581 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -291,8 +291,6 @@ 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 From 56c4b3a6f2886b62e246e0a04da89ddf002dd7a8 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:55:23 +0800 Subject: [PATCH 120/203] ci: stabilize macOS Node toolchain and build budget (#5017) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The macOS Node job installed floating stable before restoring the Rust cache, although native builds use the repository-pinned compiler. Use the existing file-aware Rust setup action with its implicit cache disabled so setup, cache selection and compilation use the same pin and one cache owner. Preserve the existing native build flags. Allow 35 minutes for the complete macOS job. In the [pinned-toolchain cold run](https://github.com/lancedb/lancedb/actions/runs/43291714333/job/131439350321), native compilation finished in 28m02s, but setup and packaging exhausted the former 30-minute job limit before TypeScript checking and Jest. Retained full Jest runs took 38–59 seconds; the new bound covers the measured work with a small margin. The runner, build profile, features, targets and complete test commands are preserved. Hosted acceptance at `ff718c03`: the [complete macOS job](https://github.com/lancedb/lancedb/actions/runs/43300424344/job/131469805138) succeeded within the 35-minute limit (20:27:07–20:56:58 UTC). Native compilation took 27m38s; the complete applicable Jest suite passed 1,695 tests, with 22 skipped, in 46.129s. This single successful run does not guarantee every cold-build duration, validate the separate beta19 composition, or establish the cause of the DynamoDB timeout. --- .github/workflows/nodejs.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index e83c8d29f..4d28ca4a1 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -234,7 +234,8 @@ jobs: NODE_OPTIONS: "--experimental-vm-modules" run: node_modules/.bin/jest --verbose macos: - timeout-minutes: 30 + # Cold native builds can take 28 minutes; reserve time for setup and Jest. + timeout-minutes: 35 # macos-15 ships a newer linker; the older macos-14 linker fails to insert # branch islands when the debug cdylib's __text section exceeds the 128 MB # AArch64 B/BL branch range. @@ -257,7 +258,11 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: dtolnay/rust-toolchain@stable + # Use the same pinned compiler for cache selection and the native build. + - uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + cache: false + rustflags: "" - uses: Swatinem/rust-cache@v2 with: # Restore everywhere, but only save from main. Per-PR saves are From 0d55457d9e030c901da64fdd24d3c88ae255e06e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:57:49 +0800 Subject: [PATCH 121/203] test(node): make blob read cancellation deterministic (#5029) The Node blob cancellation test assumes a 32 MiB local read is still in flight when JavaScript immediately aborts. The native future can finish first, in which case returning its completed buffer is valid. Replace that timing assumption with the existing HTTP fixture: send one byte of a five-byte range response, hold back the remaining body, then abort. Verify `AbortError`, response disconnection, listener cleanup, and a subsequent read on the same handle with the single request permit. Existing local pre-abort, successful-read, cursor, and close coverage remains in place; production cancellation semantics are unchanged. Validated the 97 scoped Blob tests on Linux x64 / Node 22.23.4 with both a locally built beta18 binding and the [beta19 native binding built for #4967](https://github.com/lancedb/lancedb/actions/runs/43381450237/job/131739908253). The beta19 run used the published repair tests at `8096f848`, passed all 97 cases with exit 0, and verified the downloaded artifact digest, loaded binding hash, and native build checkout against #4967's source tree. The pre-existing `CustomGC` import diagnostic remains; the process exited normally. The [hosted macOS ARM64 job](https://github.com/lancedb/lancedb/actions/runs/43395339041/job/131784902005) also passed the cancellation regression and the complete applicable Jest suite: 1,695 tests passed and 22 were skipped on Node 24.22.2 / beta18. Its actual merge checkout `e906a2da` has matching test, native Blob, dependency, and workflow sources to PR head `8096f848`. A separate [macOS ARM64 / Node 22.23.4 / beta19 composition run](https://github.com/lancedb/lancedb/actions/runs/43559120836/job/132353156252) now passed 1,694 tests (23 skipped), including both in-flight cancellation and later-response-body cancellation/permit release. It tested the normal merge of #4967 `6b175764` and this repair `8096f848`, at validation head `144e5294` whose only subsequent change narrows the workflow and disables publication. The loaded native binding hash and downloaded artifact digest were captured. The original failed #4967 job is preserved; this separate validation does not replace normal prerequisite integration or current-branch CI on #4967. --- nodejs/__test__/blob_ranges.test.ts | 73 +++++++++++++++++++++++++---- nodejs/__test__/table.test.ts | 23 --------- 2 files changed, 64 insertions(+), 32 deletions(-) diff --git a/nodejs/__test__/blob_ranges.test.ts b/nodejs/__test__/blob_ranges.test.ts index 7d2fab566..9e7b0e53d 100644 --- a/nodejs/__test__/blob_ranges.test.ts +++ b/nodejs/__test__/blob_ranges.test.ts @@ -51,9 +51,10 @@ async function withRangeServer( run: (db: Connection, calls: Request[], paths: string[]) => Promise, fault?: string | number, capability: string | null = "1", - onStall?: () => void, + onStall?: (response: http.ServerResponse) => void, ) { let takes = 0; + let rangeReads = 0; const calls: Request[] = []; const paths: string[] = []; const server = http.createServer((req, res) => { @@ -91,13 +92,18 @@ async function withRangeServer( expect(url.searchParams.get("version")).toBe("3"); const [start, end] = req.headers.range!.slice(6).split("-").map(Number); const bytes = Buffer.from("alpha").subarray(start, end + 1); - res - .writeHead(206, { - "Content-Range": `bytes ${start}-${end}/5`, - "Content-Length": bytes.length, - "x-lancedb-version": "3", - }) - .end(bytes); + res.writeHead(206, { + "Content-Range": `bytes ${start}-${end}/5`, + "Content-Length": bytes.length, + "x-lancedb-version": "3", + }); + if (fault === "stall-read" && ++rangeReads === 1) { + // Withhold the rest of the body so native completion cannot win the abort. + res.write(bytes.subarray(0, 1)); + onStall?.(res); + return; + } + res.end(bytes); return; } expect(req.method).toBe("POST"); @@ -191,7 +197,7 @@ async function withRangeServer( "x-lancedb-query-snapshot": IDENTITY, }); res.flushHeaders(); - onStall?.(); + onStall?.(res); return; } if (typeof failure === "number") { @@ -327,6 +333,55 @@ describe("fetchBlobRanges", () => { }); }); + it("cancels an in-flight BlobFile read and leaves the handle usable", async () => { + let responseTimedOut = false; + let markStalled!: () => void; + const stalled = new Promise((resolve) => { + markStalled = resolve; + }); + let markDisconnected!: () => void; + const disconnected = new Promise((resolve) => { + markDisconnected = resolve; + }); + await withRangeServer( + async (db) => { + const table = await open(db, 3); + const [handle] = await table.fetchBlobFiles("image", [10n]); + const controller = new AbortController(); + try { + const pending = handle!.readRange(0n, handle!.size(), { + signal: controller.signal, + }); + const rejected = expect(pending).rejects.toMatchObject({ + name: "AbortError", + }); + await stalled; + controller.abort(); + await rejected; + await disconnected; + expect(responseTimedOut).toBe(false); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + expect(handle!.isClosed()).toBe(false); + expect(await handle!.tell()).toBe(0n); + // The single request permit must also be released by cancellation. + expect(await handle!.readRange(0n, 5n)).toEqual(Buffer.from("alpha")); + } finally { + controller.abort(); + await handle!.close(); + } + }, + "stall-read", + null, + (response) => { + response.once("timeout", () => { + responseTimedOut = true; + }); + response.once("close", markDisconnected); + markStalled(); + }, + ); + }); + it("cancels while waiting for a later response body and releases the only permit", async () => { let markStalled!: () => void; const stalled = new Promise((resolve) => { diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 59d6929b4..2c45dbccd 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3271,29 +3271,6 @@ describe("when dealing with blob columns", () => { expect(await handle!.read()).toEqual(alpha); }); - it("cancels an in-flight read", async () => { - const db = await connect(tmpDir.name); - const schema = new Schema([ - new Field("id", new Int64(), true), - blob("payload", { inlineSizeThreshold: 0, dedicatedSizeThreshold: 1 }), - ]); - const payload = Buffer.alloc(32 * 1024 * 1024, 7); - const table = await db.createTable("large_blobs", [{ id: 1n, payload }], { - schema, - }); - const [row] = await table.query().withRowId().toArray(); - const [handle] = await table.fetchBlobFiles("payload", [ - row._rowid as bigint, - ]); - const controller = new AbortController(); - const pending = handle!.readRange(0n, handle!.size(), { - signal: controller.signal, - }); - controller.abort(); - await expect(pending).rejects.toMatchObject({ name: "AbortError" }); - expect(await handle!.readRange(0n, 4n)).toEqual(payload.subarray(0, 4)); - }); - it("toArrow returns blob bytes with blobMode bytes", async () => { const { table, alpha, beta } = await openBlobTable(); const result = await table.query().toArrow({ blobMode: "bytes" }); From 005b33fa8b8884356ba465ebe93bdbbb4831329a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:10 +0800 Subject: [PATCH 122/203] fix: preserve terminal server identity in failed job waits (#5024) A failed remote Function job loses its persisted build identity when converted into the exception from `job.wait()`. Append `result.terminal_server` to that error using the existing server-build format, preserving its message, row location, traceback and job ID. Do not substitute the responding query node's version for the writer of the saved terminal result; missing or malformed historical identity leaves the error unchanged. The reported failure was independently reproduced against a deployed server with a real Function job. The new exact Rust regression reproduces the missing terminal identity on the unpatched code. At `59c1f3e`, all 10 remote Job Rust tests and five tests using the matching native Python extension passed, including sync/async waits with known or unknown terminal identity. These transport tests use mocked HTTP responses; the original deployed Function job remains with independent acceptance for recheck after delivery. This change does not establish whole-ticket acceptance. --- python/python/tests/test_remote_db.py | 63 +++++++++++++++++ rust/lancedb/src/remote/job.rs | 98 +++++++++++++++++++++++++-- 2 files changed, 155 insertions(+), 6 deletions(-) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b38ae4a5b..c5afac308 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2991,6 +2991,69 @@ def test_remote_job_wait_raises_on_failure(): assert exc_info.value.sql_job_id is None +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False]) +@pytest.mark.parametrize("with_terminal_server", [True, False]) +async def test_remote_job_wait_preserves_terminal_build(sync, with_terminal_server): + from lancedb.exceptions import JobFailedError + + message = "ValueError: corrupt frame at frame_index=207" + server = { + "release": "1.13.0-beta.0", + "git_sha": "2a7874ecd589", + "build_date": "2026-11-12T22:45:43Z", + } + result = {"terminal_server": server} if with_terminal_server else None + + def handler(request): + assert request.path == "/v1/jobs/describe" + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.send_header( + "x-lancedb-server-build", + json.dumps({"release": "2.0.0", "git_sha": "new-query-node"}), + ) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "job-provenance", + "job_state": "FAILED", + "failure": { + "phase": "function_refresh_attempt_failed", + "message": message, + "traceback": "Traceback: original user code", + "retryable": False, + }, + "result": result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("job-provenance") + with pytest.raises(JobFailedError) as caught: + job.wait() + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("job-provenance") + with pytest.raises(JobFailedError) as caught: + await job.wait() + + expected = f"Job job-provenance failed: {message}" + if with_terminal_server: + expected += ( + " [server: 1.13.0-beta.0 (git 2a7874ecd589, built 2026-11-12T22:45:43Z)]" + ) + expected += " (in function_refresh_attempt_failed)" + assert str(caught.value) == expected + assert caught.value.job_id == "job-provenance" + assert job.failure.message == message + assert job.failure.traceback == "Traceback: original user code" + assert job.result == result + + @pytest.mark.parametrize("server_version", ["0.2.0", "0.6.0"]) def test_remote_json_fts_config(server_version): from lancedb.index import FTS diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index c546ce4d1..7e59834d0 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -322,14 +322,32 @@ impl JobHandle for RemoteJob { match description.state() { JobState::Done => return Ok(description.into_terminal_result(request_id)), JobState::Failed => { + let mut failure = description + .failure + .map(ReportedFailure::into_job_failure) + .unwrap_or_default(); + // The responding query node may have upgraded since this job + // failed. Only its persisted terminal writer identifies the failure. + if let Some(server) = description + .result + .as_ref() + .and_then(|result| result.get("terminal_server")) + .and_then(|server| { + serde_json::from_value::( + server.clone(), + ) + .ok() + }) + { + let provenance = format!("[server: {server}]"); + failure.message = Some(match failure.message { + Some(message) => format!("{message} {provenance}"), + None => provenance, + }); + } return Err(Error::JobFailed { job_id: Some(self.job_id.clone()), - failure: Box::new( - description - .failure - .map(ReportedFailure::into_job_failure) - .unwrap_or_default(), - ), + failure: Box::new(failure), }); } JobState::Cancelled => { @@ -662,4 +680,72 @@ mod tests { assert_eq!(failure.retryable, Some(true)); assert_eq!(failure.sql_job_id.as_deref(), Some("job-1")); } + + #[tokio::test] + async fn wait_failure_uses_persisted_terminal_build() { + let server = serde_json::json!({ + "release": "1.13.0-beta.0", + "git_sha": "2a7874ecd589", + "build_date": "2026-11-12T22:45:43Z" + }); + for result in [ + serde_json::Value::Null, + serde_json::json!({"terminal_server": null}), + serde_json::json!({"terminal_server": {"release": "incomplete"}}), + serde_json::json!({"terminal_server": server}), + ] { + let known_build = result["terminal_server"] == server; + let response = serde_json::json!({ + "job_id": "job-1", + "job_state": "FAILED", + "failure": { + "phase": "function_refresh_attempt_failed", + "message": "ValueError: corrupt frame at frame_index=207", + "traceback": "Traceback: original user code", + "retryable": false + }, + "result": result + }); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .header( + "x-lancedb-server-build", + r#"{"release":"2.0.0","git_sha":"new-query-node"}"#, + ) + .body(response.to_string()) + .unwrap() + }); + let job = RemoteJob::new(client, "job-1".to_string()); + let description = job.describe().await.unwrap(); + assert_eq!( + description.result.as_ref(), + (!result.is_null()).then_some(&result) + ); + assert_eq!( + description.failure.unwrap().message.as_deref(), + Some("ValueError: corrupt frame at frame_index=207") + ); + let error = job.wait().await.err().expect("failed job"); + let mut expected = + "Job job-1 failed: ValueError: corrupt frame at frame_index=207".to_string(); + if known_build { + expected.push_str( + " [server: 1.13.0-beta.0 (git 2a7874ecd589, built 2026-11-12T22:45:43Z)]", + ); + } + expected.push_str(" (in function_refresh_attempt_failed)"); + assert_eq!(error.to_string(), expected); + let crate::error::Error::JobFailed { job_id, failure } = error else { + panic!("expected JobFailed"); + }; + assert_eq!(job_id.as_deref(), Some("job-1")); + assert_eq!( + failure.traceback.as_deref(), + Some("Traceback: original user code") + ); + assert_eq!(failure.retryable, Some(false)); + } + } } From e5a5b67212ccc75ca7b69f3ac53de3dc045ffb34 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:20 +0800 Subject: [PATCH 123/203] feat: support nullable scalar Function declarations (#5030) Function declarations currently reject nullable scalar returns. Accept `Optional[T]`, `T | None`, and explicit nullable Arrow fields, preserving `nullable: true` in registration signatures, JSON round trips, and remote `add_columns` requests. The Rust planner accepts nullable scalar outputs, and binding readback recognizes the server-owned assignment marker for a single nullable scalar result. Clients do not allocate that marker. Non-nullable whole results, whole structs, and Blob v2 retain their existing assignment restrictions. Validated with 127 Python tests, 30 documentation tests (1 skipped), and seven focused Rust tests covering planning, binding readback, rejection boundaries, and the remote request body. The final condition-collapse change addresses strict Clippy; its delta check and CI are pending. Python tests use a source overlay on a retained native extension, and Rust remote coverage uses HTTP mocks. Server support and end-to-end validation remain separate. This PR does not claim that server publication distinguishes computed NULL values from pending rows. --- docs/web-tests/py/test_function.py | 28 +- docs/web/curation/create-function.mdx | 11 +- docs/web/management/function.mdx | 42 ++- python/python/lancedb/functions.py | 35 +- .../tests/test_first_class_function_slice2.py | 64 +++- rust/lancedb/src/function.rs | 4 +- rust/lancedb/src/remote/table.rs | 77 +++++ rust/lancedb/src/table/computed_columns.rs | 306 +++++++++++++++++- 8 files changed, 517 insertions(+), 50 deletions(-) diff --git a/docs/web-tests/py/test_function.py b/docs/web-tests/py/test_function.py index 147520b18..ff4c6b9a3 100644 --- a/docs/web-tests/py/test_function.py +++ b/docs/web-tests/py/test_function.py @@ -154,13 +154,27 @@ def test_function_output_nullability(): ("note", True), ] - # A scalar output, and a struct declared as one nullable field, may not be. - for nullable in ( - pa.field("result", pa.float64(), nullable=True), - pa.field("result", pa.struct(fields), nullable=True), - ): - with pytest.raises(ValueError, match="non-nullable"): - function(input_schema=inputs, output_schema=nullable)(describe) + # A scalar output may be nullable. + @function(input_schema=inputs) + def maybe_double(value: float) -> float | None: + return None if value == 0 else value * 2 + + output = maybe_double.registration_request.signature.output + assert (output.kind, output.arrow_type, output.nullable) == ( + "scalar", + "float64", + True, + ) + assert json.loads(maybe_double.registration_request.signature.to_canonical_json())[ + "output" + ] == {"kind": "scalar", "arrow_type": "float64", "nullable": True} + + # A struct declared as one nullable field may not be. + with pytest.raises(ValueError, match="non-nullable"): + function( + input_schema=inputs, + output_schema=pa.field("result", pa.struct(fields), nullable=True), + )(describe) def test_function_registration_is_remote(tmp_path): diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 9ee7d572a..0342849b4 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -295,11 +295,12 @@ extract_frame_version = db.create_function_async(extract_frame).wait( ``` -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 -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)`. +An empty byte string is a filled result. A top-level Blob v2 output cannot be +nullable; to return a nullable 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. A nullable non-Blob scalar output is declared with +`Optional[T]` or `T | None`; see [Functions](/management/function#define). +Read a nested blob with `table.fetch_blobs("payload.image", hits)`. A list or large-list output may also contain Blob v2 elements; inputs and fixed-size lists do not support this layout. List-nested values are queryable diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 27f45cb6a..57a16dbf2 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -66,11 +66,43 @@ your process, without the database, so unit tests stay ordinary tests: Where annotations cannot express the Arrow type precisely, pass `input_schema` and `output_schema` together: one without the other is rejected. A scalar -output must be non-nullable, because a physical NULL is what marks a -computed-column row as unfilled. A named-struct output may declare nullable -fields: whether a row has a result at all is the struct's own validity, which -Enterprise keeps in a separate internal column when it expands the result into -sibling columns, so a null field is a value rather than a missing row. +output is non-nullable by default. Annotate the return as `Optional[T]` or +`T | None`, or pass a nullable output field, to declare a nullable scalar: + +```python +import pyarrow as pa + +from lancedb import function + + +@function( + input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + output_schema=pa.field("result", pa.int64(), nullable=True), +) +def maybe_double(value: int) -> int | None: + return None if value == 0 else value * 2 +``` + +The signature sent in the registration request then carries the nullable +scalar: + +```json +{ + "inputs": [{"name": "value", "arrow_type": "int64", "nullable": false}], + "output": {"kind": "scalar", "arrow_type": "int64", "nullable": true} +} +``` + + +Nullable scalar outputs require an Enterprise server that supports them; +older servers reject the registration. On a supporting server, a computed +`NULL` counts as a filled result, independently of its stored value. + + +A named-struct output may declare nullable fields: whether a row has a result +at all is the struct's own validity, which Enterprise keeps in a separate +internal column when it expands the result into sibling columns, so a null +field is a value rather than a missing row. ## Connect and create a table {#table} diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index f04d3d481..86230be52 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -312,7 +312,11 @@ class FunctionResultField(_OpenRemoteValue): class FunctionOutput(_OpenRemoteValue): - """Scalar or ordered named-struct output; unknown kinds remain decodable.""" + """Scalar or ordered named-struct output; unknown kinds remain decodable. + + A scalar output may be nullable. A named-struct output has no top-level + nullability; its fields carry their own flags. + """ kind: str arrow_type: Optional[str] = None @@ -1399,12 +1403,12 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp "output_schema must be a PyArrow DataType, Field, or Schema" ) _validate_exact_arrow_field(field) - if field.nullable: - raise ValueError("Function output must be non-nullable") + if field.nullable and _is_blob_v2_field(field): + raise ValueError("Blob v2 Function output must be non-nullable") return FunctionOutput( kind="scalar", arrow_type=_canonical_arrow_field(field, collection_blobs=True), - nullable=False, + nullable=field.nullable, ) if not fields: @@ -1504,9 +1508,9 @@ def _infer_signature( 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)) + output = _function_output( + pa.field("result", output_type, nullable=output_nullable) + ) if inputs is not None: return FunctionSignature(inputs=inputs, output=output) @@ -2650,9 +2654,13 @@ def function( ``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. + both; the one omitted is inferred. A scalar output is non-nullable by + default; annotate the return as ``Optional[T]`` or ``T | None``, or pass a + nullable ``output_schema`` field, to declare a nullable scalar. The + deployment must accept nullable scalar outputs; an older server rejects + the registration. 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 @@ -2757,9 +2765,10 @@ def function( 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. When omitted, the output - is inferred from the return annotation. + Explicit scalar or named-struct output. A scalar field's ``nullable`` + flag is preserved; a top-level named-struct field and a Blob v2 output + must be 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. Syntax is validated at decoration time, including extras and environment markers. Named direct diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index a3a9e3e20..7e089a96d 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -28,6 +28,7 @@ import lancedb from lancedb import BlobReader from lancedb.db import AsyncConnection from lancedb.functions import ( + FunctionSignature, FunctionVersion, HuggingFaceModel, PythonRuntimeSpec, @@ -1214,6 +1215,42 @@ def test_explicit_arrow_schema_is_deterministic(): assert signature.output.nullable is False +def test_nullable_scalar_output_annotation_and_explicit_schema(): + input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)]) + + @function(input_schema=input_schema) + def optional_annotation(value: int) -> Optional[int]: + return None if value == 0 else value * 2 + + @function(input_schema=input_schema) + def optional_union(value: int) -> int | None: + return None if value == 0 else value * 2 + + @function( + input_schema=input_schema, + output_schema=pa.field("result", pa.int64(), nullable=True), + ) + def explicit_schema(value: int): + return None if value == 0 else value * 2 + + for definition in (optional_annotation, optional_union, explicit_schema): + signature = definition.registration_request.signature + assert (signature.output.kind, signature.output.arrow_type) == ( + "scalar", + "int64", + ) + assert signature.output.nullable is True + assert json.loads(signature.to_canonical_json())["output"] == { + "kind": "scalar", + "arrow_type": "int64", + "nullable": True, + } + assert ( + FunctionSignature.from_json(signature.to_canonical_json()).output.nullable + is True + ) + + def test_blob_fields_use_the_scalar_function_semantic_type(): @function( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), @@ -1848,12 +1885,6 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): def unsupported(value: set[str]) -> str: return "" - with pytest.raises(ValueError, match="output must be non-nullable"): - - @function - def nullable_output(value: int) -> Optional[int]: - return value - with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"): @function(input_schema=pa.schema([pa.field("value", pa.int64())])) @@ -1873,10 +1904,25 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): @function( input_schema=pa.schema([pa.field("value", pa.int64())]), - output_schema=pa.field("result", pa.int64(), nullable=True), + output_schema=pa.field( + "result", + pa.struct([pa.field("value", pa.int64(), nullable=False)]), + nullable=True, + ), ) - def nullable_explicit(value): - return value + def nullable_struct(value): + return {"value": value} + + with pytest.raises( + ValueError, match="Blob v2 Function output must be non-nullable" + ): + + @function( + input_schema=pa.schema([lancedb.blob("image", nullable=False)]), + output_schema=lancedb.blob("result", nullable=True), + ) + def nullable_blob(image): + return image for invalid_field in [ pa.field("", pa.int32(), nullable=False), diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index d1b63f2ad..387c80364 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1032,8 +1032,8 @@ pub struct OutputMapping { pub nullable: bool, } -/// Internal physical column preserving the parent validity of a flattened -/// named-struct result. +/// Internal physical column preserving assignment of a nullable scalar result +/// or the parent validity of a flattened named-struct result. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AssignmentMapping { pub output_name: String, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 5c00232f7..72d67fb5a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -10802,6 +10802,83 @@ mod tests { assert_eq!(result.version, 8); } + #[tokio::test] + async fn test_add_nullable_scalar_function_column_sends_atomic_null_declaration() { + let table = Table::new_with_handler("my_table", |request| { + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body( + r#"{"version":1,"schema":{"fields":[{"name":"description","nullable":true,"type":{"type":"string"}}]}}"#, + ) + .unwrap(), + "/v1/table/my_table/add_columns/" => { + let actual: serde_json::Value = serde_json::from_slice( + request.body().unwrap().as_bytes().unwrap(), + ) + .unwrap(); + assert_eq!( + actual["new_columns"], + serde_json::json!([ + {"name": "maybe", "all_null": true} + ]) + ); + assert_eq!( + actual["function"]["application"]["output"], + serde_json::json!({ + "kind": "scalar", + "arrow_type": "int64", + "nullable": true + }) + ); + assert_eq!( + actual["function"]["output_schema"], + serde_json::json!({ + "fields": [{ + "name": "maybe", + "nullable": true, + "type": {"type": "int64"} + }] + }) + ); + assert_eq!( + actual["function"]["outputs"], + serde_json::json!([ + { + "result_field": "$value", + "output_name": "maybe", + "output_ordinal": 0 + } + ]) + ); + assert!(actual["function"].get("assignment").is_none()); + assert_eq!(actual["auto_refresh_enabled"], serde_json::json!(true)); + http::Response::builder() + .status(200) + .body(r#"{"version":8}"#) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + } + }); + let application = crate::function::FunctionApplication::from_json( + r#"{ + "function":{"name":"nullable_scalar","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], + "output":{"kind":"scalar","arrow_type":"int64","nullable":true} + }"#, + ) + .unwrap(); + + let result = table + .add_columns() + .function_as("maybe", application) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 8); + } + /// The fixture binding's table: `title` and `body` bound as inputs, its /// two outputs declared, plus an unbound `spare`. fn fixture_bound_schema() -> Schema { diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 64e90b246..b01f45d06 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -40,7 +40,7 @@ use lance_namespace::models::{JsonArrowDataType, JsonArrowField, JsonArrowSchema use serde::{Deserialize, Serialize}; use serde_json::Value; -use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding}; +use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding, OutputMapping}; use crate::materialized_view::without_declarations; use crate::table::FunctionWorkerResourceBudget; use crate::utils::resolve_arrow_field_path; @@ -1289,6 +1289,21 @@ fn function_output_type_matches(expected: &DataType, actual: &DataType) -> bool } } +/// Whether a whole-result binding may carry the server-owned assignment marker. +/// +/// Only a nullable scalar result needs a marker to distinguish a computed NULL +/// from an unfilled row. A non-nullable result, a whole named-struct column, +/// and a Blob v2 value keep their existing rejection. +fn nullable_scalar_allows_assignment(output: &OutputMapping) -> Result { + if !output.nullable || output.arrow_type == FUNCTION_BLOB_V2_TYPE { + return Ok(false); + } + let json = parse_output_arrow_type(&output.arrow_type)?; + let data_type = lance_namespace::schema::convert_json_arrow_type(&json) + .map_err(|e| invalid_function(format!("invalid Function output type: {e}")))?; + Ok(!matches!(data_type, DataType::Struct(_))) +} + fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding) -> Result<()> { let mut input_fields = Vec::with_capacity(binding.inputs().len()); for input in binding.inputs() { @@ -1419,13 +1434,14 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding } let mut declared_output_schema = binding.output_schema().cloned(); if let Some(assignment) = binding.assignment() { - if binding + if let Some(whole_result) = binding .outputs() .iter() - .any(|output| output.result_field == WHOLE_RESULT_FIELD) + .find(|output| output.result_field == WHOLE_RESULT_FIELD) + && (binding.outputs().len() != 1 || !nullable_scalar_allows_assignment(whole_result)?) { return Err(invalid_function(format!( - "Function binding '{}' cannot attach an assignment column to a whole result", + "Function binding '{}' cannot attach an assignment column to a whole result; only a single nullable scalar output permits one", binding.binding_id() ))); } @@ -1552,14 +1568,17 @@ pub(crate) fn plan_function_application( "a scalar Function application must be mapped to one output column", ) })?; - if output.nullable != Some(false) { - return Err(invalid_function( - "Function logical outputs must be non-nullable during NULL assignment", - )); - } + let nullable = output.nullable.ok_or_else(|| { + invalid_function("scalar Function output must declare nullability") + })?; let arrow_type = output.arrow_type.as_deref().ok_or_else(|| { invalid_function("scalar Function output is missing its Arrow type") })?; + if nullable && arrow_type == FUNCTION_BLOB_V2_TYPE { + return Err(invalid_function( + "Blob v2 Function outputs cannot be nullable", + )); + } outputs.push(FunctionOutputTarget { result_field: WHOLE_RESULT_FIELD.to_string(), output_name: name.to_string(), @@ -4054,6 +4073,22 @@ mod tests { .unwrap() } + fn nullable_scalar_application() -> FunctionApplication { + FunctionApplication::from_json( + &serde_json::json!({ + "function": {"name": "nullable_scalar", "version": "1", "object_id": "fixture", "location": "memory:///fixture", "manifest_digest": "sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, + "inputs": [{ + "parameter": "value", + "kind": "column", + "value": {"path": "value"} + }], + "output": {"kind": "scalar", "arrow_type": "int64", "nullable": true} + }) + .to_string(), + ) + .unwrap() + } + fn binding_from_plan(plan: &FunctionDeclarationPlan) -> FunctionBinding { let inputs = plan .input_bindings @@ -4363,6 +4398,259 @@ mod tests { )); } + #[test] + fn test_nullable_scalar_application_plans_one_nullable_output() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input]), + &nullable_scalar_application(), + Some("maybe"), + ) + .unwrap(); + + assert_eq!(plan.application.output().nullable, Some(true)); + assert_eq!(plan.outputs.len(), 1); + assert_eq!(plan.outputs[0].result_field, WHOLE_RESULT_FIELD); + assert_eq!(plan.outputs[0].output_name, "maybe"); + assert_eq!(plan.outputs[0].output_ordinal, 0); + assert_eq!(plan.output_schema.fields.len(), 1); + assert!(plan.output_schema.fields[0].nullable); + assert_eq!(plan.output_schema.fields[0].r#type.r#type, "int64"); + } + + #[test] + fn test_invalid_nullable_scalar_applications_fail_closed() { + let input = ArrowField::new("value", DataType::Int64, false); + let schema = ArrowSchema::new(vec![input]); + + let mut missing_nullability = serde_json::to_value(nullable_scalar_application()).unwrap(); + missing_nullability["output"] + .as_object_mut() + .unwrap() + .remove("nullable"); + let application = FunctionApplication::from_json(&missing_nullability.to_string()).unwrap(); + let err = plan_function_application(&schema, &application, Some("maybe")).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("declare nullability")), + "{err:?}" + ); + + let nullable_blob = + blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":true}"#); + let err = plan_function_application( + &ArrowSchema::new(vec![crate::blob("image", false)]), + &nullable_blob, + Some("copy"), + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("Blob v2") && message.contains("nullable")), + "{err:?}" + ); + } + + #[test] + fn test_nullable_scalar_binding_accepts_server_owned_assignment() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &nullable_scalar_application(), + Some("maybe"), + ) + .unwrap(); + let assignment_name = "__function_assignment_nullable_scalar"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = ArrowField::new("maybe", DataType::Int64, true).with_metadata( + function_computed_column_metadata(binding.binding_id(), 0, &["value".into()]), + ); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["value".into()], + ), + ); + + let schema = ArrowSchema::new(vec![input.clone(), output.clone(), assignment]); + ensure_binding_matches_schema(&schema, &binding).unwrap(); + let hidden = ArrowSchema::new(vec![input, output]); + ensure_binding_matches_schema(&hidden, &binding).unwrap(); + + let schema = ArrowSchema::new_with_metadata( + schema.fields().to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(), + )]), + ); + ensure_supported_function_metadata(&schema).unwrap(); + } + + #[test] + fn test_non_nullable_scalar_binding_rejects_server_owned_assignment() { + let input = ArrowField::new("value", DataType::Int64, false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &single_input_application("value"), + Some("maybe"), + ) + .unwrap(); + let assignment_name = "__function_assignment_non_nullable_scalar"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = ArrowField::new("maybe", DataType::Int64, true).with_metadata( + function_computed_column_metadata(binding.binding_id(), 0, &["value".into()]), + ); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["value".into()], + ), + ); + + let err = ensure_binding_matches_schema( + &ArrowSchema::new(vec![input, output, assignment]), + &binding, + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + + #[test] + fn test_named_struct_whole_binding_rejects_server_owned_assignment() { + let plan = plan_function_application( + &function_input_schema(), + &named_struct_application("{}"), + Some("features"), + ) + .unwrap(); + let assignment_name = "__function_assignment_whole_struct"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let output = + lance_namespace::schema::convert_json_arrow_field(&plan.output_schema.fields[0]) + .unwrap() + .with_metadata(function_computed_column_metadata( + binding.binding_id(), + 0, + &["title".into(), "body".into()], + )); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["title".into(), "body".into()], + ), + ); + let mut fields = function_input_schema() + .fields() + .iter() + .map(|field| field.as_ref().clone()) + .collect::>(); + fields.push(output); + fields.push(assignment); + + let err = ensure_binding_matches_schema(&ArrowSchema::new(fields), &binding).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + + #[test] + fn test_blob_whole_binding_rejects_server_owned_assignment() { + let input = crate::blob("image", false); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#), + Some("thumbnail"), + ) + .unwrap(); + let assignment_name = "__function_assignment_whole_blob"; + let mut raw = serde_json::to_value(binding_from_plan(&plan)).unwrap(); + raw["outputs"][0]["nullable"] = Value::Bool(true); + raw["assignment"] = serde_json::json!({ + "output_name": assignment_name, + "output_field_id": -1, + }); + raw["output_schema"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": assignment_name, + "nullable": true, + "type": {"type": "bool"}, + })); + let binding: FunctionBinding = serde_json::from_value(raw).unwrap(); + let mut metadata = full_blob_field("thumbnail", true).metadata().clone(); + metadata.extend(function_computed_column_metadata( + binding.binding_id(), + 0, + &["image".into()], + )); + let output = full_blob_field("thumbnail", true).with_metadata(metadata); + let assignment = ArrowField::new(assignment_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &["image".into()], + ), + ); + + let err = ensure_binding_matches_schema( + &ArrowSchema::new(vec![input, output, assignment]), + &binding, + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("nullable scalar")), + "{err:?}" + ); + } + #[test] fn test_nullable_function_input_cannot_bind_to_non_nullable_parameter() { let mut raw_binding: Value = serde_json::from_str(include_str!( From 4843ac4c7e32785a03f5382bffb4a34a82bf8e26 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:41 +0800 Subject: [PATCH 124/203] fix(remote): observe new publications while waiting for Function freshness (#5033) Remote `wait_fresh()` could keep observing a cached table version after automatic refresh published new outputs. Each poll on a latest handle now requests a current snapshot, so the wait can finish without an external `checkout_latest()` call. Explicit version, tag, and query-snapshot selections remain pinned. The wait preserves existing finalization-pending and error handling and continues to perform read-only status requests. --- rust/lancedb/src/remote/table.rs | 288 ++++++++++++++++++++++++++++++- rust/lancedb/src/table.rs | 13 ++ 2 files changed, 300 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 72d67fb5a..4e9458870 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2799,6 +2799,20 @@ impl BaseTable for RemoteTable { Ok(()) } + async fn checkout_latest_if_latest(&self) -> Result<()> { + let write_guard = self.version.write().await; + if write_guard.is_some() || self.expected_query_snapshot.is_some() { + return Ok(()); + } + // Poll within the same timeline: in-flight writes must still advance + // its watermarks. Only an explicit checkout changes the generation. + let mut state = self.freshness.lock().unwrap(); + let now = SystemTime::now(); + state.checkout_baseline = Some(state.checkout_baseline.map_or(now, |t| t.max(now))); + drop(state); + self.invalidate_schema_cache(); + Ok(()) + } async fn snapshot_at_current_version(&self) -> Result>> { // A checked-out handle already names its snapshot. Otherwise resolve // latest exactly once before creating the independent pinned handle. @@ -4756,8 +4770,8 @@ impl TryFrom for MergeInsertRequest { #[cfg(test)] mod tests { - use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; use std::time::Duration; use std::{collections::HashMap, pin::Pin}; @@ -12023,6 +12037,278 @@ mod tests { assert_eq!(calls.load(Ordering::SeqCst), 1); } + #[tokio::test] + async fn test_wait_for_function_column_observes_latest_publications_without_checkout() { + let calls = Arc::new(AtomicUsize::new(0)); + let observed_headers = Arc::new(Mutex::new(Vec::new())); + let table = Table::new_with_handler("my_table", { + let calls = calls.clone(); + let observed_headers = observed_headers.clone(); + move |request| { + assert_eq!(request.method(), "GET"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/function_columns/status" + ); + let query: std::collections::BTreeMap<_, _> = request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert!( + !query.contains_key("version"), + "a latest status poll must not use an explicit version" + ); + + let min_timestamp = request + .headers() + .get("x-lancedb-min-timestamp") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let min_read_version = request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + observed_headers + .lock() + .unwrap() + .push((min_timestamp.clone(), min_read_version)); + + let call = calls.fetch_add(1, Ordering::SeqCst); + let (version, fresh, never_computed) = if call > 0 && min_timestamp.is_some() { + (11, 2, 0) + } else { + (4, 0, 2) + }; + http::Response::builder() + .status(200) + .header("x-lancedb-version", version.to_string()) + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":{version}, + "rows":2, + "fresh":{fresh}, + "stale":0, + "never_computed":{never_computed}, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + }); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 11); + assert_eq!(status.fresh, 2); + assert_eq!(status.never_computed, 0); + assert_eq!(calls.load(Ordering::SeqCst), 2); + + let observed_headers = observed_headers.lock().unwrap(); + assert_eq!(observed_headers.len(), 2); + assert!( + observed_headers[0].0.is_some(), + "the first latest poll must establish a current timestamp baseline" + ); + assert!( + observed_headers[1].0.is_some(), + "each latest poll must advance the timestamp baseline" + ); + assert_eq!( + observed_headers[1].1.as_deref(), + Some("4"), + "the latest poll must retain the monotonic read watermark" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_wait_for_function_column_preserves_inflight_write_fence() { + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = std::sync::Arc::new(std::sync::Mutex::new(release_rx)); + let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/update/" => { + arrived_tx.send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(15)) + .unwrap(); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "5") + .body(r#"{"rows_updated":2,"version":5}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + // This node caches version 4 during the status request, + // after its timestamp fence and before the write commits. + assert!(request.headers().contains_key("x-lancedb-min-timestamp")); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "4") + .body( + r#"[{"column":"embedding","binding_id":"fb_01", + "function":{"name":"embed","object_id":"embed", + "location":"objects/embed","version":"7", + "manifest_digest":"sha256:abc"}, + "table_version":4,"rows":2,"fresh":2,"stale":0, + "never_computed":0,"failed":0, + "auto_refresh":{"enabled":false,"state":"disabled", + "failure_streak":0,"next_run_at_millis":null}}]"# + .to_string(), + ) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + captured.lock().unwrap().push(request.headers().clone()); + // The timestamp still admits the cached pre-write view. + // The write-version fence is what must force a refresh. + let count = if request + .headers() + .get("x-lancedb-min-version") + .and_then(|v| v.to_str().ok()) + == Some("5") + { + "2" + } else { + "1" + }; + http::Response::builder() + .status(200) + .body(count.to_string()) + .unwrap() + } + path => panic!("unexpected path: {path}"), + } + }); + let update = tokio::spawn({ + let table = table.clone(); + async move { table.update().column("a", "a + 1").execute().await } + }); + tokio::task::spawn_blocking(move || { + arrived_rx + .recv_timeout(std::time::Duration::from_secs(15)) + .unwrap() + }) + .await + .unwrap(); + table + .wait_for_function_column("embedding", Some(std::time::Duration::from_secs(2))) + .await + .unwrap(); + release_tx.send(()).unwrap(); + assert_eq!(update.await.unwrap().unwrap().version, 5); + // With initial values [0, 1], a += 1 changes a > 0 from one row to two. + let count = table.count_rows(Some("a > 0".to_string())).await.unwrap(); + let requests = requests.lock().unwrap(); + let headers = &requests[0]; + assert_eq!( + headers + .get("x-lancedb-min-version") + .and_then(|v| v.to_str().ok()), + Some("5"), + "polling must not discard an in-flight write's returned version" + ); + assert_eq!( + count, 2, + "read after completed write must observe the write" + ); + } + + #[tokio::test] + async fn test_wait_for_function_column_does_not_unpin_a_pinned_handle() { + let status_calls = Arc::new(AtomicUsize::new(0)); + let table = Table::new_with_handler("my_table", { + let status_calls = status_calls.clone(); + move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + assert_eq!(request_body_json(&request)["version"], 42); + http::Response::builder() + .status(200) + .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/function_columns/status" => { + let query: std::collections::BTreeMap<_, _> = + request.url().query_pairs().collect(); + assert_eq!( + query.get("column").map(|value| value.as_ref()), + Some("embedding") + ); + assert_eq!(query.get("version").map(|value| value.as_ref()), Some("42")); + assert!( + !request.headers().contains_key("x-lancedb-min-timestamp"), + "a pinned status poll must not carry latest freshness headers" + ); + let call = status_calls.fetch_add(1, Ordering::SeqCst); + let (fresh, never_computed) = if call == 0 { (0, 2) } else { (2, 0) }; + http::Response::builder() + .status(200) + .header("x-lancedb-version", "42") + .body(format!( + r#"[{{ + "column":"embedding", + "binding_id":"fb_01", + "function":{{ + "name":"embed", + "object_id":"embed", + "location":"objects/embed", + "version":"7", + "manifest_digest":"sha256:abc" + }}, + "table_version":42, + "rows":2, + "fresh":{fresh}, + "stale":0, + "never_computed":{never_computed}, + "failed":0, + "auto_refresh":{{ + "enabled":false, + "state":"disabled", + "failure_streak":0, + "next_run_at_millis":null + }} + }}]"#, + )) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + } + }); + table.checkout(42).await.unwrap(); + + let status = table + .wait_for_function_column("embedding", Some(Duration::from_secs(2))) + .await + .unwrap(); + assert_eq!(status.table_version, 42); + assert_eq!(status.fresh, 2); + assert_eq!(status.never_computed, 0); + assert_eq!(status_calls.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn test_function_column_status_decodes_agent_up_to_date() { let table = Table::new_with_handler("my_table", |_request| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index ff0ab8b94..b9708f16b 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1009,6 +1009,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn checkout_tag(&self, tag: &str) -> Result<()>; /// Checkout the latest version of the table. async fn checkout_latest(&self) -> Result<()>; + /// Advance a latest handle to the current snapshot before a polling read. + /// + /// Pinned version, tag, and snapshot handles must remain unchanged. This + /// lets a freshness wait observe publications that arrive after it starts + /// without changing an explicit time-travel selection. + #[doc(hidden)] + async fn checkout_latest_if_latest(&self) -> Result<()> { + Ok(()) + } /// Return an independent handle pinned to the version currently selected. /// /// Backends that can advance between requests should override this for @@ -2328,6 +2337,9 @@ impl Table { /// Failed rows do not keep the call pending. A typed /// `function_column_status_finalization_pending` response is retried with /// bounded exponential backoff; every other error is returned immediately. + /// Latest handles checkout the current snapshot before each poll so they + /// observe publications that happened after the wait started. Pinned + /// handles keep their explicit version. pub async fn wait_for_function_column( &self, column: &str, @@ -2336,6 +2348,7 @@ impl Table { let started = std::time::Instant::now(); let mut delay = std::time::Duration::from_millis(250); loop { + self.inner.checkout_latest_if_latest().await?; let result = self.function_column_status(column).await; match result { Ok(status) if status.stale == 0 && status.never_computed == 0 => return Ok(status), From f6f8119ba4fc285914f084fde560ea4e7affd9af Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:44 +0800 Subject: [PATCH 125/203] feat: expose structured Function refresh options in SDKs (#5047) ## Problem ENT-3267 still lacks typed refresh controls for `supervisor_resources` and `planning_workers` in Python, Rust, and Node, and Node has no `retry_policy` refresh option. Callers must drop to SQL for those controls. ## Change - Add canonical Rust `FunctionRefreshPodResources` and `FunctionRefreshPlanningConfig`, and serialize them through `RefreshColumnOptions`. - Expose both options in the Python sync/async wrappers and PyO3 binding. - Expose both options in the Node NAPI object and add a Node `retryPolicy` object backed by the existing Rust `FunctionRetryPolicy`. - Omitted options stay omitted; branch targeting continues through the table handle. No server, dependency, or pin changes are included. Client-side checks only reject non-positive structural values. Deployment resource limits and column-kind validation remain server-side. ## Validation `cargo fmt --all -- --check`, `python3 -m py_compile`, and `git diff --check` pass. No native build was run locally; CI compiles and tests the change. Generated JS API pages are unchanged. --- docs/src/js/classes/Table.md | 10 +- docs/src/js/globals.md | 3 + .../FunctionRefreshPlanningConfig.md | 50 +++++++ .../interfaces/FunctionRefreshPodResources.md | 40 +++++ docs/src/js/interfaces/FunctionRetryPolicy.md | 91 ++++++++++++ .../src/js/interfaces/RefreshColumnOptions.md | 30 ++++ .../feature-engineering/refresh-column.mdx | 128 ++++++++++++++++ nodejs/__test__/remote.test.ts | 121 +++++++++++++++ nodejs/__test__/table.test.ts | 25 ++++ nodejs/lancedb/index.ts | 3 + nodejs/lancedb/table.ts | 10 +- nodejs/src/table.rs | 140 ++++++++++++++++++ python/python/lancedb/_lancedb.pyi | 4 + python/python/lancedb/remote/table.py | 8 + python/python/lancedb/table.py | 64 ++++++++ python/python/tests/test_remote_db.py | 65 ++++++++ python/python/tests/test_table.py | 25 ++++ python/src/table.rs | 118 ++++++++++++++- rust/lancedb/src/remote/table.rs | 106 ++++++++++++- rust/lancedb/src/table.rs | 5 +- rust/lancedb/src/table/refresh.rs | 128 ++++++++++++++++ 21 files changed, 1164 insertions(+), 10 deletions(-) create mode 100644 docs/src/js/interfaces/FunctionRefreshPlanningConfig.md create mode 100644 docs/src/js/interfaces/FunctionRefreshPodResources.md create mode 100644 docs/src/js/interfaces/FunctionRetryPolicy.md diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 3150d94ec..f93c1b7cd 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1225,12 +1225,18 @@ LanceDB Enterprise it is the server's backfill job. `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, - `maxConcurrency`, `resourceBudget` and - `maxExecutorProcessesPerWorker` size registered Function refreshes. + `maxConcurrency`, `resourceBudget`, `supervisorResources`, + `planningWorkers` and `maxExecutorProcessesPerWorker` size registered + Function refreshes. `retryPolicy` overrides user-code retries only when + repeating partial work is safe; set `maxAttempts: 1` to disable retries. `maxConcurrency` overrides the registered default for this logical execution only and is a positive integer; it is not an account-wide quota. A `resourceBudget` requires `cpuMillis` and `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. + `supervisorResources` and each `planningWorkers.resources` entry require + positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`. + `planningWorkers` also requires positive `maxWorkers`, + `rowsPerWorker` and `fragmentsPerWorker`. The budget applies only to this explicit refresh and does not configure a later automatic refresh. `gpuCount` at the top level is the shorthand that preserves the diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index beed7c8af..23e576877 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -103,6 +103,9 @@ - [FunctionErrorRecord](interfaces/FunctionErrorRecord.md) - [FunctionErrors](interfaces/FunctionErrors.md) - [FunctionErrorsOptions](interfaces/FunctionErrorsOptions.md) +- [FunctionRefreshPlanningConfig](interfaces/FunctionRefreshPlanningConfig.md) +- [FunctionRefreshPodResources](interfaces/FunctionRefreshPodResources.md) +- [FunctionRetryPolicy](interfaces/FunctionRetryPolicy.md) - [FunctionWorkerResourceBudget](interfaces/FunctionWorkerResourceBudget.md) - [HnswPqOptions](interfaces/HnswPqOptions.md) - [HnswSqOptions](interfaces/HnswSqOptions.md) diff --git a/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md b/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md new file mode 100644 index 000000000..48a8a209d --- /dev/null +++ b/docs/src/js/interfaces/FunctionRefreshPlanningConfig.md @@ -0,0 +1,50 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionRefreshPlanningConfig + +# Interface: FunctionRefreshPlanningConfig + +Resources and sizing policy for the planning fleet of one registered +Function refresh. + +## Properties + +### fragmentsPerWorker + +```ts +fragmentsPerWorker: number; +``` + +Maximum fragments assigned to one planning worker. + +*** + +### maxWorkers + +```ts +maxWorkers: number; +``` + +Maximum number of planning workers. + +*** + +### resources + +```ts +resources: FunctionRefreshPodResources; +``` + +CPU, memory, and ephemeral-storage limits for one planning worker. + +*** + +### rowsPerWorker + +```ts +rowsPerWorker: number; +``` + +Maximum rows assigned to one planning worker. diff --git a/docs/src/js/interfaces/FunctionRefreshPodResources.md b/docs/src/js/interfaces/FunctionRefreshPodResources.md new file mode 100644 index 000000000..99d55512e --- /dev/null +++ b/docs/src/js/interfaces/FunctionRefreshPodResources.md @@ -0,0 +1,40 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionRefreshPodResources + +# Interface: FunctionRefreshPodResources + +CPU, memory, and ephemeral-storage limits for one Function refresh +control-plane pod. + +## Properties + +### cpuMillis + +```ts +cpuMillis: number; +``` + +CPU limit in millicores; 1000 is one CPU. + +*** + +### ephemeralStorageBytes + +```ts +ephemeralStorageBytes: number; +``` + +Ephemeral storage limit in bytes. + +*** + +### memoryBytes + +```ts +memoryBytes: number; +``` + +Memory limit in bytes. diff --git a/docs/src/js/interfaces/FunctionRetryPolicy.md b/docs/src/js/interfaces/FunctionRetryPolicy.md new file mode 100644 index 000000000..43d4ed8b2 --- /dev/null +++ b/docs/src/js/interfaces/FunctionRetryPolicy.md @@ -0,0 +1,91 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / FunctionRetryPolicy + +# Interface: FunctionRetryPolicy + +Overrides retries of failed user-code calls for one refresh. Omitted +fields use the Function refresh defaults. + +## Properties + +### errorCodes? + +```ts +optional errorCodes: string[]; +``` + +Structured provider error codes or HTTP status codes. + +*** + +### exceptionTypes? + +```ts +optional exceptionTypes: string[]; +``` + +Exception class names, preferably qualified. + +*** + +### honorRetryAfter? + +```ts +optional honorRetryAfter: boolean; +``` + +Honor Retry-After within the configured maximum. + +*** + +### initialBackoffSeconds? + +```ts +optional initialBackoffSeconds: number; +``` + +Initial exponential-backoff ceiling, in seconds. + +*** + +### maxAttempts? + +```ts +optional maxAttempts: number; +``` + +Total calls, including the first; 1 disables retries, maximum 100. + +*** + +### maxBackoffSeconds? + +```ts +optional maxBackoffSeconds: number; +``` + +Maximum backoff, in seconds. + +*** + +### messagePattern? + +```ts +optional messagePattern: string; +``` + +Regular expression matched against the exception class and message. + +*** + +### transient? + +```ts +optional transient: boolean; +``` + +Match connection/timeouts, HTTP 429/503, SlowDown and +ServiceUnavailable. diff --git a/docs/src/js/interfaces/RefreshColumnOptions.md b/docs/src/js/interfaces/RefreshColumnOptions.md index c534e0fac..07157e4ab 100644 --- a/docs/src/js/interfaces/RefreshColumnOptions.md +++ b/docs/src/js/interfaces/RefreshColumnOptions.md @@ -117,6 +117,16 @@ Worker count for an expression column; Function columns reject it. *** +### planningWorkers? + +```ts +optional planningWorkers: FunctionRefreshPlanningConfig; +``` + +Resources and sizing for the refresh planning fleet. + +*** + ### publicationIntervalRows? ```ts @@ -141,6 +151,16 @@ refresh. `gpuCount` inside the budget defaults to zero. *** +### retryPolicy? + +```ts +optional retryPolicy: FunctionRetryPolicy; +``` + +Override retries of failed user-code calls for this refresh. + +*** + ### rowTimeoutSeconds? ```ts @@ -151,6 +171,16 @@ Deadline for one Function call, in seconds. *** +### supervisorResources? + +```ts +optional supervisorResources: FunctionRefreshPodResources; +``` + +CPU, memory, and ephemeral-storage limits for the refresh supervisor. + +*** + ### where? ```ts diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index d82fb1eef..f893118fc 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -400,6 +400,101 @@ for changing only the aggregate GPU budget. It cannot be combined with the complete resource budget. Omitting both preserves the server's existing defaults. +{/* +Draft for the Function refresh control-plane resource release. + +`resource_budget` above sizes the Function workers. Two independent options +size the refresh control plane for a registered Function. +`supervisor_resources` sets the CPU, memory and ephemeral-storage limits of +the supervisor pod. `planning_workers` sets the resources of one planning +worker and the sizing of the CPU-only planning fleet: `max_workers`, +`rows_per_worker` and `fragments_per_worker`. Every field is required and +must be positive. Omitting either option leaves the server's configured +defaults unchanged, and either can be combined with `resource_budget`. + + +```python Python icon="python" +job = table.refresh_column_async( + "embedding", + supervisor_resources={ + "cpu_millis": 2_000, + "memory_bytes": 4 * 1024**3, + "ephemeral_storage_bytes": 10 * 1024**3, + }, + planning_workers={ + "resources": { + "cpu_millis": 1_000, + "memory_bytes": 2 * 1024**3, + "ephemeral_storage_bytes": 5 * 1024**3, + }, + "max_workers": 4, + "rows_per_worker": 100_000, + "fragments_per_worker": 8, + }, +) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::table::{ + FunctionRefreshPlanningConfig, + FunctionRefreshPodResources, + RefreshColumnOptions, +}; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default() + .supervisor_resources( + FunctionRefreshPodResources::new( + 2_000, + 4 * 1024 * 1024 * 1024, + 10 * 1024 * 1024 * 1024, + ), + ) + .planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new( + 1_000, + 2 * 1024 * 1024 * 1024, + 5 * 1024 * 1024 * 1024, + ), + 4, + 100_000, + 8, + ), + ), + ) + .await?; +``` + +```typescript TypeScript icon="typescript" +const job = await table.refreshColumnAsync("embedding", { + supervisorResources: { + cpuMillis: 2_000, + memoryBytes: 4 * 1024 ** 3, + ephemeralStorageBytes: 10 * 1024 ** 3, + }, + planningWorkers: { + resources: { + cpuMillis: 1_000, + memoryBytes: 2 * 1024 ** 3, + ephemeralStorageBytes: 5 * 1024 ** 3, + }, + maxWorkers: 4, + rowsPerWorker: 100_000, + fragmentsPerWorker: 8, + }, +}); +await job.wait(); +``` + + +The SDK validates the shape and sends these values only with this explicit +refresh request. A supporting LanceDB Enterprise server is required. +*/} + These examples configure only the explicit refresh shown. A registered Function declaration can separately set `auto_refresh_resource_budget` on `add_columns`; that declaration controls the budget for its automatic @@ -457,6 +552,39 @@ from `lancedb.functions`. Use `FunctionRetryPolicy(max_attempts=1)` to disable user-error retries. Omitting the override preserves the registered policy. + +```python Python icon="python" +from lancedb.functions import FunctionRetryPolicy + +job = table.refresh_column_async( + "embedding", + retry_policy=FunctionRetryPolicy(transient=True, max_attempts=3), +) +job.wait() +``` + +```rust Rust icon="rust" +use lancedb::{function::FunctionRetryPolicy, table::RefreshColumnOptions}; + +let mut retry_policy = FunctionRetryPolicy::transient(); +retry_policy.max_attempts = 3; + +let _job = table + .refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().retry_policy(retry_policy), + ) + .await?; +``` + +```typescript TypeScript icon="typescript" +const job = await table.refreshColumnAsync("embedding", { + retryPolicy: { transient: true, maxAttempts: 3 }, +}); +await job.wait(); +``` + + This requires a supporting LanceDB Enterprise server as well as an SDK that exposes these options. An older Function image may need re-registration before it accepts a refresh override. Only enable retries diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index a9989b84e..3e8d5a79b 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -979,6 +979,42 @@ describe("remote connection", () => { }, "resourceBudget.gpuCount", ], + [ + { + supervisorResources: { + cpuMillis: 0, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + }, + "supervisorResources.cpuMillis", + ], + [ + { + supervisorResources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 0, + }, + }, + "supervisorResources.ephemeralStorageBytes", + ], + [ + { + planningWorkers: { + resources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + maxWorkers: 0, + rowsPerWorker: 100, + fragmentsPerWorker: 1, + }, + }, + "planningWorkers.maxWorkers", + ], + [{ retryPolicy: { maxAttempts: 0 } }, "retry_policy.max_attempts"], ] as const) { await expect( table.refreshColumnAsync("embedding", options), @@ -1016,6 +1052,91 @@ describe("remote connection", () => { ]); }); + it("forwards structured Function refresh options and Node retry policy", async () => { + const bodies: unknown[] = []; + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "docs", + version: 1, + schema: { fields: [] }, + }), + ); + return; + } + if (path === "/v1/table/docs/backfill_column") { + let body = ""; + req.on("data", (chunk) => { + body += chunk; + }); + req.on("end", () => { + bodies.push(JSON.parse(body)); + res + .writeHead(202, { "Content-Type": "application/json" }) + .end('{"job_id": "j-structured"}'); + }); + return; + } + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("docs"); + const job = await table.refreshColumnAsync("embedding", { + supervisorResources: { + cpuMillis: 2_000, + memoryBytes: 4 * 1024 ** 3, + ephemeralStorageBytes: 10 * 1024 ** 3, + }, + planningWorkers: { + resources: { + cpuMillis: 1_000, + memoryBytes: 2 * 1024 ** 3, + ephemeralStorageBytes: 5 * 1024 ** 3, + }, + maxWorkers: 4, + rowsPerWorker: 100_000, + fragmentsPerWorker: 8, + }, + retryPolicy: { transient: true }, + }); + expect(job.id).toBe("j-structured"); + }, + ); + expect(bodies).toEqual([ + { + column: "embedding", + ["supervisor_resources"]: { + ["cpu_millis"]: 2_000, + ["memory_bytes"]: 4 * 1024 ** 3, + ["ephemeral_storage_bytes"]: 10 * 1024 ** 3, + }, + ["planning_workers"]: { + resources: { + ["cpu_millis"]: 1_000, + ["memory_bytes"]: 2 * 1024 ** 3, + ["ephemeral_storage_bytes"]: 5 * 1024 ** 3, + }, + ["max_workers"]: 4, + ["rows_per_worker"]: 100_000, + ["fragments_per_worker"]: 8, + }, + ["retry_policy"]: { + ["max_attempts"]: 3, + ["initial_backoff_seconds"]: 0.2, + ["max_backoff_seconds"]: 30, + ["exception_types"]: [], + ["message_pattern"]: null, + ["error_codes"]: [], + transient: true, + ["honor_retry_after"]: true, + }, + }, + ]); + }); + it("surfaces JSON server errors from remote table operations", async () => { await withMockDatabase( (req, res) => { diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 2c45dbccd..e97b32e78 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5716,6 +5716,31 @@ describe("computed columns", () => { resourceBudget: { cpuMillis: 1_000, memoryBytes: 1_024 }, }), ).rejects.toThrow("resource_budget requires a LanceDB Enterprise refresh"); + await expect( + table.refreshColumn("x", { + supervisorResources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + }), + ).rejects.toThrow( + "supervisor_resources requires a LanceDB Enterprise refresh", + ); + await expect( + table.refreshColumnAsync("x", { + planningWorkers: { + resources: { + cpuMillis: 1_000, + memoryBytes: 1_024, + ephemeralStorageBytes: 2_048, + }, + maxWorkers: 2, + rowsPerWorker: 100, + fragmentsPerWorker: 1, + }, + }), + ).rejects.toThrow("planning_workers requires a LanceDB Enterprise refresh"); }); it("records Function errors only on remote tables", async () => { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 08a254bdb..a6bcd68f5 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -57,6 +57,9 @@ export { AddResult, AddColumnsResult, RefreshColumnOptions, + FunctionRefreshPlanningConfig, + FunctionRefreshPodResources, + FunctionRetryPolicy, FunctionWorkerResourceBudget, RefreshColumnResult, FunctionErrors, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 136eb1d6c..f949bd00a 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -831,12 +831,18 @@ export abstract class Table { * `REFRESH COLUMN ... WHERE ... WITH (...)` form: `where` narrows the rows, * `errorPolicy`, `maxFailedFraction`, `maxFailedRows`, `rowTimeoutSeconds` * and `initTimeoutSeconds` govern failing rows. `batchSize`, `gpuClass`, - * `maxConcurrency`, `resourceBudget` and - * `maxExecutorProcessesPerWorker` size registered Function refreshes. + * `maxConcurrency`, `resourceBudget`, `supervisorResources`, + * `planningWorkers` and `maxExecutorProcessesPerWorker` size registered + * Function refreshes. `retryPolicy` overrides user-code retries only when + * repeating partial work is safe; set `maxAttempts: 1` to disable retries. * `maxConcurrency` overrides the registered default for this logical * execution only and is a positive integer; it is not an account-wide * quota. A `resourceBudget` requires `cpuMillis` and * `memoryBytes`; its `gpuCount` defaults to zero for a CPU-only Function. + * `supervisorResources` and each `planningWorkers.resources` entry require + * positive `cpuMillis`, `memoryBytes` and `ephemeralStorageBytes`. + * `planningWorkers` also requires positive `maxWorkers`, + * `rowsPerWorker` and `fragmentsPerWorker`. * The budget applies only to this explicit refresh and does not configure * a later automatic refresh. * `gpuCount` at the top level is the shorthand that preserves the diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index c82c2cd93..a0a220e24 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -9,6 +9,8 @@ use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; use lancedb::table::{ AddDataMode, ColumnAlteration as LanceColumnAlteration, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, + FunctionRefreshPlanningConfig as LanceFunctionRefreshPlanningConfig, + FunctionRefreshPodResources as LanceFunctionRefreshPodResources, FunctionWorkerResourceBudget as LanceFunctionWorkerResourceBudget, NewColumnTransform, Ref, Table as LanceDbTable, }; @@ -1705,6 +1707,58 @@ pub struct FunctionWorkerResourceBudget { pub gpu_count: Option, } +/// CPU, memory, and ephemeral-storage limits for one Function refresh +/// control-plane pod. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionRefreshPodResources { + /// CPU limit in millicores; 1000 is one CPU. + pub cpu_millis: f64, + /// Memory limit in bytes. + pub memory_bytes: f64, + /// Ephemeral storage limit in bytes. + pub ephemeral_storage_bytes: f64, +} + +/// Resources and sizing policy for the planning fleet of one registered +/// Function refresh. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct FunctionRefreshPlanningConfig { + /// CPU, memory, and ephemeral-storage limits for one planning worker. + pub resources: FunctionRefreshPodResources, + /// Maximum number of planning workers. + pub max_workers: f64, + /// Maximum rows assigned to one planning worker. + pub rows_per_worker: f64, + /// Maximum fragments assigned to one planning worker. + pub fragments_per_worker: f64, +} + +/// Overrides retries of failed user-code calls for one refresh. Omitted +/// fields use the Function refresh defaults. +#[napi(object)] +#[derive(Clone, Debug, Default)] +pub struct FunctionRetryPolicy { + /// Total calls, including the first; 1 disables retries, maximum 100. + pub max_attempts: Option, + /// Initial exponential-backoff ceiling, in seconds. + pub initial_backoff_seconds: Option, + /// Maximum backoff, in seconds. + pub max_backoff_seconds: Option, + /// Exception class names, preferably qualified. + pub exception_types: Option>, + /// Regular expression matched against the exception class and message. + pub message_pattern: Option, + /// Structured provider error codes or HTTP status codes. + pub error_codes: Option>, + /// Match connection/timeouts, HTTP 429/503, SlowDown and + /// ServiceUnavailable. + pub transient: Option, + /// Honor Retry-After within the configured maximum. + pub honor_retry_after: Option, +} + fn positive_safe_integer(value: f64, name: &str) -> napi::Result { const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; if !value.is_finite() || value.fract() != 0.0 || !(1.0..=MAX_SAFE_INTEGER).contains(&value) { @@ -1768,8 +1822,14 @@ pub struct RefreshColumnOptions { /// Complete aggregate CPU and memory budget for a registered Function /// refresh. `gpuCount` inside the budget defaults to zero. pub resource_budget: Option, + /// CPU, memory, and ephemeral-storage limits for the refresh supervisor. + pub supervisor_resources: Option, + /// Resources and sizing for the refresh planning fleet. + pub planning_workers: Option, /// Positive aggregate GPU budget for Function workers. pub gpu_count: Option, + /// Override retries of failed user-code calls for this refresh. + pub retry_policy: Option, /// `"fail"` (default) stops on a row error; `"skip"` writes null and /// records the error, subject to the failure limits. pub error_policy: Option, @@ -1814,7 +1874,87 @@ impl TryFrom for lancedb::table::RefreshColumnOptions { ) }) .transpose()?; + options.supervisor_resources = value + .supervisor_resources + .map(|resources| { + Ok::<_, napi::Error>(LanceFunctionRefreshPodResources::new( + positive_safe_integer(resources.cpu_millis, "supervisorResources.cpuMillis")?, + positive_safe_integer( + resources.memory_bytes, + "supervisorResources.memoryBytes", + )?, + positive_safe_integer( + resources.ephemeral_storage_bytes, + "supervisorResources.ephemeralStorageBytes", + )?, + )) + }) + .transpose()?; + options.planning_workers = value + .planning_workers + .map(|planning| { + let resources = LanceFunctionRefreshPodResources::new( + positive_safe_integer( + planning.resources.cpu_millis, + "planningWorkers.resources.cpuMillis", + )?, + positive_safe_integer( + planning.resources.memory_bytes, + "planningWorkers.resources.memoryBytes", + )?, + positive_safe_integer( + planning.resources.ephemeral_storage_bytes, + "planningWorkers.resources.ephemeralStorageBytes", + )?, + ); + let max_workers = usize::try_from(positive_safe_integer( + planning.max_workers, + "planningWorkers.maxWorkers", + )?) + .map_err(|_| napi::Error::from_reason("planningWorkers.maxWorkers is too large"))?; + Ok::<_, napi::Error>(LanceFunctionRefreshPlanningConfig::new( + resources, + max_workers, + positive_safe_integer( + planning.rows_per_worker, + "planningWorkers.rowsPerWorker", + )?, + positive_safe_integer( + planning.fragments_per_worker, + "planningWorkers.fragmentsPerWorker", + )?, + )) + }) + .transpose()?; options.gpu_count = value.gpu_count; + options.retry_policy = value.retry_policy.map(|policy| { + let mut converted = lancedb::function::FunctionRetryPolicy::default(); + if let Some(max_attempts) = policy.max_attempts { + converted.max_attempts = max_attempts; + } + if let Some(seconds) = policy.initial_backoff_seconds { + converted.initial_backoff_seconds = seconds; + } + if let Some(seconds) = policy.max_backoff_seconds { + converted.max_backoff_seconds = seconds; + } + if let Some(exception_types) = policy.exception_types { + converted.exception_types = exception_types; + } + if let Some(pattern) = policy.message_pattern { + converted.message_pattern = Some(pattern); + } + if let Some(error_codes) = policy.error_codes { + converted.error_codes = error_codes; + } + if let Some(transient) = policy.transient { + converted.transient = transient; + } + if let Some(honor_retry_after) = policy.honor_retry_after { + converted.honor_retry_after = honor_retry_after; + } + converted + }); options.error_policy = match value.error_policy.as_deref() { None => None, Some("fail") => Some(lancedb::function::FunctionErrorPolicy::Fail), diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 1e811d865..cce3efeef 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -663,6 +663,8 @@ class Table: max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[dict[str, int]] = None, + supervisor_resources: Optional[dict[str, int]] = None, + planning_workers: Optional[dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, @@ -683,6 +685,8 @@ class Table: max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[dict[str, int]] = None, + supervisor_resources: Optional[dict[str, int]] = None, + planning_workers: Optional[dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[str] = None, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index dbfd127ee..b5d97eb62 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1164,6 +1164,8 @@ class RemoteTable(Table): max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1183,6 +1185,8 @@ class RemoteTable(Table): max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, + supervisor_resources=supervisor_resources, + planning_workers=planning_workers, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -1205,6 +1209,8 @@ class RemoteTable(Table): max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -1225,6 +1231,8 @@ class RemoteTable(Table): max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, + supervisor_resources=supervisor_resources, + planning_workers=planning_workers, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index e0b96e476..45b2eb4f6 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3258,6 +3258,8 @@ class Table(ABC): max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3315,6 +3317,17 @@ class Table(ABC): CPU-only budget. This budget cannot be combined with the top-level ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes reject it. + supervisor_resources: dict[str, int], optional + CPU, memory, and ephemeral-storage limits for the Function refresh + supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and + ``ephemeral_storage_bytes``; all are required and positive. + LanceDB Enterprise only; local refreshes reject it. + planning_workers: dict[str, object], optional + Resources and sizing for the Function refresh planning fleet. + ``resources`` has the same keys as ``supervisor_resources``; the + other keys are ``max_workers``, ``rows_per_worker`` and + ``fragments_per_worker``. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -3367,6 +3380,8 @@ class Table(ABC): max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -3423,6 +3438,17 @@ class Table(ABC): CPU-only budget. This budget cannot be combined with the top-level ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes reject it. + supervisor_resources: dict[str, int], optional + CPU, memory, and ephemeral-storage limits for the Function refresh + supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and + ``ephemeral_storage_bytes``; all are required and positive. + LanceDB Enterprise only; local refreshes reject it. + planning_workers: dict[str, object], optional + Resources and sizing for the Function refresh planning fleet. + ``resources`` has the same keys as ``supervisor_resources``; the + other keys are ``max_workers``, ``rows_per_worker`` and + ``fragments_per_worker``. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -5632,6 +5658,8 @@ class LanceTable(Table): max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5654,6 +5682,8 @@ class LanceTable(Table): max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, + supervisor_resources=supervisor_resources, + planning_workers=planning_workers, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -5676,6 +5706,8 @@ class LanceTable(Table): max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -5700,6 +5732,8 @@ class LanceTable(Table): max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, + supervisor_resources=supervisor_resources, + planning_workers=planning_workers, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=retry_policy, @@ -8109,6 +8143,8 @@ class AsyncTable: max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -8166,6 +8202,17 @@ class AsyncTable: CPU-only budget. This budget cannot be combined with the top-level ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes reject it. + supervisor_resources: dict[str, int], optional + CPU, memory, and ephemeral-storage limits for the Function refresh + supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and + ``ephemeral_storage_bytes``; all are required and positive. + LanceDB Enterprise only; local refreshes reject it. + planning_workers: dict[str, object], optional + Resources and sizing for the Function refresh planning fleet. + ``resources`` has the same keys as ``supervisor_resources``; the + other keys are ``max_workers``, ``rows_per_worker`` and + ``fragments_per_worker``. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -8213,6 +8260,8 @@ class AsyncTable: max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, + supervisor_resources=supervisor_resources, + planning_workers=planning_workers, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None @@ -8351,6 +8400,8 @@ class AsyncTable: max_concurrency: Optional[int] = None, publication_interval_rows: Optional[int] = None, resource_budget: Optional[Dict[str, int]] = None, + supervisor_resources: Optional[Dict[str, int]] = None, + planning_workers: Optional[Dict[str, Any]] = None, gpu_class: Optional[str] = None, gpu_count: Optional[int] = None, retry_policy: Optional[FunctionRetryPolicy] = None, @@ -8407,6 +8458,17 @@ class AsyncTable: CPU-only budget. This budget cannot be combined with the top-level ``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes reject it. + supervisor_resources: dict[str, int], optional + CPU, memory, and ephemeral-storage limits for the Function refresh + supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and + ``ephemeral_storage_bytes``; all are required and positive. + LanceDB Enterprise only; local refreshes reject it. + planning_workers: dict[str, object], optional + Resources and sizing for the Function refresh planning fleet. + ``resources`` has the same keys as ``supervisor_resources``; the + other keys are ``max_workers``, ``rows_per_worker`` and + ``fragments_per_worker``. LanceDB Enterprise only; local refreshes + reject it. gpu_class: str, optional GPU class for Function workers. Must be a lowercase name of 1-63 letters, digits, or hyphens, without a leading or trailing hyphen. @@ -8471,6 +8533,8 @@ class AsyncTable: max_concurrency=max_concurrency, publication_interval_rows=publication_interval_rows, resource_budget=resource_budget, + supervisor_resources=supervisor_resources, + planning_workers=planning_workers, gpu_class=gpu_class, gpu_count=gpu_count, retry_policy=None diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index c5afac308..fc5b5df73 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2076,6 +2076,23 @@ def test_remote_create_index_async_returns_job(): "gpu_count": 2, } }, + { + "supervisor_resources": { + "cpu_millis": 2000, + "memory_bytes": 4 * 1024**3, + "ephemeral_storage_bytes": 10 * 1024**3, + }, + "planning_workers": { + "resources": { + "cpu_millis": 1000, + "memory_bytes": 2 * 1024**3, + "ephemeral_storage_bytes": 5 * 1024**3, + }, + "max_workers": 4, + "rows_per_worker": 100_000, + "fragments_per_worker": 8, + }, + }, {"gpu_class": "a10g", "gpu_count": 2}, { "retry_policy": {"transient": True, "max_attempts": 3}, @@ -2122,6 +2139,9 @@ async def test_remote_refresh_async_returns_typed_terminal_result( **budget, "gpu_count": budget.get("gpu_count", 0), } + for key in ("supervisor_resources", "planning_workers"): + if refresh_kwargs.get(key) is not None: + expected[key] = refresh_kwargs[key] if refresh_kwargs.get("retry_policy") is not None: expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate( refresh_kwargs["retry_policy"] @@ -2350,6 +2370,51 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle(): }, "unsupported key 'unknown'", ), + ( + { + "supervisor_resources": { + "cpu_millis": 0, + "memory_bytes": 1, + "ephemeral_storage_bytes": 1, + } + }, + "supervisor_resources.cpu_millis", + ), + ( + { + "supervisor_resources": { + "cpu_millis": 1, + "memory_bytes": 1, + } + }, + "supervisor_resources.ephemeral_storage_bytes", + ), + ( + { + "supervisor_resources": { + "cpu_millis": 1, + "memory_bytes": 1, + "ephemeral_storage_bytes": 1, + "unknown": 1, + } + }, + "unsupported key 'unknown'", + ), + ( + { + "planning_workers": { + "resources": { + "cpu_millis": 1, + "memory_bytes": 1, + "ephemeral_storage_bytes": 1, + }, + "max_workers": 0, + "rows_per_worker": 1, + "fragments_per_worker": 1, + } + }, + "planning_workers.max_workers", + ), ( {"max_executor_processes_per_worker": -2}, "max_executor_processes_per_worker", diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 604d6afb3..ce4f57c48 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6013,6 +6013,31 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size) {"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}}, "resource_budget", ), + ( + { + "supervisor_resources": { + "cpu_millis": 1000, + "memory_bytes": 1024, + "ephemeral_storage_bytes": 2048, + } + }, + "supervisor_resources", + ), + ( + { + "planning_workers": { + "resources": { + "cpu_millis": 1000, + "memory_bytes": 1024, + "ephemeral_storage_bytes": 2048, + }, + "max_workers": 2, + "rows_per_worker": 100, + "fragments_per_worker": 1, + } + }, + "planning_workers", + ), ({"num_workers": 2}, "num_workers"), ({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"), ], diff --git a/python/src/table.rs b/python/src/table.rs index f77ff5a7f..f5270a594 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -30,8 +30,9 @@ use lancedb::connection::LanceFileVersion; use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration, - FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionWorkerResourceBudget, IndexRemapMode, - NewColumnTransform, Ref, RefreshColumnOptions, Table as LanceDbTable, + FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig, + FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform, + Ref, RefreshColumnOptions, Table as LanceDbTable, }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ @@ -52,6 +53,8 @@ struct RefreshColumnArgs { max_concurrency: Option, publication_interval_rows: Option, resource_budget: Option, + supervisor_resources: Option, + planning_workers: Option, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -159,6 +162,101 @@ fn parse_resource_budget( )) } +fn structured_integer(value: &Bound<'_, PyAny>, name: &str) -> PyResult { + if value.is_none() || value.is_instance_of::() { + return Err(PyValueError::new_err(format!("{name} must be an integer"))); + } + let parsed = value + .extract::() + .map_err(|_| PyValueError::new_err(format!("{name} must be an integer")))?; + if parsed == 0 { + return Err(PyValueError::new_err(format!( + "{name} must be greater than zero" + ))); + } + Ok(parsed) +} + +fn parse_pod_resources( + resources: &Bound<'_, PyDict>, + prefix: &str, +) -> PyResult { + for key in resources.keys() { + let key = key + .extract::() + .map_err(|_| PyValueError::new_err(format!("{prefix} keys must be strings")))?; + if !matches!( + key.as_str(), + "cpu_millis" | "memory_bytes" | "ephemeral_storage_bytes" + ) { + return Err(PyValueError::new_err(format!( + "{prefix} contains unsupported key '{key}'" + ))); + } + } + let get = |name: &str| -> PyResult { + let value = resources + .get_item(name)? + .ok_or_else(|| PyValueError::new_err(format!("{prefix}.{name} is required")))?; + structured_integer(&value, &format!("{prefix}.{name}")) + }; + Ok(FunctionRefreshPodResources::new( + get("cpu_millis")?, + get("memory_bytes")?, + get("ephemeral_storage_bytes")?, + )) +} + +fn parse_supervisor_resources( + resources: Option<&Bound<'_, PyDict>>, +) -> PyResult> { + resources + .map(|resources| parse_pod_resources(resources, "supervisor_resources")) + .transpose() +} + +fn parse_planning_workers( + planning: Option<&Bound<'_, PyDict>>, +) -> PyResult> { + let Some(planning) = planning else { + return Ok(None); + }; + for key in planning.keys() { + let key = key + .extract::() + .map_err(|_| PyValueError::new_err("planning_workers keys must be strings"))?; + if !matches!( + key.as_str(), + "resources" | "max_workers" | "rows_per_worker" | "fragments_per_worker" + ) { + return Err(PyValueError::new_err(format!( + "planning_workers contains unsupported key '{key}'" + ))); + } + } + let resources = planning + .get_item("resources")? + .ok_or_else(|| PyValueError::new_err("planning_workers.resources is required"))?; + let resources = resources + .cast::() + .map_err(|_| PyValueError::new_err("planning_workers.resources must be a dict"))?; + let resources = parse_pod_resources(resources, "planning_workers.resources")?; + let get = |name: &str| -> PyResult { + let value = planning + .get_item(name)? + .ok_or_else(|| PyValueError::new_err(format!("planning_workers.{name} is required")))?; + structured_integer(&value, &format!("planning_workers.{name}")) + }; + let max_workers = usize::try_from(get("max_workers")?) + .map_err(|_| PyValueError::new_err("planning_workers.max_workers is too large"))?; + Ok(Some(FunctionRefreshPlanningConfig::new( + resources, + max_workers, + get("rows_per_worker")?, + get("fragments_per_worker")?, + ))) +} + fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { let RefreshColumnArgs { where_clause, @@ -166,6 +264,8 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult PyResult( self_: PyRef<'py, Self>, @@ -2502,6 +2604,8 @@ impl Table { max_concurrency: Option>, publication_interval_rows: Option, resource_budget: Option>, + supervisor_resources: Option>, + planning_workers: Option>, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2519,6 +2623,8 @@ impl Table { max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, resource_budget: parse_resource_budget(resource_budget.as_ref())?, + supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, + planning_workers: parse_planning_workers(planning_workers.as_ref())?, gpu_class, gpu_count, retry_policy, @@ -2540,7 +2646,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, @@ -2550,6 +2656,8 @@ impl Table { max_concurrency: Option>, publication_interval_rows: Option, resource_budget: Option>, + supervisor_resources: Option>, + planning_workers: Option>, gpu_class: Option, gpu_count: Option, retry_policy: Option, @@ -2567,6 +2675,8 @@ impl Table { max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, publication_interval_rows, resource_budget: parse_resource_budget(resource_budget.as_ref())?, + supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?, + planning_workers: parse_planning_workers(planning_workers.as_ref())?, gpu_class, gpu_count, retry_policy, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 4e9458870..e556d131c 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -11560,6 +11560,59 @@ mod tests { assert_eq!(job.id(), Some("j-budget")); } + #[tokio::test] + async fn test_refresh_column_async_structured_resource_options() { + use crate::table::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions, + }; + + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + assert_eq!( + request_body_json(&request), + serde_json::json!({ + "column": "quality", + "supervisor_resources": { + "cpu_millis": 2_000, + "memory_bytes": 4_294_967_296_u64, + "ephemeral_storage_bytes": 10_737_418_240_u64, + }, + "planning_workers": { + "resources": { + "cpu_millis": 1_000, + "memory_bytes": 2_147_483_648_u64, + "ephemeral_storage_bytes": 5_368_709_120_u64, + }, + "max_workers": 4, + "rows_per_worker": 100_000, + "fragments_per_worker": 8, + }, + }) + ); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"j-structured"}"#) + .unwrap() + }); + let supervisor = FunctionRefreshPodResources::new(2_000, 4_294_967_296, 10_737_418_240); + let planning = FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1_000, 2_147_483_648, 5_368_709_120), + 4, + 100_000, + 8, + ); + let job = table + .refresh_column_async_with_options( + "quality", + RefreshColumnOptions::default() + .supervisor_resources(supervisor) + .planning_workers(planning), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("j-structured")); + } + #[tokio::test] async fn test_refresh_column_async_retry_policy() { use crate::function::{FunctionErrorPolicy, FunctionRetryPolicy}; @@ -11640,7 +11693,9 @@ mod tests { #[tokio::test] async fn test_refresh_column_rejects_invalid_filter_and_limit_options_before_request() { - use crate::table::RefreshColumnOptions; + use crate::table::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, RefreshColumnOptions, + }; let table = Table::new_with_handler("my_table", |_| -> http::Response { panic!("invalid refresh options must not send a request") @@ -11679,6 +11734,55 @@ mod tests { RefreshColumnOptions::default().publication_interval_rows(0), "publication_interval_rows", ), + ( + RefreshColumnOptions::default() + .supervisor_resources(FunctionRefreshPodResources::new(0, 1, 1)), + "supervisor_resources.cpu_millis", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 0), + 1, + 1, + 1, + ), + ), + "planning_workers.resources.ephemeral_storage_bytes", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 0, + 1, + 1, + ), + ), + "planning_workers.max_workers", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 1, + 0, + 1, + ), + ), + "planning_workers.rows_per_worker", + ), + ( + RefreshColumnOptions::default().planning_workers( + FunctionRefreshPlanningConfig::new( + FunctionRefreshPodResources::new(1, 1, 1), + 1, + 1, + 0, + ), + ), + "planning_workers.fragments_per_worker", + ), ] { let error = table .refresh_column_async_with_options("quality", options) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index b9708f16b..00505220b 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -120,7 +120,10 @@ pub use optimize::{ CompactionMode, CompactionOptions, CompactionOverrides, IndexRemapMode, OptimizeAction, OptimizeStats, }; -pub use refresh::{FunctionWorkerResourceBudget, RefreshColumnOptions, RefreshColumnResult}; +pub use refresh::{ + FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget, + RefreshColumnOptions, RefreshColumnResult, +}; pub use rte_stats::{MemtableStats, RTEStats, SsTableStats, TableShardStats}; pub use schema_evolution::{ AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate, diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index ff73e6366..f38509002 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -104,6 +104,106 @@ impl FunctionWorkerResourceBudget { } } +/// CPU, memory, and ephemeral-storage limits for one Function refresh +/// control-plane pod. +/// +/// This sizes the supervisor or planning worker pod for a registered +/// Function refresh. LanceDB Embedded rejects it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRefreshPodResources { + /// CPU limit in millicores; 1000 is one CPU. + pub cpu_millis: u64, + /// Memory limit in bytes. + pub memory_bytes: u64, + /// Ephemeral storage limit in bytes. + pub ephemeral_storage_bytes: u64, +} + +impl FunctionRefreshPodResources { + /// Create positive CPU, memory, and ephemeral-storage limits. + pub fn new(cpu_millis: u64, memory_bytes: u64, ephemeral_storage_bytes: u64) -> Self { + Self { + cpu_millis, + memory_bytes, + ephemeral_storage_bytes, + } + } + + fn validate(&self, prefix: &str) -> Result<()> { + for (name, value) in [ + ("cpu_millis", self.cpu_millis), + ("memory_bytes", self.memory_bytes), + ("ephemeral_storage_bytes", self.ephemeral_storage_bytes), + ] { + if value == 0 { + return Err(Error::InvalidInput { + message: format!("{prefix}.{name} must be greater than zero"), + }); + } + } + Ok(()) + } +} + +/// Resources and sizing policy for the CPU-only planning fleet of one +/// registered Function refresh. +/// +/// `resources` describes one planning worker pod. The remaining fields bound +/// how many workers may run and how much work each worker receives. LanceDB +/// Embedded rejects this option. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct FunctionRefreshPlanningConfig { + /// CPU, memory, and ephemeral-storage limits for one planning worker. + pub resources: FunctionRefreshPodResources, + /// Maximum number of planning workers. + pub max_workers: usize, + /// Maximum rows assigned to one planning worker. + pub rows_per_worker: u64, + /// Maximum fragments assigned to one planning worker. + pub fragments_per_worker: u64, +} + +impl FunctionRefreshPlanningConfig { + /// Create a planning configuration; every value must be positive. + pub fn new( + resources: FunctionRefreshPodResources, + max_workers: usize, + rows_per_worker: u64, + fragments_per_worker: u64, + ) -> Self { + Self { + resources, + max_workers, + rows_per_worker, + fragments_per_worker, + } + } + + fn validate(&self) -> Result<()> { + self.resources.validate("planning_workers.resources")?; + if self.max_workers == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.max_workers must be greater than zero".into(), + }); + } + if self.rows_per_worker == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.rows_per_worker must be greater than zero".into(), + }); + } + if self.fragments_per_worker == 0 { + return Err(Error::InvalidInput { + message: "planning_workers.fragments_per_worker must be greater than zero".into(), + }); + } + Ok(()) + } +} + /// Options for refreshing a computed column. /// /// Serializes to the Enterprise backfill request body, one key per set @@ -167,6 +267,14 @@ pub struct RefreshColumnOptions { /// Function refresh. Cannot be combined with `gpu_count`. #[serde(skip_serializing_if = "Option::is_none")] pub resource_budget: Option, + /// CPU, memory, and ephemeral-storage limits for the Function refresh + /// supervisor pod. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub supervisor_resources: Option, + /// Resources and sizing limits for the Function refresh planning fleet. + /// Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub planning_workers: Option, /// GPU class for Function workers in LanceDB Enterprise. /// /// `None` keeps the Function's registered class, or the deployment default @@ -264,6 +372,18 @@ impl RefreshColumnOptions { self } + /// Set the Function refresh supervisor pod resources. + pub fn supervisor_resources(mut self, resources: FunctionRefreshPodResources) -> Self { + self.supervisor_resources = Some(resources); + self + } + + /// Set the Function refresh planning fleet resources and sizing. + pub fn planning_workers(mut self, planning: FunctionRefreshPlanningConfig) -> Self { + self.planning_workers = Some(planning); + self + } + /// Request Function workers from `gpu_class`. pub fn gpu_class(mut self, gpu_class: impl Into) -> Self { self.gpu_class = Some(gpu_class.into()); @@ -297,6 +417,8 @@ impl RefreshColumnOptions { self.publication_interval_rows.is_some(), ), ("resource_budget", self.resource_budget.is_some()), + ("supervisor_resources", self.supervisor_resources.is_some()), + ("planning_workers", self.planning_workers.is_some()), ] .into_iter() .find_map(|(name, set)| set.then_some(name)) @@ -367,6 +489,12 @@ impl RefreshColumnOptions { if let Some(budget) = &self.resource_budget { budget.validate()?; } + if let Some(resources) = &self.supervisor_resources { + resources.validate("supervisor_resources")?; + } + if let Some(planning) = &self.planning_workers { + planning.validate()?; + } if let Some(gpu_class) = &self.gpu_class { validate_gpu_class_name(gpu_class)?; } From 12b95b59ab170a248b263d2a36eb21f678986e53 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 20:59:52 +0800 Subject: [PATCH 126/203] feat(function): support literal inputs in column declarations (#5021) Function-column declarations now preserve constants such as `fn(video=col("mp4"), num_frames=lit(16))` without changing its Function version. Constants travel in the application inputs; column bindings, request input schemas, and dependency tracking contain only columns. Changing a constant uses a new column binding rather than rebaking the Function. Persisted bindings with literals use metadata version 2, which older readers reject. Column-only bindings retain version 1. Python preserves scalar literal identity, including null and unsigned integers, and rejects composed expressions or values outside the canonical literal domain. This SDK change requires matching server declaration and execution support, after a dedicated SDK dependency update. Native validation passed 48 Rust metadata tests, four request-transport cases and 57 rebuilt Python tests on `a42d680`; 32 pre-existing experimental tests remained ignored. The test-assertion correction passed its exact regression and strict Clippy on `53ff80a2`. On `993fae7d`, the three remote metadata compatibility regressions, native Python public-export test and strict Clippy passed. These review corrections use v3 for unknown-version rejection, cover existing v2 literal bindings through remote mutation guards, and export `LiteralInputBinding`. The unchanged native implementation and verified extension are reused. Matching server execution and original-workload acceptance are not established by this PR. Refs ENT-3667. --- docs/src/python/python.md | 2 + docs/web/management/function.mdx | 46 ++++ python/python/lancedb/_lancedb.pyi | 2 +- python/python/lancedb/expr.py | 23 +- python/python/lancedb/functions.py | 68 ++++- .../tests/test_first_class_function_slice1.py | 64 ++++- python/src/expr.rs | 8 +- rust/lancedb/src/function.rs | 55 +++- rust/lancedb/src/remote/table.rs | 119 +++++++-- rust/lancedb/src/table/computed_columns.rs | 247 +++++++++++++++++- 10 files changed, 576 insertions(+), 58 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 36f47c8f0..5aa21f691 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -578,6 +578,8 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.InputBinding +::: lancedb.functions.LiteralInputBinding + ::: lancedb.functions.OutputMapping ::: lancedb.functions.AssignmentMapping diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 57a16dbf2..41e64d482 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -245,6 +245,52 @@ 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=...)`. +{/* Draft for the Function literal binding release. + +### Bind a constant input {#literal-inputs} + + +Literal inputs require an SDK that supports binding metadata version 2 and an +Enterprise deployment with matching literal declaration and execution support. +Upgrading the SDK alone does not enable this server capability. Older clients +reject version 2 bindings; column-only bindings continue to use version 1. + + +Use `lit(...)` to pass the same value for every row while another parameter +reads a column. For example, using the table above: + + +```python Python icon="python" +from lancedb import col, function, lit + + +@function +def multiply(value: float, factor: int) -> float: + return value * factor + + +multiplier = db.create_function_async(multiply).wait() +table.add_columns( + {"scaled": multiplier(value=col("value"), factor=lit(16))}, + auto_refresh_enabled=False, +) +``` + + +Supported scalar constants are booleans, strings, integers from `-(2**63)` +through `2**64 - 1`, and `None` for a nullable parameter. Each value must match +the parameter's declared type. Floating-point, binary, date, datetime and +decimal constants are not supported in Function input bindings, even though +`lit(...)` accepts them in other SQL expressions. Bind a direct literal; +expressions such as `lit(16) + lit(8)` are not supported here. + +The constant belongs to the column binding, so the Function version and its +image stay the same. Only column inputs contribute table dependencies. Refresh +`scaled` to fill it. To change the constant to `lit(8)`, drop and redeclare the +column using the same `multiplier` version; the new binding needs a refresh. + +*/} + ### Bind more than one input, or fill more than one column {#multi} Parameters bind by name, so a function that takes several arguments binds diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index cce3efeef..a87b82a21 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -117,7 +117,7 @@ class PyExpr: def expr_col(name: str) -> PyExpr: ... def expr_lit( - value: Union[bool, int, float, str, bytes, date, datetime, Decimal], + value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None], ) -> PyExpr: ... def expr_func(name: str, args: List[PyExpr]) -> PyExpr: ... diff --git a/python/python/lancedb/expr.py b/python/python/lancedb/expr.py index f65fbd21a..b25e5d012 100644 --- a/python/python/lancedb/expr.py +++ b/python/python/lancedb/expr.py @@ -29,6 +29,8 @@ from lancedb._lancedb import PyExpr, expr_col, expr_lit, expr_func __all__ = ["Expr", "col", "lit", "func"] +_NOT_LITERAL = object() + _STR_TO_PA_TYPE: dict = { "bool": pa.bool_(), "boolean": pa.bool_(), @@ -92,9 +94,16 @@ class Expr: # for dict keys / set membership. __hash__ = None # type: ignore[assignment] - def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None: + def __init__( + self, + inner: PyExpr, + *, + column_path: str | None = None, + literal_value: object = _NOT_LITERAL, + ) -> None: self._inner = inner self._column_path = column_path + self._literal_value = literal_value def __bool__(self) -> bool: # An Expr describes a predicate that the query engine evaluates per row, @@ -301,14 +310,16 @@ def col(name: str) -> Expr: return Expr(expr_col(name), column_path=name) -def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr: +def lit( + value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None], +) -> Expr: """Create a literal (constant) value expression. Parameters ---------- value: A Python ``bool``, ``int``, ``float``, ``str``, ``bytes``, ``date``, - ``datetime``, or ``Decimal``. + ``datetime``, ``Decimal``, or ``None`` for SQL NULL. Examples -------- @@ -316,10 +327,12 @@ def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> >>> col("price") * lit(1.1) Expr((price * 1.1)) """ - if not isinstance(value, (bool, int, float, str, bytes, date, datetime, Decimal)): + if value is not None and not isinstance( + value, (bool, int, float, str, bytes, date, datetime, Decimal) + ): raise TypeError(f"Unsupported literal type: {type(value).__name__}") - return Expr(expr_lit(value)) + return Expr(expr_lit(value), literal_value=value) def func(name: str, *args: ExprLike) -> Expr: diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 86230be52..471fc2437 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -158,11 +158,15 @@ def _validate_literal(value): "Function integer literal is outside the canonical JSON range" ) elif isinstance(value, Mapping): + if not all(isinstance(key, str) for key in value): + raise TypeError("Function literal object keys must be strings") for child in value.values(): _validate_literal(child) elif isinstance(value, (list, tuple)): for child in value: _validate_literal(child) + elif value is not None and not isinstance(value, (bool, str)): + raise TypeError(f"unsupported Function literal type: {type(value).__name__}") return value @@ -193,7 +197,7 @@ class _RemoteValue(BaseModel): known = {} for name, field in self.__class__.model_fields.items(): value = getattr(self, name) - if value is None: + if value is None and not field.is_required(): continue if not field.is_required(): default_factory = field.default_factory @@ -626,10 +630,17 @@ class FunctionVersion(_RemoteValue): return _validate_row_timeout(value) def __call__(self, **arguments: Any) -> FunctionApplication: - """Bind this exact version to named table columns. + """Bind this exact version to named table columns and constant inputs. Every input must be a direct [lancedb.col][lancedb.expr.col] - reference. A Function that declares initialization fields takes their + reference or [lancedb.lit][lancedb.expr.lit] constant. Constants support + integers, strings, booleans, and null; floating-point, binary and + temporal literals are not in the canonical Function input contract. + The Enterprise service must support literal bindings and validates + constants against this exact version's input signature. To change a + constant, redeclare the column using the same Function version. + + A Function that declares initialization fields takes their values as further keyword arguments; they are constants of this binding, fixed for every row, and every instance the binding runs is created with them. A non-nullable field without a default must be @@ -658,7 +669,7 @@ class FunctionVersion(_RemoteValue): ... "embedding": embed(text=col("body"), model="small", dimensions=512) ... }) """ - from lancedb.expr import Expr + from lancedb.expr import Expr, _NOT_LITERAL parameters = tuple(parameter.name for parameter in self.signature.inputs) fields = {field.name: field for field in self.signature.initialization} @@ -682,17 +693,27 @@ class FunctionVersion(_RemoteValue): bindings = [] for parameter in parameters: value = arguments[parameter] - if not isinstance(value, Expr) or value._column_path is None: + if isinstance(value, Expr) and value._literal_value is not _NOT_LITERAL: + bindings.append( + ApplicationInput( + parameter=parameter, + kind="literal", + value=value._literal_value, + ) + ) + elif isinstance(value, Expr) and value._column_path is not None: + bindings.append( + ApplicationInput( + parameter=parameter, + kind="column", + value={"path": value._column_path}, + ) + ) + else: raise TypeError( - f"Function input {parameter!r} must be a direct col(...) reference" + f"Function input {parameter!r} must be a direct col(...) reference " + "or lit(...) constant" ) - bindings.append( - ApplicationInput( - parameter=parameter, - kind="column", - value={"path": value._column_path}, - ) - ) initialization = {} for name in fields: if name in arguments: @@ -876,6 +897,18 @@ class InputBinding(_RemoteValue): nullable: bool +class LiteralInputBinding(_RemoteValue): + """Constant supplied to a Function parameter for every input row.""" + + parameter: str + value: Any + + @field_validator("value") + @classmethod + def _validate_value(cls, value): + return _validate_literal(value) + + class OutputMapping(_RemoteValue): """One stable result-field mapping.""" @@ -900,6 +933,7 @@ class FunctionBinding(_RemoteValue): binding_id: str function: FunctionVersionRef inputs: tuple[InputBinding, ...] + literal_inputs: tuple[LiteralInputBinding, ...] = () outputs: tuple[OutputMapping, ...] assignment: Optional[AssignmentMapping] = None input_schema: Optional[Mapping[str, Any]] = None @@ -907,6 +941,13 @@ class FunctionBinding(_RemoteValue): initialization: Optional[str] = None """Standard base64 of the validated one-row Arrow IPC initialization stream.""" + @model_validator(mode="after") + def _validate_input_parameters(self): + parameters = [input.parameter for input in (*self.inputs, *self.literal_inputs)] + if len(parameters) != len(set(parameters)): + raise ValueError("Function binding input parameters must be unique") + return self + def initialization_row(self) -> Optional[dict[str, Any]]: """The initialization values this binding creates instances with.""" if self.initialization is None: @@ -2979,6 +3020,7 @@ __all__ = [ "FunctionVersionRef", "HuggingFaceModel", "InputBinding", + "LiteralInputBinding", "OutputMapping", "PythonEnvironmentSpec", "PythonAdapterSpec", diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 867672fe9..07be57e15 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -8,7 +8,7 @@ from types import MappingProxyType import pytest -from lancedb import col +from lancedb import col, lit import lancedb.functions as functions from lancedb.functions import ( FunctionApplication, @@ -58,6 +58,7 @@ def assert_no_secret_values(value): def test_public_function_values_are_in_api_reference(): + assert "LiteralInputBinding" in functions.__all__ docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md" rendered = docs.read_text() for name in functions.__all__: @@ -286,6 +287,67 @@ def test_function_version_binding_validates_names_and_direct_columns(): version(text=col("text").lower()) +@pytest.mark.parametrize("constant", [16, 8, True, "prompt", None, 2**64 - 1]) +def test_function_version_binds_direct_literals_without_changing_identity(constant): + value = job_result("remote_function_job.json") + value["signature"]["inputs"].append( + { + "name": "option", + "arrow_type": "bool" + if type(constant) is bool + else "utf8" + if isinstance(constant, str) + else "uint64" + if constant == 2**64 - 1 + else "int64", + "nullable": True, + } + ) + version = FunctionVersion.from_json(json.dumps(value)) + expression = lit(constant) + application = version(text=col("body"), option=expression) + encoded = json.loads(application.to_canonical_json()) + assert encoded["inputs"] == [ + {"parameter": "text", "kind": "column", "value": {"path": "body"}}, + {"parameter": "option", "kind": "literal", "value": constant}, + ] + assert application.function.version == version.version + assert application.function.object_id == version.object_id + assert application.function.manifest_digest == version.image.manifest_digest + assert FunctionApplication.from_json(application.to_canonical_json()) == application + if constant is None: + assert expression.to_sql() == "NULL" + if type(constant) is int: + assert expression.to_sql() == str(constant) + + +def test_function_literals_reject_expressions_and_unsupported_values(): + version = FunctionVersion.from_json( + json.dumps(job_result("remote_function_job.json")) + ) + with pytest.raises(TypeError, match="direct col"): + version(text=lit(16) + lit(8)) + with pytest.raises(ValueError, match="floating-point Function literals"): + version(text=lit(1.5)) + with pytest.raises(TypeError, match="unsupported Function literal type"): + version(text=lit(b"data")) + + +def test_function_literal_binding_preserves_null_and_rejects_duplicate_parameters(): + value = json.loads((FIXTURES / "remote_function_binding.json").read_text()) + value["inputs"] = value["inputs"][:1] + value["literal_inputs"] = [{"parameter": "body", "value": None}] + binding = FunctionBinding.from_json(json.dumps(value)) + assert binding.literal_inputs[0].value is None + assert json.loads(binding.to_canonical_json())["literal_inputs"] == [ + {"parameter": "body", "value": None} + ] + assert FunctionBinding.from_json(binding.to_canonical_json()) == binding + value["literal_inputs"][0]["parameter"] = "title" + with pytest.raises(ValueError, match="input parameters must be unique"): + FunctionBinding.from_json(json.dumps(value)) + + def test_function_version_keeps_named_struct_outputs_in_one_application(): value = job_result("remote_function_job.json") value["name"] = "text_features" diff --git a/python/src/expr.rs b/python/src/expr.rs index bb779bc1d..c4c7cbbb1 100644 --- a/python/src/expr.rs +++ b/python/src/expr.rs @@ -164,9 +164,12 @@ pub fn expr_col(name: &str) -> PyExpr { /// Create a literal value expression. /// /// Supported Python types: `bool`, `int`, `float`, `str`, `bytes`, `date`, -/// `datetime`, `Decimal`. +/// `datetime`, `Decimal`, and `None` (SQL NULL). #[pyfunction] pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult { + if value.is_none() { + return Ok(PyExpr(df_lit(ScalarValue::Null))); + } // bool must be checked before int because bool is a subclass of int in Python if let Ok(b) = value.extract::() { return Ok(PyExpr(df_lit(b))); @@ -174,6 +177,9 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult { if let Ok(i) = value.extract::() { return Ok(PyExpr(df_lit(i))); } + if let Ok(i) = value.extract::() { + return Ok(PyExpr(df_lit(i))); + } // Decimal must be checked before f64: Python's Decimal implements __float__, // so value.extract::() would succeed and silently truncate the value to // f64, losing precision. Build a Decimal128 scalar to preserve it instead. diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 387c80364..582b5b08a 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -111,7 +111,7 @@ fn from_json(json: &str) -> Result { serde_json::from_str(json).map_err(invalid_json) } -fn validate_literal(value: &Value) -> Result<()> { +pub(crate) fn validate_literal(value: &Value) -> Result<()> { match value { Value::Number(number) if number.is_f64() => Err(Error::InvalidInput { message: "floating-point Function literals are not part of the Slice 1 canonical wire contract" @@ -1018,6 +1018,18 @@ pub struct InputBinding { pub nullable: bool, } +/// Constant value bound to a Function parameter for every input row. +/// +/// Values use the same canonical JSON domain as [`ApplicationInput`]. The +/// Enterprise service validates their types against the exact Function version. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LiteralInputBinding { + /// Function parameter name, distinct from all column-bound parameters. + pub parameter: String, + /// Immutable canonical JSON value. + pub value: Value, +} + /// Ordered result-field to table-field mapping for a Function binding. /// /// `nullable` describes the logical Function result. Physical computed-column @@ -1046,6 +1058,8 @@ pub struct FunctionBinding { binding_id: String, function: FunctionVersionRef, inputs: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + literal_inputs: Vec, outputs: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] assignment: Option, @@ -1076,6 +1090,30 @@ impl FunctionBinding { &self.inputs } + /// Constants supplied for every row; these are not table dependencies. + pub fn literal_inputs(&self) -> &[LiteralInputBinding] { + &self.literal_inputs + } + + pub(crate) fn validate_inputs(&self) -> Result<()> { + let mut parameters = std::collections::HashSet::new(); + for parameter in self + .inputs + .iter() + .map(|input| &input.parameter) + .chain(self.literal_inputs.iter().map(|input| &input.parameter)) + { + if !parameters.insert(parameter) { + return Err(invalid_json(format!( + "duplicate Function parameter '{parameter}'" + ))); + } + } + self.literal_inputs + .iter() + .try_for_each(|input| validate_literal(&input.value)) + } + pub fn outputs(&self) -> &[OutputMapping] { &self.outputs } @@ -1098,7 +1136,20 @@ impl FunctionBinding { } } -impl_json!(FunctionBinding); +impl FunctionBinding { + /// Decode an immutable binding, validating its canonical input values. + pub fn from_json(json: &str) -> Result { + let binding: Self = from_json(json)?; + binding.validate_inputs()?; + Ok(binding) + } + + /// Encode this binding without dropping its constant inputs. + pub fn to_canonical_json(&self) -> Result { + self.validate_inputs()?; + canonical_json(self) + } +} /// Stable terminal result of an expression-backed or Function-backed column /// refresh [`crate::Job`]. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index e556d131c..29f3ab50e 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -10769,9 +10769,17 @@ mod tests { } } + #[rstest] + #[case::column_only(None)] + #[case::sixteen(Some(serde_json::json!(16)))] + #[case::eight(Some(serde_json::json!(8)))] + #[case::null(Some(serde_json::Value::Null))] #[tokio::test] - async fn test_add_scalar_function_column_sends_atomic_null_declaration() { - let table = Table::new_with_handler("my_table", |request| { + async fn test_add_scalar_function_column_sends_atomic_null_declaration( + #[case] literal: Option, + ) { + let expected_literal = literal.clone(); + let table = Table::new_with_handler("my_table", move |request| { match request.url().path() { "/v1/table/my_table/describe/" => http::Response::builder() .status(200) @@ -10789,6 +10797,13 @@ mod tests { )) .unwrap(); expected["auto_refresh_enabled"] = serde_json::json!(true); + if let Some(literal) = &expected_literal { + expected["function"]["binding_metadata_version"] = serde_json::json!(2); + expected["function"]["application"]["inputs"] + .as_array_mut().unwrap().push(serde_json::json!({ + "parameter": "num_frames", "kind": "literal", "value": literal, + })); + } assert_eq!(actual, expected); http::Response::builder() .status(200) @@ -10798,7 +10813,7 @@ mod tests { path => panic!("Unexpected path: {path}"), } }); - let application = crate::function::FunctionApplication::from_json( + let mut application: serde_json::Value = serde_json::from_str( r#"{ "function":{"name":"embed","version":"1","object_id":"fixture","location":"memory:///fixture","manifest_digest":"sha256:7e22f815b6648e14f093a3979a8e5a2082fa773ebe1ec84b135cae7e84d6f8e6"}, "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], @@ -10806,6 +10821,18 @@ mod tests { }"#, ) .unwrap(); + if let Some(literal) = literal { + application["inputs"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "parameter": "num_frames", "kind": "literal", "value": literal, + })); + } + let application = crate::function::FunctionApplication::from_json( + &serde_json::to_string(&application).unwrap(), + ) + .unwrap(); let result = table .add_columns() @@ -10934,19 +10961,64 @@ mod tests { /// Only a column the binding uses is refused, and it is refused before /// any request goes out; the rest reach the server as usual. + #[rstest] + #[case::column_only(false)] + #[case::literal(true)] #[tokio::test] - async fn test_add_columns_scopes_to_the_columns_a_binding_uses() { - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_response(&fixture_bound_schema())) - .unwrap(), - "/v1/table/my_table/add_columns/" => http::Response::builder() - .status(200) - .body(r#"{"version":10}"#.to_string()) - .unwrap(), - path => panic!("Unexpected path: {path}"), - }); + async fn test_add_columns_scopes_to_the_columns_a_binding_uses(#[case] literal: bool) { + let mut schema = fixture_bound_schema(); + if literal { + let key = crate::table::computed_columns::FUNCTION_BINDINGS_META_KEY; + let mut metadata = schema.metadata().clone(); + let mut envelope: serde_json::Value = + serde_json::from_str(metadata.get(key).unwrap()).unwrap(); + envelope["version"] = serde_json::json!(2); + envelope["bindings"][0]["inputs"] + .as_array_mut() + .unwrap() + .pop(); + envelope["bindings"][0]["literal_inputs"] = + serde_json::json!([{"parameter": "body", "value": null}]); + let binding = + crate::function::FunctionBinding::from_json(&envelope["bindings"][0].to_string()) + .unwrap(); + let fields = schema + .fields() + .iter() + .map(|field| { + let mut field = field.as_ref().clone(); + if let Some(output) = binding + .outputs() + .iter() + .find(|output| output.output_name == *field.name()) + { + field = field.with_metadata( + crate::table::computed_columns::function_computed_column_metadata( + binding.binding_id(), + output.output_ordinal, + &["title".into()], + ), + ); + } + field + }) + .collect::>(); + metadata.insert(key.to_string(), envelope.to_string()); + schema = Schema::new_with_metadata(fields, metadata); + } + let allowed_schema = schema.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&allowed_schema)) + .unwrap(), + "/v1/table/my_table/add_columns/" => http::Response::builder() + .status(200) + .body(r#"{"version":10}"#.to_string()) + .unwrap(), + path => panic!("Unexpected path: {path}"), + }); table .add_columns() .computed("doubled", "spare * 2") @@ -10963,13 +11035,14 @@ mod tests { .await .unwrap(); - let table = Table::new_with_handler("my_table", |request| match request.url().path() { - "/v1/table/my_table/describe/" => http::Response::builder() - .status(200) - .body(describe_response(&fixture_bound_schema())) - .unwrap(), - path => panic!("mutation request must not be sent: {path}"), - }); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap(), + path => panic!("mutation request must not be sent: {path}"), + }); for name in ["title", "search_text"] { let err = table .add_columns() @@ -11327,7 +11400,7 @@ mod tests { "/v1/table/my_table/describe/" => http::Response::builder() .status(200) .body( - r#"{"version":1,"schema":{"fields":[{"name":"x","nullable":true,"type":{"type":"int32"}}],"metadata":{"lancedb::function_bindings":"{\"version\":2,\"bindings\":[]}"}}}"#, + r#"{"version":1,"schema":{"fields":[{"name":"x","nullable":true,"type":{"type":"int32"}}],"metadata":{"lancedb::function_bindings":"{\"version\":3,\"bindings\":[]}"}}}"#, ) .unwrap(), path => panic!("mutation request must not be sent: {path}"), diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index b01f45d06..7348e659d 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -203,6 +203,10 @@ pub const FUNCTION_BINDINGS_META_KEY: &str = "lancedb::function_bindings"; /// Version of the schema-level Function binding envelope. pub const FUNCTION_BINDINGS_VERSION: u32 = 1; +/// Envelope version required when a Function binding contains constant inputs. +/// Older readers reject this version instead of dropping those inputs. +pub const FUNCTION_LITERAL_BINDINGS_VERSION: u32 = 2; + /// Field metadata key holding `{fragment id -> input signature}` as JSON, /// recorded by the refresh that last computed each fragment. Outside the /// declaration namespace on purpose: a declaration is immutable through @@ -329,6 +333,17 @@ struct FunctionBindingEnvelope { /// Encode immutable Function bindings for schema-level persistence. pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result { + bindings + .iter() + .try_for_each(FunctionBinding::validate_inputs)?; + let version = if bindings + .iter() + .any(|binding| !binding.literal_inputs().is_empty()) + { + FUNCTION_LITERAL_BINDINGS_VERSION + } else { + FUNCTION_BINDINGS_VERSION + }; let bindings = bindings .iter() .map(serde_json::to_value) @@ -336,12 +351,10 @@ pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result Result> { .bindings .into_iter() .map(|binding| { - serde_json::from_value(binding).map_err(|e| Error::InvalidInput { - message: format!("invalid Function binding metadata: {e}"), - }) + let binding: FunctionBinding = + serde_json::from_value(binding).map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + })?; + binding.validate_inputs()?; + Ok(binding) }) .collect() } @@ -370,7 +386,10 @@ fn function_binding_envelope(schema: &ArrowSchema) -> Result Result Result .collect::>>()?; let mut binding_ids = BTreeSet::new(); for binding in &bindings { + binding.validate_inputs()?; if !binding_ids.insert(binding.binding_id().to_string()) { return Err(Error::InvalidInput { message: format!("duplicate Function binding '{}'", binding.binding_id()), @@ -821,6 +853,7 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "binding_id", "function", "inputs", + "literal_inputs", "outputs", "assignment", "input_schema", @@ -830,6 +863,14 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "binding", )?; let object = value.as_object().unwrap(); + if let Some(inputs) = object.get("literal_inputs") { + for input in inputs + .as_array() + .ok_or_else(|| invalid_function("Function literal_inputs must be an array"))? + { + reject_unknown_object_fields(input, &["parameter", "value"], "literal input binding")?; + } + } reject_unknown_object_fields( object .get("function") @@ -1305,6 +1346,7 @@ fn nullable_scalar_allows_assignment(output: &OutputMapping) -> Result { } fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding) -> Result<()> { + binding.validate_inputs()?; let mut input_fields = Vec::with_capacity(binding.inputs().len()); for input in binding.inputs() { let resolved = resolve_field_path(schema, &input.field_path)?; @@ -1350,6 +1392,52 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding } input_fields.push(parameter_field); } + if !binding.literal_inputs().is_empty() { + // Column types still come from the table. Literal types come from the + // complete signature schema persisted by the Enterprise service. + let declared: JsonArrowSchema = + serde_json::from_value(binding.input_schema().cloned().ok_or_else(|| { + invalid_function("literal Function binding requires an input schema") + })?) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + let mut columns = input_fields + .into_iter() + .map(|field| (field.name().clone(), field)) + .collect::>(); + let mut literals = binding + .literal_inputs() + .iter() + .map(|input| (input.parameter.as_str(), &input.value)) + .collect::>(); + input_fields = Vec::with_capacity(declared.fields.len()); + for field in &declared.fields { + if let Some(column) = columns.remove(&field.name) { + input_fields.push(column); + } else if let Some(value) = literals.remove(field.name.as_str()) { + let field = + lance_namespace::schema::convert_json_arrow_field(field).map_err(|e| { + invalid_function(format!("invalid Function literal field: {e}")) + })?; + if field.is_blob_v2() || (value.is_null() && !field.is_nullable()) { + return Err(invalid_function(format!( + "invalid literal for Function parameter '{}'", + field.name() + ))); + } + input_fields.push(field); + } else { + return Err(invalid_function(format!( + "Function input schema has an unknown or duplicate parameter '{}'", + field.name + ))); + } + } + if !columns.is_empty() || !literals.is_empty() { + return Err(invalid_function( + "Function input schema is missing bound parameters", + )); + } + } let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(input_fields)) .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; @@ -1502,6 +1590,10 @@ pub(crate) fn plan_function_application( input.parameter ))); } + if input.kind == "literal" { + crate::function::validate_literal(&input.value)?; + continue; + } if input.kind != "column" { return Err(Error::NotSupported { message: format!( @@ -1680,7 +1772,15 @@ pub(crate) fn plan_function_application( Ok(FunctionDeclarationPlan { application: application.clone(), - binding_metadata_version: FUNCTION_BINDINGS_VERSION, + binding_metadata_version: if application + .inputs() + .iter() + .any(|input| input.kind == "literal") + { + FUNCTION_LITERAL_BINDINGS_VERSION + } else { + FUNCTION_BINDINGS_VERSION + }, input_bindings, input_schema, output_schema: JsonArrowSchema::new(output_fields), @@ -4738,6 +4838,129 @@ mod tests { ensure_binding_matches_schema(&ArrowSchema::new(fields), &binding).unwrap(); } + #[test] + fn test_literal_function_application_keeps_only_column_dependencies() { + let mut value = serde_json::to_value(single_input_application("title")).unwrap(); + value["inputs"] = serde_json::json!([ + {"parameter": "count", "kind": "literal", "value": 16}, + {"parameter": "text", "kind": "column", "value": {"path": "title"}}, + {"parameter": "optional", "kind": "literal", "value": null} + ]); + let application = FunctionApplication::from_json(&value.to_string()).unwrap(); + let plan = + plan_function_application(&function_input_schema(), &application, Some("result")) + .unwrap(); + assert_eq!(plan.binding_metadata_version, 2); + assert_eq!(plan.input_bindings.len(), 1); + assert_eq!(plan.input_bindings[0].parameter, "text"); + assert_eq!(plan.input_bindings[0].field_path, "title"); + assert_eq!(plan.input_schema.fields.len(), 1); + assert_eq!(plan.input_schema.fields[0].name, "text"); + assert_eq!( + serde_json::to_value(plan.application).unwrap()["inputs"], + value["inputs"] + ); + value["inputs"][0]["parameter"] = serde_json::json!("text"); + let duplicate = FunctionApplication::from_json(&value.to_string()).unwrap(); + assert!( + plan_function_application(&function_input_schema(), &duplicate, Some("result")) + .unwrap_err() + .to_string() + .contains("duplicate Function parameter") + ); + } + + #[test] + fn test_literal_function_metadata_survives_schema_mutation_guards() { + let legacy = FunctionBinding::from_json(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + let legacy_envelope: Value = serde_json::from_str( + &function_bindings_metadata(std::slice::from_ref(&legacy)).unwrap(), + ) + .unwrap(); + assert_eq!(legacy_envelope["version"], 1); + let mut value = serde_json::to_value(&legacy).unwrap(); + value["inputs"].as_array_mut().unwrap().pop(); + value["literal_inputs"] = serde_json::json!([{"parameter": "body", "value": null}]); + let binding = FunctionBinding::from_json(&value.to_string()).unwrap(); + let raw = function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(); + let mut envelope: Value = serde_json::from_str(&raw).unwrap(); + assert_eq!(envelope["version"], 2); + assert_eq!( + envelope["bindings"][0]["literal_inputs"], + value["literal_inputs"] + ); + let schema = valid_function_binding_schema(true, true, &binding); + let schema = schema.with_metadata(HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + raw.clone(), + )])); + ensure_supported_function_metadata(&schema).unwrap(); + let decoded = function_bindings(&schema).unwrap(); + assert_eq!(decoded.as_slice(), std::slice::from_ref(&binding)); + assert_eq!(function_bindings_metadata(&decoded).unwrap(), raw); + assert!(!protected_roots(&decoded).unwrap().contains("body")); + + envelope["version"] = serde_json::json!(1); + let downgraded = schema.clone().with_metadata(HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + envelope.to_string(), + )])); + assert!( + function_bindings(&downgraded) + .unwrap_err() + .to_string() + .contains("require metadata version 2") + ); + + value["literal_inputs"][0]["parameter"] = serde_json::json!("title"); + assert!( + FunctionBinding::from_json(&value.to_string()) + .unwrap_err() + .to_string() + .contains("duplicate Function parameter") + ); + } + + #[test] + fn test_literal_function_binding_requires_complete_input_schema() { + let mut value: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + value["inputs"].as_array_mut().unwrap().pop(); + value["literal_inputs"] = serde_json::json!([{"parameter": "body", "value": null}]); + value["input_schema"]["fields"][1]["nullable"] = serde_json::json!(false); + let binding = FunctionBinding::from_json(&value.to_string()).unwrap(); + let schema = valid_function_binding_schema(true, true, &binding); + assert!( + ensure_binding_matches_schema(&schema, &binding) + .unwrap_err() + .to_string() + .contains("invalid literal") + ); + value["input_schema"]["fields"] + .as_array_mut() + .unwrap() + .pop(); + let missing = FunctionBinding::from_json(&value.to_string()).unwrap(); + assert!( + ensure_binding_matches_schema(&schema, &missing) + .unwrap_err() + .to_string() + .contains("missing bound parameters") + ); + value["literal_inputs"][0]["value"] = serde_json::json!(1.5); + assert!( + FunctionBinding::from_json(&value.to_string()) + .unwrap_err() + .to_string() + .contains("floating-point Function literals") + ); + } + #[test] fn test_function_binding_metadata_survives_schema_round_trip() { let binding = FunctionBinding::from_json(include_str!( @@ -5391,7 +5614,7 @@ mod tests { function_input_schema().fields().to_vec(), HashMap::from([( FUNCTION_BINDINGS_META_KEY.to_string(), - r#"{"version":2,"bindings":[]}"#.to_string(), + r#"{"version":3,"bindings":[]}"#.to_string(), )]), ); let err = plan_function_application(&mixed_schema, &named_struct_application("{}"), None) From ea59f8acb61a6ac93fc940d055efe3c8f823991c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 21:49:45 +0800 Subject: [PATCH 127/203] feat(python): preserve Function timestamp and duration types (#5032) Function declarations currently reject exact timestamp and duration types. Preserve their Arrow units and timezones in canonical signature JSON, including fixed-offset timezones and nested fields. Bare `datetime` and microsecond/no-timezone declarations keep their existing representation; `timedelta` requires an explicit unit. Compound temporal signatures require the Lance Namespace decoder in https://github.com/lance-format/lance/pull/11059 and corresponding server validation support. Older readers reject these signatures; this change does not upgrade server support or dependency pins. Validation: 128 Python signature tests and 30 documentation tests passed (one skipped), using the changed Python source with an existing native extension. No Rust rebuild or end-to-end Function registration/refresh was performed. --- docs/web/management/function.mdx | 35 ++++ python/python/lancedb/functions.py | 48 +++++- .../tests/test_first_class_function_slice2.py | 156 +++++++++++++++++- 3 files changed, 227 insertions(+), 12 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 41e64d482..f6264edbf 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -104,6 +104,41 @@ at all is the struct's own validity, which Enterprise keeps in a separate internal column when it expands the result into sibling columns, so a null field is a value rather than a missing row. +### Timestamps and durations {#timestamps-durations} + +Bare `datetime` keeps its existing `timestamp[us]` default without a timezone. +For any other unit or a timezone, declare the Arrow type explicitly: + +```python +from datetime import datetime +from typing import Annotated + +import pyarrow as pa + + +@function +def normalize( + ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")], +) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]: + ... +``` + +`pa.timestamp` accepts `s`, `ms`, `us`, and `ns`, and a timezone such as +`UTC`, `America/New_York`, or `+08:00`. The canonical signature uses +`{"type":"timestamp::"}`, with `-` for no timezone; the +microsecond/no-timezone case keeps the legacy `{"type":"timestamp"}` shape. +A timezone string of `-` is reserved for "no timezone" and is rejected. + +`pa.duration` accepts the same four units and uses +`{"type":"duration:"}`; the microsecond case keeps the legacy +`{"type":"duration"}` shape. A bare `timedelta` has no unit and is rejected; +use `Annotated[timedelta, pa.duration("s")]` or an explicit schema. + +Other units are never downgraded to microseconds. A reader that predates the +compound temporal representation cannot read those signatures. A deployment +must include the corresponding Lance Namespace and Sophon support; this +client-side declaration does not add server support. + ## Connect and create a table {#table} The remaining steps run against your Enterprise deployment. Replace the database diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 471fc2437..18c504a8f 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -29,7 +29,7 @@ import textwrap import types import warnings from collections.abc import Mapping, Sequence -from datetime import date, datetime +from datetime import date, datetime, timedelta from pathlib import Path from typing import ( Annotated, @@ -1043,6 +1043,7 @@ _GRAMMAR_PRIMITIVES = ( (pa.date32(), "date32"), (pa.date64(), "date64"), ) +_FUNCTION_TIMEUNITS = ("s", "ms", "us", "ns") def _canonical_arrow_type( @@ -1259,6 +1260,26 @@ def _exact_arrow_type( for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return {"type": name} + if pa.types.is_timestamp(data_type): + unit = data_type.unit + if unit not in _FUNCTION_TIMEUNITS: + raise TypeError(f"unsupported Function timestamp unit: {unit!r}") + timezone = data_type.tz + if timezone == "-": + raise TypeError( + "unsupported Function timestamp timezone: '-' is reserved for " + "no timezone" + ) + if unit == "us" and timezone is None: + return {"type": "timestamp"} + return {"type": f"timestamp:{unit}:{timezone if timezone is not None else '-'}"} + if pa.types.is_duration(data_type): + unit = data_type.unit + if unit not in _FUNCTION_TIMEUNITS: + raise TypeError(f"unsupported Function duration unit: {unit!r}") + if unit == "us": + return {"type": "duration"} + return {"type": f"duration:{unit}"} if pa.types.is_struct(data_type): fields = list(data_type) names = [field.name for field in fields] @@ -1344,9 +1365,9 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError( "Annotated Function types require exactly one PyArrow DataType" ) - # A struct value is written as a dict, which has no Arrow type of its - # own; the Annotated metadata supplies it. - if base is dict or get_origin(base) is dict: + # A struct value is written as a dict, and timedelta has no unit of + # its own; the Annotated metadata supplies those types. + if base is dict or get_origin(base) is dict or base is timedelta: base_nullable = False else: _, base_nullable = _annotation_type(base) @@ -1372,7 +1393,14 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: if annotation is date: return pa.date32(), nullable if annotation is datetime: + # Existing default: microsecond precision, no timezone. Other units + # and timezones require Annotated or an explicit schema. return pa.timestamp("us"), nullable + if annotation is timedelta: + raise TypeError( + "timedelta Function annotations require an explicit unit; use " + "Annotated[timedelta, pyarrow.duration(unit)] or an explicit schema" + ) if get_origin(annotation) is list: arguments = get_args(annotation) if len(arguments) != 1: @@ -2701,7 +2729,11 @@ def function( deployment must accept nullable scalar outputs; an older server rejects the registration. Every named-struct field may be nullable; Enterprise preserves the struct's validity when the result is expanded into sibling - columns. + columns. Bare ``datetime`` keeps its existing ``timestamp[us]`` default + without a timezone; other units and timezones require + ``Annotated[datetime, pyarrow.timestamp(unit, tz=...)]`` or an explicit + schema. A bare ``timedelta`` has no unit and is rejected; use + ``Annotated[timedelta, pyarrow.duration(unit)]`` or an explicit schema. **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 @@ -2808,8 +2840,10 @@ def function( output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional Explicit scalar or named-struct output. A scalar field's ``nullable`` flag is preserved; a top-level named-struct field and a Blob v2 output - must be non-nullable. Required for batch annotations. When omitted, the - output is inferred from the return annotation. + must be non-nullable. Temporal fields use canonical Arrow JSON; the + microsecond/no-timezone case keeps the legacy timestamp/duration + shape. 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. Syntax is validated at decoration time, including extras and environment markers. Named direct diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 7e089a96d..1e896f780 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -9,7 +9,7 @@ import functools import importlib.util import inspect import types -from datetime import date +from datetime import date, datetime, timedelta import http.server import json import os @@ -19,7 +19,7 @@ import sys import typing import urllib.parse import warnings -from typing import Optional +from typing import Annotated, Optional import pyarrow as pa import pytest @@ -884,12 +884,11 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): == "large_list" ) for outside in [ - pa.timestamp("us"), pa.decimal128(10, 2), pa.binary(4), - pa.duration("s"), + pa.time32("s"), + pa.time64("us"), pa.list_(pa.float32(), 0), - pa.list_(pa.timestamp("us")), ]: with pytest.raises(TypeError, match="unsupported Arrow type"): _canonical_arrow_type(outside) @@ -1215,6 +1214,153 @@ def test_explicit_arrow_schema_is_deterministic(): assert signature.output.nullable is False +def test_timestamp_annotation_and_explicit_schema_serialization(): + for unit in ("s", "ms", "us", "ns"): + for timezone in (None, "UTC", "America/New_York", "+08:00", "-05:00"): + encoded = json.loads(_canonical_arrow_type(pa.timestamp(unit, tz=timezone))) + if unit == "us" and timezone is None: + assert encoded == {"type": "timestamp"} + else: + suffix = timezone if timezone is not None else "-" + assert encoded == {"type": f"timestamp:{unit}:{suffix}"} + + with pytest.raises(TypeError, match="reserved for no timezone"): + _canonical_arrow_type(pa.timestamp("us", tz="-")) + + @function + def normalize( + ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")], + ) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]: + return ts + + signature = normalize.registration_request.signature + assert json.loads(signature.inputs[0].arrow_type) == {"type": "timestamp:ns:UTC"} + assert json.loads(signature.output.arrow_type) == {"type": "timestamp:ns:UTC"} + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + + @function + def optional_timestamp( + ts: Optional[Annotated[datetime, pa.timestamp("ms", tz="UTC")]], + ) -> int: + return 0 + + optional_input = optional_timestamp.registration_request.signature.inputs[0] + assert optional_input.nullable is True + assert json.loads(optional_input.arrow_type) == {"type": "timestamp:ms:UTC"} + + @function + def legacy(ts: datetime) -> datetime: + return ts + + legacy_signature = legacy.registration_request.signature + assert json.loads(legacy_signature.inputs[0].arrow_type) == {"type": "timestamp"} + assert json.loads(legacy_signature.output.arrow_type) == {"type": "timestamp"} + legacy_round_trip = FunctionSignature.from_json( + legacy_signature.to_canonical_json() + ) + assert legacy_round_trip.inputs[0].arrow_type == '{"type":"timestamp"}' + + input_schema = pa.schema( + [pa.field("ts", pa.timestamp("ms", tz="America/New_York"), nullable=True)] + ) + output_schema = pa.schema( + [ + pa.field("ts", pa.timestamp("ns", tz="+08:00"), nullable=True), + pa.field("elapsed", pa.duration("ms"), nullable=False), + ] + ) + + @function(input_schema=input_schema, output_schema=output_schema) + def nested(ts): + return {"ts": ts, "elapsed": None} + + nested_signature = nested.registration_request.signature + assert nested_signature.inputs[0].nullable is True + assert json.loads(nested_signature.inputs[0].arrow_type) == { + "type": "timestamp:ms:America/New_York" + } + assert nested_signature.output.kind == "named_struct" + assert nested_signature.output.fields[0].nullable is True + assert json.loads(nested_signature.output.fields[0].arrow_type) == { + "type": "timestamp:ns:+08:00" + } + assert json.loads(nested_signature.output.fields[1].arrow_type) == { + "type": "duration:ms" + } + + list_type = pa.list_(pa.field("item", pa.timestamp("ms", tz="UTC"), nullable=False)) + assert json.loads(_canonical_arrow_type(list_type)) == { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": False, + "type": {"type": "timestamp:ms:UTC"}, + } + ], + } + + +def test_duration_annotation_and_explicit_schema_serialization(): + for unit in ("s", "ms", "us", "ns"): + encoded = json.loads(_canonical_arrow_type(pa.duration(unit))) + expected = ( + {"type": "duration"} if unit == "us" else {"type": f"duration:{unit}"} + ) + assert encoded == expected + + @function + def elapsed( + value: Annotated[timedelta, pa.duration("s")], + ) -> Annotated[timedelta, pa.duration("ns")]: + return value + + signature = elapsed.registration_request.signature + assert json.loads(signature.inputs[0].arrow_type) == {"type": "duration:s"} + assert json.loads(signature.output.arrow_type) == {"type": "duration:ns"} + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + + @function + def optional_elapsed( + value: Optional[Annotated[timedelta, pa.duration("ms")]], + ) -> int: + return 0 + + optional_input = optional_elapsed.registration_request.signature.inputs[0] + assert optional_input.nullable is True + assert json.loads(optional_input.arrow_type) == {"type": "duration:ms"} + + with pytest.raises( + TypeError, match="timedelta Function annotations require an explicit unit" + ): + + @function + def missing(value: timedelta) -> timedelta: + return value + + input_schema = pa.schema([pa.field("elapsed", pa.duration("ms"), nullable=True)]) + output_schema = pa.field("result", pa.duration("us"), nullable=False) + + @function(input_schema=input_schema, output_schema=output_schema) + def explicit(elapsed: timedelta) -> timedelta: + return elapsed + + explicit_signature = explicit.registration_request.signature + assert explicit_signature.inputs[0].nullable is True + assert json.loads(explicit_signature.inputs[0].arrow_type) == { + "type": "duration:ms" + } + assert json.loads(explicit_signature.output.arrow_type) == {"type": "duration"} + explicit_round_trip = FunctionSignature.from_json( + explicit_signature.to_canonical_json() + ) + assert explicit_round_trip.output.arrow_type == '{"type":"duration"}' + + def test_nullable_scalar_output_annotation_and_explicit_schema(): input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)]) From 2499342fa1bccdaafdf4c38a8da35459b25b247d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:30:28 +0800 Subject: [PATCH 128/203] feat(function): expose resolved environments and fresh lock requests (#5034) Function registration clients cannot request fresh dependency resolution or inspect the measured environment returned by the server. Add `refresh_lock=True` to Python registration and preserve the requested runtime and measured environments in Rust/Python Function version readback. Registration forwards both `exist_ok` and `refresh_lock`; defaults remain unchanged. Single-platform versions retain `resolved_environment`. Multiarchitecture versions expose `resolved_environments`, keyed by OCI `os/architecture`, and the Python `environment_report` alias. Platforms are never flattened: absent entries mean unknown measurements, while measured empty package lists remain present. Registration waits emit scalar and per-platform server warnings once per Job; catalog reads do not repeat them. Requires matching server support, including Sophon #10344 for per-platform publication. Nine focused Python source-overlay tests and 29 documentation tests passed for the additive map change; one documentation test requiring a newer native `exist_ok` binding was excluded. These checks reuse a prebuilt extension and do not establish current native integration. PR CI exercises the Rust transport/readback and Python bindings. Live multiarchitecture registration and GPU acceptance remain separate. --- docs/src/python/python.md | 8 + docs/web/management/function.mdx | 118 ++++++ python/python/lancedb/__init__.py | 4 + python/python/lancedb/db.py | 56 ++- python/python/lancedb/functions.py | 122 ++++++ python/python/lancedb/remote/db.py | 2 + .../tests/test_first_class_function_slice2.py | 371 +++++++++++++++++- rust/lancedb/src/function.rs | 279 ++++++++++++- rust/lancedb/src/remote/sql_test.rs | 135 +++++++ 9 files changed, 1087 insertions(+), 8 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5aa21f691..b7eb1704a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -564,6 +564,14 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.FunctionVersion +::: lancedb.functions.FunctionEnvironment + +::: lancedb.functions.ResolvedEnvironment + +::: lancedb.functions.ResolvedPackage + +::: lancedb.functions.ResolvedEnvironmentProvenance + ::: lancedb.functions.HuggingFaceModel ::: lancedb.functions.PythonRuntimeSpec diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index f6264edbf..efcbcc799 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -178,6 +178,13 @@ with `db.get_function(name, version=...)`. The version may be an integer or its string form. Omit `version` to resolve and return the latest currently visible revision. +Re-registering unchanged code reuses the published version and its resolved +environment lock. Pass `refresh_lock=True` to `create_function` or +`create_function_async` to request a fresh lock for this registration. It is a +registration action, not part of the Function's source or runtime identity. +A deployment must support the field; an older server rejects the unknown +field rather than silently reusing the old lock. + {/* Draft for the function exist_ok release. Use `exist_ok=True` on `create_function` or `create_function_async` to return @@ -246,6 +253,117 @@ are not included; list each namespace separately. A version's `created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are all readable this way without applying or calling the function. +### Inspect the resolved environment {#resolved-environment} + +The version keeps the requested runtime separate from what the server actually +installed. The typed catalog API is available in Python and Rust; TypeScript +does not yet expose this readback API. `version.runtime` is the specification +sent at registration. `version.resolved_environment` is measured data from the +built image: + + +```python +version = db.get_function("double") +print(version.runtime) # requested runtime, or None for legacy +print(version.environment.resolved) # measured environment, or None for legacy +print(version.environment_report) # platform -> measured environment map + +if version.environment.resolved is not None: + for package in version.environment.resolved.packages: + print(package.name, package.version) # versions keep labels such as +cu130 +``` + +{/* Draft for the typed Rust environment inspection release. +```rust +# async fn inspect_environment(connection: &lancedb::Connection) -> Result<(), Box> { +let version = connection.get_function_latest("double", &[]).await?; +println!("Requested runtime: {:?}", version.runtime()); + +if let Some(environment) = version.resolved_environment() { + for package in &environment.packages { + println!("{} {}", package.name, package.version); + } +} + +for (platform, environment) in version.resolved_environments() { + println!("{platform}: {} measured packages", environment.packages.len()); + for package in &environment.packages { + println!("{} {}", package.name, package.version); + } +} +# Ok(()) +# } +``` +*/} + + +`version.environment.requested` and `version.environment.resolved` are +convenience members over the same canonical fields; they do not add another +wire shape. The canonical JSON exposes top-level `runtime` and +`resolved_environment`. A missing `resolved_environment` means the version or +environment cache predates measurement; it is unknown, not an empty installed +package list. A package's `source` is present only when the submitted lock +retained it, and provenance fields are reported without client-side guessing. + +For a multiarchitecture image, the scalar field is absent and +`version.resolved_environments` (also available as +`version.environment_report`) maps OCI `os/architecture` keys to the measured +environment for that platform. A missing platform key means its measurement is +unknown; an empty `packages` list inside a key is a measured empty environment +and is retained. The SDK never merges platforms or fabricates an aggregate +package list. + +The corresponding canonical payload has this shape: + +```json +{ + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": {"kind": "pip", "packages": ["vllm==0.11.0"]} + }, + "resolved_environment": { + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "torch resolved to torch==2.9.0+cu130 but is not pinned exactly; add torch==2.9.0+cu130 to pin it." + ] + } +} +``` + +The multiarchitecture form has the same package shape per platform: + +```json +{ + "resolved_environments": { + "linux/amd64": { + "packages": [{"name": "torch", "version": "2.9.0+cu130"}] + }, + "linux/arm64": { + "packages": [] + } + } +} +``` + +Environment warnings are part of the registration result. Waiting on +`create_function_async(...)` (or calling `create_function`) emits each server +warning from the scalar or per-platform measurements as a Python `UserWarning`; +`get_function` and `list_functions` read the same version but do not +replay those registration warnings. + ## Try it in SQL {#try-sql} A registered function is callable in SQL by its name, the same as any other diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 31285d100..acf25d35c 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -51,11 +51,15 @@ from .functions import ( FunctionApplication as FunctionApplication, FunctionBinding as FunctionBinding, FunctionDefinition as FunctionDefinition, + FunctionEnvironment as FunctionEnvironment, FunctionRegistrationRequest as FunctionRegistrationRequest, FunctionRetryPolicy as FunctionRetryPolicy, FunctionVersion as FunctionVersion, HuggingFaceModel as HuggingFaceModel, PythonRuntimeSpec as PythonRuntimeSpec, + ResolvedEnvironment as ResolvedEnvironment, + ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance, + ResolvedPackage as ResolvedPackage, RefreshColumnResult as RefreshColumnResult, function as function, udf as udf, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b84e4d581..12c7edd5c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -154,6 +154,38 @@ def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[ raise TypeError("version must be an int, str, or None") +def _function_registration_decoder(): + """Parse a registration result and emit its server warnings once. + + The warnings come from the scalar environment or, for a multiarchitecture + image, each measured platform entry. They are part of the registration job + result, not a new client-side package policy. Catalog get/list readbacks + use ``FunctionVersion.from_json`` directly and therefore do not replay + them. + """ + warned = False + + def decode(payload: str) -> FunctionVersion: + nonlocal warned + version = FunctionVersion.from_json(payload) + if not warned: + environments = [ + environment + for environment in ( + version.resolved_environment, + *version.resolved_environments.values(), + ) + if environment is not None + ] + for environment in environments: + for message in environment.warnings: + warnings.warn(message, UserWarning, stacklevel=3) + warned = True + return version + + return decode + + class DBConnection(EnforceOverrides): """An active LanceDB connection interface. @@ -1018,6 +1050,7 @@ class DBConnection(EnforceOverrides): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. @@ -1040,6 +1073,13 @@ class DBConnection(EnforceOverrides): namespace_path : list of str, optional The namespace holding the Function. None or an empty list is the root namespace. + refresh_lock : bool, default False + Ask the server to resolve a fresh environment lock instead of + reusing the published version's lock. + + When the registration job resolves, each resolved-environment warning + reported by the server is emitted as a Python ``UserWarning``. Catalog + reads do not replay those registration warnings. Examples -------- @@ -1060,6 +1100,7 @@ class DBConnection(EnforceOverrides): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ).wait() def create_function_async( @@ -1069,6 +1110,7 @@ class DBConnection(EnforceOverrides): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> Job[FunctionVersion]: """Submit a scalar Python function for building and registration. @@ -1079,6 +1121,11 @@ class DBConnection(EnforceOverrides): artifact. The returned job has type ``query`` and the SQL query UUID as its ID. Waiting on it returns the immutable Function version. LanceDB Embedded connections raise ``NotImplementedError``. + + ``refresh_lock`` asks the server to resolve a fresh environment lock + instead of reusing the published version's lock. Waiting on the job + emits the server's resolved-environment warnings as Python warnings; + reading the same version later does not repeat them. """ raise NotImplementedError( _append_doc_url( @@ -2432,6 +2479,7 @@ class LanceDBConnection(DBConnection): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( @@ -2439,6 +2487,7 @@ class LanceDBConnection(DBConnection): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ) ) return Job(job) @@ -3788,6 +3837,7 @@ class AsyncConnection(object): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> AsyncJob[FunctionVersion]: """Submit a scalar Python function for building and registration. @@ -3802,14 +3852,16 @@ class AsyncConnection(object): 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. LanceDB Embedded connections raise ``NotImplementedError``. + ``refresh_lock`` asks the server to resolve a fresh environment lock + instead of reusing the published version's lock. """ if not isinstance(definition, FunctionDefinition): raise TypeError("create_function_async requires a @function definition") - request = definition.bind_secrets(secrets) + request = definition.bind_secrets(secrets).with_refresh_lock(refresh_lock) inner = await self._inner.create_function_async( request.to_canonical_json(), namespace_path, exist_ok=exist_ok ) - return _typed_job(inner, FunctionVersion.from_json) + return _typed_job(inner, _function_registration_decoder()) async def get_function( self, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 18c504a8f..ecbc697d1 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -36,6 +36,7 @@ from typing import ( Any, Callable, Literal, + NamedTuple, Optional, TYPE_CHECKING, Union, @@ -101,6 +102,12 @@ def _validate_batch_size(value: Any) -> Optional[int]: return value +def _validate_refresh_lock(value: Any) -> bool: + if not isinstance(value, bool): + raise ValueError("refresh_lock must be a boolean") + return value + + def _validate_max_concurrency(value: Any) -> Optional[int]: if value is None: return None @@ -544,6 +551,67 @@ class FunctionImage(_RemoteValue): models: tuple[HuggingFaceModel, ...] = () +class ResolvedPackage(_RemoteValue): + """One installed Python distribution measured from a baked environment. + + ``version`` is the complete version reported by package metadata, + including local labels such as ``+cu130``. ``source`` is present only when + the submitted lock retained a per-package source; absent means unknown, not + an inferred index. + """ + + name: str + version: str + source: Optional[str] = None + + +class ResolvedEnvironmentProvenance(_RemoteValue): + """Sanitized source and accelerator provenance for a resolved environment. + + ``configured_index_urls`` and ``configured_find_links`` record build + inputs. ``resolved_indexes`` records indexes visible in the submitted lock, + so a configured source is not by itself evidence that a package came from + it. Empty lists and absent fields remain absent; the client does not + synthesize them. + """ + + configured_index_urls: tuple[str, ...] = () + configured_find_links: tuple[str, ...] = () + resolved_indexes: tuple[str, ...] = () + cuda_toolkit: Optional[str] = None + torch_version: Optional[str] = None + + +class ResolvedEnvironment(_RemoteValue): + """Actual installed distributions and registration warnings for one platform. + + A missing value means its measurement is unknown, not an empty + installed-package list. Versions are retained verbatim, including local + labels; package ``source`` is retained only when the producer recorded it. + """ + + packages: tuple[ResolvedPackage, ...] + provenance: Optional[ResolvedEnvironmentProvenance] = None + warnings: tuple[str, ...] = () + + +class FunctionEnvironment(NamedTuple): + """Requested and measured environment view for a Function version. + + This is a view over + [FunctionVersion.runtime][lancedb.functions.FunctionVersion.runtime] + and + [FunctionVersion.resolved_environment][lancedb.functions.FunctionVersion.resolved_environment]. + It adds no wire field and performs no second parse. ``requested`` is the + runtime specification supplied at registration; ``resolved`` is measured + data and is ``None`` when unknown. For per-platform multiarchitecture + measurements, use ``FunctionVersion.environment_report``. + """ + + requested: Optional[PythonRuntimeSpec] + resolved: Optional[ResolvedEnvironment] + + def _validate_object_version(value: str) -> str: if int(value) > 2**64 - 1: raise ValueError("Function version exceeds uint64") @@ -593,6 +661,17 @@ class FunctionVersion(_RemoteValue): ``result_stability`` retain the execution controls reported by the catalog. They are ``None`` for versions registered before the corresponding declaration. + + ``runtime`` is the runtime specification requested at registration. It is + not evidence of what was installed. ``resolved_environment`` is measured + data for a single-platform image: actual package names and complete + versions, optional per-package source, provenance, and registration + warnings. ``resolved_environments`` is the corresponding map for a + multiarchitecture image, keyed by OCI ``os/architecture``. It is never + flattened into an aggregate package list. ``None`` or an empty map means + unknown data, not an empty installed environment. ``environment`` is a + convenience view with ``requested`` and ``resolved`` members over the same + fields. """ name: str @@ -613,6 +692,11 @@ class FunctionVersion(_RemoteValue): max_concurrency: Optional[int] = None row_timeout_seconds: Optional[float] = None result_stability: Optional[str] = None + runtime: Optional[PythonRuntimeSpec] = None + resolved_environment: Optional[ResolvedEnvironment] = None + resolved_environments: Mapping[str, ResolvedEnvironment] = Field( + default_factory=dict + ) @field_validator("batch_size", mode="before") @classmethod @@ -629,6 +713,24 @@ class FunctionVersion(_RemoteValue): def _validate_row_timeout(cls, value): return _validate_row_timeout(value) + @property + def environment(self) -> FunctionEnvironment: + """Requested and measured environment without adding a second parser.""" + return FunctionEnvironment( + requested=self.runtime, + resolved=self.resolved_environment, + ) + + @property + def environment_report(self) -> Mapping[str, ResolvedEnvironment]: + """Per-platform measured reports, keyed by OCI ``os/architecture``. + + This is the same map as ``resolved_environments`` and is never + flattened. Single-platform images use ``resolved_environment`` instead; + an absent platform means its measurement is unknown. + """ + return self.resolved_environments + def __call__(self, **arguments: Any) -> FunctionApplication: """Bind this exact version to named table columns and constant inputs. @@ -769,6 +871,9 @@ class FunctionRegistrationRequest(_RemoteValue): Credential values deliberately have no field here. The only secret-shaped thing a client sends is ``secret_bindings``: the name of a Secret the database already holds, which the remote service resolves at execution. + ``refresh_lock`` is a per-registration action, not part of the Function's + source or runtime identity; its false default is omitted from canonical + JSON. """ name: str @@ -781,6 +886,7 @@ class FunctionRegistrationRequest(_RemoteValue): retry_policy: Optional[FunctionRetryPolicy] = None secret_bindings: tuple[SecretBinding, ...] = () models: tuple[HuggingFaceModel, ...] = () + refresh_lock: bool = False @field_validator("batch_size", mode="before") @classmethod @@ -797,6 +903,18 @@ class FunctionRegistrationRequest(_RemoteValue): def _validate_row_timeout(cls, value): return _validate_row_timeout(value) + @field_validator("refresh_lock", mode="before") + @classmethod + def _validate_refresh_lock(cls, value): + return _validate_refresh_lock(value) + + def with_refresh_lock(self, refresh_lock: bool) -> FunctionRegistrationRequest: + """Return this request with the registration-time refresh action set.""" + refresh_lock = _validate_refresh_lock(refresh_lock) + if self.refresh_lock == refresh_lock: + return self + return self._copy(update={"refresh_lock": refresh_lock}) + class FunctionVersionRef(_OpenRemoteValue): name: str @@ -3043,6 +3161,7 @@ __all__ = [ "FunctionArtifactContent", "FunctionArtifactRequest", "FunctionBinding", + "FunctionEnvironment", "FunctionOutput", "FunctionParameter", "FunctionRegistrationRequest", @@ -3059,6 +3178,9 @@ __all__ = [ "PythonEnvironmentSpec", "PythonAdapterSpec", "PythonRuntimeSpec", + "ResolvedEnvironment", + "ResolvedEnvironmentProvenance", + "ResolvedPackage", "RefreshColumnResult", "FunctionDefinition", ] diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index b9928d278..913c8fc2c 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1002,6 +1002,7 @@ class RemoteDBConnection(DBConnection): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> Job[FunctionVersion]: job = LOOP.run( self._conn.create_function_async( @@ -1009,6 +1010,7 @@ class RemoteDBConnection(DBConnection): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ) ) return Job(job) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 1e896f780..6dcc0bbbe 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -26,8 +26,9 @@ import pytest import lancedb from lancedb import BlobReader -from lancedb.db import AsyncConnection +from lancedb.db import AsyncConnection, DBConnection, LanceDBConnection from lancedb.functions import ( + FunctionRegistrationRequest, FunctionSignature, FunctionVersion, HuggingFaceModel, @@ -82,6 +83,63 @@ def analyze_caption(caption: str) -> str: return caption.strip() +def _function_version_with_resolved_environment(): + version = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + version["runtime"] = json.loads( + normalize_score.registration_request.runtime.to_canonical_json() + ) + version["resolved_environment"] = { + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple", + }, + {"name": "transformers", "version": "4.57.1"}, + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": ["https://downloads.example/wheels"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130", + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned " + "exactly; add transformers==4.57.1 to pin it." + ], + } + return version + + +def _function_version_with_resolved_environments(): + version = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + version["runtime"] = json.loads( + normalize_score.registration_request.runtime.to_canonical_json() + ) + version["resolved_environments"] = { + "linux/amd64": { + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple", + } + ], + "warnings": ["amd64 environment warning"], + }, + "linux/arm64": { + "packages": [], + "warnings": ["arm64 environment warning"], + }, + } + return version + + def test_scalar_function_matches_shared_registration_golden_and_remains_callable(): assert isinstance(normalize_score, FunctionDefinition) assert normalize_score(25.0) == 0.25 @@ -98,6 +156,118 @@ def test_scalar_function_matches_shared_registration_golden_and_remains_callable } +def test_refresh_lock_is_a_registration_option_not_part_of_identity(): + default = normalize_score.registration_request + old_json = default.to_canonical_json() + assert "refresh_lock" not in json.loads(old_json) + + refreshed = default.with_refresh_lock(True) + payload = json.loads(refreshed.to_canonical_json()) + assert payload["refresh_lock"] is True + assert ( + FunctionRegistrationRequest.from_json( + refreshed.to_canonical_json() + ).refresh_lock + is True + ) + assert refreshed.artifact.digest == default.artifact.digest + assert refreshed.runtime.digest == default.runtime.digest + assert default.with_refresh_lock(False).to_canonical_json() == old_json + with pytest.raises(ValueError, match="refresh_lock must be a boolean"): + default.with_refresh_lock(1) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("exist_ok", [False, True]) +async def test_async_create_function_forwards_refresh_lock(exist_ok): + calls = [] + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + calls.append((json.loads(request_json), namespace_path, exist_ok)) + return object() + + connection = object.__new__(AsyncConnection) + connection._inner = Inner() + await connection.create_function_async(normalize_score) + await connection.create_function_async( + normalize_score, refresh_lock=True, exist_ok=exist_ok, namespace_path=["team"] + ) + with pytest.raises(ValueError, match="refresh_lock must be a boolean"): + await connection.create_function_async(normalize_score, refresh_lock=1) + + assert len(calls) == 2 + assert "refresh_lock" not in calls[0][0] + assert calls[0][1:] == (None, False) + assert calls[1][0]["refresh_lock"] is True + assert calls[1][1:] == (["team"], exist_ok) + + +@pytest.mark.parametrize("exist_ok", [False, True]) +def test_sync_create_function_paths_forward_refresh_lock(exist_ok): + calls = [] + + class AsyncInner: + async def create_function_async( + self, + definition, + *, + secrets=None, + exist_ok=False, + namespace_path=None, + refresh_lock=False, + ): + calls.append(("wrapped", refresh_lock, namespace_path, exist_ok)) + return object() + + for connection_type in (LanceDBConnection, RemoteDBConnection): + connection = object.__new__(connection_type) + connection._conn = AsyncInner() + connection.create_function_async( + normalize_score, + refresh_lock=True, + exist_ok=exist_ok, + namespace_path=["team"], + ) + + class BlockingConnection: + def create_function_async( + self, + definition, + *, + secrets=None, + exist_ok=False, + namespace_path=None, + refresh_lock=False, + ): + calls.append(("blocking", refresh_lock, namespace_path, exist_ok)) + + class ImmediateJob: + def wait(self): + return "version" + + return ImmediateJob() + + blocking = BlockingConnection() + assert ( + DBConnection.create_function( + blocking, + normalize_score, + refresh_lock=True, + exist_ok=exist_ok, + namespace_path=["team"], + ) + == "version" + ) + assert calls == [ + ("wrapped", True, ["team"], exist_ok), + ("wrapped", True, ["team"], exist_ok), + ("blocking", True, ["team"], exist_ok), + ] + + def test_function_declares_pinned_hugging_face_models(): model = HuggingFaceModel( repo="sentence-transformers/all-MiniLM-L6-v2", @@ -2205,6 +2375,205 @@ class _RawFunctionCatalog: return None +def test_function_version_reads_requested_and_resolved_environments(): + legacy = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + legacy_version = FunctionVersion.from_json(json.dumps(legacy)) + assert legacy_version.runtime is None + assert legacy_version.resolved_environment is None + assert legacy_version.environment.requested is None + assert legacy_version.environment.resolved is None + + payload = _function_version_with_resolved_environment() + version = FunctionVersion.from_json(json.dumps(payload)) + assert version.environment.requested is version.runtime + assert version.environment.resolved is version.resolved_environment + assert version.runtime.kind == "python" + resolved = version.resolved_environment + assert resolved.packages[0].version == "2.9.0+cu130" + assert resolved.packages[0].source == "https://packages.example/simple" + assert resolved.packages[1].source is None + assert resolved.provenance.torch_version == "torch==2.9.0+cu130" + assert resolved.warnings == tuple(payload["resolved_environment"]["warnings"]) + + encoded = json.loads(version.to_canonical_json()) + assert encoded["runtime"]["kind"] == "python" + assert encoded["resolved_environment"]["packages"][0]["version"] == "2.9.0+cu130" + assert "source" not in encoded["resolved_environment"]["packages"][1] + assert ( + encoded["resolved_environment"]["provenance"]["torch_version"] + == "torch==2.9.0+cu130" + ) + assert FunctionVersion.from_json(version.to_canonical_json()) == version + + invalid = json.loads(json.dumps(payload)) + del invalid["resolved_environment"]["packages"] + with pytest.raises(ValueError): + FunctionVersion.from_json(json.dumps(invalid)) + + +def test_function_version_reads_resolved_environments_by_platform(): + legacy = json.loads( + (FIXTURES / "remote_function_version.canonical.json").read_text() + ) + legacy_version = FunctionVersion.from_json(json.dumps(legacy)) + assert legacy_version.resolved_environment is None + assert legacy_version.resolved_environments == {} + assert legacy_version.environment_report == {} + + payload = _function_version_with_resolved_environments() + version = FunctionVersion.from_json(json.dumps(payload)) + assert version.resolved_environment is None + assert version.resolved_environments == version.environment_report + assert set(version.environment_report) == {"linux/amd64", "linux/arm64"} + assert ( + version.environment_report["linux/amd64"].packages[0].version == "2.9.0+cu130" + ) + assert version.environment_report["linux/arm64"].packages == () + assert version.environment_report["linux/arm64"].warnings == ( + "arm64 environment warning", + ) + + encoded = json.loads(version.to_canonical_json()) + assert "resolved_environment" not in encoded + assert ( + encoded["resolved_environments"]["linux/amd64"]["packages"][0]["version"] + == "2.9.0+cu130" + ) + assert encoded["resolved_environments"]["linux/arm64"]["packages"] == [] + assert FunctionVersion.from_json(version.to_canonical_json()) == version + + missing_platform = json.loads(json.dumps(payload)) + del missing_platform["resolved_environments"]["linux/arm64"] + missing_version = FunctionVersion.from_json(json.dumps(missing_platform)) + assert "linux/arm64" not in missing_version.environment_report + assert "linux/amd64" in missing_version.environment_report + + empty_map = json.loads(json.dumps(payload)) + empty_map["resolved_environments"] = {} + empty_version = FunctionVersion.from_json(json.dumps(empty_map)) + assert empty_version.resolved_environments == {} + assert "resolved_environments" not in json.loads(empty_version.to_canonical_json()) + + invalid = json.loads(json.dumps(payload)) + del invalid["resolved_environments"]["linux/amd64"]["packages"] + with pytest.raises(ValueError): + FunctionVersion.from_json(json.dumps(invalid)) + + +@pytest.mark.asyncio +async def test_registration_job_emits_server_environment_warnings_once(): + payload = _function_version_with_resolved_environment() + + class InnerJob: + async def wait(self): + return json.dumps(payload) + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + assert "refresh_lock" not in json.loads(request_json) + return InnerJob() + + connection = object.__new__(AsyncConnection) + connection._inner = Inner() + job = await connection.create_function_async(normalize_score) + with pytest.warns(UserWarning) as recorded: + version = await job.wait() + assert [str(w.message) for w in recorded] == list( + payload["resolved_environment"]["warnings"] + ) + assert version.environment.resolved.warnings == tuple( + payload["resolved_environment"]["warnings"] + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert await job.wait() is not None + assert caught == [] + + +@pytest.mark.asyncio +async def test_registration_job_emits_per_platform_environment_warnings(): + payload = _function_version_with_resolved_environments() + + class InnerJob: + async def wait(self): + return json.dumps(payload) + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + return InnerJob() + + connection = object.__new__(AsyncConnection) + connection._inner = Inner() + job = await connection.create_function_async(normalize_score) + with pytest.warns(UserWarning) as recorded: + version = await job.wait() + assert [str(w.message) for w in recorded] == [ + "amd64 environment warning", + "arm64 environment warning", + ] + assert version.environment_report["linux/arm64"].warnings == ( + "arm64 environment warning", + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert await job.wait() is not None + assert caught == [] + + +def test_blocking_create_function_emits_server_environment_warnings(): + payload = _function_version_with_resolved_environment() + + class InnerJob: + async def wait(self): + return json.dumps(payload) + + class Inner: + async def create_function_async( + self, request_json, namespace_path=None, *, exist_ok=False + ): + return InnerJob() + + connection = object.__new__(RemoteDBConnection) + connection._conn = AsyncConnection(Inner()) + with pytest.warns(UserWarning) as recorded: + version = DBConnection.create_function(connection, normalize_score) + assert [str(w.message) for w in recorded] == list( + payload["resolved_environment"]["warnings"] + ) + assert version.environment.resolved.packages[0].version == "2.9.0+cu130" + + +@pytest.mark.asyncio +async def test_catalog_readback_does_not_replay_registration_warnings(): + payload = _function_version_with_resolved_environment() + connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True)) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + version = await connection.get_function("embed") + listed = [item async for item in connection.list_functions()] + assert caught == [] + assert version.environment.resolved.packages[0].version == "2.9.0+cu130" + assert listed[0].environment.resolved == version.resolved_environment + + +@pytest.mark.asyncio +async def test_catalog_readback_does_not_replay_per_platform_warnings(): + payload = _function_version_with_resolved_environments() + connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True)) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + version = await connection.get_function("embed") + listed = [item async for item in connection.list_functions()] + assert caught == [] + assert version.environment_report == listed[0].environment_report + + def _assert_execution_control_encoding(version): encoded = json.loads(version.to_canonical_json()) assert type(encoded["batch_size"]) is int diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 582b5b08a..d0ef6570d 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -521,6 +521,59 @@ pub struct HuggingFaceModel { pub revision: String, } +/// One installed Python distribution as measured from a Function's baked +/// environment. +/// +/// `version` is the complete version string reported by the package metadata, +/// including local labels such as `+cu130`. `source` is present only when the +/// submitted lock retained a per-package source; a missing value is unknown and +/// must not be inferred from other package indexes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedPackage { + pub name: String, + pub version: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +/// Sanitized source and accelerator provenance retained with a resolved +/// environment. +/// +/// `configured_*` records what the build was asked to use. `resolved_indexes` +/// records indexes visible in the submitted lock, so a configured source is +/// not mistaken for evidence that a package came from it. Empty lists and +/// absent fields remain absent rather than being synthesized by the client. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironmentProvenance { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_index_urls: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_find_links: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub resolved_indexes: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cuda_toolkit: Option, + /// The fully resolved `torch==` when torch was installed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub torch_version: Option, +} + +/// Actual installed distributions and registration warnings for one native +/// Function environment. +/// +/// A missing environment means its measurement is unknown, not an empty +/// installed-package list. The field keeps the complete versions and only the +/// provenance the producer recorded; SDK readers do not recompute package +/// policy. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironment { + pub packages: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provenance: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + /// A complete OCI Function image. Its digest is independent of catalog names. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionImage { @@ -578,7 +631,9 @@ impl<'de> Deserialize<'de> for RowTimeoutSeconds { /// decoding, but they are not part of this value and are omitted from /// canonical JSON. Known fields retain their complete values, while unknown /// fields inside the open [`FunctionImage::descriptor`] JSON object remain -/// available. +/// available. Single-platform measurements use `resolved_environment`; +/// multiarchitecture measurements use `resolved_environments`, keyed by OCI +/// `os/architecture`, without flattening the platforms. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersion { name: String, @@ -626,6 +681,28 @@ pub struct FunctionVersion { /// Result-stability value declared at registration. #[serde(default, skip_serializing_if = "Option::is_none")] result_stability: Option, + /// The runtime requested at registration, with submitted lock bytes omitted. + /// + /// This is a specification, not the measured installation. Compare it with + /// [`Self::resolved_environment`] when the caller needs actual package + /// versions. + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime: Option, + /// Actual installed distributions, provenance, and registration warnings. + /// + /// This is the single-platform compatibility field. `None` on a + /// multiarchitecture version is expected; use + /// [`Self::resolved_environments`] for its per-platform measurements. + #[serde(default, skip_serializing_if = "Option::is_none")] + resolved_environment: Option, + /// Measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// Unmeasured platforms are absent. An empty map is unknown, not an + /// aggregate of packages from the available platforms. Single-platform + /// images use [`Self::resolved_environment`] instead. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + resolved_environments: BTreeMap, } impl FunctionVersion { @@ -716,6 +793,35 @@ impl FunctionVersion { self.result_stability.as_deref() } + /// The runtime specification requested at registration, when exposed by the + /// server. + /// + /// This is the requested configuration, not evidence of what was installed. + pub fn runtime(&self) -> Option<&PythonRuntimeSpec> { + self.runtime.as_ref() + } + + /// Actual installed distributions and registration warnings for a + /// single-platform image, when measured by the server. + /// + /// `None` is unknown, not an empty environment. Package versions are + /// retained verbatim, including local labels such as `+cu130`; `source` + /// remains absent when the producer did not retain it. + pub fn resolved_environment(&self) -> Option<&ResolvedEnvironment> { + self.resolved_environment.as_ref() + } + + /// Per-platform measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// The map is returned without flattening or synthesis. A missing platform + /// means its measurement is unknown; an empty environment value is a + /// measured empty environment and is retained. Single-platform images use + /// [`Self::resolved_environment`] instead. + pub fn resolved_environments(&self) -> &BTreeMap { + &self.resolved_environments + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } @@ -827,6 +933,10 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s Ok(()) } +fn is_false(value: &bool) -> bool { + !*value +} + /// Stable request envelope for remote immutable Function registration. /// /// Credential values deliberately have no field here. The only secret-shaped @@ -877,10 +987,10 @@ pub struct FunctionRegistrationRequest { /// Model snapshots prepared by the service before user code runs. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, -} - -fn is_false(value: &bool) -> bool { - !*value + /// Ask the service to resolve a fresh environment lock for this request + /// instead of reusing the published version's lock. Omitted when false. + #[serde(default, skip_serializing_if = "is_false")] + pub refresh_lock: bool, } impl FunctionRegistrationRequest { @@ -1465,6 +1575,165 @@ mod tests { assert!(FunctionVersion::from_json(&document.to_string()).is_err()); } + #[test] + fn function_version_preserves_requested_and_resolved_environments() { + 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!(legacy.runtime().is_none()); + assert!(legacy.resolved_environment().is_none()); + assert!(legacy.resolved_environments().is_empty()); + + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environment"] = serde_json::json!({ + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + }, + { + "name": "transformers", + "version": "4.57.1" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": ["https://downloads.example/wheels"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it." + ] + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime().unwrap().kind(), "python"); + assert!(version.resolved_environments().is_empty()); + let resolved = version.resolved_environment().unwrap(); + assert_eq!(resolved.packages[0].version, "2.9.0+cu130"); + assert_eq!( + resolved.packages[0].source.as_deref(), + Some("https://packages.example/simple") + ); + assert_eq!(resolved.packages[1].source, None); + assert_eq!( + resolved + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(resolved.warnings.len(), 1); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert_eq!( + encoded_value["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + encoded_value["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environment"] = serde_json::json!({"warnings": []}); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + + #[test] + fn function_version_preserves_resolved_environments_by_platform() { + 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(); + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [ + {"name": "torch", "version": "2.9.0+cu130"} + ], + "warnings": ["amd64 measurement"] + }, + "linux/arm64": { + "packages": [], + "warnings": ["arm64 measurement"] + } + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(version.resolved_environment().is_none()); + let environments = version.resolved_environments(); + assert_eq!(environments.len(), 2); + assert_eq!( + environments["linux/amd64"].packages[0].version, + "2.9.0+cu130" + ); + assert!(environments["linux/arm64"].packages.is_empty()); + assert_eq!(environments["linux/arm64"].warnings, ["arm64 measurement"]); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert!(encoded_value.get("resolved_environment").is_none()); + assert_eq!( + encoded_value["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + encoded_value["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environments"] + .as_object_mut() + .unwrap() + .remove("linux/arm64"); + let missing_platform = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!( + !missing_platform + .resolved_environments() + .contains_key("linux/arm64") + ); + + document["resolved_environments"] = serde_json::json!({}); + let empty_map = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(empty_map.resolved_environments().is_empty()); + assert!( + !empty_map + .to_canonical_json() + .unwrap() + .contains("resolved_environments") + ); + + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": {"warnings": []} + }); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + #[test] fn blob_reader_access_survives_signature_round_trip() { let parameter: FunctionParameter = serde_json::from_value(serde_json::json!({ diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 1c39eda19..5c7ae7673 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3171,6 +3171,38 @@ async fn function_creation_and_description_use_sql_query_handles() { version_json["max_concurrency"] = serde_json::json!(4); version_json["row_timeout_seconds"] = serde_json::json!(8.0); version_json["result_stability"] = serde_json::json!("input_and_context"); + version_json["runtime"] = request_json["runtime"].clone(); + version_json["resolved_environment"] = serde_json::json!({ + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + }, + { + "name": "transformers", + "version": "4.57.1" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "configured_find_links": [], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it." + ] + }); + version_json["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [{"name": "torch", "version": "2.9.0+cu130"}] + }, + "linux/arm64": { + "packages": [] + } + }); if with_models { let models = serde_json::json!([{ "repo": "sentence-transformers/all-MiniLM-L6-v2", @@ -3217,6 +3249,17 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created.max_concurrency(), Some(4)); assert_eq!(created.row_timeout_seconds(), Some(8.0)); assert_eq!(created.result_stability(), Some("input_and_context")); + assert_eq!(created.runtime().unwrap().kind(), "python"); + assert_eq!( + created.resolved_environment().unwrap().packages[0].version, + "2.9.0+cu130" + ); + assert_eq!(created.resolved_environments().len(), 2); + assert!( + created.resolved_environments()["linux/arm64"] + .packages + .is_empty() + ); // Assert the actual SQL body, after the same native JSON decode used // by the Python binding, rather than only the Python declaration. { @@ -3240,6 +3283,23 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created_json["max_concurrency"], 4); assert_eq!(created_json["row_timeout_seconds"], 8.0); assert_eq!(created_json["result_stability"], "input_and_context"); + assert_eq!( + created_json["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + created_json["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!( + created_json["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + created_json["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); assert_eq!( client.describe(id).await.unwrap().status, QueryStatus::Finished @@ -3253,6 +3313,19 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(described.max_concurrency(), Some(4)); assert_eq!(described.row_timeout_seconds(), Some(8.0)); assert_eq!(described.result_stability(), Some("input_and_context")); + assert_eq!(described.runtime().unwrap().kind(), "python"); + assert_eq!( + described + .resolved_environment() + .unwrap() + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(described.resolved_environments().len(), 2); let described_json: serde_json::Value = serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap(); assert_eq!(described_json["image"].get("models"), expected_models); @@ -3279,6 +3352,16 @@ async fn function_creation_and_description_use_sql_query_handles() { listed.items[0].result_stability(), Some("input_and_context") ); + assert_eq!(listed.items[0].runtime().unwrap().kind(), "python"); + assert_eq!( + listed.items[0] + .resolved_environment() + .unwrap() + .warnings + .len(), + 1 + ); + assert_eq!(listed.items[0].resolved_environments().len(), 2); let listed_json: serde_json::Value = serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap(); assert_eq!(listed_json["image"].get("models"), expected_models); @@ -3293,6 +3376,58 @@ async fn function_creation_and_description_use_sql_query_handles() { } } +#[tokio::test] +async fn function_creation_refresh_lock_is_forwarded_only_when_true() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + const REQUEST: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" + ); + for (refresh_lock, expect_field) in [(false, false), (true, true)] { + let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + if refresh_lock { + request_json["refresh_lock"] = serde_json::json!(true); + } + let request = + crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) + .unwrap(); + assert_eq!(request.refresh_lock, refresh_lock); + let result = RecordBatch::try_from_iter(vec![( + "definition", + Arc::new(StringArray::from(vec![VERSION.to_string()])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: false, + result, + ..Default::default() + }; + let statements = service.statements.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.create_function_async(request, &[]).await.unwrap(); + job.wait().await.unwrap(); + let seen = statements.lock().unwrap(); + let encoded = seen[0] + .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .unwrap() + .strip_suffix('\'') + .unwrap(); + let sent: serde_json::Value = serde_json::from_str(&encoded.replace("''", "'")).unwrap(); + assert_eq!(sent.get("refresh_lock").is_some(), expect_field); + if expect_field { + assert_eq!(sent["refresh_lock"], serde_json::json!(true)); + } + drop(seen); + shutdown.send(()).unwrap(); + } +} + #[tokio::test] async fn function_creation_rejects_invalid_execution_controls_before_sql() { const REQUEST: &str = include_str!( From dc9eb269b15bae731e3d99ddcf67f61723fc703c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:30:47 +0800 Subject: [PATCH 129/203] feat(python): support map and decimal Function signatures (#5031) Python Function declarations reject Arrow map and decimal types before registration. Accept `dict[str, T]`, nullable map values, explicit Arrow maps, and `Annotated[Decimal, pa.decimal128/256(...)]` using the existing canonical JSON representation. Preserve map key/value nullability and decimal precision/scale; reject unsupported map keys, sorted maps, nested Blob values, and a bare Decimal without precision/scale. This is the SDK map/decimal portion of ENT-3414. Server validation and SQL support are separate changes; older servers can still reject these signatures. Nullable scalar output support remains separate in #5030. Validation: 129 Function signature tests passed; 30 documentation tests passed with one existing skip. Ruff format/lint and diff checks passed. Python tests used the existing Python 3.13 environment and prebuilt native extension with this Python source overlaid; no Rust build or remote-server execution was performed. --- docs/web/management/function.mdx | 40 +++++ python/python/lancedb/functions.py | 85 ++++++++-- .../tests/test_first_class_function_slice2.py | 153 +++++++++++++++++- 3 files changed, 267 insertions(+), 11 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index efcbcc799..41e47dee1 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -139,6 +139,46 @@ compound temporal representation cannot read those signatures. A deployment must include the corresponding Lance Namespace and Sophon support; this client-side declaration does not add server support. +### Maps and decimals {#maps-decimals} + +A `dict[str, T]` annotation declares an Arrow map with a non-nullable `utf8` +key. A plain `T` value is non-nullable; annotate `dict[str, Optional[T]]` for +nullable values. An explicit `pa.map_(...)` schema preserves the value field's +own `nullable` flag: + +```python +@function +def word_counts(text: str) -> dict[str, int]: + ... +``` + +Map keys must be non-nullable `utf8`; `keys_sorted=True` is not supported, and +Blob v2 values inside a map are not supported. + +`Decimal` carries no precision or scale by itself, so a bare `Decimal` +annotation is rejected. Declare both explicitly with `Annotated`, or use an +explicit Arrow schema: + +```python +from decimal import Decimal +from typing import Annotated + +import pyarrow as pa + + +@function +def add_tax( + amount: Annotated[Decimal, pa.decimal128(12, 2)], +) -> Annotated[Decimal, pa.decimal128(12, 2)]: + ... +``` + +`decimal128` and `decimal256` keep the declared precision and scale in the +canonical signature; no default is chosen. Map and decimal signatures are sent +as canonical Arrow JSON. A deployment must support those types; an older +Enterprise server may reject the registration, and this client-side +declaration does not add server support. + ## Connect and create a table {#table} The remaining steps run against your Enterprise deployment. Replace the database diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index ecbc697d1..548129211 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -30,6 +30,7 @@ import types import warnings from collections.abc import Mapping, Sequence from datetime import date, datetime, timedelta +from decimal import Decimal from pathlib import Path from typing import ( Annotated, @@ -1378,6 +1379,13 @@ def _exact_arrow_type( for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return {"type": name} + if pa.types.is_decimal128(data_type) or pa.types.is_decimal256(data_type): + return { + "type": ( + "decimal128" if pa.types.is_decimal128(data_type) else "decimal256" + ), + "length": data_type.precision * 1000 + data_type.scale, + } if pa.types.is_timestamp(data_type): unit = data_type.unit if unit not in _FUNCTION_TIMEUNITS: @@ -1453,8 +1461,29 @@ def _exact_arrow_type( if pa.types.is_fixed_size_list(data_type): value["length"] = data_type.list_size return value - if pa.types.is_map(data_type) and _data_type_has_blob_v2(data_type): - raise TypeError(_NESTED_BLOB_COLLECTION_ERROR) + if pa.types.is_map(data_type): + if data_type.keys_sorted: + raise TypeError( + "unsupported Arrow type for Function signature: map keys_sorted=true " + "is not supported" + ) + key_field = data_type.key_field + if key_field.nullable or key_field.type != pa.string(): + raise TypeError( + "unsupported Arrow type for Function signature: map keys must be " + "non-nullable utf8" + ) + if _data_type_has_blob_v2(data_type): + raise TypeError(_NESTED_BLOB_COLLECTION_ERROR) + return { + "type": "map", + "fields": [ + _exact_arrow_field( + data_type.field(0), + inside_collection=True, + ) + ], + } raise TypeError(f"unsupported Arrow type for Function signature: {data_type}") @@ -1483,9 +1512,15 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError( "Annotated Function types require exactly one PyArrow DataType" ) - # A struct value is written as a dict, and timedelta has no unit of - # its own; the Annotated metadata supplies those types. - if base is dict or get_origin(base) is dict or base is timedelta: + # A struct value is written as a dict, while Decimal and timedelta + # carry no precision or unit of their own; the Annotated metadata + # supplies those types. + if ( + base is dict + or get_origin(base) is dict + or base is Decimal + or base is timedelta + ): base_nullable = False else: _, base_nullable = _annotation_type(base) @@ -1514,6 +1549,13 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: # Existing default: microsecond precision, no timezone. Other units # and timezones require Annotated or an explicit schema. return pa.timestamp("us"), nullable + if annotation is Decimal: + raise TypeError( + "Decimal Function annotations require precision and scale; use " + "Annotated[Decimal, pyarrow.decimal128(precision, scale)], " + "Annotated[Decimal, pyarrow.decimal256(precision, scale)], or an " + "explicit schema" + ) if annotation is timedelta: raise TypeError( "timedelta Function annotations require an explicit unit; use " @@ -1527,6 +1569,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: if value_nullable: raise TypeError("nullable Function list elements are not supported") return _list_of(value_type), nullable + if get_origin(annotation) is dict: + arguments = get_args(annotation) + if len(arguments) != 2: + raise TypeError(f"unsupported dict annotation: {annotation!r}") + key_type, value_annotation = arguments + if key_type is not str: + raise TypeError("Function map keys must be str") + value_type, value_nullable = _annotation_type(value_annotation) + return ( + pa.map_( + pa.string(), + pa.field("value", value_type, nullable=value_nullable), + ), + nullable, + ) raise TypeError(f"unsupported Function annotation: {annotation!r}") @@ -2847,7 +2904,13 @@ def function( deployment must accept nullable scalar outputs; an older server rejects the registration. Every named-struct field may be nullable; Enterprise preserves the struct's validity when the result is expanded into sibling - columns. Bare ``datetime`` keeps its existing ``timestamp[us]`` default + columns. + ``dict[str, T]`` declares an Arrow map with a non-nullable utf8 key; the + value is non-nullable for ``T`` and nullable for ``Optional[T]``. A bare + ``Decimal`` has no precision or scale; use + ``Annotated[Decimal, pyarrow.decimal128(precision, scale)]``, + ``Annotated[Decimal, pyarrow.decimal256(precision, scale)]``, or an + explicit schema. Bare ``datetime`` keeps its existing ``timestamp[us]`` default without a timezone; other units and timezones require ``Annotated[datetime, pyarrow.timestamp(unit, tz=...)]`` or an explicit schema. A bare ``timedelta`` has no unit and is rejected; use @@ -2958,10 +3021,12 @@ def function( output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional Explicit scalar or named-struct output. A scalar field's ``nullable`` flag is preserved; a top-level named-struct field and a Blob v2 output - must be non-nullable. Temporal fields use canonical Arrow JSON; the - microsecond/no-timezone case keeps the legacy timestamp/duration - shape. Required for batch annotations. When omitted, the output is - inferred from the return annotation. + must be non-nullable. Map and decimal fields use canonical Arrow JSON; + a map key must be non-nullable utf8 and its value field keeps the + declared nullability. Temporal fields use canonical Arrow JSON; the + microsecond/no-timezone case keeps the legacy timestamp/duration shape. + 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. Syntax is validated at decoration time, including extras and environment markers. Named direct diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 6dcc0bbbe..dbc574e88 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -19,6 +19,7 @@ import sys import typing import urllib.parse import warnings +from decimal import Decimal from typing import Annotated, Optional import pyarrow as pa @@ -1054,7 +1055,6 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): == "large_list" ) for outside in [ - pa.decimal128(10, 2), pa.binary(4), pa.time32("s"), pa.time64("us"), @@ -1531,6 +1531,157 @@ def test_duration_annotation_and_explicit_schema_serialization(): assert explicit_round_trip.output.arrow_type == '{"type":"duration"}' +def test_map_annotation_and_explicit_schema_serialization(): + @function + def map_round_trip(values: dict[str, int]) -> dict[str, int]: + return values + + signature = map_round_trip.registration_request.signature + expected = { + "type": "map", + "fields": [ + { + "name": "entries", + "nullable": False, + "type": { + "type": "struct", + "fields": [ + { + "name": "key", + "nullable": False, + "type": {"type": "utf8"}, + }, + { + "name": "value", + "nullable": False, + "type": {"type": "int64"}, + }, + ], + }, + } + ], + } + assert json.loads(signature.inputs[0].arrow_type) == expected + assert json.loads(signature.output.arrow_type) == expected + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + + @function + def nullable_values( + values: dict[str, Optional[int]], + ) -> dict[str, Optional[int]]: + return values + + nullable_signature = nullable_values.registration_request.signature + nullable_map = json.loads(nullable_signature.inputs[0].arrow_type) + assert nullable_map["fields"][0]["type"]["fields"][1] == { + "name": "value", + "nullable": True, + "type": {"type": "int64"}, + } + + input_schema = pa.schema( + [ + pa.field( + "values", + pa.map_(pa.string(), pa.field("custom", pa.int64(), nullable=True)), + nullable=False, + ) + ] + ) + output_schema = pa.field( + "result", + pa.map_(pa.string(), pa.field("value", pa.int64(), nullable=False)), + nullable=False, + ) + + @function(input_schema=input_schema, output_schema=output_schema) + def explicit(values): + return {} + + explicit_signature = explicit.registration_request.signature + explicit_input = json.loads(explicit_signature.inputs[0].arrow_type) + assert explicit_input["fields"][0]["type"]["fields"][1] == { + "name": "custom", + "nullable": True, + "type": {"type": "int64"}, + } + explicit_output = json.loads(explicit_signature.output.arrow_type) + assert explicit_output["fields"][0]["type"]["fields"][1]["nullable"] is False + + +def test_map_rejects_unsupported_boundaries(): + with pytest.raises(TypeError, match="map keys_sorted=true"): + _canonical_arrow_type(pa.map_(pa.string(), pa.int64(), keys_sorted=True)) + with pytest.raises(TypeError, match="map keys must be non-nullable utf8"): + _canonical_arrow_type(pa.map_(pa.int64(), pa.int64())) + with pytest.raises(TypeError, match="Blob v2 fields nested under"): + _canonical_arrow_type(pa.map_(pa.string(), lancedb.blob("image").type)) + with pytest.raises(TypeError, match="map keys must be str"): + + @function + def invalid_keys(values: dict[int, int]) -> int: + return 0 + + +def test_decimal_annotation_and_explicit_schema_serialization(): + @function + def price( + amount: Annotated[Decimal, pa.decimal128(10, 2)], + ) -> Annotated[Decimal, pa.decimal256(50, 4)]: + return Decimal("1.0000") + + signature = price.registration_request.signature + assert json.loads(signature.inputs[0].arrow_type) == { + "type": "decimal128", + "length": 10002, + } + assert json.loads(signature.output.arrow_type) == { + "type": "decimal256", + "length": 50004, + } + round_trip = FunctionSignature.from_json(signature.to_canonical_json()) + assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type + assert round_trip.output.arrow_type == signature.output.arrow_type + assert json.loads(_canonical_arrow_type(pa.decimal128(10, -2))) == { + "type": "decimal128", + "length": 9998, + } + decimal_map = json.loads( + _canonical_arrow_type(pa.map_(pa.string(), pa.decimal128(10, 2))) + ) + assert decimal_map["fields"][0]["type"]["fields"][1]["type"] == { + "type": "decimal128", + "length": 10002, + } + + input_schema = pa.schema([pa.field("amount", pa.decimal128(12, 2), nullable=False)]) + output_schema = pa.field("result", pa.decimal256(60, 6), nullable=False) + + @function(input_schema=input_schema, output_schema=output_schema) + def explicit(amount: Decimal) -> Decimal: + return amount + + explicit_signature = explicit.registration_request.signature + assert json.loads(explicit_signature.inputs[0].arrow_type) == { + "type": "decimal128", + "length": 12002, + } + assert json.loads(explicit_signature.output.arrow_type) == { + "type": "decimal256", + "length": 60006, + } + + with pytest.raises( + TypeError, match="Decimal Function annotations require precision and scale" + ): + + @function + def missing(amount: Decimal) -> Decimal: + return amount + + def test_nullable_scalar_output_annotation_and_explicit_schema(): input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)]) From e2f836da99deacb6b1a3a9ca7acc1222e7d39d3f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:43:56 +0800 Subject: [PATCH 130/203] feat: expose per-call merge retry controls in Python and Node (#5015) Python and Node callers could not disable precommit retries for one merge without changing the connection. Add `execute(..., retries=0)` for Python sync/async and `execute(data, { retries: 0 })` for TypeScript, forwarding into the existing Rust control without persisting the override. Ambiguous 5xx outcomes remain non-replayable; permitted merge retries now log status and attempt at WARN, and the API docs explain retry budgets and timeout boundaries. Validation at `6001300` passed 70 Python HTTP cases, 36 Node HTTP cases, 14 local merge regressions per binding, and 34 scoped Rust tests, with rebuilt native extensions, TypeScript compilation, Clippy, scoped formatting/lint, and generated API docs. The public API and feature diff are unchanged after integrating main and the reviewed ingestion guide; that binding evidence is retained. Focused merged-tree validation additionally passed 267 Rust merge/retry/provenance cases and the CI fixtures. Existing root Ruff issues in docs/web-tests remain; local fixtures do not establish live proxy/server cancellation behavior. Refs #4256 and OSS-2370. --- .../js/interfaces/WriteExecutionOptions.md | 23 +++ docs/web/ingestion/merge-insert.mdx | 7 + nodejs/__test__/remote.test.ts | 157 +++++++++++++++++ nodejs/__test__/table.test.ts | 3 +- nodejs/lancedb/merge.ts | 28 +++- nodejs/src/merge.rs | 9 +- python/python/lancedb/_lancedb.pyi | 6 + python/python/lancedb/merge.py | 23 ++- python/python/lancedb/remote/table.py | 3 +- python/python/lancedb/table.py | 6 +- python/python/tests/test_remote_db.py | 158 ++++++++++++++++++ python/python/tests/test_table.py | 5 +- python/src/table.rs | 5 + rust/lancedb/src/remote/table.rs | 10 ++ 14 files changed, 433 insertions(+), 10 deletions(-) diff --git a/docs/src/js/interfaces/WriteExecutionOptions.md b/docs/src/js/interfaces/WriteExecutionOptions.md index 0ca796b6b..9c9be4489 100644 --- a/docs/src/js/interfaces/WriteExecutionOptions.md +++ b/docs/src/js/interfaces/WriteExecutionOptions.md @@ -8,6 +8,26 @@ ## Properties +### retries? + +```ts +optional retries: number; +``` + +Override the remote retry budget for this execution only (an integer from +0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after +precommit conflicts (409) or rate limits (429). This does not change +connection-wide/read budgets or local transaction conflict retries. + +By default, remote calls use the connection's `clientConfig.retryConfig` +([RetryConfig](RetryConfig.md)). Its `statuses` (also set through +`LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget; +it never permits replay of ambiguous merge outcomes. In particular, 502, +ordinary 503, and 504 are never replayed, even if configured. Reconcile table +contents before manually repeating a merge whose commit outcome is unknown. + +*** + ### timeoutMs? ```ts @@ -24,3 +44,6 @@ the second attempt will be cancelled after 10 seconds, hitting the first attempt will not be cancelled. When this is set, the timeout is enforced on all attempts, including the first. +For remote tables this is sent as a server execution timeout. It does not +extend HTTP read or proxy idle timeouts, or prove that a failed request did +not commit. diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index 8106e7706..2d6fd8470 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -221,6 +221,13 @@ and check inserted or deleted counts when the SDK returns them. Repeating a merge is only safe when its keys, conditions and update values produce the intended result on retry. +To override the transport retry budget for one merge, pass `retries=0` to +Python's synchronous or asynchronous `builder.execute(data, retries=0)`, or +use TypeScript's `builder.execute(data, { retries: 0 })`. The override applies +only to that execution. A larger budget does not make an ambiguous 5xx result +safe to replay. See [write retry boundaries](/ingestion/insert#performance) +for the distinction between retryable failures and an unknown commit outcome. + ### Embeddings and expression predicates {#advanced} When a table uses an [embedding definition](/embedding), behavior depends on diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 3e8d5a79b..215df992d 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -542,6 +542,163 @@ describe("remote connection", () => { expect(attempts).toBe(scenario.attempts); }); + it.each( + [409, 429, 502, 503, 504].flatMap((status) => + [undefined, 0, 2].flatMap((retries) => + [[], ["analytics", "features"]].map((namespacePath) => ({ + status, + retries, + namespacePath, + })), + ), + ), + )("applies per-call merge retries: %j", async (scenario) => { + let attempts = 0; + const identifier = [...scenario.namespacePath, "items"].join("$"); + const succeeds = + [409, 429].includes(scenario.status) && scenario.retries !== 0; + await withMockDatabase( + (req, res) => { + const url = new URL(req.url ?? "", "http://localhost"); + if (url.pathname === `/v1/table/${identifier}/describe/`) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + try { + expect(url.pathname).toBe(`/v1/table/${identifier}/merge_insert/`); + expect(url.searchParams.get("use_index")).toBe("false"); + expect(req.headers["x-request-timeout-ms"]).toBe("10000"); + // Rust compresses the batches; Arrow JS can inspect the schema without a codec. + const reader = RecordBatchReader.from(Buffer.concat(chunks)).open(); + expect(reader.schema.fields.map((field) => field.name)).toEqual([ + "id", + ]); + } finally { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + } + }); + }, + async (db) => { + const table = await db.openTable("items", scenario.namespacePath); + const merge = table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .useIndex(false); + const result = merge.execute([{ id: 1n }], { + timeoutMs: 10_000, + retries: scenario.retries, + }); + if (succeeds) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [409, 429, 502, 503, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(succeeds ? 2 : 1); + }); + + it("isolates merge retry overrides across reused builders and reads", async () => { + let attempts = 0; + let readAttempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + req.resume(); + req.on("end", () => { + if (req.url?.endsWith("/count_rows/")) { + readAttempts++; + res.writeHead(readAttempts % 2 ? 429 : 200).end("1"); + } else { + attempts++; + res + .writeHead([1, 2, 4, 6].includes(attempts) ? 429 : 200) + .end('{"version":2}'); + expect(req.url).toContain("/merge_insert/"); + } + }); + }, + async (db) => { + const table = await db.openTable("items"); + const merge = table.mergeInsert("id").whenNotMatchedInsertAll(); + for (const retries of [ + -1, + 256, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + ]) { + await expect( + merge.execute([{ id: 1n }], { retries }), + ).rejects.toThrow("retries must be an integer between 0 and 255"); + } + expect(attempts).toBe(0); + await expect( + merge.execute([{ id: 1n }], { retries: 0 }), + ).rejects.toThrow(); + expect(attempts).toBe(1); + await expect(merge.execute([{ id: 1n }])).resolves.toMatchObject({ + version: 2, + }); + await expect( + merge.execute([{ id: 1n }], { retries: 255 }), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(5); + await expect(table.countRows()).resolves.toBe(1); + expect(readAttempts).toBe(2); + await expect( + table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .execute([{ id: 1n }]), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(7); + }, + { + clientConfig: { + retryConfig: { retries: 3, backoffFactor: 0, backoffJitter: 0 }, + }, + }, + ); + }); + it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index e97b32e78..99c58a8c9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -938,7 +938,8 @@ describe("merge insert", () => { .mergeInsert("a") .whenMatchedUpdateAll() .whenNotMatchedInsertAll() - .execute(newData, { timeoutMs: 10_000 }); + .useIndex(false) + .execute(newData, { timeoutMs: 10_000, retries: 0 }); expect(mergeInsertRes).toHaveProperty("version"); expect(mergeInsertRes.version).toBe(2); expect(mergeInsertRes.numInsertedRows).toBe(1); diff --git a/nodejs/lancedb/merge.ts b/nodejs/lancedb/merge.ts index 7bb36e678..7d95d4a36 100644 --- a/nodejs/lancedb/merge.ts +++ b/nodejs/lancedb/merge.ts @@ -127,6 +127,14 @@ export class MergeInsertBuilder { data: Data, execOptions?: Partial, ): Promise { + if ( + execOptions?.retries !== undefined && + (!Number.isInteger(execOptions.retries) || + execOptions.retries < 0 || + execOptions.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } let schema: Schema; if (this.#schema instanceof Promise) { schema = await this.#schema; @@ -140,7 +148,7 @@ export class MergeInsertBuilder { } const buffer = await fromDataToBuffer(data, undefined, schema); - return await this.#native.execute(buffer); + return await this.#native.execute(buffer, execOptions?.retries); } } @@ -156,6 +164,24 @@ export interface WriteExecutionOptions { * first attempt will not be cancelled. * * When this is set, the timeout is enforced on all attempts, including the first. + * For remote tables this is sent as a server execution timeout. It does not + * extend HTTP read or proxy idle timeouts, or prove that a failed request did + * not commit. */ timeoutMs?: number; + + /** + * Override the remote retry budget for this execution only (an integer from + * 0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after + * precommit conflicts (409) or rate limits (429). This does not change + * connection-wide/read budgets or local transaction conflict retries. + * + * By default, remote calls use the connection's `clientConfig.retryConfig` + * ({@link RetryConfig}). Its `statuses` (also set through + * `LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget; + * it never permits replay of ambiguous merge outcomes. In particular, 502, + * ordinary 503, and 504 are never replayed, even if configured. Reconcile table + * contents before manually repeating a merge whose commit outcome is unknown. + */ + retries?: number; } diff --git a/nodejs/src/merge.rs b/nodejs/src/merge.rs index ccff2a689..86901c04f 100644 --- a/nodejs/src/merge.rs +++ b/nodejs/src/merge.rs @@ -65,12 +65,17 @@ impl NativeMergeInsertBuilder { } #[napi(catch_unwind)] - pub async fn execute(&self, buf: Buffer) -> napi::Result { + pub async fn execute(&self, buf: Buffer, retries: Option) -> napi::Result { let data = ipc_file_to_batches(buf.to_vec()).map_err(|e| { napi::Error::from_reason(format!("Failed to read IPC file: {}", convert_error(&e))) })?; - let this = self.clone(); + let mut this = self.clone(); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + this.inner.retries(retries); + } let res = this.inner.execute(data).await.map_err(|e| { napi::Error::from_reason(format!( diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a87b82a21..a86bae9d5 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -565,6 +565,12 @@ class Table: allow_external_blob_outside_bases: bool = False, retries: Optional[int] = None, ) -> AddResult: ... + async def execute_merge_insert( + self, + data: pa.RecordBatchReader, + parameters: Dict[str, Any], + retries: Optional[int] = None, + ) -> MergeResult: ... async def update( self, updates: Dict[str, str], where: Optional[str] ) -> UpdateResult: ... diff --git a/python/python/lancedb/merge.py b/python/python/lancedb/merge.py index 49f4793ed..c861414aa 100644 --- a/python/python/lancedb/merge.py +++ b/python/python/lancedb/merge.py @@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object): on_bad_vectors: str = "error", fill_value: float = 0.0, timeout: Optional[timedelta] = None, + *, + retries: Optional[int] = None, ) -> MergeInsertResult: """ Executes the merge insert operation @@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object): first attempt will not be cancelled. When this is set, the timeout is enforced on all attempts, including - the first. + the first. For remote tables it is sent as a server execution timeout; + it does not extend HTTP read or proxy idle timeouts, or prove that a + failed request did not commit. + retries: int, optional + Override the remote retry budget for this execution only (0 to 255). + Use ``execute(new_data, retries=0)`` to disable even retries after + precommit conflicts (409) or rate limits (429). This does not change + connection-wide/read budgets or local transaction conflict retries. + + By default, remote calls use the connection's + [RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set + through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within + the retry budget; it never permits replay of ambiguous merge outcomes. + In particular, 502, ordinary 503, and 504 are never replayed, even if + configured. Reconcile table contents before manually repeating a merge + whose commit outcome is unknown. Returns ------- @@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object): """ if timeout is not None: self._timeout = timeout - return self._table._do_merge(self, new_data, on_bad_vectors, fill_value) + return self._table._do_merge( + self, new_data, on_bad_vectors, fill_value, retries=retries + ) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index b5d97eb62..818d2a257 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -945,9 +945,10 @@ class RemoteTable(Table): new_data: DATA, on_bad_vectors: str, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: return LOOP.run( - self._table._do_merge(merge, new_data, on_bad_vectors, fill_value) + self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries) ) @_deprecated_keyword("predicate", "where") diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 45b2eb4f6..4a713da06 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2810,6 +2810,7 @@ class Table(ABC): new_data: DATA, on_bad_vectors: OnBadVectorsType, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: ... @abstractmethod @@ -5443,9 +5444,10 @@ class LanceTable(Table): new_data: DATA, on_bad_vectors: OnBadVectorsType, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: return LOOP.run( - self._table._do_merge(merge, new_data, on_bad_vectors, fill_value) + self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries) ) @property @@ -7777,6 +7779,7 @@ class AsyncTable: new_data: DATA, on_bad_vectors: OnBadVectorsType, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: schema = await self.schema() if on_bad_vectors is None: @@ -7808,6 +7811,7 @@ class AsyncTable: use_rte=merge._use_rte, validate_single_shard=merge._validate_single_shard, ), + retries=retries, ) async def delete(self, where: Union[str, Expr]) -> DeleteResult: diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index fc5b5df73..f404e36f7 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -310,6 +310,164 @@ async def test_add_retry_override(sync_api, retries, status): assert attempts == (2 if expected_success else 1) +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "features"]]) +@pytest.mark.parametrize("retries", [None, 0, 2]) +@pytest.mark.parametrize("status", [409, 429, 502, 503, 504]) +@pytest.mark.asyncio +async def test_merge_retry_override(sync_api, namespace_path, retries, status, capfd): + attempts = 0 + identifier = "$".join(namespace_path + ["test"]) + + def handler(request): + nonlocal attempts + if request.path == f"/v1/table/{identifier}/describe/": + send_json( + request, + { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": True} + ] + }, + }, + ) + return + assert urlparse(request.path).path == f"/v1/table/{identifier}/merge_insert/" + query = parse_qs(urlparse(request.path).query) + assert query["use_index"] == ["false"] + assert request.headers["x-request-timeout-ms"] == "10000" + body = bytearray() + if request.headers.get("Transfer-Encoding") == "chunked": + while True: + size = int(request.rfile.readline().strip(), 16) + if size == 0: + request.rfile.readline() + break + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body.extend( + request.rfile.read(int(request.headers.get("Content-Length", 0))) + ) + assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}] + attempts += 1 + send_json(request, {"version": 2}, status if attempts == 1 else 200) + + config = { + "retry_config": { + "retries": 3, + "statuses": [409, 429, 502, 503, 504], + "backoff_factor": 0, + "backoff_jitter": 0, + } + } + expected_success = status in (409, 429) and retries != 0 + + async def check(table): + merge = table.merge_insert("id").when_not_matched_insert_all().use_index(False) + options = {"timeout": timedelta(seconds=10)} + if retries is not None: + options["retries"] = retries + if expected_success: + result = merge.execute([{"id": 1}], **options) + if not sync_api: + result = await result + assert result.version == 2 + else: + with pytest.raises((HttpError, RetryError)): + result = merge.execute([{"id": 1}], **options) + if not sync_api: + await result + + if sync_api: + with mock_lancedb_connection(handler, **config) as db: + await check(db.open_table("test", namespace_path=namespace_path)) + else: + async with mock_lancedb_connection_async(handler, **config) as db: + await check(await db.open_table("test", namespace_path=namespace_path)) + assert attempts == (2 if expected_success else 1) + warnings = [ + line + for line in capfd.readouterr().err.splitlines() + if "Retrying merge insert" in line + ] + assert len(warnings) == (1 if expected_success else 0) + if expected_success: + assert "WARN" in warnings[0] + assert f"status Some({status}); attempt 2" in warnings[0] + + +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.asyncio +async def test_merge_retry_override_isolation(sync_api): + attempts = 0 + read_attempts = 0 + + def handler(request): + nonlocal attempts, read_attempts + if request.path.endswith("/describe/"): + send_json( + request, + { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": True} + ] + }, + }, + ) + elif request.path.endswith("/count_rows/"): + read_attempts += 1 + send_json(request, 1, 429 if read_attempts % 2 else 200) + else: + assert urlparse(request.path).path.endswith("/merge_insert/") + attempts += 1 + send_json(request, {"version": 2}, 429 if attempts in (1, 2, 4, 6) else 200) + + async def check(table): + merge = table.merge_insert("id").when_not_matched_insert_all() + for retries in [-1, 256, 1.5, "1"]: + with pytest.raises((OverflowError, TypeError, ValueError)): + result = merge.execute([{"id": 1}], retries=retries) + if not sync_api: + await result + assert attempts == 0 + with pytest.raises((HttpError, RetryError)): + result = merge.execute([{"id": 1}], retries=0) + if not sync_api: + await result + assert attempts == 1 + for options in ({}, {"retries": 255}): + result = merge.execute([{"id": 1}], **options) + if not sync_api: + result = await result + assert result.version == 2 + assert attempts == 5 + result = table.count_rows() + if not sync_api: + result = await result + assert result == 1 + assert read_attempts == 2 + result = ( + table.merge_insert("id").when_not_matched_insert_all().execute([{"id": 1}]) + ) + if not sync_api: + result = await result + assert result.version == 2 + assert attempts == 7 + + config = {"retry_config": {"retries": 3, "backoff_factor": 0, "backoff_jitter": 0}} + if sync_api: + with mock_lancedb_connection(handler, **config) as db: + await check(db.open_table("test")) + else: + async with mock_lancedb_connection_async(handler, **config) as db: + await check(await db.open_table("test")) + + @pytest.fixture def missing_table_handler(cached, namespace_path): request_ids = [] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index ce4f57c48..4b26a9003 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3448,7 +3448,8 @@ def test_merge_insert(mem_db: DBConnection): table.merge_insert("a") .when_matched_update_all() .when_not_matched_insert_all() - .execute(new_data, timeout=timedelta(seconds=10)) + .use_index(False) + .execute(new_data, timeout=timedelta(seconds=10), retries=0) ) assert merge_insert_res.version == 2 assert merge_insert_res.num_inserted_rows == 1 @@ -3527,7 +3528,7 @@ def test_merge_insert(mem_db: DBConnection): # timeout with pytest.raises(Exception, match="merge insert timed out"): table.merge_insert("a").when_matched_update_all().execute( - new_data, timeout=timedelta(0) + new_data, timeout=timedelta(0), retries=255 ) diff --git a/python/src/table.rs b/python/src/table.rs index f5270a594..25a99e5db 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2269,10 +2269,12 @@ impl Table { }) } + #[pyo3(signature = (data, parameters, retries=None))] pub fn execute_merge_insert<'a>( self_: PyRef<'a, Self>, data: Bound<'a, PyAny>, parameters: MergeInsertParams, + retries: Option, ) -> PyResult> { let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; let on = parameters.on.iter().map(|s| s.as_str()).collect::>(); @@ -2295,6 +2297,9 @@ impl Table { if let Some(timeout) = parameters.timeout { builder.timeout(timeout); } + if let Some(retries) = retries { + builder.retries(retries); + } if let Some(use_index) = parameters.use_index { builder.use_index(use_index); } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 29f3ab50e..2224203cf 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3707,7 +3707,17 @@ impl BaseTable for RemoteTable { return Ok(merge_result); } Err(err) if rescannable && self.is_retryable_write_error(&err) => { + let status = err.status_code(); retry_counter.increment_from_error(err)?; + log::warn!( + "Retrying merge insert {} after status {:?}; attempt {}", + retry_counter.request_id, + status.map(|s| s.as_u16()), + u16::from(retry_counter.request_failures) + + u16::from(retry_counter.connect_failures) + + u16::from(retry_counter.read_failures) + + 1, + ); tokio::time::sleep(retry_counter.next_sleep_time()).await; merge = merge.reset_state()?; continue; From e8a8dd1b2a240646b39ecfc848b1c3dd4a0701fc Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 14 Nov 2026 16:55:42 -0800 Subject: [PATCH 131/203] feat(sql): use server-issued catalog listing tokens (#5026) Migrates SQL-backed catalog listing APIs to `LIMIT ... FROM ''` and server-issued Arrow continuation metadata. Namespace-specific APIs send an explicit `IN` schema clause, including `IN "public"` for root, so raw SQL can default to all namespaces. ```sql SHOW VIEWS LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100 FROM ''; SHOW VIEWS IN other_db.team$ml LIMIT 100; ``` SDK clients forward opaque tokens unchanged, preserve empty continuations, and decode identifier columns by name. Removes legacy cursor reconstruction and updates the SQL reference and Python Flight fixture. Public docs cover optional direct schema paths, all-namespace defaults, and the shared pagination syntax across every catalog listing. --- docs/web/docs.json | 1 + docs/web/management/function.mdx | 4 +- docs/web/management/index.mdx | 2 +- docs/web/sql/ddl/database.mdx | 20 +- docs/web/sql/ddl/function.mdx | 37 +- docs/web/sql/ddl/materialized-view.mdx | 25 +- docs/web/sql/ddl/namespace.mdx | 40 +- docs/web/sql/ddl/secret.mdx | 30 +- docs/web/sql/ddl/storage-integration.mdx | 25 +- docs/web/sql/ddl/table.mdx | 20 + docs/web/sql/ddl/view.mdx | 33 +- docs/web/sql/pagination.mdx | 68 +++ .../python/tests/test_storage_integration.py | 30 +- rust/lancedb/src/listing.rs | 8 +- rust/lancedb/src/remote/db.rs | 27 +- rust/lancedb/src/remote/sql/function.rs | 85 +-- .../src/remote/sql/materialized_view.rs | 58 +- rust/lancedb/src/remote/sql/objects.rs | 144 ++++- rust/lancedb/src/remote/sql/secret.rs | 62 +- rust/lancedb/src/remote/sql/view.rs | 62 +- rust/lancedb/src/remote/sql_test.rs | 554 +++++++++--------- .../lancedb/src/remote/storage_integration.rs | 23 - 22 files changed, 663 insertions(+), 695 deletions(-) create mode 100644 docs/web/sql/pagination.mdx diff --git a/docs/web/docs.json b/docs/web/docs.json index c586d4f62..0b26a7fc0 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -543,6 +543,7 @@ "group": "SQL Reference", "pages": [ "sql/index", + "sql/pagination", "sql/data-types", { "group": "DDL", diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 41e47dee1..562de05c6 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -280,7 +280,9 @@ let latest = connection.get_function_latest("double", &[]).await?; ```sql SQL icon="database" SHOW FUNCTIONS -SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100) +SHOW FUNCTIONS IN "analytics" LIMIT 100 +SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 +SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 FROM '' DESCRIBE FUNCTION double WITH (version = '1') DESCRIBE FUNCTION double diff --git a/docs/web/management/index.mdx b/docs/web/management/index.mdx index fbef65756..50f6e7507 100644 --- a/docs/web/management/index.mdx +++ b/docs/web/management/index.mdx @@ -85,7 +85,7 @@ enables them; the SDK methods send the view's SQL query to the deployment. See | --- | --- | --- | --- | | create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` | | get | `get_function` | -- | `DESCRIBE FUNCTION` | -| list | `list_functions` | -- | `SHOW FUNCTIONS` | +| list | `list_functions` | -- | `SHOW FUNCTIONS HISTORY` | | drop | `drop_function` | -- | `DROP FUNCTION` | Enterprise A function runs on the server, and only on diff --git a/docs/web/sql/ddl/database.mdx b/docs/web/sql/ddl/database.mdx index e8cdb55bc..f84d4cfb9 100644 --- a/docs/web/sql/ddl/database.mdx +++ b/docs/web/sql/ddl/database.mdx @@ -57,15 +57,21 @@ properties and requires system `USAGE`. ## SHOW DATABASES {#show} - -```sql SQL icon="database" -SHOW DATABASES +```sql +SHOW DATABASES LIMIT 100; +SHOW DATABASES LIMIT 100 FROM ''; ``` - -Returns a sorted `name` column containing the databases the caller has -`USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters -are unsupported. +Returns one non-null `name` column, sorted by database name and filtered to +databases the caller has `USAGE` on, including `system` when permitted. +Databases are above namespaces, so this command does not accept `IN` or +return a `namespace_path` column. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## ATTACH DATABASE {#attach} diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 55e2d6fe7..691118026 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -135,20 +135,33 @@ from it. ## SHOW FUNCTIONS {#show} - -```sql SQL icon="database" -SHOW FUNCTIONS -SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100) -SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100) +```sql +SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100; +SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -`SHOW FUNCTIONS` returns the highest published numeric revision for each name. -Add `HISTORY` to list every published revision, as Python's `list_functions()` -does. Rows are ordered by name and numeric revision, so `2` comes before `10`. -`after_name` and `after_version` must be supplied together for keyset pagination. -`limit` bounds -the response; `include_definition = false` omits the optional definition JSON. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +`SHOW FUNCTIONS` lists each function once. Add `HISTORY` to list every +published revision with its metadata and definition, as `list_functions()` +does. History uses the same pagination suffix; numeric revision order is +encoded in the token, so revision `2` precedes `10`. + +```sql +SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100; +SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100 FROM ''; +``` + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP FUNCTION {#drop} diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index a2453ba01..a2a5024f6 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -70,16 +70,25 @@ automatic execution needs the same server-side switch enabled. Omitting ## SHOW MATERIALIZED VIEWS {#show} - -```sql SQL icon="database" -SHOW MATERIALIZED VIEWS +```sql +SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100; +SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - - -This asks the server for its views, as the SDK's `list_materialized_views` does -on a `db://` connection. - +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +The listing contains identifiers; use `DESCRIBE MATERIALIZED VIEW` for its defining query and refresh metadata. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## Refreshing one {#refresh} diff --git a/docs/web/sql/ddl/namespace.mdx b/docs/web/sql/ddl/namespace.mdx index 8f446f1e7..14391ac18 100644 --- a/docs/web/sql/ddl/namespace.mdx +++ b/docs/web/sql/ddl/namespace.mdx @@ -17,7 +17,7 @@ backtick-quoted identifier with `$` between components, such as one path component, relative to an explicit parent schema or the session's current schema -- it cannot contain `$` or be qualified with a database. -`SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete +For single-object commands, `SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete schema identifier. Names are lowercased unless quoted. ## CREATE SCHEMA and CREATE NAMESPACE {#create} @@ -126,27 +126,30 @@ Requires `USAGE` on the database and the namespace. ## SHOW SCHEMAS and SHOW NAMESPACES {#show} - -```sql SQL icon="database" -SHOW SCHEMAS -SHOW NAMESPACES -SHOW NAMESPACES IN analytics.team +```sql +SHOW SCHEMAS LIMIT 100; +SHOW SCHEMAS LIMIT 100 FROM ''; +SHOW NAMESPACES IN analytics.team LIMIT 100; +SHOW NAMESPACES IN analytics.team LIMIT 100 FROM ''; ``` - -`SHOW SCHEMAS` returns complete paths in the current database, recursively, -including `public` when the caller can use it. It does not accept `IN`. +Both commands return two non-null string columns: `namespace_path`, the +parent path as a compact JSON array, and `name`, the unqualified child name. +Results are ordered by parent path components, then name, and omit namespaces +the caller cannot use. -`SHOW NAMESPACES` lists only immediate child names under the session's -current schema. `IN` selects a different parent schema, optionally in -another database -- use `IN public` for the current database's root, or -`IN analytics.public` for another database's root. A missing parent is an -error. +`SHOW SCHEMAS` and `SHOW NAMESPACES` are equivalent listings. Without `IN`, +both list recursively in the current database, include the implicit `public` +root, and ignore the session namespace. With `IN`, both list immediate children +of the selected parent. A schema path can appear directly: `IN team$features`; +a database qualifier is optional. `IN public` selects the current database root, +and `IN analytics.public` selects another database's root. -Both forms return a sorted `name` column and omit namespaces the caller -cannot use. Large listings that exceed 10,000 namespaces, or recursive -listings deeper than 32 levels, return an error suggesting a narrower -listing. +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP SCHEMA and DROP NAMESPACE {#drop} @@ -187,7 +190,6 @@ with `IF EXISTS`. Inspect a cascade drop's child jobs with | `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` | | `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` | | `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` | -| `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` | ## What to read next {#next} diff --git a/docs/web/sql/ddl/secret.mdx b/docs/web/sql/ddl/secret.mdx index 922dec247..15039c6c7 100644 --- a/docs/web/sql/ddl/secret.mdx +++ b/docs/web/sql/ddl/secret.mdx @@ -98,21 +98,25 @@ picked up by every Function still bound to that name. ## SHOW SECRETS {#show} - -```sql SQL icon="database" -SHOW SECRETS -SHOW SECRETS IN platform -SHOW SECRETS IN analytics.`ml$vision` -SHOW SECRETS IN public -SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50 +```sql +SHOW SECRETS IN analytics.`team$ml` LIMIT 100; +SHOW SECRETS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -Lists the Secret names in one namespace as a sorted `name` column. Without -`IN`, it lists the session's namespace; `IN public` lists the root. `WHERE -name > ''` pages past the last name already seen, and `LIMIT` -bounds the page size; `WHERE` must compare `name` with `>`. Requires -`USAGE` on the database and the namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +Secret listings contain no values or Secret metadata. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DESCRIBE SECRET {#describe} diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx index 9444824ac..de64ba4e5 100644 --- a/docs/web/sql/ddl/storage-integration.mdx +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -194,16 +194,25 @@ only the reference naming it. ## SHOW STORAGE INTEGRATIONS {#show} - -```sql SQL icon="database" -SHOW STORAGE INTEGRATIONS -SHOW STORAGE INTEGRATIONS IN platform -LIST STORAGE INTEGRATIONS +```sql +SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100; +SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -`LIST` is an alias for `SHOW` here. Returns one `name` column; `IN` -narrows the listing to one namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +`LIST STORAGE INTEGRATIONS` is an exact alias, including pagination. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP STORAGE INTEGRATION {#drop} diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index c8c42d4e0..d2196b93a 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -268,3 +268,23 @@ deployment stores its catalog. See Renaming, retyping and dropping columns from the SDK. + +## SHOW TABLES {#show} + +```sql +SHOW TABLES IN analytics.`team$ml` LIMIT 100; +SHOW TABLES IN analytics.`team$ml` LIMIT 100 FROM ''; +``` + +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index 3d94292ab..38fd37e30 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -81,29 +81,22 @@ was none to begin with. ## Listing {#listing} ```sql -SHOW VIEWS -SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100 +SHOW VIEWS IN analytics.`team$ml` LIMIT 100; +SHOW VIEWS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` -`SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to -the selected namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. -Object commands retain their small results in shared storage even when general -query-result copying is disabled, so asynchronous polling can use any query node. - -Views and tables share a namespace, and both are things you can query. The -catalog distinguishes them: - -| | | -| --- | --- | -| view names | the views in the database | -| table names | the tables | -| relation names | everything queryable (both) | - -Use the relation listing when the question is "what can I select from," and the -separate listings when the distinction matters: before dropping, for -instance, since dropping a view removes only the saved query while dropping a -table removes data. +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## Choosing between a view and a materialized view {#choosing} diff --git a/docs/web/sql/pagination.mdx b/docs/web/sql/pagination.mdx new file mode 100644 index 000000000..d6649ebfe --- /dev/null +++ b/docs/web/sql/pagination.mdx @@ -0,0 +1,68 @@ +--- +title: "Catalog listing pagination" +description: "Use one continuation-token syntax for SQL catalog listings." +--- + +Catalog `SHOW` statements share one pagination suffix: + +```sql +SHOW [IN ] [LIMIT [FROM '']]; +``` + +This applies to tables, views, materialized views, functions and function +history, secrets, storage integrations, namespaces/schemas, and databases. + +```sql +SHOW TABLES LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100 FROM ''; +SHOW TABLES IN analytics.team$ml LIMIT 100; +SHOW DATABASES LIMIT 100 FROM ''; +``` + +## Namespace scope + +`IN` is optional. Without it, listings include root and every authorized +namespace in the current database, regardless of the session's default namespace. +With `IN`, objects are listed only in that exact namespace. The scope accepts a +schema directly: `IN team$ml` means the absolute namespace path `["team", "ml"]` +in the current database. Use `IN public` for root, or `IN other_db.team$ml` to +select a different database. Quote schema identifiers containing punctuation or +mixed case, for example `IN "Team$ML"`. + +`SHOW SCHEMAS` and `SHOW NAMESPACES` use the same rules: without `IN` they +include all namespace paths and the public root; with `IN` they list the +selected parent's immediate children. `SHOW DATABASES` remains global and +does not accept `IN`. + +SDK APIs that take a namespace send an explicit `IN` clause and continue to +list that one namespace. + +## Continuation metadata + +The Arrow result schema carries `lancedb.next_page_token` when more results +remain. Pass that opaque value unchanged in `FROM` on the next request. +The token identifies the object type, database, namespace scope, and complete +position, including namespace path and any numeric revision. It cannot be +reused with another object type or scope. + +The token is metadata, not an additional result column or a synthetic row. +Namespace-scoped object listings contain `namespace_path` and `name`; +databases contain only `name`. Function history retains revision metadata. +SDK listing APIs expose this server-issued value as the page's `page_token`. + +Continue until no token is returned. A short or empty page may still have a +token. Pages observe the live catalog; continuation does not create a snapshot. + +## Page size and ordering + +The default page limit is 1,000, with a maximum of 10,000. `LIMIT 0` returns +no rows. Object catalogs order identifiers by namespace path components and +unqualified name; database names are ordered by name. Table page boundaries +follow native catalog order, which may differ from logical name order for +directory-backed tables; table names are sorted within each returned page. Function history uses +numeric revision order within each name. The token preserves that complete +position, including when names repeat in different namespaces. + +The old name-comparison `WHERE` and Function `WITH` pagination forms are no +longer supported. Use the same `LIMIT ... FROM ...` suffix for every listing. diff --git a/python/python/tests/test_storage_integration.py b/python/python/tests/test_storage_integration.py index ff7995ab3..84052e54c 100644 --- a/python/python/tests/test_storage_integration.py +++ b/python/python/tests/test_storage_integration.py @@ -3,6 +3,7 @@ import contextlib import json +import re from pathlib import Path import pytest @@ -39,7 +40,30 @@ def remote_server(text_type=pa.string()): command = ticket.ticket calls.append(command) if b"SHOW STORAGE INTEGRATIONS" in command: - result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)}) + match = re.search( + rb'SHOW STORAGE INTEGRATIONS IN "public" ' + rb"LIMIT (\d+)(?: FROM '([^']+)')?", + command, + ) + assert match is not None, command + limit = int(match.group(1)) + names = [NAME, "zeta"] + if match.group(2) is not None: + assert match.group(2) == b"server-storage-page", command + names = names[1:] + page = names[:limit] + result = pa.table( + { + "namespace_path": pa.array( + ["[]"] * len(page), type=pa.string() + ), + "name": pa.array(page, type=text_type), + } + ) + if len(names) > limit: + result = result.replace_schema_metadata( + {b"lancedb.next_page_token": b"server-storage-page"} + ) elif b"DROP STORAGE INTEGRATION" in command: result = pa.table({"dropped": [True]}) else: @@ -195,6 +219,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type): assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0] assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0] assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1] + listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call] + assert len(listings) == 2 + assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0] + assert b"FROM 'server-storage-page'" in listings[1] @pytest.mark.asyncio diff --git a/rust/lancedb/src/listing.rs b/rust/lancedb/src/listing.rs index a0f6e5d5e..a5541b629 100644 --- a/rust/lancedb/src/listing.rs +++ b/rust/lancedb/src/listing.rs @@ -19,7 +19,10 @@ pub struct ListingOptions { /// Starting continuation token; `None` starts at the beginning. pub page_token: Option, /// Maximum results per request, not a limit on the entire listing. - /// `None` uses the backend default. Must be between 1 and `i32::MAX`. + /// `None` uses the backend default. SQL-backed catalog listings default to + /// 1,000 rows and accept 1 through 10,000. The public listing API rejects + /// zero; SQL statements can separately use `LIMIT 0`. Other backends may + /// impose different limits. pub page_limit: Option, } @@ -31,6 +34,9 @@ impl ListingOptions { } /// Set the maximum number of results requested per page. + /// + /// SQL-backed catalog listings accept 1 through 10,000. A server can return + /// fewer rows, including none, with a continuation token. pub fn page_limit(mut self, limit: u32) -> Self { self.page_limit = Some(limit); self diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 7100e1b04..1a825bebc 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1008,30 +1008,9 @@ impl Database for RemoteDatabase { namespace_path: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace_path)?; - let result = self - .execute_query_async(ExecuteQueryRequest { - query: "SHOW STORAGE INTEGRATIONS".into(), - default_namespace_path: namespace_path.to_vec(), - parameters: None, - }) - .await?; - let mut names = - integration_sql::decode_names(&result.reader().await?.try_collect::>().await?)?; - if let Some(token) = options.page_token { - names.retain(|name| name > &token); - } - let mut page_token = None; - if let Some(limit) = options.page_limit - && names.len() > limit as usize - { - names.truncate(limit as usize); - page_token = names.last().cloned(); - } - Ok(ListingPage { - items: names, - page_token, - }) + self.sql_client()? + .list_names("SHOW STORAGE INTEGRATIONS", namespace_path, options) + .await } async fn drop_storage_integration(&self, name: &str, namespace_path: &[String]) -> Result<()> { diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index 19a1a6cbc..f0ebf1894 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -14,7 +14,6 @@ use crate::{ listing::{ListingOptions, ListingPage}, utils::{validate_function_name, validate_namespace}, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; /// The SQL result of one Function drop, before the public boolean wrapper /// discards the advisory details. @@ -89,81 +88,17 @@ impl SqlClient { 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 = || Error::InvalidInput { - message: "invalid function page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid())?; - let (database, prefix, path, name, version): ( - String, - Option, - Vec, - String, - String, - ) = serde_json::from_slice(&bytes).map_err(|_| invalid())?; - if database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid()); - } - Some((name, version)) - } else { - None - }; - let mut sql_options = vec![ - format!("limit = {}", u64::from(limit) + 1), - "include_definition = true".to_owned(), - ]; - if let Some((name, version)) = &after { - sql_options.push(format!("after_name = {}", literal(name))); - sql_options.push(format!("after_version = {}", literal(version))); - } - let mut items: Vec = self - .object_job( - ExecuteQueryRequest { - query: format!("SHOW FUNCTIONS HISTORY WITH ({})", sql_options.join(", ")), - default_namespace_path: namespace.to_vec(), - parameters: None, - }, - |batches| { - strings(&batches, "definition")? - .into_iter() - .map(|value| { - serde_json::from_str(&value).map_err(|error| Error::Runtime { - message: error.to_string(), - }) - }) - .collect::>>() - }, - ) - .await? - .wait() + let (batches, page_token) = self + .listing_page("SHOW FUNCTIONS HISTORY", namespace, options) .await?; - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let last = items.last().unwrap(); - let bytes = serde_json::to_vec(&( - &self.inner.database, - &self.inner.database_prefix, - namespace, - last.name(), - last.version(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(bytes)) - } else { - None - }; + let items = strings(&batches, "definition")? + .into_iter() + .map(|value| { + serde_json::from_str(&value).map_err(|error| Error::Runtime { + message: error.to_string(), + }) + }) + .collect::>>()?; Ok(ListingPage { items, page_token }) } pub(in crate::remote) async fn drop_function_outcome( diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index e982afac7..c8e1aa5c3 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -4,7 +4,6 @@ use std::sync::Arc; use arrow_array::{Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::TryStreamExt; use super::SqlClient; @@ -157,60 +156,7 @@ impl SqlClient { 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 }) + self.list_names("SHOW MATERIALIZED VIEWS", namespace, options) + .await } } diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index ff87e0000..2ffb08936 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -1,42 +1,118 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::SqlClient; +use super::{SqlClient, materialized_view::quote_identifier}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, job::Job, + listing::{ListingOptions, ListingPage}, + utils::validate_namespace, }; -use arrow_array::{Array, ListArray, RecordBatch, StringArray}; +use arrow_array::{Array, LargeStringArray, ListArray, RecordBatch, StringArray, StringViewArray}; use futures::TryStreamExt; use serde::{Serialize, de::DeserializeOwned}; use std::sync::Arc; +const DEFAULT_SQL_LISTING_LIMIT: u32 = 1_000; +const MAX_SQL_LISTING_LIMIT: u32 = 10_000; +const NEXT_PAGE_TOKEN_METADATA_KEY: &str = "lancedb.next_page_token"; + +impl SqlClient { + pub(in crate::remote) async fn listing_page( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result<(Vec, Option)> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(DEFAULT_SQL_LISTING_LIMIT); + if limit > MAX_SQL_LISTING_LIMIT { + return Err(Error::InvalidInput { + message: format!("page limit must be between 0 and {MAX_SQL_LISTING_LIMIT}"), + }); + } + if options.page_token.as_ref().is_some_and(String::is_empty) { + return Err(Error::InvalidInput { + message: "page token must not be empty".into(), + }); + } + if limit == 0 { + return Ok((Vec::new(), None)); + } + let schema = if namespace.is_empty() { + "public".to_owned() + } else { + namespace.join("$") + }; + let mut statement = format!("{statement} IN {} LIMIT {limit}", quote_identifier(&schema)); + if let Some(token) = options.page_token { + statement.push_str(&format!(" FROM {}", literal(&token))); + } + let query = self + .execute(ExecuteQueryRequest { + query: statement, + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let reader = query.reader().await?; + let token = reader + .schema() + .metadata() + .get(NEXT_PAGE_TOKEN_METADATA_KEY) + .cloned() + .filter(|token| !token.is_empty()); + let batches = reader.try_collect::>().await?; + if batches.iter().map(RecordBatch::num_rows).sum::() > limit as usize { + return Err(Error::Runtime { + message: "SQL listing exceeded its requested page size".into(), + }); + } + Ok((batches, token)) + } + + pub(in crate::remote) async fn list_names( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + let (batches, page_token) = self.listing_page(statement, namespace, options).await?; + Ok(ListingPage { + items: strings(&batches, "name")?, + page_token, + }) + } +} + pub(super) fn literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } pub(super) fn strings(batches: &[RecordBatch], name: &str) -> Result> { - batches - .iter() - .map(|batch| { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("SQL result is missing UTF-8 column '{name}'"), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: format!("SQL result contains null '{name}'"), - }); - } - Ok(values - .iter() - .map(|value| value.unwrap().to_owned()) - .collect::>()) - }) - .collect::>>() - .map(|rows| rows.into_iter().flatten().collect()) + let mut result = Vec::new(); + for batch in batches { + let column = batch.column_by_name(name).ok_or_else(|| Error::Runtime { + message: format!("SQL result is missing string column '{name}'"), + })?; + if column.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result contains null '{name}'"), + }); + } + if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else { + return Err(Error::Runtime { + message: format!("SQL result column '{name}' is not a string"), + }); + } + } + Ok(result) } /// Read an optional `List` column. Older servers do not return the @@ -112,9 +188,9 @@ impl SqlClient { #[cfg(test)] mod tests { - use super::string_lists; + use super::{string_lists, strings}; use arrow_array::builder::{ListBuilder, StringBuilder}; - use arrow_array::{ArrayRef, RecordBatch}; + use arrow_array::{ArrayRef, LargeStringArray, RecordBatch, StringArray, StringViewArray}; use arrow_schema::{DataType, Field, Schema}; use std::sync::Arc; @@ -126,6 +202,24 @@ mod tests { )])) } + #[test] + fn listing_strings_accept_all_arrow_string_representations() { + for values in [ + Arc::new(StringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(LargeStringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(StringViewArray::from(vec!["a", "z"])) as ArrayRef, + ] { + let batch = RecordBatch::try_from_iter(vec![("name", values)]).unwrap(); + assert_eq!(strings(&[batch], "name").unwrap(), ["a", "z"]); + } + let batch = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringViewArray::from(vec![Some("a"), None])) as ArrayRef, + )]) + .unwrap(); + assert!(strings(&[batch], "name").is_err()); + } + #[test] fn reads_warnings_after_an_empty_first_batch() { let schema = warning_schema(); diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index 6ddc78645..93c2a6c6e 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -10,8 +10,6 @@ use crate::{ utils::{validate_namespace, validate_secret_name}, }; use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; use std::sync::Arc; pub(in crate::remote) enum SecretWriteOperation { @@ -135,65 +133,7 @@ impl SqlClient { 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 secret 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 (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "secret" - || 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 SECRETS{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(&( - "secret", - &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 }) + self.list_names("SHOW SECRETS", namespace, options).await } } diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 513113187..b058269a0 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -9,8 +9,6 @@ use crate::{ utils::{validate_namespace, validate_view_name}, view::ViewDescription, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; use lance_namespace::models::JsonArrowSchema; use std::sync::Arc; #[derive(Clone, serde::Serialize, serde::Deserialize)] @@ -147,64 +145,6 @@ impl SqlClient { 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 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 (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "view" - || 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 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(&( - "view", - &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 }) + self.list_names("SHOW VIEWS", namespace, options).await } } diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 5c7ae7673..d7249da9b 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -14,7 +14,6 @@ use arrow_flight::{ FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, }; use arrow_schema::{DataType, Field, Schema}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::stream::BoxStream; use futures::{StreamExt, TryStreamExt}; use tonic::metadata::MetadataMap; @@ -2919,25 +2918,54 @@ async fn remote_optimize_full_rejects_explicit_pruning_options() { assert_rejected_before_submission(None, None, Some(true)).await; } +fn sql_listing_batch(column: &str, values: &[&str], token: Option<&str>) -> RecordBatch { + let mut columns: Vec<(&str, ArrayRef)> = Vec::new(); + if column == "name" { + columns.push(( + "namespace_path", + Arc::new(StringArray::from(vec![ + r#"["team","reports"]"#; + values.len() + ])), + )); + } + columns.push((column, Arc::new(StringArray::from(values.to_vec())))); + let batch = RecordBatch::try_from_iter(columns).unwrap(); + let metadata = token + .map(|token| HashMap::from([("lancedb.next_page_token".to_owned(), token.to_owned())])) + .unwrap_or_default(); + let schema = Arc::new(batch.schema().as_ref().clone().with_metadata(metadata)); + RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap() +} + #[tokio::test] -async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { +async fn remote_mv_listing_uses_server_continuation_tokens() { 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 token = "server'opaque:token"; + let next_sql = + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..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()); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; @@ -2948,41 +2976,31 @@ async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { ) .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!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_materialized_views( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); assert_eq!( *statements.lock().unwrap(), [ - "SHOW MATERIALIZED VIEWS LIMIT 3", - "SHOW MATERIALIZED VIEWS WHERE name > 'b''c' LIMIT 3" + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2", + next_sql ] ); - 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 { .. }) - )); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } @@ -3123,7 +3141,10 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() let statements = statements.lock().unwrap(); assert!(statements[0].contains("STORAGE_AWS_REGION = 'us-east-1'")); assert_eq!(statements[1], "DESCRIBE STORAGE INTEGRATION \"raw\""); - assert_eq!(statements[2], "SHOW STORAGE INTEGRATIONS"); + assert_eq!( + statements[2], + "SHOW STORAGE INTEGRATIONS IN \"platform$aws\" LIMIT 1000" + ); assert_eq!(statements[3], "DROP STORAGE INTEGRATION \"raw\""); assert!(statements[4].contains( "STORAGE_AWS_ACCESS_KEY_ID_SECRET = \"platform/raw\".\"credentials\".\"key\"" @@ -3670,29 +3691,20 @@ async fn secret_description_uses_the_sql_metadata_projection() { } #[tokio::test] -async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { +async fn secret_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["api-key", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW SECRETS LIMIT 3".to_string(), first_result), - ( - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -3704,11 +3716,10 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let first = db .list_secrets( &namespace, @@ -3716,90 +3727,144 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await .unwrap(); - assert_eq!(first.items, ["api-key", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); let second = db .list_secrets( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) .await .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW SECRETS LIMIT 3", - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW SECRETS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - for (path, token) in [ - (vec!["other".to_owned()], token), - (namespace.clone(), "invalid".to_owned()), - ] { - assert!(matches!( - db.list_secrets( - &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 secret_listing_handles_empty_pages_and_rejects_invalid_limits() { - let empty = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(Vec::::new())) as ArrayRef, - )]) - .unwrap(); +async fn storage_integration_listing_uses_server_continuation_tokens() { + for defer in [false, true] { + let token = "server'opaque:token"; + let next_sql = + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + let first = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2", + next_sql + ] + ); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn secret_listing_preserves_empty_continuations_and_validates_page_options() { let service = TestSqlService { adaptive: true, defer: true, - result: empty, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &[], Some("continue-empty")), + ), + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'continue-empty'".to_owned(), + sql_listing_batch("name", &["last"], None), + ), + ]))), ..Default::default() }; let statements = service.statements.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let page = db .list_secrets( &namespace, - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(""), + crate::listing::ListingOptions::default().page_limit(2), ) .await .unwrap(); assert!(page.items.is_empty()); - assert!(page.page_token.is_none()); - - for limit in [0, i32::MAX as u32 + 1] { + assert_eq!(page.page_token.as_deref(), Some("continue-empty")); + let last = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(page.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items, ["last"]); + assert!(last.page_token.is_none()); + for limit in [10_001, u32::MAX] { assert!(matches!( db.list_secrets( &namespace, @@ -3809,12 +3874,29 @@ async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { Err(Error::InvalidInput { .. }) )); } - assert_eq!(*statements.lock().unwrap(), ["SHOW SECRETS LIMIT 3"]); + assert!( + db.list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_token("") + ) + .await + .is_err() + ); + let zero = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_limit(0), + ) + .await + .unwrap(); + assert!(zero.items.is_empty()); + assert!(zero.page_token.is_none()); + assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } #[tokio::test] -async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { +async fn function_listing_uses_server_tokens_for_numeric_revision_pages() { const VERSION: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" ); @@ -3824,74 +3906,65 @@ async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { let mut tenth: serde_json::Value = serde_json::from_str(VERSION).unwrap(); tenth["version"] = serde_json::json!("10"); let tenth = tenth.to_string(); - let result = RecordBatch::try_from_iter(vec![( - "definition", - Arc::new(StringArray::from(vec![ - VERSION, - second.as_str(), - tenth.as_str(), - ])) as ArrayRef, - )]) - .unwrap(); - let service = TestSqlService { - adaptive: true, - defer: true, - result, - ..Default::default() - }; - service.result_overrides.lock().unwrap().insert( - "SHOW FUNCTIONS HISTORY WITH (limit = 3, include_definition = true, after_name = 'embed', after_version = '2')".into(), - RecordBatch::try_from_iter(vec![("definition", Arc::new(StringArray::from(vec![tenth.as_str()])) as ArrayRef)]).unwrap(), - ); - let statements = service.statements.clone(); - let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; - let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); - }) - .with_sql_client(client); - let first = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default().page_limit(2), - ) - .await - .unwrap(); - assert_eq!( - first - .items - .iter() - .map(|item| item.version()) - .collect::>(), - ["1", "2"] - ); - let token = first.page_token.unwrap(); - let second = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token.clone()), - ) - .await - .unwrap(); - assert_eq!(second.items.len(), 1); - assert_eq!(second.items[0].version(), "10"); - assert!(second.page_token.is_none()); - assert!( - db.list_functions( - &["other".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token) - ) - .await - .is_err() - ); - let seen = statements.lock().unwrap(); - assert_eq!(seen.len(), 2); - assert!(seen[0].starts_with("SHOW FUNCTIONS HISTORY WITH (limit = 3,")); - assert!(seen[1].contains("after_version = '2'")); - shutdown.send(()).unwrap(); + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2".to_owned(), + sql_listing_batch("definition", &[VERSION, &second], Some("revision-cursor")), + ), + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'".to_owned(), + sql_listing_batch("definition", &[&tenth], None), + ), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let first = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!( + first + .items + .iter() + .map(|item| item.version()) + .collect::>(), + ["1", "2"] + ); + assert_eq!(first.page_token.as_deref(), Some("revision-cursor")); + let last = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items.len(), 1); + assert_eq!(last.items[0].version(), "10"); + assert!(last.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2", + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'" + ] + ); + shutdown.send(()).unwrap(); + } } #[tokio::test] @@ -3999,29 +4072,20 @@ async fn view_drop_uses_a_repeatable_query_job() { } #[tokio::test] -async fn view_listing_uses_bounded_sql_and_scoped_cursors() { +async fn view_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["adults", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW VIEWS LIMIT 3".to_string(), first_result), - ( - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -4033,107 +4097,39 @@ async fn view_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); - let connection = Connection::new( - Arc::new(db), - Arc::new(crate::embeddings::MemoryRegistry::new()), - ); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - - let first = connection + let first = db .list_views( &namespace, crate::listing::ListingOptions::default().page_limit(2), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(first.items, ["adults", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - - let second = connection + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db .list_views( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW VIEWS LIMIT 3", - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW VIEWS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - let encode_token = - |kind: &str, database: &str, prefix: Option<&str>, path: &[String], last: &str| { - URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&(kind, database, prefix, path.to_vec(), last)).unwrap(), - ) - }; - for forged in [ - encode_token( - "secret", - "analytics", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token( - "view", - "billing", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token("view", "analytics", Some("other"), &namespace, "hf'prod"), - encode_token( - "view", - "analytics", - Some("tenant/production"), - &["other".to_owned()], - "hf'prod", - ), - "not-a-json-token".to_string(), - ] { - let mut listing = connection.list_views( - &namespace, - crate::listing::ListingOptions::default().page_token(forged), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - } - let mut listing = connection.list_views( - &["other".to_owned()], - crate::listing::ListingOptions::default().page_token(&token), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index 48dab4c6a..6c132ab4b 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -259,29 +259,6 @@ pub(super) fn decode_info(batches: &[RecordBatch]) -> Result Result> { - let mut names = Vec::new(); - for batch in batches { - let column = batch - .column_by_name("name") - .ok_or_else(|| invalid("SQL storage integration listing is missing names"))?; - for row in 0..batch.num_rows() { - if column.is_null(row) { - return Err(invalid("SQL storage integration name cannot be null")); - } - names.push( - string_value(column.as_ref(), row) - .ok_or_else(|| { - invalid("SQL storage integration listing requires string names") - })? - .to_string(), - ); - } - } - names.sort(); - Ok(names) -} - #[cfg(test)] mod tests { use std::sync::Arc; From 530d379fc4d3abbf8c4c8759f7d48804d2055677 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 15 Nov 2026 02:08:34 +0000 Subject: [PATCH 132/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.13=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.14?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 04ce71470..8491e70dc 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.13" +current_version = "0.42.0-beta.14" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a84f1d6fd..755ba70a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5992,7 +5992,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "ahash", "anyhow", @@ -6103,7 +6103,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "anyhow", "arrow-array", @@ -6146,7 +6146,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "arrow-array", "arrow-buffer", @@ -6171,7 +6171,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1aadbe68f..ca0113382 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.42.0-beta.13 + 0.42.0-beta.14 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index e8a9a76ec..0ed2c85d9 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.13 + 0.42.0-beta.14 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9b062f4e8..ead5955fa 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.13 + 0.42.0-beta.14 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 7f8468eb5..87919848f 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.13" +version = "0.42.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 0fb6fde09..4c29cfeb3 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.42.0-beta.13", + "version": "0.42.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 24e779721..86c223618 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.42.0-beta.13", + "version": "0.42.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 8ee7bd66b..2e32e7fc3 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.42.0-beta.13", + "version": "0.42.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 3c7c63b86..7d984b9f4 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.42.0-beta.13", + "version": "0.42.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 75e68cacd..3607a6b93 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.42.0-beta.13", + "version": "0.42.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 3422e095c..369ff1c10 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.42.0-beta.13", + "version": "0.42.0-beta.14", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e9ceb4dfb..d0852d725 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.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 512e390aa..8520e7b83 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 0f7667320..08113dee6 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.13" +version = "0.42.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 2dac7bda3..3a963d193 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 581504423..0b566e596 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" edition = "2021" license.workspace = true repository.workspace = true From f17a07a2cda583af25f67797192ea776b8b8efa2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 15 Nov 2026 00:50:58 -0800 Subject: [PATCH 133/203] feat: expose server-side job listing filters (#5041) Expose server-side job filters and lazy Listing indexing, slicing, and length helpers. Document cache, cursor, and SDK/server compatibility behavior. --- docs/web/basics/jobs.mdx | 51 ++++++-- nodejs/__test__/remote.test.ts | 53 +++++++-- python/python/lancedb/_lancedb.pyi | 14 ++- python/python/lancedb/db.py | 136 ++++++++++++++++++--- python/python/lancedb/listing.py | 72 ++++++++++- python/python/lancedb/remote/db.py | 48 +++++++- python/python/tests/test_listing.py | 178 +++++++++++++++++++++++++++- python/src/connection.rs | 38 +++++- rust/lancedb/src/connection.rs | 35 +++++- rust/lancedb/src/database.rs | 47 ++++++++ rust/lancedb/src/remote/db.rs | 137 ++++++++++++++++++++- 11 files changed, 756 insertions(+), 53 deletions(-) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 264acd728..db5b49ab5 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -177,14 +177,51 @@ for info in db.list_jobs(page_limit=50): live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds each server request, not the total yielded items, and `page_token` resumes a listing. It is a lazy iterator: iteration performs requests and can raise -request errors. To materialize it, use `list(db.list_jobs(...))`; it does not -support list indexing, `len()`, or a `.to_list()` method. +request errors. Use `list(db.list_jobs(...))` to collect all remaining results; +there is no `.to_list()` method. -`Listing.num_page_results()` reports cached items remaining in the current -page and `Listing.page_token()` reports the next request's token. Drain the -cached items before saving that token, or resuming can skip them. A `None` -token after the final page can coexist with unread cached items. A resumed -listing is not a transactionally frozen view of jobs submitted in the meantime. + +Job filters and synchronous `Listing` indexing, slicing, and `len()` require +a Python SDK release that includes these APIs. Older SDKs expose only +`page_token` and `page_limit`; collect results with `list(...)` before indexing +or counting them. Filtering also requires a matching Enterprise server that +supports the requested filters. + + +Filter jobs on the server before pagination with `table`, `state`, `job_type` +or `job_types`, and creation-time bounds. `table` names a table in +`namespace_path` (the root by default) and includes all its branches. Requests +stay scoped to the connected database. Creation times are Unix milliseconds: +`created_at_gte_millis` is inclusive and `created_at_lt_millis` is exclusive. +Choose either `job_type` or `job_types`. + +The `state` filter uses registry states: `in_progress`, `succeeded`, `failed`, +`canceled`, and `timed_out`. These differ from the SDK lifecycle labels such +as `running` and `finished` returned in `JobInfo.state`. + +```python +jobs = db.list_jobs(table="events", state="in_progress", page_limit=5) +first_five = jobs[:5] +for info in first_five: + print(info.job_id, info.state) +``` + +Synchronous indexing and slicing refer to the remaining results without +consuming them. A bounded forward slice such as `jobs[:5]` fetches only enough +pages to reach its stop. `len(jobs)` returns the remaining count by fetching +and caching every remaining result. Negative indexes and open-ended or reverse +slices also fetch and cache all remaining results. These operations can raise +request errors; later iteration drains their cache. `AsyncListing` remains an +async iterator: use `async for` to read it. + +`Listing.num_page_results()` reports cached items available without another +request, including items retained by indexing, slicing, or counting. +`Listing.page_token()` reports the next request's token. Drain all cached +items before saving that token, or resuming can skip them. Resume with the same +filters, for example `db.list_jobs(table="events", state="in_progress", +page_token=saved_token, page_limit=5)`. A `None` token after the final page can +coexist with unread cached items. A resumed listing is not a transactionally +frozen view of jobs submitted in the meantime. `events.schema` describes the Arrow response. Use `events.to_pylist()` for Python row dictionaries. Common event columns are `event_seq` (int64), `state` diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 215df992d..9baa51292 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2318,10 +2318,30 @@ describe("remote connection jobs surface", () => { queue_reason: "Waiting for Function worker capacity", }); const descriptions = [ - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 3000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 2000, + knownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 40, + 60, + 1000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress( + 60, + 0, + 0, + unknownFleet, + )}}`, ]; let describeCount = 0; @@ -2393,12 +2413,24 @@ describe("remote connection jobs surface", () => { it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => { const now = Date.now(); const descriptions = [ - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 5000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 4000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 3000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 2000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1500 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1000 + }}}`, ]; await withMockDatabase( @@ -2574,6 +2606,7 @@ describe("lazy resource listings", () => { if (kind === "jobs") { expect(url.pathname).toBe("/v1/jobs/list"); expect(request.body).toEqual({ + database: "dev", // biome-ignore lint/style/useNamingConvention: server wire format page_token: token, limit: 2, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a86bae9d5..0cce2085e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -300,7 +300,19 @@ class Connection(object): page_limit: Optional[int] = None, ) -> NameListing: ... def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> JobListing: ... async def cancel_job(self, job_id: str) -> bool: ... async def pause_job(self, job_id: str) -> str: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 12c7edd5c..b225a6e65 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1602,13 +1602,39 @@ class DBConnection(EnforceOverrides): ) def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> Listing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = jobs[:5] """ raise NotImplementedError( _append_doc_url( @@ -2799,16 +2825,52 @@ class LanceDBConnection(DBConnection): @override def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> Listing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = jobs[:5] """ return Listing( - self._conn.list_jobs(page_token=page_token, page_limit=page_limit) + self._conn.list_jobs( + page_token=page_token, + page_limit=page_limit, + table=table, + namespace_path=namespace_path, + state=state, + job_type=job_type, + job_types=job_types, + created_at_gte_millis=created_at_gte_millis, + created_at_lt_millis=created_at_lt_millis, + ) ) @override @@ -4375,16 +4437,56 @@ class AsyncConnection(object): ) def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> AsyncListing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = [] + async for job in jobs: + first_five.append(job) + if len(first_five) == 5: + break """ return AsyncListing( - self._inner.list_jobs(page_token=page_token, page_limit=page_limit) + self._inner.list_jobs( + page_token=page_token, + page_limit=page_limit, + table=table, + namespace_path=namespace_path, + state=state, + job_type=job_type, + job_types=job_types, + created_at_gte_millis=created_at_gte_millis, + created_at_lt_millis=created_at_lt_millis, + ) ) async def cancel_job(self, job_id: str) -> bool: diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 59aba1431..f85599b2d 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -6,7 +6,19 @@ from __future__ import annotations import asyncio -from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar +from collections import deque +from itertools import islice +from operator import index +from typing import ( + Any, + AsyncIterator, + Callable, + Generic, + Iterator, + Optional, + TypeVar, + overload, +) from .background_loop import LOOP @@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]): print(name) Use ``list(connection.list_views())`` to collect all results. + + Indexes and slices refer to the remaining items and do not consume them. + A bounded forward slice, such as ``listing[:5]``, fetches only enough pages + to reach its stop. ``len(listing)``, negative indexes, and open-ended or + reverse slices fetch and cache all remaining results. Iteration then drains + that cache. These operations may perform requests and raise request errors. """ def __init__(self, inner: AsyncListing[T]): self._inner = inner + self._buffer: deque[T] = deque() def __iter__(self) -> Listing[T]: return self def __next__(self) -> T: + if self._buffer: + return self._buffer.popleft() try: return LOOP.run(self._inner.__anext__()) except StopAsyncIteration: raise StopIteration from None + def _fill(self, count: Optional[int]) -> None: + while count is None or len(self._buffer) < count: + try: + item = LOOP.run(self._inner.__anext__()) + except StopAsyncIteration: + return + self._buffer.append(item) + + def __len__(self) -> int: + """Fetch and cache every remaining item, returning the remaining count.""" + self._fill(None) + return len(self._buffer) + + def __bool__(self) -> bool: + self._fill(1) + return bool(self._buffer) + + @overload + def __getitem__(self, key: int) -> T: ... + + @overload + def __getitem__(self, key: slice) -> list[T]: ... + + def __getitem__(self, key: int | slice) -> T | list[T]: + """Read remaining items without consuming them; bounded slices stay lazy.""" + if isinstance(key, slice): + start = 0 if key.start is None else index(key.start) + stop = None if key.stop is None else index(key.stop) + step = 1 if key.step is None else index(key.step) + if step == 0: + raise ValueError("slice step cannot be zero") + if start >= 0 and stop is not None and stop >= 0 and step > 0: + if start >= stop: + return [] + self._fill(stop) + start, stop, step = key.indices(len(self._buffer)) + return list( + islice(self._buffer, start, stop, min(step, len(self._buffer) + 1)) + ) + self._fill(None) + return list(self._buffer)[key] + position = index(key) + self._fill(None if position < 0 else position + 1) + return self._buffer[position] + def num_page_results(self) -> int: """Return the number of cached items available without another request.""" - return self._inner.num_page_results() + return len(self._buffer) + self._inner.num_page_results() def page_token(self) -> Optional[str]: """Return the next request's token. See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token] for initial, cached, final-page, and error behavior. + Indexing, slicing, and counting can also advance this token; drain all + ``num_page_results()`` cached items before resuming from it. """ return self._inner.page_token() diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 913c8fc2c..2927f2726 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1324,16 +1324,52 @@ class RemoteDBConnection(DBConnection): @override def list_jobs( - self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None + self, + *, + page_token: Optional[str] = None, + page_limit: Optional[int] = None, + table: Optional[str] = None, + namespace_path: Optional[List[str]] = None, + state: Optional[ + Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"] + ] = None, + job_type: Optional[str] = None, + job_types: Optional[List[str]] = None, + created_at_gte_millis: Optional[int] = None, + created_at_lt_millis: Optional[int] = None, ) -> Listing[JobInfo]: - """List server-side jobs across the database's tables. + """List server-side jobs, optionally filtered before pagination. - Returns a lazy iterator. ``page_limit`` limits each request, not the total; - ``page_token`` resumes from a saved token. Requests and errors occur during - iteration. See [pagination state][lancedb.listing.AsyncListing]. + ``table`` names a table in ``namespace_path`` (the root by default). + Listings include all branches of the table. A namespace filter requires + ``table``. + ``state`` uses registry states such as ``in_progress``, ``succeeded``, + ``failed``, ``timed_out``, and ``canceled``, rather than the SDK's + ``running``/``finished`` labels. Set either ``job_type`` or ``job_types``. + Creation-time bounds are Unix milliseconds, inclusive at + ``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``. + + Returns a lazy iterator. ``page_limit`` limits each request, not the total. + Resume a ``page_token`` with the same filters. Requests and errors occur + during iteration. See [pagination state][lancedb.listing.AsyncListing]. + + For example, to inspect up to five jobs without fetching all history:: + + jobs = db.list_jobs(table="events", page_limit=5) + first_five = jobs[:5] """ return Listing( - self._conn.list_jobs(page_token=page_token, page_limit=page_limit) + self._conn.list_jobs( + page_token=page_token, + page_limit=page_limit, + table=table, + namespace_path=namespace_path, + state=state, + job_type=job_type, + job_types=job_types, + created_at_gte_millis=created_at_gte_millis, + created_at_lt_millis=created_at_lt_millis, + ) ) @override diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index cc1c44e90..d18e8580b 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous) if kind == "jobs": assert verb == "POST" assert path.path == "/v1/jobs/list" - assert body == {"page_token": token, "limit": 2} + assert body == {"database": "dev", "page_token": token, "limit": 2} else: namespace = "team" resource = kind.removesuffix("s") @@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l with pytest.raises(ValueError, match="limit"): await items.__anext__() assert requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("namespace", [[], ["team", "project"]]) +@pytest.mark.parametrize("multiple_types", [False, True]) +async def test_job_filters_persist_across_pages_and_resume( + listing_server, asynchronous, namespace, multiple_types +): + endpoint, requests, responses = listing_server + responses.extend( + (200, response_page("jobs", names, token)) + for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)] + ) + db = await connection(endpoint, asynchronous) + types = ["column_refresh", "materialized_view_refresh"] + filters = dict( + table="events", + namespace_path=namespace, + state="in_progress", + created_at_gte_millis=100, + created_at_lt_millis=200, + **({"job_types": types} if multiple_types else {"job_type": types[0]}), + ) + items = db.list_jobs(page_limit=1, **filters) + assert requests == [] + assert (await advance(items, asynchronous)).job_id == "a" + assert len(requests) == 1 + resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters) + assert (await advance(resumed, asynchronous)).job_id == "b" + assert resumed.page_token() is None + assert len(requests) == 3 + expected = dict( + database="dev", + limit=1, + table_ref={ + "db_name": "dev", + "table_id": {"namespace_path": namespace, "table_name": "events"}, + }, + state="in_progress", + job_types=types if multiple_types else types[:1], + created_at_gte_millis=100, + created_at_lt_millis=200, + ) + for (_, path, body), token in zip(requests, [None, "empty", "last"]): + assert path == "/v1/jobs/list" + assert body == {**expected, **({"page_token": token} if token else {})} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "filters", + [ + {}, + {"state": "failed"}, + {"job_types": ["column_refresh"]}, + {"created_at_lt_millis": 200}, + ], +) +async def test_job_listing_without_table_stays_in_connected_database( + listing_server, asynchronous, filters +): + endpoint, requests, responses = listing_server + responses.append((200, response_page("jobs", ["a"], None))) + db = await connection(endpoint, asynchronous) + items = db.list_jobs(**filters) + assert (await advance(items, asynchronous)).job_id == "a" + assert requests[0][2] == {"database": "dev", **filters} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "filters, message", + [ + ({"namespace_path": ["team"]}, "requires a table"), + ({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"), + ({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"), + ({"job_type": "column_refresh", "job_types": []}, "only one"), + ({"state": "unknown"}, "state must be"), + ], +) +async def test_invalid_job_filters_do_not_fetch( + listing_server, asynchronous, filters, message +): + endpoint, requests, _ = listing_server + db = await connection(endpoint, asynchronous) + with pytest.raises(ValueError, match=message): + items = db.list_jobs(**filters) + await advance(items, asynchronous) + assert requests == [] + + +@pytest.mark.asyncio +async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server): + endpoint, requests, responses = listing_server + responses.extend( + (200, response_page("jobs", names, token)) + for names, token in [(["a", "b"], "second"), (["c", "d"], "last")] + ) + db = await connection(endpoint, False) + items = db.list_jobs(table="events", page_limit=2) + assert items[:0] == [] + assert items[5:2] == [] + assert requests == [] + assert [job.job_id for job in items[:2]] == ["a", "b"] + assert len(requests) == 1 + assert items.num_page_results() == 2 + assert items.page_token() == "second" + assert items[1].job_id == "b" + assert next(items).job_id == "a" + assert [job.job_id for job in items[:2]] == ["b", "c"] + assert len(requests) == 2 + assert items.num_page_results() == 3 + assert items.page_token() == "last" + assert [job.job_id for job in items[0:3:2][:1]] == ["b"] + assert len(requests) == 2 + + +@pytest.mark.asyncio +async def test_listing_length_and_slices_preserve_remaining_items(listing_server): + endpoint, requests, responses = listing_server + responses.extend( + (200, response_page("jobs", names, token)) + for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)] + ) + db = await connection(endpoint, False) + items = db.list_jobs(page_limit=2) + assert bool(items) + assert len(requests) == 1 + assert next(items).job_id == "a" + assert len(items) == 3 + assert len(requests) == 3 + assert items.num_page_results() == 3 + assert items.page_token() is None + assert items[-1].job_id == "d" + assert [job.job_id for job in items[::-1]] == ["d", "c", "b"] + assert [job.job_id for job in items[1:]] == ["c", "d"] + assert [job.job_id for job in items[:100:2]] == ["b", "d"] + assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"] + with pytest.raises(IndexError): + _ = items[3] + assert [job.job_id for job in items] == ["b", "c", "d"] + assert len(items) == 0 + assert not items + assert len(requests) == 3 + + +@pytest.mark.asyncio +async def test_listing_invalid_slice_does_not_fetch(listing_server): + endpoint, requests, _ = listing_server + db = await connection(endpoint, False) + items = db.list_jobs() + with pytest.raises(ValueError, match="step"): + _ = items[::0] + with pytest.raises(TypeError): + _ = items["invalid"] + with pytest.raises(TypeError): + _ = items[:1.5] + assert requests == [] + + +@pytest.mark.asyncio +async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server): + endpoint, requests, responses = listing_server + responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})]) + db = await connection(endpoint, False) + items = db.list_jobs(page_limit=2) + with pytest.raises(HttpError): + _ = items[:3] + assert items.page_token() == "retry" + assert items.num_page_results() == 2 + assert [job.job_id for job in items[:2]] == ["a", "b"] + assert [job.job_id for job in items] == ["a", "b"] + assert len(requests) == 2 diff --git a/python/src/connection.rs b/python/src/connection.rs index 1a171032c..2d65a0459 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -23,7 +23,7 @@ use lancedb::{ connection::Connection as LanceConnection, connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, - database::{CreateTableMode, Database, ReadConsistency}, + database::{CreateTableMode, Database, JobListFilter, JobListState, ReadConsistency}, function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, materialized_view::CreateMaterializedViewBuilder, @@ -1319,15 +1319,47 @@ impl Connection { )) } - #[pyo3(signature = (*, page_token=None, page_limit=None))] + #[allow(clippy::too_many_arguments)] + #[pyo3(signature = (*, page_token=None, page_limit=None, table=None, namespace_path=None, state=None, job_type=None, job_types=None, created_at_gte_millis=None, created_at_lt_millis=None))] pub fn list_jobs( &self, page_token: Option, page_limit: Option, + table: Option, + namespace_path: Option>, + state: Option, + job_type: Option, + job_types: Option>, + created_at_gte_millis: Option, + created_at_lt_millis: Option, ) -> PyResult { + if job_type.is_some() && job_types.is_some() { + return Err(PyValueError::new_err( + "set only one of job_type and job_types", + )); + } + let mut filter = JobListFilter::default(); + filter.table = table; + filter.namespace_path = namespace_path.unwrap_or_default(); + filter.state = state + .as_deref() + .map(|state| match state { + "in_progress" => Ok(JobListState::InProgress), + "succeeded" => Ok(JobListState::Succeeded), + "failed" => Ok(JobListState::Failed), + "canceled" => Ok(JobListState::Canceled), + "timed_out" => Ok(JobListState::TimedOut), + _ => Err(PyValueError::new_err( + "state must be one of: in_progress, succeeded, failed, canceled, timed_out", + )), + }) + .transpose()?; + filter.job_types = job_types.unwrap_or_else(|| job_type.into_iter().collect()); + filter.created_at_gte_millis = created_at_gte_millis; + filter.created_at_lt_millis = created_at_lt_millis; Ok(crate::listing::JobListing::new( self.get_inner()? - .list_jobs(crate::listing::options(page_token, page_limit)), + .list_jobs_filtered(filter, crate::listing::options(page_token, page_limit)), )) } diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 6dacbbbea..29f70d164 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -23,8 +23,8 @@ use crate::connection::create_table::CreateTableBuilder; use crate::data::scannable::Scannable; use crate::database::listing::ListingDatabase; use crate::database::{ - CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, OpenTableRequest, - PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, + CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, JobListFilter, + OpenTableRequest, PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; @@ -1366,6 +1366,37 @@ impl Connection { }) } + /// List jobs using server-side filters, without scanning all history in the client. + /// + /// Filters are preserved on every page, including when resuming with a saved + /// token. Requests and errors occur during iteration, as with [`Self::list_jobs`]. + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// use lancedb::{database::JobListFilter, listing::ListingOptions}; + /// let mut filter = JobListFilter::default(); + /// filter.table = Some("events".into()); + /// let mut jobs = connection.list_jobs_filtered(filter, ListingOptions::default().page_limit(5)); + /// if let Some(job) = jobs.try_next().await? { + /// println!("{}", job.job_id); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + Listing::new(options, move |options| { + let database = database.clone(); + let filter = filter.clone(); + async move { database.list_jobs_filtered(filter, options).await } + }) + } + /// Request cancellation of a server-side job by id. Returns true if the /// server accepted the cancellation, false if no such job exists. pub async fn cancel_job(&self, job_id: impl AsRef) -> Result { diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 638ae0dd5..8a7a941f6 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -238,6 +238,45 @@ pub enum ReadConsistency { Strong, } +/// Registry lifecycle states accepted when filtering jobs. +#[derive(Clone, Copy, Debug, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum JobListState { + /// A job that has not reached a terminal state. + InProgress, + /// A job that completed successfully. + Succeeded, + /// A job that failed. + Failed, + /// A job that was canceled. + Canceled, + /// A job that exceeded its timeout. + TimedOut, +} + +/// Server-side filters applied before job pagination. +/// +/// Continuation tokens must be resumed with the same filters. Creation times +/// are Unix timestamps in milliseconds; the lower bound is inclusive and the +/// upper bound is exclusive. +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct JobListFilter { + /// Table name within `namespace_path`, including all its branches; absent means all tables. + pub table: Option, + /// Namespace of `table`; requires a table name. + pub namespace_path: Vec, + /// Registry state, such as `in_progress`, `succeeded`, or `failed`. + /// These are server states, rather than the labels in [`JobInfo::state`]. + pub state: Option, + /// Include jobs of any of these types; empty means all types. + pub job_types: Vec, + /// Inclusive creation-time lower bound. + pub created_at_gte_millis: Option, + /// Exclusive creation-time upper bound. + pub created_at_lt_millis: Option, +} + /// A row from [`Database::list_jobs`]: one server-side job (index build, /// compaction, column refresh, ...). #[derive(Debug, Clone)] @@ -781,6 +820,14 @@ pub trait Database: async fn list_jobs(&self, _options: ListingOptions) -> Result> { job_op_not_supported("list_jobs") } + /// Fetch one page of jobs matching server-side filters. + async fn list_jobs_filtered( + &self, + _filter: JobListFilter, + _options: ListingOptions, + ) -> Result> { + job_op_not_supported("list_jobs_filtered") + } /// Request cancellation of a job by id. Returns true if the server /// accepted the cancellation, false if no such job exists. Cancelling an /// already-terminal job is a no-op success. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 1a825bebc..125930cb7 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -22,7 +22,8 @@ use lance_namespace::models::{ use crate::Error; use crate::database::{ CloneTableRequest, CreateTableMode, CreateTableRequest, Database, DatabaseOptions, - ExecuteQueryRequest, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, + ExecuteQueryRequest, JobInfo, JobListFilter, OpenTableRequest, ReadConsistency, + TableNamesRequest, }; use crate::error::Result; use crate::function::{FunctionRegistrationRequest, FunctionVersion, GpuClass}; @@ -1290,7 +1291,54 @@ impl Database for RemoteDatabase { } async fn list_jobs(&self, options: ListingOptions) -> Result> { - let mut body = serde_json::json!({}); + self.list_jobs_filtered(JobListFilter::default(), options) + .await + } + + async fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Result> { + if self.db_name.is_empty() { + return Err(Error::InvalidInput { + message: "list_jobs requires a connected database".into(), + }); + } + if filter.table.is_none() && !filter.namespace_path.is_empty() { + return Err(Error::InvalidInput { + message: "namespace_path requires a table filter".into(), + }); + } + if let (Some(start), Some(end)) = + (filter.created_at_gte_millis, filter.created_at_lt_millis) + && start >= end + { + return Err(Error::InvalidInput { + message: "created_at_gte_millis must be less than created_at_lt_millis".into(), + }); + } + let mut body = serde_json::json!({"database": self.db_name}); + if let Some(table) = filter.table { + validate_table_name(&table)?; + validate_namespace(&filter.namespace_path)?; + body["table_ref"] = serde_json::json!({ + "db_name": self.db_name, + "table_id": {"namespace_path": filter.namespace_path, "table_name": table}, + }); + } + if let Some(state) = filter.state { + body["state"] = serde_json::json!(state); + } + if !filter.job_types.is_empty() { + body["job_types"] = serde_json::json!(filter.job_types); + } + if let Some(start) = filter.created_at_gte_millis { + body["created_at_gte_millis"] = start.into(); + } + if let Some(end) = filter.created_at_lt_millis { + body["created_at_lt_millis"] = end.into(); + } if let Some(token) = options.page_token { body["page_token"] = token.into(); } @@ -1999,7 +2047,7 @@ mod tests { use rstest::rstest; use crate::connection::ConnectBuilder; - use crate::database::Database; + use crate::database::{Database, JobListFilter, JobListState}; use crate::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity}; use crate::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition}; use crate::materialized_view::CreateMaterializedViewRequest; @@ -4133,7 +4181,10 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) .unwrap(); - assert_eq!(body, serde_json::json!({"page_token": token, "limit": 2})); + assert_eq!( + body, + serde_json::json!({"database": "default", "page_token": token, "limit": 2}) + ); } else { let ns = "team"; assert_eq!( @@ -4336,6 +4387,84 @@ mod tests { )); } + #[tokio::test] + async fn test_list_jobs_filters_every_page_without_eager_fetching() { + let count = Arc::new(AtomicUsize::new(0)); + let seen = count.clone(); + let conn = Connection::new_with_handler(move |request| { + let page = seen.fetch_add(1, Ordering::SeqCst); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + let mut expected = serde_json::json!({ + "database": "default", + "table_ref": { + "db_name": "default", + "table_id": {"namespace_path": ["team", "project"], "table_name": "events"}, + }, + "state": "in_progress", + "job_types": ["column_refresh", "materialized_view_refresh"], + "created_at_gte_millis": 100, + "created_at_lt_millis": 200, + "limit": 1, + }); + if page > 0 { + expected["page_token"] = "next".into(); + } + assert_eq!(body, expected); + http::Response::builder().status(200).body(serde_json::json!({ + "jobs": [{"job_id": format!("job-{page}"), "table": "events", "job_type": "column_refresh", "state": "in_progress", "created_at_millis": 100}], + "page_token": (page == 0).then_some("next"), + }).to_string()).unwrap() + }); + let filter = JobListFilter { + table: Some("events".into()), + namespace_path: vec!["team".into(), "project".into()], + state: Some(JobListState::InProgress), + job_types: vec!["column_refresh".into(), "materialized_view_refresh".into()], + created_at_gte_millis: Some(100), + created_at_lt_millis: Some(200), + }; + let mut jobs = + conn.list_jobs_filtered(filter.clone(), ListingOptions::default().page_limit(1)); + assert_eq!(count.load(Ordering::SeqCst), 0); + assert_eq!(jobs.try_next().await.unwrap().unwrap().job_id, "job-0"); + assert_eq!(count.load(Ordering::SeqCst), 1); + let resumed = conn.list_jobs_filtered( + filter, + ListingOptions::default() + .page_limit(1) + .page_token(jobs.page_token().unwrap()), + ); + let remaining = resumed.try_collect::>().await.unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].job_id, "job-1"); + assert_eq!(count.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_list_jobs_invalid_filters_never_reach_server() { + let conn = Connection::new_with_handler(|_| -> http::Response { + panic!("invalid filters must not reach the server") + }); + let namespace_only = JobListFilter { + namespace_path: vec!["team".into()], + ..Default::default() + }; + let invalid_time = JobListFilter { + created_at_gte_millis: Some(200), + created_at_lt_millis: Some(100), + ..Default::default() + }; + for filter in [namespace_only, invalid_time] { + let mut jobs = conn.list_jobs_filtered(filter, ListingOptions::default()); + assert!(matches!( + jobs.try_next().await, + Err(Error::InvalidInput { .. }) + )); + assert!(jobs.try_next().await.unwrap().is_none()); + } + } + #[tokio::test] async fn test_list_jobs_does_not_truncate_after_100_pages() { let conn = Connection::new_with_handler(|request| { From 1feec84d2bb8166919a9c52640a7ad64d6f6e0e2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 15 Nov 2026 01:21:28 -0800 Subject: [PATCH 134/203] feat(python): expose FTS operators and match counts (#5042) String full-text searches now accept `operator="AND"` or `operator="OR"`, preserving the existing OR default. Sync and async FTS builders expose `count_rows()` to count every match satisfying the filter, independently of pagination, projection, ordering, and reranking. Counting streams matching scores without reading document columns; it can scan all matches. ```python query = table.search("gripper closed", query_type="fts", operator="AND") query = query.where("active = true") matching_rows = query.count_rows() page = query.limit(20).to_list() query = await async_table.search("gripper closed", query_type="fts", operator="AND") matching_rows = await query.where("active = true").count_rows() ``` Phrase searches keep the existing index default and now explain how to rebuild an index with `FTS(with_position=True)`. AND requests retain their operator through namespace pushdown and fail explicitly on older remote servers that cannot represent it. Regression coverage includes indexed and unindexed queries, filtered counts above the default limit, pagination preservation, remote serialization, and phrase indexes with and without positions. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/namespace.py | 25 ++++ python/python/lancedb/query.py | 127 ++++++++++++++++-- python/python/lancedb/remote/table.py | 8 ++ python/python/lancedb/table.py | 59 ++++++++- python/python/tests/test_fts.py | 184 ++++++++++++++++++++++++-- python/python/tests/test_namespace.py | 42 +++++- python/python/tests/test_remote_db.py | 43 ++++++ python/src/query.rs | 37 +++++- rust/lancedb/src/remote/table.rs | 16 ++- rust/lancedb/src/table/query.rs | 118 ++++++++++++----- 11 files changed, 599 insertions(+), 61 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 0cce2085e..63d442703 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -943,6 +943,7 @@ class FTSQuery: def add_query_vector(self, query_vec: pa.Array) -> None: ... def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ... def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... + async def count_rows(self) -> int: ... async def output_schema(self) -> pa.Schema: ... async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 67fcc61f7..463536619 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -10,6 +10,7 @@ through a namespace abstraction. from __future__ import annotations +import json import sys import warnings from typing import Any, Dict, Iterable, List, Optional, Union @@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import ( QueryTableRequestVector, ) from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery +from lance_namespace_urllib3_client.models.structured_fts_query import ( + StructuredFtsQuery, +) from lance_namespace.errors import ( NamespaceNotEmptyError, NamespaceNotFoundError, @@ -78,6 +82,7 @@ from lancedb.materialized_view import ( SelectArg, ) from lancedb.table import AsyncTable, LanceTable, Table +from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery from lancedb.util import validate_table_name from lancedb.common import DATA from lancedb.pydantic import LanceModel @@ -178,6 +183,26 @@ def _query_to_namespace_request( full_text_query_request = QueryTableRequestFullTextQuery( string_query=StringFtsQuery(query=fts_query) ) + elif getattr(fts_query, "operator", None) is not None: + columns = fts_query.columns or [] + text = fts_query.query + if len(text) >= 2 and text.startswith('"') and text.endswith('"'): + if len(columns) > 1: + raise ValueError( + "Phrase queries cannot be used with multiple columns." + ) + structured = PhraseQuery(text[1:-1], columns[0] if columns else None) + elif len(columns) > 1: + structured = MultiMatchQuery(text, columns, operator=fts_query.operator) + else: + structured = MatchQuery( + text, columns[0] if columns else None, operator=fts_query.operator + ) + full_text_query_request = QueryTableRequestFullTextQuery( + structured_query=StructuredFtsQuery.from_dict( + {"query": json.loads(structured.to_json())} + ) + ) elif hasattr(fts_query, "query"): full_text_query_request = QueryTableRequestFullTextQuery( string_query=StringFtsQuery( diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index f99aaeb73..214d2255f 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -42,7 +42,7 @@ from .rerankers.base import Reranker from .rerankers.rrf import RRFReranker from .rerankers.util import check_reranker_result from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field -from .util import _validate_query_vector, flatten_columns, get_uri_scheme +from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme from . import _wal_hybrid # WAL-PK-FUSION: delete. from ._blob import ( BLOB_MODE_TO_HANDLING, @@ -873,10 +873,29 @@ class FullTextSearchQuery(pydantic.BaseModel): query: str | FullTextQuery If a string, it is treated as a MatchQuery. If a FullTextQuery object, it is used directly. + operator: FullTextOperator, optional + Combine terms in a string query using AND or OR (the default). + Quoted strings keep phrase semantics regardless of the operator. """ columns: Optional[List[str]] = None query: Union[str, FullTextQuery] + operator: Optional[FullTextOperator] = None + + @pydantic.model_validator(mode="after") + def _validate_operator(self) -> Self: + if self.operator is not None and not isinstance(self.query, str): + raise ValueError("operator requires a string full-text query") + return self + + +def _add_fts_position_error_note(error: Exception) -> None: + if "position is not found but required for phrase queries" in str(error): + add_note( + error, + "Phrase queries require an index built with positions. Rebuild it with " + "table.create_index(column, config=FTS(with_position=True), replace=True).", + ) class Query(pydantic.BaseModel): @@ -1147,6 +1166,7 @@ class LanceQueryBuilder(ABC): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: bool = None, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> Self: """ Create a query builder based on the given query and query type. @@ -1171,6 +1191,10 @@ class LanceQueryBuilder(ABC): fast_search: bool Skip flat search of unindexed data. """ + if operator is not None: + operator = FullTextOperator(operator) + if not isinstance(query, str) or query_type not in ("auto", "fts"): + raise ValueError("operator requires a string full-text query") if query_type != "fts": _validate_query_vector(query) @@ -1201,6 +1225,9 @@ class LanceQueryBuilder(ABC): table, query, query_type, vector_column_name ) + if operator is not None and query_type != "fts": + raise ValueError("operator requires a string full-text query") + if query_type == "hybrid": return LanceHybridQueryBuilder( table, query, vector_column_name, fts_columns=fts_columns @@ -1214,7 +1241,7 @@ class LanceQueryBuilder(ABC): ordering_field_name=ordering_field_name, fts_columns=fts_columns, fast_search=fast_search, - ) + ).operator(operator) if isinstance(query, (list, tuple)): query = np.array(query, dtype=np.float32) @@ -2563,6 +2590,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): super().__init__(table) self._query = query self._phrase_query = False + self._operator: Optional[FullTextOperator] = None # Deprecated compatibility parameter. Native FTS ordering is now # configured through order_by(); LanceQueryBuilder.create emits the warning. _ = ordering_field_name @@ -2572,6 +2600,36 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): fts_columns = [fts_columns] self._fts_columns = fts_columns + def operator( + self, operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] + ) -> LanceFtsQueryBuilder: + """Combine terms in a string query with ``"AND"`` or ``"OR"``. + + The default is OR. AND requires every term to match. For example, + ``table.search("gripper closed", query_type="fts").operator("AND")``. + Structured queries specify their own operators. Quoted strings and + ``phrase_query()`` retain their phrase semantics. + """ + if operator is not None and not isinstance(self._query, str): + raise ValueError("operator requires a string full-text query") + self._operator = FullTextOperator(operator) if operator is not None else None + return self + + def count_rows(self) -> int: + """Count all full-text matches satisfying the query's filter. + + Ignores limit, offset, selection, ordering, and reranking. ``fast_search`` + still restricts the count to indexed data. This streams matching scores + without loading document columns and may scan every match. + + For example, ``table.search("gripper closed", query_type="fts",`` + ``operator="AND").where("active = true").count_rows()``. + """ + self._table._ensure_no_legacy_fts_index() + query = self._table._table._sync_query_to_async(self.to_query_object()) + assert isinstance(query, AsyncFTSQuery) + return LOOP.run(query.count_rows()) + def phrase_query(self, phrase_query: bool = True) -> LanceFtsQueryBuilder: """Set whether to use phrase query. @@ -2628,7 +2686,9 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): fragment_ids=self._fragment_ids, use_rte=self._use_rte, full_text_query=FullTextSearchQuery( - query=self._query_with_phrase_semantics(), columns=self._fts_columns + query=self._query_with_phrase_semantics(), + columns=self._fts_columns, + operator=self._operator, ), offset=self._offset, fast_search=self._fast_search, @@ -4443,7 +4503,11 @@ class AsyncQuery(AsyncStandardQuery): ) def nearest_to_text( - self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None + self, + query: str | FullTextQuery, + columns: Union[str, List[str], None] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncFTSQuery: """ Find the documents that are most relevant to the given text query. @@ -4464,7 +4528,11 @@ class AsyncQuery(AsyncStandardQuery): columns: str or list of str, default None The columns to search in. If None, all indexed columns are searched. For now only one column can be searched at a time. + operator: "AND" or "OR", optional + Combine terms in a string query. Defaults to OR. Quoted strings use + phrase semantics and require an index built with positions. """ + fts_query = FullTextSearchQuery(query=query, operator=operator) if isinstance(columns, str): columns = [columns] if columns is None: @@ -4472,7 +4540,13 @@ class AsyncQuery(AsyncStandardQuery): if isinstance(query, str): return AsyncFTSQuery( - self._inner.nearest_to_text({"query": query, "columns": columns}), + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), self._table, ) # FullTextQuery object @@ -4487,6 +4561,22 @@ class AsyncFTSQuery(AsyncStandardQuery): self._inner = inner self._reranker = None + async def count_rows(self) -> int: + """Count all full-text matches satisfying the query's filter. + + Ignores limit, offset, selection, ordering, and reranking. ``fast_search`` + still restricts the count to indexed data. Matching scores are streamed + without loading document columns, so counting may scan every match. + + For example, ``await table.query().nearest_to_text("gripper closed",`` + ``operator="AND").where("active = true").count_rows()``. + """ + try: + return await self._inner.count_rows() + except Exception as error: + _add_fts_position_error_note(error) + raise + def get_query(self) -> str: return self._inner.get_query() @@ -4580,10 +4670,16 @@ class AsyncFTSQuery(AsyncStandardQuery): timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: - reader = await super()._execute_batches( - timeout=timeout, blob_sources=blob_sources - ) - results = pa.Table.from_batches(await reader.read_all(), reader.schema) + try: + reader = await super()._execute_batches( + max_batch_length=max_batch_length, + timeout=timeout, + blob_sources=blob_sources, + ) + results = pa.Table.from_batches(await reader.read_all(), reader.schema) + except Exception as error: + _add_fts_position_error_note(error) + raise if self._reranker: source = results results = self._reranker.rerank_fts(self.get_query(), results) @@ -4861,7 +4957,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): return self def nearest_to_text( - self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None + self, + query: str | FullTextQuery, + columns: Union[str, List[str], None] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncHybridQuery: """ Find the documents that are most relevant to the given text query, @@ -4886,7 +4986,10 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): columns: str or list of str, default None The columns to search in. If None, all indexed columns are searched. For now only one column can be searched at a time. + operator: "AND" or "OR", optional + Combine terms in a string query. Defaults to OR. """ + fts_query = FullTextSearchQuery(query=query, operator=operator) if isinstance(columns, str): columns = [columns] if columns is None: @@ -4894,7 +4997,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): if isinstance(query, str): return AsyncHybridQuery( - self._inner.nearest_to_text({"query": query, "columns": columns}), + self._inner.nearest_to_text( + {"query": query, "columns": columns, "operator": fts_query.operator} + ), self._table, ) # FullTextQuery object diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 818d2a257..2d068536e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -65,6 +65,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry from lancedb.table import _normalize_progress from ..query import ( + FullTextOperator, AnalyzePlanDistributedMetrics, DocumentGranularity, FullTextQuery, @@ -799,6 +800,8 @@ class RemoteTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceQueryBuilder: """Create a search query to find the nearest neighbors of the given query vector. We currently support @@ -857,6 +860,10 @@ class RemoteTable(Table): - *default None*, which leaves fast search disabled. + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- LanceQueryBuilder @@ -893,6 +900,7 @@ class RemoteTable(Table): ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], fast_search=fast_search, + operator=operator, ) def _execute_query( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 4a713da06..807edbc46 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -91,6 +91,7 @@ from .functions import ( from .merge import LanceMergeInsertBuilder from .pydantic import LanceModel, model_to_dict from .query import ( + FullTextOperator, AnalyzePlanDistributedMetrics, AsyncFTSQuery, AsyncHybridQuery, @@ -138,6 +139,11 @@ def _requires_local_namespace_execution(query: Query) -> bool: or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None + or ( + query.full_text_query is not None + and query.fast_search is True + and query.vector is None + ) ) @@ -2443,6 +2449,8 @@ class Table(ABC): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = 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/) @@ -2506,6 +2514,10 @@ class Table(ABC): - If `query` is a string, then the query type is "vector" if the table has embedding functions else the query type is "fts" + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- LanceQueryBuilder @@ -5061,6 +5073,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceVectorQueryBuilder: ... @overload @@ -5072,6 +5086,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceFtsQueryBuilder: ... @overload @@ -5085,6 +5101,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceHybridQueryBuilder: ... @overload @@ -5096,6 +5114,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> LanceEmptyQueryBuilder: ... def search( @@ -5108,6 +5128,8 @@ class LanceTable(Table): ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, fast_search: Optional[bool] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = 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/) @@ -5168,6 +5190,10 @@ class LanceTable(Table): If None then the search is performed on all indexed columns. For now, only one column can be searched at a time. + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- LanceQueryBuilder @@ -5193,6 +5219,7 @@ class LanceTable(Table): ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], fast_search=fast_search, + operator=operator, ) @classmethod @@ -7376,6 +7403,8 @@ class AsyncTable: query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncQuery: ... @overload @@ -7386,6 +7415,8 @@ class AsyncTable: query_type: Literal["auto"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> Union[AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: ... @overload @@ -7396,6 +7427,8 @@ class AsyncTable: query_type: Literal["hybrid"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncHybridQuery: ... @overload @@ -7406,6 +7439,8 @@ class AsyncTable: query_type: Literal["auto"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncVectorQuery: ... @overload @@ -7416,6 +7451,8 @@ class AsyncTable: query_type: Literal["fts"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncFTSQuery: ... @overload @@ -7426,6 +7463,8 @@ class AsyncTable: query_type: Literal["vector"] = ..., ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> AsyncVectorQuery: ... async def search( @@ -7437,6 +7476,8 @@ class AsyncTable: query_type: QueryType = "auto", ordering_field_name: Optional[str] = None, fts_columns: Optional[Union[str, List[str]]] = None, + *, + operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None, ) -> Union[AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: """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/) @@ -7480,12 +7521,20 @@ class AsyncTable: - If `query` is a string, then the query type is "vector" if the table has embedding functions else the query type is "fts" + operator: "AND" or "OR", optional + Combine terms in a string full-text query; the default is OR. + Use ``query_type="fts"`` when the table also has embeddings. + Returns ------- AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, or AsyncVectorQuery A query builder object representing the query. """ + if operator is not None: + operator = FullTextOperator(operator) + if not isinstance(query, str) or query_type not in ("auto", "fts"): + raise ValueError("operator requires a string full-text query") if query is None: return self.query() @@ -7604,13 +7653,17 @@ class AsyncTable: ) vector_query = await make_embedding(embedding_conf, query) + if operator is not None and query_type != "fts": + raise ValueError("operator requires a string full-text query") if query_type == "vector": builder = self.query().nearest_to(vector_query) if vector_column_name: builder = builder.column(vector_column_name) return builder elif query_type == "fts": - return self.query().nearest_to_text(query, columns=fts_columns) + return self.query().nearest_to_text( + query, columns=fts_columns, operator=operator + ) elif query_type == "hybrid": builder = self.query().nearest_to(vector_query) if vector_column_name: @@ -7720,7 +7773,9 @@ class AsyncTable: if query.full_text_query: async_query = async_query.nearest_to_text( - query.full_text_query.query, query.full_text_query.columns + query.full_text_query.query, + query.full_text_query.columns, + operator=query.full_text_query.operator, ) return async_query diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index f2fcc970b..26ce5e528 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -29,6 +29,7 @@ from lancedb.query import ( CombinedFieldsQuery, DocumentGranularity, FullTextOperator, + FullTextSearchQuery, MatchQuery, MultiMatchQuery, PhraseQuery, @@ -530,11 +531,9 @@ async def test_fts_select_async(async_table): def test_search_fts_phrase_query(table): table.create_fts_index("text", with_position=False) - try: - phrase_results = table.search('"puppy runs"').limit(100).to_list() - assert False - except Exception: - pass + with pytest.raises(Exception) as error: + table.search('"puppy runs"').limit(100).to_list() + assert "FTS(with_position=True)" in exception_output(error) table.create_fts_index("text", with_position=True, replace=True) results = table.search("puppy").limit(100).to_list() @@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table): @pytest.mark.asyncio async def test_search_fts_phrase_query_async(async_table): await async_table.create_index("text", config=FTS(with_position=False)) - try: - phrase_results = ( - await async_table.query().nearest_to_text("puppy runs").limit(100).to_list() - ) - assert False - except Exception: - pass + with pytest.raises(Exception) as error: + await async_table.query().nearest_to_text('"puppy runs"').to_list() + assert "FTS(with_position=True)" in exception_output(error) await async_table.create_index("text", config=FTS(with_position=True)) results = await async_table.query().nearest_to_text("puppy").limit(100).to_list() phrase_results = ( @@ -1948,3 +1943,168 @@ async def test_async_fts_code_analyzer(mem_db_async): rows = await table.query().nearest_to_text("http").to_list() assert len(rows) == 1 + + +@pytest.mark.parametrize("indexed", [False, True]) +@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)]) +def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected): + db = ldb.connect(tmp_path) + table = db.create_table( + "matches", + pa.table( + { + "id": list(range(30)), + "text": ["gripper closed"] * 15 + + ["gripper open"] * 10 + + ["camera ready"] * 5, + } + ), + ) + if indexed: + table.create_index("text", config=FTS()) + kwargs = {"fts_columns": "text"} + if operator is not None: + kwargs["operator"] = operator + query = table.search("gripper closed", query_type="fts", **kwargs) + assert query.count_rows() == expected + assert len(query.limit(100).to_list()) == expected + assert ( + table.search("gripper closed", query_type="fts", fts_columns="text") + .operator("AND") + .count_rows() + == 15 + ) + if operator is not None: + assert query.to_query_object().full_text_query.operator == operator + query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1) + before = query.to_query_object() + assert query.count_rows() == expected - 5 + assert query.to_query_object() == before + assert len(query.to_list()) <= 2 + assert ( + table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0 + ) + assert ( + table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows() + == 15 + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("indexed", [False, True]) +@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)]) +async def test_simple_fts_operator_and_count_async( + tmp_path, indexed, operator, expected +): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "matches", + pa.table( + { + "id": list(range(30)), + "text": ["gripper closed"] * 15 + + ["gripper open"] * 10 + + ["camera ready"] * 5, + } + ), + ) + if indexed: + await table.create_index("text", config=FTS()) + query = await table.search( + "gripper closed", query_type="fts", fts_columns="text", operator=operator + ) + assert await query.count_rows() == expected + assert len(await query.limit(100).to_list()) == expected + query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1) + before = query.to_query_object() + assert await query.count_rows() == expected - 5 + assert query.to_query_object() == before + direct = table.query().nearest_to_text( + "gripper closed", columns="text", operator="AND" + ) + assert await direct.count_rows() == 15 + assert direct.to_query_object().full_text_query.query.operator == "AND" + assert ( + await table.query().nearest_to_text("absent", columns="text").count_rows() == 0 + ) + + +@pytest.mark.parametrize("with_position", [False, True]) +@pytest.mark.parametrize( + "query", ['"gripper closed"', PhraseQuery("gripper closed", "text")] +) +def test_fts_phrase_count_positions(tmp_path, with_position, query): + table = ldb.connect(tmp_path).create_table( + "phrases", pa.table({"text": ["gripper closed", "gripper often closed"]}) + ) + table.create_index("text", config=FTS(with_position=with_position)) + search = table.search(query, query_type="fts") + if with_position: + assert search.count_rows() == 1 + assert len(search.to_list()) == 1 + assert ( + table.search("gripper closed", query_type="fts", operator="AND") + .phrase_query() + .count_rows() + == 1 + ) + else: + with pytest.raises(Exception) as error: + search.count_rows() + assert "FTS(with_position=True)" in exception_output(error) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("with_position", [False, True]) +@pytest.mark.parametrize( + "query", ['"gripper closed"', PhraseQuery("gripper closed", "text")] +) +async def test_fts_phrase_count_positions_async(tmp_path, with_position, query): + db = await ldb.connect_async(tmp_path) + table = await db.create_table( + "phrases", pa.table({"text": ["gripper closed", "gripper often closed"]}) + ) + await table.create_index("text", config=FTS(with_position=with_position)) + search = table.query().nearest_to_text(query) + if with_position: + assert await search.count_rows() == 1 + assert len(await search.to_list()) == 1 + else: + with pytest.raises(Exception) as error: + await search.count_rows() + assert "FTS(with_position=True)" in exception_output(error) + + +def test_fts_operator_rejects_invalid_queries(table): + with pytest.raises(ValueError): + table.search("gripper", query_type="fts", operator="XOR") + for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]: + with pytest.raises( + ValueError, match="operator requires a string full-text query" + ): + table.search(query, operator="AND") + with pytest.raises(ValueError, match="operator requires a string full-text query"): + FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND") + + +@pytest.mark.asyncio +async def test_fts_operator_rejects_invalid_queries_async(async_table): + with pytest.raises(ValueError): + await async_table.search("gripper", query_type="fts", operator="XOR") + for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]: + with pytest.raises( + ValueError, match="operator requires a string full-text query" + ): + await async_table.search(query, operator="AND") + with pytest.raises(ValueError): + async_table.query().nearest_to_text(query, operator="AND") + + +def test_fts_count_fast_search(tmp_path): + table = ldb.connect(tmp_path).create_table( + "matches", pa.table({"text": ["gripper closed"] * 15}) + ) + table.create_index("text", config=FTS()) + table.add(pa.table({"text": ["gripper closed"] * 5})) + assert table.search("gripper", query_type="fts").count_rows() == 20 + assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15 diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 9bce1059d..b4ca746b0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -18,6 +18,7 @@ import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from utils import start_server_thread from lancedb.listing import AsyncListing, Listing +from lancedb.index import FTS from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY from lancedb.namespace import ( _MAX_QUERY_K, @@ -25,7 +26,7 @@ from lancedb.namespace import ( LanceNamespaceDBConnection, _query_to_namespace_request, ) -from lancedb.query import Query +from lancedb.query import FullTextSearchQuery, Query from lancedb.table import AsyncTable, LanceTable @@ -1524,3 +1525,42 @@ def test_python_namespace_attribute_access(tmp_path): # Missing dunder lookups still raise, so copy/hasattr probes work. assert not hasattr(request, "__missing_dunder__") assert copy.deepcopy(request) == request + + +@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]]) +def test_namespace_fts_operator_is_preserved(columns): + request = _query_to_namespace_request( + ["matches"], + Query( + full_text_query=FullTextSearchQuery( + query="gripper closed", columns=columns, operator="AND" + ) + ), + ) + structured = request.to_dict()["full_text_query"]["structured_query"]["query"] + if columns and len(columns) > 1: + assert all( + query["operator"] == "And" + for query in structured["multi_match"]["match_queries"] + ) + else: + assert structured["match"]["operator"] == "And" + assert structured["match"].get("column") == (columns[0] if columns else None) + + +def test_namespace_fts_count_fast_search(tmp_path): + properties = {"root": str(tmp_path)} + db = lancedb.connect_namespace("dir", properties) + table = db.create_table("matches", pa.table({"text": ["gripper"] * 15})) + table.create_index("text", config=FTS()) + table.add(pa.table({"text": ["gripper"] * 5})) + assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15 + pushed = lancedb.connect_namespace( + "dir", properties, namespace_client_pushdown_operations=["QueryTable"] + ).open_table("matches") + assert pushed.search("gripper", query_type="fts").count_rows() == 20 + query = pushed.search("gripper", query_type="fts").fast_search() + assert query.use_rte(False).count_rows() == 15 + query = pushed.search("gripper", query_type="fts").fast_search() + assert query.count_rows() == 15 + assert len(query.limit(100).to_list()) == 15 diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index f404e36f7..587e2d587 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -7802,3 +7802,46 @@ async def test_remote_index_exist_ok_wire(is_async, background, kwargs): assert body["replace"] is False else: assert "replace" not in body + + +@pytest.mark.parametrize("operator", ["AND", "OR"]) +def test_remote_fts_operator_and_count(operator): + def handler(body): + query = body["full_text_query"]["query"]["match"] + assert query["terms"] == "gripper closed" + assert query["operator"] == operator.title() + assert query["column"] == "text" + assert body["k"] == 2**63 - 1 + assert "offset" not in body + assert body["columns"] == ["_score"] + assert body["filter"] == "text IS NOT NULL" + assert body["prefilter"] is False + return pa.table({"_score": [1.0] * 25}) + + with query_test_table( + handler, server_version=Version("0.6.0"), vector_columns={} + ) as table: + query = ( + table.search( + "gripper closed", + query_type="fts", + fts_columns="text", + operator=operator, + ) + .where("text IS NOT NULL", prefilter=False) + .select(["text"]) + .limit(1) + .offset(3) + ) + assert query.count_rows() == 25 + assert query.to_query_object().limit == 1 + assert query.to_query_object().offset == 3 + + +def test_remote_fts_and_rejects_legacy_server(): + def handler(body): + pytest.fail("AND must not silently become OR on a legacy server") + + with query_test_table(handler, vector_columns={}) as table: + with pytest.raises(NotImplementedError, match="server version 0.3.0"): + table.search("gripper closed", query_type="fts", operator="AND").to_list() diff --git a/python/src/query.rs b/python/src/query.rs index 2097dac69..9864d7d74 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -16,19 +16,20 @@ use arrow::array::make_array; use arrow::pyarrow::FromPyArrow; use arrow::pyarrow::IntoPyArrow; use arrow::pyarrow::ToPyArrow; +use futures::TryStreamExt; use lancedb::ApproxMode; use lancedb::index::scalar::{ BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery, FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery, }; use lancedb::query::AnalyzePlanDistributedMetrics; -use lancedb::query::QueryBase; use lancedb::query::QueryExecutionOptions; use lancedb::query::QueryFilter; use lancedb::query::{ ColumnOrdering, ExecutableQuery, Query as LanceDbQuery, Select, TakeQuery as LanceDbTakeQuery, VectorQuery as LanceDbVectorQuery, }; +use lancedb::query::{HasQuery, QueryBase}; use lancedb::table::AnyQuery; use pyo3::Bound; use pyo3::IntoPyObject; @@ -616,8 +617,18 @@ impl Query { query_text = query_text[1..query_text.len() - 1].to_string(); } + let operator = query + .get_item("operator")? + .filter(|operator| !operator.is_none()) + .map(|operator| { + let operator = operator.extract::()?; + Operator::try_from(operator.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string())) + }) + .transpose()? + .unwrap_or(Operator::Or); let query: FtsQuery = match (is_phrase, is_multi_match) { - (false, _) => MatchQuery::new(query_text).into(), + (false, _) => MatchQuery::new(query_text).with_operator(operator).into(), (true, false) => PhraseQuery::new(query_text).into(), (true, true) => { return Err(PyValueError::new_err( @@ -898,6 +909,28 @@ impl FTSQuery { }) } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { + let mut inner = self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()); + let request = inner.mut_query(); + request.limit = None; + request.offset = None; + request.select = Select::columns(&["_score"]); + request.order_by = None; + request.with_row_id = false; + request.reranker = None; + future_into_py(self_.py(), async move { + let mut stream = inner.execute().await.infer_error()?; + let mut count = 0_u64; + while let Some(batch) = stream.try_next().await.infer_error()? { + count += batch.num_rows() as u64; + } + Ok(count) + }) + } + pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult { let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?; Ok(HybridQuery { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2224203cf..1394f1ab0 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -20,7 +20,7 @@ use crate::error::{HttpErrorSource, RemoteErrorMetadata}; use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; -use crate::index::scalar::FtsQuery; +use crate::index::scalar::{FtsQuery, Operator}; use crate::index::waiter::{MAX_WAIT, wait_for_index}; use crate::job::Job; use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult}; @@ -1374,6 +1374,20 @@ impl RemoteTable { "query": full_text_search.query.clone(), }); } else { + let has_and = match &full_text_search.query { + FtsQuery::Match(query) => query.operator == Operator::And, + FtsQuery::MultiMatch(query) => query + .match_queries + .iter() + .any(|query| query.operator == Operator::And), + _ => false, + }; + if has_and { + return Err(Error::NotSupported { + message: "AND full-text queries require server version 0.3.0 or later" + .into(), + }); + } body["full_text_query"] = serde_json::json!({ "columns": full_text_search.columns().into_iter().collect::>(), "query": full_text_search.query.query(), diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index e9bcd380d..7d98dc001 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -12,6 +12,7 @@ use super::NativeTable; use crate::connection::NamespaceClientPushdownOperation; use crate::error::{Error, Result}; use crate::expr::expr_to_sql_string; +use crate::index::scalar::{FtsQuery, Operator as FullTextOperator}; use crate::query::{ DEFAULT_TOP_K, QueryExecutionOptions, QueryFilter, QueryRequest, Select, VectorQueryRequest, }; @@ -36,12 +37,13 @@ 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::scalar::FullTextSearchQuery; 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, - QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, + QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, StructuredFtsQuery, }; #[derive(Debug, Clone)] @@ -124,6 +126,10 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { if query.base().use_rte.is_some() || query.base().has_take() { return true; } + if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) + { + return true; + } matches!( query, AnyQuery::VectorQuery(vector_query) @@ -858,6 +864,33 @@ async fn execute_namespace_query( parse_arrow_ipc_response(response_bytes).await } +fn namespace_fts_query(fts: &FullTextSearchQuery) -> Result> { + if !matches!(&fts.query, FtsQuery::Match(query) if query.operator == FullTextOperator::Or) { + let query = serde_json::to_value(&fts.query) + .and_then(serde_json::from_value) + .map_err(|error| Error::InvalidInput { + message: format!("Cannot serialize namespace full-text query: {error}"), + })?; + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: None, + structured_query: Some(Box::new(StructuredFtsQuery::new(query))), + })) + } else { + let columns = fts.columns(); + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: Some(Box::new(StringFtsQuery { + query: fts.query.query().clone(), + columns: if columns.is_empty() { + None + } else { + Some(columns.into_iter().collect()) + }, + })), + structured_query: None, + })) + } +} + /// Convert an AnyQuery to the namespace QueryTableRequest format. fn convert_to_namespace_query(query: &AnyQuery) -> Result { query.base().check_filter()?; @@ -912,21 +945,12 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { } // Convert FTS query if present - let full_text_query = vq.base.full_text_search.as_ref().map(|fts| { - let columns = fts.columns(); - let columns_vec = if columns.is_empty() { - None - } else { - Some(columns.into_iter().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = vq + .base + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; Ok(NsQueryTableRequest { id: None, // Will be set in namespace_query @@ -963,7 +987,6 @@ 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, }; @@ -995,20 +1018,11 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { }; // Handle full text search if present - let full_text_query = q.full_text_search.as_ref().map(|fts| { - let columns_vec = if fts.columns().is_empty() { - None - } else { - Some(fts.columns().iter().cloned().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = q + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; // Empty vector for non-vector queries let vector = Box::new(QueryTableRequestVector { @@ -1023,6 +1037,7 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { filter, columns, prefilter: Some(q.prefilter), + fast_search: Some(q.fast_search), offset: q.offset.map(|o| o as i32), vector_column: None, // No vector column for plain queries with_row_id: Some(q.with_row_id), @@ -1147,6 +1162,7 @@ async fn parse_arrow_ipc_response(bytes: bytes::Bytes) -> Result Date: Sun, 15 Nov 2026 02:05:06 -0800 Subject: [PATCH 135/203] fix(python): show Function registration progress and image details (#5040) Report registration lifecycle and client elapsed time through existing job handles, and provide concise image inspection. Preserve quiet wait behavior, environment-lock forwarding, failure diagnostics and timeout recovery. --- docs/src/python/python.md | 19 ++ python/python/lancedb/db.py | 11 +- python/python/lancedb/functions.py | 59 +++++- python/python/lancedb/job.py | 75 ++++++- .../tests/test_first_class_function_slice1.py | 55 +++++ python/python/tests/test_job.py | 190 +++++++++++++++++- 6 files changed, 396 insertions(+), 13 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b7eb1704a..b0425e1f7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -424,6 +424,25 @@ code that used the former LanceDB Enterprise-only argument order. ## Functions and Jobs +Use `progress=True` when waiting for Function registration in a notebook or +terminal. A callback receives structured snapshots instead: + +```python +fn = db.create_function(my_function, progress=True) +registration = db.create_function_async(other_function) +fn = registration.wait(progress=lambda snapshot: print(snapshot)) +print(fn.image.describe()) +``` + +Registration uses the existing SQL query handle. The current handle reports +lifecycle state and `client_elapsed_time_millis` since the handle was created; +detailed build phases and build logs are unavailable. Keep the same handle after +a wait timeout to resume waiting. Failures retain the server error and request +identifiers. `fn.image` has a concise representation; `describe()` exposes Python +and CUDA requirements without inspecting Pydantic internals. Platforms, base image +and size are `None` until the service reports them. The full image descriptor and +canonical JSON remain available. + A `@function` definition is also a local callable. Call a decorated function directly with row inputs, or call a decorated class with its initialization fields and then call the returned instance; call `close()` if the class defines it. This diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b225a6e65..8c9901aff 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1051,6 +1051,7 @@ class DBConnection(EnforceOverrides): exist_ok: bool = False, namespace_path: Optional[List[str]] = None, refresh_lock: bool = False, + progress: Any = False, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. @@ -1076,6 +1077,9 @@ class DBConnection(EnforceOverrides): refresh_lock : bool, default False Ask the server to resolve a fresh environment lock instead of reusing the published version's lock. + progress : bool, callable, or tqdm-like object, default False + Display lifecycle state and elapsed time, or receive structured + snapshots through a callback. See [Job.wait][lancedb.job.Job.wait]. When the registration job resolves, each resolved-environment warning reported by the server is emitted as a Python ``UserWarning``. Catalog @@ -1095,13 +1099,16 @@ class DBConnection(EnforceOverrides): ) ``` """ - return self.create_function_async( + job = self.create_function_async( definition, secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, refresh_lock=refresh_lock, - ).wait() + ) + if progress is False or progress is None: + return job.wait() + return job.wait(progress=progress) def create_function_async( self, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 548129211..f57a114dc 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -544,13 +544,70 @@ class PythonRuntimeSpec(_RemoteValue): class FunctionImage(_RemoteValue): - """A complete OCI Function image identified by its exact manifest digest.""" + """A complete OCI Function image identified by its exact manifest digest. + + ``describe()`` and the concise representation inspect the descriptor without + walking Pydantic model internals. Missing metadata is ``None`` (unknown). + The current service does not report image platforms, base image or byte size; + these cannot be inferred from the client's platform or the manifest digest. + The full descriptor remains available through ``descriptor``. + """ manifest_digest: str descriptor: Mapping[str, Any] source: bool models: tuple[HuggingFaceModel, ...] = () + def describe(self) -> dict[str, Any]: + """Return concise image details without fetching registry content. + + ``requires_gpu`` reflects a ``lance.cuda`` requirement in a v1 + descriptor, rather than promising compatibility with every GPU. + ``platforms``, ``base_image`` and ``size_bytes`` are unavailable from + the current wire contract and return ``None``. + + Examples + -------- + >>> print(fn.image.describe()) # doctest: +SKIP + """ + python = self.descriptor.get("python") + requires = self.descriptor.get("requires") + capabilities = ( + requires.get("capabilities") if isinstance(requires, Mapping) else None + ) + known_capabilities = ( + self.descriptor.get("format_version") == 1 + and isinstance(capabilities, (list, tuple)) + and all(isinstance(item, Mapping) for item in capabilities) + ) + cuda = ( + next( + (item for item in capabilities if item.get("type") == "lance.cuda"), + None, + ) + if known_capabilities + else None + ) + python_version = python.get("version") if isinstance(python, Mapping) else None + cuda_toolkit = cuda.get("cuda_toolkit") if cuda is not None else None + return { + "manifest_digest": self.manifest_digest, + "python_version": python_version + if isinstance(python_version, str) + else None, + "requires_gpu": cuda is not None if known_capabilities else None, + "cuda_toolkit": cuda_toolkit if isinstance(cuda_toolkit, str) else None, + "platforms": None, + "base_image": None, + "size_bytes": None, + } + + def __repr_args__(self): + for name, value in self.describe().items(): + if isinstance(value, str) and len(value) > 80: + value = value[:77] + "..." + yield name, value + class ResolvedPackage(_RemoteValue): """One installed Python distribution measured from a baked environment. diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 9195e01ae..e49609e1f 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -4,8 +4,10 @@ """Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio +import logging import reprlib import time +from contextlib import suppress from datetime import timedelta from os import PathLike from pathlib import Path @@ -53,11 +55,13 @@ def _timeout_message( ) -def _normalize_job_progress(progress): +def _normalize_job_progress(progress, *, query=False): """Normalize ``wait(progress=...)`` using the same convention as writes.""" if progress is True: from tqdm.auto import tqdm + if query: + return tqdm(bar_format="Query{postfix} [{elapsed}]"), True return tqdm(unit=" rows"), True if progress is False or progress is None: return None, False @@ -65,6 +69,7 @@ def _normalize_job_progress(progress): _ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000 +_QUERY_PROGRESS_INTERVAL_SECONDS = 1.0 def _progress_eta(previous, current): @@ -203,6 +208,7 @@ class AsyncJob(Generic[T]): self._inner = inner self._result_decoder = result_decoder self._last_progress_snapshot = None + self._created_at = time.monotonic() def _enrich_progress(self, snapshot): enriched = _with_progress_eta(self._last_progress_snapshot, snapshot) @@ -235,17 +241,29 @@ class AsyncJob(Generic[T]): async def progress(self) -> Optional[dict[str, Any]]: """Fetch a structured progress snapshot. - Registry jobs always report lifecycle fields. Queue metadata and - counters are included when supplied by the server. Older servers may + Registry jobs always report lifecycle fields. SQL query handles report + lifecycle state and ``client_elapsed_time_millis``, measured since this + handle was created. They do not expose server build phases or logs. + Queue metadata and counters are included when supplied by the server. + Older servers may omit counters, and in-process operations return ``None``. A missing counter is unknown rather than zero. This is additive to :meth:`status`, whose string contract is unchanged. """ if self._inner is None: return None - await self._inner.status() + state = await self._inner.status() description = getattr(self._inner, "_description", None) if description is None or description.progress is None: + if self.job_type == "query": + return { + "job_id": self.id, + "job_type": "query", + "state": state, + "client_elapsed_time_millis": int( + (time.monotonic() - self._created_at) * 1_000 + ), + } return None return self._enrich_progress(description.progress) @@ -270,6 +288,13 @@ class AsyncJob(Generic[T]): new execution epoch or smaller plan resets the bar to that plan. ``False`` preserves the original wait behavior. + For SQL-backed Function registration, progress shows the query's + lifecycle state and client elapsed time. It observes the existing + query handle while its original waiter runs; it does not resubmit or + cancel the registration. Detailed bake phases and build logs are not + available from the current query handle. Failure exceptions retain the + server's cause and request identifiers. + Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. Transient connection and read errors are retried with capped exponential @@ -285,7 +310,10 @@ class AsyncJob(Generic[T]): """ if self._inner is None: return cast(T, None) - progress_obj, owns = _normalize_job_progress(progress) + query_progress = ( + progress is not False and progress is not None and self.job_type == "query" + ) + progress_obj, owns = _normalize_job_progress(progress, query=query_progress) progress_callback = _job_progress_callback(progress_obj, self._enrich_progress) last_error = None @@ -311,13 +339,46 @@ class AsyncJob(Generic[T]): await asyncio.sleep(delay) delay = min(delay * 2, 30.0) + async def observe_query(): + async def report(): + try: + snapshot = await self.progress() + if snapshot is not None: + progress_callback(snapshot) + except Exception: + logging.getLogger(__name__).warning( + "job progress observer failed", exc_info=True + ) + + waiter = asyncio.create_task(wait_with_retries()) + try: + while not waiter.done(): + await report() + await asyncio.wait( + {waiter}, timeout=_QUERY_PROGRESS_INTERVAL_SECONDS + ) + try: + return await waiter + finally: + await report() + finally: + if not waiter.done(): + waiter.cancel() + with suppress(asyncio.CancelledError): + await waiter + + wait_for_result = ( + observe_query + if query_progress and progress_callback is not None + else wait_with_retries + ) try: try: if timeout is None: - result = await wait_with_retries() + result = await wait_for_result() else: result = await asyncio.wait_for( - wait_with_retries(), timeout.total_seconds() + wait_for_result(), timeout.total_seconds() ) except asyncio.TimeoutError as error: if last_error is None: diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 07be57e15..004aca90c 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import json +import warnings from collections import UserDict from pathlib import Path from types import MappingProxyType @@ -13,6 +14,7 @@ import lancedb.functions as functions from lancedb.functions import ( FunctionApplication, FunctionBinding, + FunctionImage, FunctionVersion, PythonRuntimeSpec, SecretBinding, @@ -149,6 +151,59 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize("gpu", [False, True]) +def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu): + value = job_result("remote_function_job.json")["image"] + value["descriptor"]["future_metadata"] = "x" * 100_000 + if gpu: + value["descriptor"]["requires"]["capabilities"] = [ + { + "type": "lance.cuda", + "version": 1, + "device_count": 1, + "cuda_toolkit": "12.4", + } + ] + image = FunctionImage(**value) + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + details = image.describe() + rendered = repr(image) + assert "manifest_digest=" in str(image) + encoded = json.loads(image.to_canonical_json()) + assert details == { + "manifest_digest": value["manifest_digest"], + "python_version": "3.12.14", + "requires_gpu": gpu, + "cuda_toolkit": "12.4" if gpu else None, + "platforms": None, + "base_image": None, + "size_bytes": None, + } + assert len(rendered) < 350 + assert f"requires_gpu={gpu}" in rendered + assert "future_metadata" not in rendered + assert encoded == value + + +@pytest.mark.parametrize( + "descriptor", + [ + {}, + {"format_version": 2, "requires": {"capabilities": []}}, + {"format_version": 1, "requires": {"capabilities": [None]}}, + {"python": {"version": {"future": "x" * 100_000}}}, + ], +) +def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor): + image = FunctionImage( + manifest_digest="sha256:example", descriptor=descriptor, source=True + ) + assert image.describe()["requires_gpu"] is None + assert image.describe()["python_version"] is None + assert len(repr(image)) < 350 + + @pytest.mark.parametrize( "case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"] ) diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 9897d97b5..e71945b7f 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest from lancedb.exceptions import JobCancelledError, JobFailedError +from lancedb.db import DBConnection from lancedb.job import AsyncJob, Job, _progress_eta from lancedb.remote.errors import HttpError, RetryError @@ -729,15 +730,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing( @pytest.mark.asyncio -async def test_wait_progress_false_keeps_legacy_inner_wait_call(): +@pytest.mark.parametrize("progress", [False, None]) +async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress): class NoProgressArgument: id = "job-legacy" - job_type = None + + @property + def job_type(self): + raise AssertionError("quiet waits must not inspect progress metadata") async def wait(self): return None - assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None + assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None + + +class _RegistrationQuery: + id = "registration-query" + job_type = "query" + _description = None + + def __init__(self, error=None): + self.ready = asyncio.Event() + self.error = error + self.state = "running" + self.wait_calls = 0 + self.cancel_calls = 0 + + async def status(self): + return self.state + + async def wait(self, progress=None): + self.wait_calls += 1 + await self.ready.wait() + if self.error is not None: + self.state = ( + "cancelled" if isinstance(self.error, JobCancelledError) else "failed" + ) + raise self.error + self.state = "finished" + return '{"version": "1"}' + + async def cancel(self): + self.cancel_calls += 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch): + monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0) + inner = _RegistrationQuery() + job = AsyncJob(inner, json.loads) + updates = [] + + def observe(snapshot): + updates.append(snapshot) + if len(updates) == 2: + inner.ready.set() + + if sync: + result = await asyncio.to_thread(Job(job).wait, progress=observe) + else: + result = await job.wait(progress=observe) + assert result == {"version": "1"} + assert inner.wait_calls == 1 + assert inner.cancel_calls == 0 + assert updates[0]["state"] == "running" + assert updates[-1]["state"] == "finished" + assert all(snapshot["job_id"] == inner.id for snapshot in updates) + elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates] + assert elapsed == sorted(elapsed) + assert elapsed[0] >= 0 + assert all("phase" not in snapshot for snapshot in updates) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "error", + [ + JobFailedError("bake failed", job_id="registration-query"), + JobCancelledError("cancelled"), + ], +) +async def test_query_progress_preserves_terminal_exceptions(error): + inner = _RegistrationQuery(error) + inner.ready.set() + updates = [] + with pytest.raises(type(error)) as raised: + await AsyncJob(inner).wait(progress=updates.append) + assert raised.value is error + assert updates[-1]["state"] == inner.state + assert inner.wait_calls == 1 + + +@pytest.mark.asyncio +async def test_query_progress_display_has_no_row_counter_and_closes_on_failure( + monkeypatch, +): + tqdm_module = pytest.importorskip("tqdm.auto") + bar = SimpleNamespace( + n=0, + total=None, + update=MagicMock(), + set_postfix_str=MagicMock(), + close=MagicMock(), + ) + constructor = MagicMock(return_value=bar) + monkeypatch.setattr(tqdm_module, "tqdm", constructor) + inner = _RegistrationQuery(JobFailedError("bake failed")) + inner.ready.set() + + with pytest.raises(JobFailedError, match="bake failed"): + await AsyncJob(inner).wait(progress=True) + assert "elapsed" in constructor.call_args.kwargs["bar_format"] + assert "rows" not in str(constructor.call_args) + assert bar.set_postfix_str.call_args.args == ("failed",) + bar.close.assert_called_once_with() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failed", [False, True]) +@pytest.mark.parametrize("observer_error", ["status", "callback"]) +async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure( + failed, observer_error, caplog +): + error = ( + JobFailedError("bake failed", job_id="registration-query") if failed else None + ) + inner = _RegistrationQuery(error) + inner.ready.set() + if observer_error == "status": + inner.status = AsyncMock(side_effect=RuntimeError("observer failed")) + + def observe(snapshot): + if observer_error == "callback": + raise RuntimeError("observer failed") + + job = AsyncJob(inner, json.loads) + if failed: + with pytest.raises(JobFailedError) as raised: + await job.wait(progress=observe) + assert raised.value is error + else: + assert await job.wait(progress=observe) == {"version": "1"} + assert inner.wait_calls == 1 + assert inner.cancel_calls == 0 + assert "job progress observer failed" in caplog.text + + +@pytest.mark.asyncio +async def test_query_progress_timeout_keeps_registration_available_on_same_handle(): + inner = _RegistrationQuery() + job = AsyncJob(inner, json.loads) + updates = [] + with pytest.raises(TimeoutError, match="keep this handle"): + await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append) + assert inner.state == "running" + assert inner.cancel_calls == 0 + inner.ready.set() + assert await job.wait(progress=updates.append) == {"version": "1"} + assert inner.wait_calls == 2 + assert updates[-1]["state"] == "finished" + + +@pytest.mark.parametrize("refresh_lock", [False, True]) +def test_blocking_create_function_forwards_progress_to_registration_handle( + refresh_lock, +): + connection = MagicMock() + definition = object() + progress = object() + result = DBConnection.create_function( + connection, definition, refresh_lock=refresh_lock, progress=progress + ) + connection.create_function_async.assert_called_once_with( + definition, + secrets=None, + exist_ok=False, + namespace_path=None, + refresh_lock=refresh_lock, + ) + connection.create_function_async.return_value.wait.assert_called_once_with( + progress=progress + ) + assert result is connection.create_function_async.return_value.wait.return_value + + +@pytest.mark.parametrize("progress", [False, None]) +def test_blocking_create_function_preserves_quiet_wait_call(progress): + connection = MagicMock() + result = DBConnection.create_function(connection, object(), progress=progress) + connection.create_function_async.return_value.wait.assert_called_once_with() + assert result is connection.create_function_async.return_value.wait.return_value @pytest.mark.asyncio From 613653a7db1d023da706823e5287d9e4a236af6b Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sun, 15 Nov 2026 06:04:30 -0800 Subject: [PATCH 136/203] chore: update lance dependency to v15.0.0-beta.22 (#5057) Update Rust and Java Lance dependencies to [v15.0.0-beta.22](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.22), synchronize the Python test pin to `pylance==15.0.0b22`, and refresh the lockfiles with all published platform wheels. Preserve Function freshness only when an UPDATE changes rows, so beta.22's no-match updates cannot mark previously invalidated outputs as fresh. Extend the existing regression cases to cover no-match updates after input and output changes, including unchanged table versions. Rust formatting passed. CI validates the compatibility fix; no local builds or tests were run. --------- Co-authored-by: Jack Ye --- Cargo.lock | 134 +++++++++++++++++----------- Cargo.toml | 30 +++---- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 18 ++-- rust/lancedb/src/table/freshness.rs | 19 ++-- rust/lancedb/src/table/update.rs | 15 ++-- 7 files changed, 132 insertions(+), 88 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 755ba70a4..f454ff87a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1361,6 +1361,12 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "better_io" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef0a3155e943e341e557863e69a708999c94ede624e37865c8e2a91b94efa78f" + [[package]] name = "bigdecimal" version = "0.4.10" @@ -3278,6 +3284,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "dtype_dispatch" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab23e69df104e2fd85ee63a533a22d2132ef5975dc6b36f9f3e5a7305e4a8ed7" + [[package]] name = "dunce" version = "1.0.5" @@ -3824,8 +3836,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5303,8 +5315,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5379,8 +5391,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5402,7 +5414,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5416,7 +5428,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5425,8 +5437,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrayref", "crunchy", @@ -5436,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5475,8 +5487,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5507,8 +5519,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5533,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5546,13 +5558,13 @@ dependencies = [ "hex", "rand 0.9.5", "rand_distr 0.5.1", - "rand_xoshiro", + "rand_xoshiro 0.7.0", ] [[package]] name = "lance-derive" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "proc-macro2", "quote", @@ -5561,8 +5573,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-arith", "arrow-array", @@ -5585,6 +5597,7 @@ dependencies = [ "log", "lz4", "num-traits", + "pco", "prost", "serde_json", "tokio", @@ -5595,8 +5608,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-arith", "arrow-array", @@ -5627,8 +5640,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5659,8 +5672,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5733,8 +5746,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5757,8 +5770,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5803,8 +5816,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "byteorder", "ethnum", @@ -5821,8 +5834,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5837,8 +5850,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "async-trait", @@ -5852,8 +5865,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5907,8 +5920,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5922,8 +5935,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5964,8 +5977,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5978,8 +5991,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "frostem", "icu_segmenter", @@ -6651,7 +6664,7 @@ dependencies = [ "quanta", "radix_trie", "rand 0.9.5", - "rand_xoshiro", + "rand_xoshiro 0.7.0", "sketches-ddsketch", ] @@ -7837,6 +7850,18 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "pco" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f01ab51a847e7002371c2384b2c88f50dd45982cc2764e7997751971f1bfbf" +dependencies = [ + "better_io", + "dtype_dispatch", + "half", + "rand_xoshiro 0.6.0", +] + [[package]] name = "pem" version = "3.0.6" @@ -9025,6 +9050,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xoshiro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand_xoshiro" version = "0.7.0" diff --git a/Cargo.toml b/Cargo.toml index bc9d85c72..0e60bcb51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index ead5955fa..2b7a90e03 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.21 + 15.0.0-beta.22 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index d464424c7..e2b140626 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b21", + "pylance==15.0.0b22", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 31ac68b4d..8e03e90d8 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b21" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b22" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b21" +version = "15.0.0b22" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,13 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" }, - { url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" }, - { url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2gkGO/pylance-15.0.0b22-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:401df8ce31ae6263656915c63d3da4411cae59bde2a6d71d12c552e3fa72b6bf" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pfuJc/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5c9ee37b23da4d6fbc341d0e18d355b1602c98fbf096e4589b08ecce57c56ea" }, + { url = "https://pypi.fury.io/lance-format/-/ver_YPb1X/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:38e6ed648816ae54ee3e76f21a30c092d47028da1f99242922ec1288d79a1722" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1a1jcd/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1b7e9f1dfe7ff8e3cbb3b06a3ebd99667629725b6d9a119146f9e1bfac20871f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_KRwHG/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c31b41b8a8d070f969dcb9dd06aa31190f79d036b27cb5d5ae6d64d5d425502f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2cABdZ/pylance-15.0.0b22-cp310-abi3-win_amd64.whl", hash = "sha256:7b3d36ea7ab7a6a43caecc96ca7f969be11ad89d24ccc6d1788d751fb39e720d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1j6gGW/pylance-15.0.0b22-cp310-abi3-win_arm64.whl", hash = "sha256:20c4e391b4b83008dc2b7877bdd0ad9b3b1251ea05116d79b5637807f4961cc8" }, ] [[package]] diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 563a2a4e5..9980c3a75 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -3460,15 +3460,18 @@ mod tests { } #[rstest::rstest] - #[case::input_same_rows("body", "a", true)] - #[case::input_other_rows("body", "c", false)] - #[case::output_same_rows("search_text", "a", true)] - #[case::output_other_rows("search_text", "c", false)] + #[case::input_same_rows("body", "a", true, 1)] + #[case::input_other_rows("body", "c", false, 1)] + #[case::input_no_rows("body", "missing", false, 0)] + #[case::output_same_rows("search_text", "a", true, 1)] + #[case::output_other_rows("search_text", "c", false, 1)] + #[case::output_no_rows("search_text", "missing", false, 0)] #[tokio::test] async fn function_write_preserves_prior_invalidation( #[case] changed_column: &str, #[case] title: &str, #[case] dirty_product: bool, + #[case] expected_updated_rows: u64, ) { let table = fresh_function_table().await; let native = table.as_native().unwrap(); @@ -3489,14 +3492,20 @@ mod tests { ); native.dataset.update(result.new_dataset.as_ref().clone()); - table + let before_version = table.version().await.unwrap(); + let update = table .update() .only_if(format!("title = '{title}'")) .column("spare", "1") .execute() .await .unwrap(); + assert_eq!(update.rows_updated, expected_updated_rows); let dataset = native.dataset.get().await.unwrap(); + if expected_updated_rows == 0 { + assert_eq!(update.version, before_version); + assert_eq!(dataset.version().version, before_version); + } let stale = function_plan(&dataset, "search_text").await; assert_eq!(stale.is_dirty(3), dirty_product, "{stale:?}"); if !dirty_product { diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 93e8a08ea..10895aa69 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -130,13 +130,14 @@ pub(crate) async fn execute_update( let operation = builder.build()?; let res = operation.execute().await?; let mut new_dataset = res.new_dataset.as_ref().clone(); - if let Err(error) = super::freshness::preserve_function_freshness( - &mut new_dataset, - super::freshness::FunctionWrite::Update { - columns: &written_columns, - }, - ) - .await + if res.rows_updated > 0 + && let Err(error) = super::freshness::preserve_function_freshness( + &mut new_dataset, + super::freshness::FunctionWrite::Update { + columns: &written_columns, + }, + ) + .await { log::warn!("update committed but Function freshness could not be preserved: {error}"); } From 2ab103d7754308cac7e4eceb91fd72b0ed8460df Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 15 Nov 2026 14:05:38 +0000 Subject: [PATCH 137/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.14=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.15?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 8491e70dc..99297338c 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.14" +current_version = "0.42.0-beta.15" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index f454ff87a..a6ae84b72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index ca0113382..9d7162444 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.42.0-beta.14 + 0.42.0-beta.15 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 0ed2c85d9..21f80cd99 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.14 + 0.42.0-beta.15 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 2b7a90e03..26c94d3bf 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.14 + 0.42.0-beta.15 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 87919848f..3cee8b0ad 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.14" +version = "0.42.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 4c29cfeb3..03c295432 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.42.0-beta.14", + "version": "0.42.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 86c223618..2cb5a722c 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.42.0-beta.14", + "version": "0.42.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 2e32e7fc3..70880c70a 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.42.0-beta.14", + "version": "0.42.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 7d984b9f4..ed2f276a1 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.42.0-beta.14", + "version": "0.42.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 3607a6b93..748cc1640 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.42.0-beta.14", + "version": "0.42.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 369ff1c10..52d79a178 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.42.0-beta.14", + "version": "0.42.0-beta.15", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index d0852d725..60cebaa37 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.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 8520e7b83..92c70bc3b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 08113dee6..fe135a99d 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.14" +version = "0.42.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 3a963d193..d00feaf72 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 0b566e596..5b1744cc3 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" edition = "2021" license.workspace = true repository.workspace = true From c7d972fe48000ae3c91563b5f699a0e378455d0f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 16 Nov 2026 18:56:39 +0800 Subject: [PATCH 138/203] fix(python): explain blob descriptor copy guidance (#5060) The descriptor-copy error only named the missing `data`/`uri` child. It now says that this shape is an SDK blob descriptor rather than payload bytes, and points to `blob_mode="bytes"` for supported materialization, `blob_mode="descriptions"` for inspection, and the row-id plus `fetch_blobs`/`fetch_blob_files` copy path while the source stays unchanged. This reuses the merged guidance from #4940 and the direct-materialization contract from #4973. Ray integration remains out of scope for ENT-3556. Refs ENT-3556 Test: `python/tests/test_blob.py` (210 passed, 39 skipped), including a regression that writes default lazy descriptor rows into a blob-schema table, checks the guidance, and confirms no target is created. `python/tests/test_util.py -k blob` (12 passed, 2 skipped). --- python/python/lancedb/table.py | 9 ++++++++- python/python/tests/test_blob.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 807edbc46..7f378a34c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1150,7 +1150,14 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field: if not any(child.name in ("data", "uri") for child in source_type): raise ValueError( f"blob struct input for column '{field.name}' must contain " - "a 'data' or 'uri' child" + "a 'data' or 'uri' child. A blob query returns an SDK " + "descriptor in this shape, and a descriptor is not payload " + "bytes. Use blob_mode='bytes' to materialize payloads, or " + "inspect descriptors with blob_mode='descriptions'. To copy " + "payloads, select row IDs with with_row_id(True), then call " + "table.fetch_blobs(column, row_ids) or " + "table.fetch_blob_files(column, row_ids). Keep the source " + "unchanged between selection and fetching." ) elif not _can_coerce_to_blob(source_type) and not isinstance( source_type, pa.ExtensionType diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index bb946c37c..f1bacb262 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1135,6 +1135,24 @@ def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path): assert sorted(copied, key=lambda row: row["id"]) == rows[:3] +def test_copy_blob_descriptor_rows_explains_payload_materialization(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + source = db.create_table("source", data=[{"id": 1, "image": b"one"}], schema=schema) + hits = source.search().where("id = 1").to_arrow() + + with pytest.raises(ValueError, match="must contain a 'data' or 'uri' child") as exc: + db.create_table("copy", data=hits, schema=schema) + + message = str(exc.value) + assert "blob_mode='bytes'" in message + assert "blob_mode='descriptions'" in message + assert "with_row_id(True)" in message + assert "fetch_blobs(column, row_ids)" in message + assert "fetch_blob_files(column, row_ids)" in message + assert not db.table_exists(["copy"]) + + def test_fetch_blobs_round_trip(): table = _blob_table( "round_trip", From d475005592fd9a0290f9da48783380adfef15c50 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 16 Nov 2026 11:40:27 +0000 Subject: [PATCH 139/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.15=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 99297338c..865a04f56 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.15" +current_version = "0.42.0-beta.16" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a6ae84b72..8e0589190 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 9d7162444..6c223c01b 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.42.0-beta.15 + 0.42.0-beta.16 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 21f80cd99..852218a55 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.15 + 0.42.0-beta.16 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 26c94d3bf..c5ee0dbf0 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.15 + 0.42.0-beta.16 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 3cee8b0ad..38a88697c 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.15" +version = "0.42.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 03c295432..ab5c07329 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.42.0-beta.15", + "version": "0.42.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 2cb5a722c..c527594ba 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.42.0-beta.15", + "version": "0.42.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 70880c70a..21d262c8e 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.42.0-beta.15", + "version": "0.42.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 ed2f276a1..dd6cccb01 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.42.0-beta.15", + "version": "0.42.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 748cc1640..c0e414ca5 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.42.0-beta.15", + "version": "0.42.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 52d79a178..f7fcbc5db 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.42.0-beta.15", + "version": "0.42.0-beta.16", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 60cebaa37..9dfeb21e2 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.42.0-beta.15", + "version": "0.42.0-beta.16", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 92c70bc3b..9f9665a26 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.15", + "version": "0.42.0-beta.16", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index fe135a99d..2d9579e04 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.15" +version = "0.42.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 d00feaf72..d2054c9e6 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 5b1744cc3..31428d5f3 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.15" +version = "0.42.0-beta.16" edition = "2021" license.workspace = true repository.workspace = true From 3b7c4dcf6602b97f6a5543937e2544dce6af25cd Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 16 Nov 2026 20:23:25 +0800 Subject: [PATCH 140/203] fix: allow matched merge updates to Function inputs (#5062) Matched merge-insert updates rejected every non-key source column that a Function binding reads, while update already accepts input changes and the merge freshness path records their changed signatures. Use the same `ensure_not_written` guard for the matched source columns: inputs pass, computed outputs and assignment columns stay rejected before any write, and insert-only or unrelated-column merges keep their behavior. Regressions confirm a matched input update retains prior outputs, dirties only the affected rows, keeps an independent binding fresh, and rejects mixed input/output sources without committing. Tested on `2ab103d7` + this change: `cargo test -p lancedb --lib` 1083 passed, 82 ignored. Refs ENT-3515 --- rust/lancedb/src/table/freshness.rs | 130 ++++++++++++++++++++++++++++ rust/lancedb/src/table/merge.rs | 68 +++++++++++---- 2 files changed, 180 insertions(+), 18 deletions(-) diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 9980c3a75..5d9ee26a6 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -3248,6 +3248,136 @@ mod tests { } } + #[tokio::test] + async fn input_merge_dirties_only_the_updated_rows_and_retains_outputs() { + let table = fresh_function_table().await; + let source = + arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + let result = merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + for output in ["search_text", "search_token_count"] { + let stale = function_plan(&dataset, output).await; + let mut dirty_rows = 0; + for fragment in dataset.get_fragments() { + if stale.needs_recompute(fragment.id() as u32) { + let batch = fragment + .scan() + .project(&["title"]) + .unwrap() + .try_into_batch() + .await + .unwrap(); + let titles = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}"); + dirty_rows += batch.num_rows(); + } + } + assert_eq!(dirty_rows, 1, "{stale:?}"); + } + assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1); + } + + #[tokio::test] + async fn input_merge_keeps_an_independent_function_binding_fresh() { + let batch = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "c", "d"]), + ("body", Utf8, ["x", "y", "z", "w"]), + ("search_text", Utf8, ["a x", "b y", "c z", "d w"]), + ("search_token_count", Int64, [2, 2, 2, 2]), + ("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]), + ("search_token_count_other", Int64, [2, 2, 2, 2]) + ) + .unwrap(); + let table = crate::connect("memory://") + .execute() + .await + .unwrap() + .create_table("independent_merge", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + max_rows_per_file: 2, + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let mut other = serde_json::to_value(text_features_binding("_other")).unwrap(); + other["inputs"][1]["field_path"] = serde_json::json!("title"); + other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone(); + let bindings = [ + text_features_binding(""), + serde_json::from_value(other).unwrap(), + ]; + stamp_bindings(&table, &bindings).await; + let native = table.as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + for binding in &bindings { + let paths = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + let inputs = fields_for_paths(dataset.schema(), &paths).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + for output in binding.outputs() { + write_signatures( + &mut dataset, + &output.output_name, + binding.binding_id(), + signatures.clone(), + ) + .await + .unwrap(); + } + } + native.dataset.update(dataset); + let source = + arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"])) + .unwrap(); + let mut merge = table.merge_insert(&["title"]); + merge.when_matched_update_all(None); + merge + .execute(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let dataset = native.dataset.get().await.unwrap(); + assert!( + function_plan(&dataset, "search_text") + .await + .needs_recompute(2) + ); + let other = &bindings[1]; + let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap(); + for output in other.outputs() { + let stale = + staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs) + .await + .unwrap(); + assert!( + !stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(), + "{stale:?}" + ); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index fe131d907..79c724f3e 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -249,11 +249,13 @@ impl MergeInsertBuilder { 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 { + /// The source columns a matched row writes: every column but the join + /// keys, which a match leaves equal. Function inputs stay writable; the + /// merge records their changed signatures so the next refresh recomputes + /// the affected rows. Computed outputs and assignment columns remain + /// protected by the direct-write guard. An insert-only merge writes none; + /// its new rows get Function outputs from the next refresh. + pub(crate) fn matched_source_columns(&self, source: &Fields) -> Vec { if !self.when_matched_update_all { return Vec::new(); } @@ -351,10 +353,10 @@ pub(crate) async fn execute_merge_insert( ) -> Result { params.canonicalize_filters()?; let schema = table.schema().await?; - super::computed_columns::ensure_not_function_bound( + let matched_columns = params.matched_source_columns(new_data.schema().fields()); + super::computed_columns::ensure_not_written( schema.as_ref(), - "merge_insert", - params.function_guarded_columns(new_data.schema().fields()), + matched_columns.iter().map(String::as_str), )?; // Normalize blob layouts and JSON extension metadata just as on append. // Keep arrow.json text labelled until Lance encodes it as JSONB. @@ -970,10 +972,11 @@ mod tests { 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. + /// A matched row takes every non-key source column. Function inputs are + /// writable and become stale for the next refresh; computed outputs stay + /// protected, and a mixed input/output source is rejected before commit. #[tokio::test] - async fn merge_update_on_a_function_table_refuses_only_bound_columns() { + async fn merge_update_allows_function_inputs_but_protects_outputs() { let table = crate::table::computed_columns::test_support::bound_table_from( arrow_array::record_batch!( ("id", Int32, [1]), @@ -998,18 +1001,47 @@ mod tests { let mut merge = table.merge_insert(&["id"]); merge.when_matched_update_all(None); - let err = merge + let result = 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:?}" + .unwrap(); + assert_eq!(result.num_updated_rows, 1); + assert_eq!( + table + .count_rows(Some("title = 'z' AND search_text = 'a b'".into())) + .await + .unwrap(), + 1 ); + + let version = table.version().await.unwrap(); + for source in [ + arrow_array::record_batch!(("id", Int32, [1]), ("search_text", Utf8, ["uncomputed"])) + .unwrap(), + arrow_array::record_batch!( + ("id", Int32, [1]), + ("title", Utf8, ["must not commit"]), + ("search_text", Utf8, ["uncomputed"]) + ) + .unwrap(), + ] { + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(None); + let err = merge.execute(reader(source)).await.unwrap_err(); + assert!( + matches!(&err, crate::Error::InvalidInput { message } + if message.contains("is computed") + && message.contains("cannot be written directly")), + "{err:?}" + ); + assert_eq!(table.version().await.unwrap(), version); + assert_eq!( + table.count_rows(Some("title = 'z'".into())).await.unwrap(), + 1 + ); + } } } From 161318466a3c82bce51ad88456bcd539916963de Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Mon, 16 Nov 2026 11:50:28 -0800 Subject: [PATCH 141/203] chore: update lance dependency to v15.0.0-beta.23 (#5063) Updates the Rust workspace and Java Lance dependencies to [v15.0.0-beta.23](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.23), with the matching Python `pylance==15.0.0b23` test pin and refreshed Cargo and uv lockfiles. No source compatibility fixes were needed. Validation: workspace Clippy with all features and warnings denied, Rust formatting, all 35 CI-script tests, Python dependency guards, Python formatting/lint, and uv lock consistency checks passed; the root-wide Ruff check has 59 pre-existing diagnostics, confirmed unchanged from HEAD. --- Cargo.lock | 96 +++++++++++++++++++++---------------------- Cargo.toml | 30 +++++++------- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 18 ++++---- 5 files changed, 74 insertions(+), 74 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8e0589190..17271e8df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3836,8 +3836,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5315,8 +5315,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arc-swap", "arrow", @@ -5391,8 +5391,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-buffer", @@ -5414,7 +5414,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-buffer", @@ -5428,7 +5428,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-schema", @@ -5437,8 +5437,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrayref", "crunchy", @@ -5448,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-buffer", @@ -5487,8 +5487,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow", "arrow-array", @@ -5519,8 +5519,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow", "arrow-array", @@ -5545,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow", "arrow-array", @@ -5563,8 +5563,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "proc-macro2", "quote", @@ -5573,8 +5573,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-arith", "arrow-array", @@ -5608,8 +5608,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-arith", "arrow-array", @@ -5640,8 +5640,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-schema", @@ -5672,8 +5672,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arc-swap", "arrow", @@ -5746,8 +5746,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-schema", @@ -5770,8 +5770,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow", "arrow-array", @@ -5816,8 +5816,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "byteorder", "ethnum", @@ -5834,8 +5834,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5850,8 +5850,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow", "async-trait", @@ -5865,8 +5865,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arc-swap", "arrow", @@ -5920,8 +5920,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-buffer", @@ -5935,8 +5935,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow", "arrow-array", @@ -5977,8 +5977,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "arrow-array", "arrow-schema", @@ -5991,8 +5991,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" +version = "15.0.0-beta.23" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 0e60bcb51..6a8450cf7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index c5ee0dbf0..7649f7972 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.22 + 15.0.0-beta.23 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index e2b140626..201e9fd07 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b22", + "pylance==15.0.0b23", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 8e03e90d8..0cbcea617 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b22" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b23" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b22" +version = "15.0.0b23" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,13 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_2gkGO/pylance-15.0.0b22-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:401df8ce31ae6263656915c63d3da4411cae59bde2a6d71d12c552e3fa72b6bf" }, - { url = "https://pypi.fury.io/lance-format/-/ver_pfuJc/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5c9ee37b23da4d6fbc341d0e18d355b1602c98fbf096e4589b08ecce57c56ea" }, - { url = "https://pypi.fury.io/lance-format/-/ver_YPb1X/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:38e6ed648816ae54ee3e76f21a30c092d47028da1f99242922ec1288d79a1722" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1a1jcd/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1b7e9f1dfe7ff8e3cbb3b06a3ebd99667629725b6d9a119146f9e1bfac20871f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_KRwHG/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c31b41b8a8d070f969dcb9dd06aa31190f79d036b27cb5d5ae6d64d5d425502f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2cABdZ/pylance-15.0.0b22-cp310-abi3-win_amd64.whl", hash = "sha256:7b3d36ea7ab7a6a43caecc96ca7f969be11ad89d24ccc6d1788d751fb39e720d" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1j6gGW/pylance-15.0.0b22-cp310-abi3-win_arm64.whl", hash = "sha256:20c4e391b4b83008dc2b7877bdd0ad9b3b1251ea05116d79b5637807f4961cc8" }, + { url = "https://pypi.fury.io/lance-format/-/ver_ldwuz/pylance-15.0.0b23-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:b7980c606424e63e9be645536dbcaff75b479886a53abdae3aef64684c9a6fc4" }, + { url = "https://pypi.fury.io/lance-format/-/ver_5wKzE/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a6d887bc81d5f79b8a23d5cbc840cb56dbea4d8b0a9d2c2edf063dea48bcf741" }, + { url = "https://pypi.fury.io/lance-format/-/ver_FKuk6/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1424bd48cac2160b7745c9b87cd24d81c7cf2b0a89f342ea46ecd2a473ea74e6" }, + { url = "https://pypi.fury.io/lance-format/-/ver_SVglj/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:09de71b60ac6b8b91fdd73207f71c74bc521626de7e437102ebfe4f2c1f78fa0" }, + { url = "https://pypi.fury.io/lance-format/-/ver_SgTr6/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d9385471578bec51ae546f7bd7ea638e20bd12d687082d43ed465017dfd992e7" }, + { url = "https://pypi.fury.io/lance-format/-/ver_wyipY/pylance-15.0.0b23-cp310-abi3-win_amd64.whl", hash = "sha256:7b98b0d78564c5acea3693334c41dc3ced20484fb2c8e738113eeb078281a109" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1v2uEn/pylance-15.0.0b23-cp310-abi3-win_arm64.whl", hash = "sha256:0f4d2645143d44c11237e6ea00772c169a3c6ed23a7c36beaeaef9a18d1be14d" }, ] [[package]] From bf4d6c8083855e1e4f7ed41079638dafc63f8420 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 16 Nov 2026 19:55:39 +0000 Subject: [PATCH 142/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.16=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.17?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 865a04f56..9ddd23172 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.16" +current_version = "0.42.0-beta.17" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 17271e8df..906577f07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.16" +version = "0.42.0-beta.17" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.16" +version = "0.42.0-beta.17" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.16" +version = "0.42.0-beta.17" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.16" +version = "0.42.0-beta.17" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 6c223c01b..4aa029baf 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.42.0-beta.16 + 0.42.0-beta.17 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 852218a55..2301b9e1d 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.16 + 0.42.0-beta.17 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 7649f7972..43b70e500 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.16 + 0.42.0-beta.17 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 38a88697c..c0bf9ca9b 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.16" +version = "0.42.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 ab5c07329..924ff3967 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.42.0-beta.16", + "version": "0.42.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 c527594ba..b265cd7f1 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.42.0-beta.16", + "version": "0.42.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 21d262c8e..031d20477 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.42.0-beta.16", + "version": "0.42.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 dd6cccb01..6c71adeee 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.42.0-beta.16", + "version": "0.42.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 c0e414ca5..2d05ddca1 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.42.0-beta.16", + "version": "0.42.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 f7fcbc5db..013568ae2 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.42.0-beta.16", + "version": "0.42.0-beta.17", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 9dfeb21e2..fec9adb4f 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.42.0-beta.16", + "version": "0.42.0-beta.17", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 9f9665a26..cd8dd8be7 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.16", + "version": "0.42.0-beta.17", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 2d9579e04..189950963 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.16" +version = "0.42.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 d2054c9e6..cdc575e69 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.16" +version = "0.42.0-beta.17" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 31428d5f3..ff16ccb7b 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.16" +version = "0.42.0-beta.17" edition = "2021" license.workspace = true repository.workspace = true From c278f90cc196784b3a0921f1046e51c30bffaa93 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 17 Nov 2026 13:31:32 +0800 Subject: [PATCH 143/203] feat: expose shared Arrow type golden behind test-fixtures (#5065) Downstream compatibility tests currently load the Function Arrow type golden from a LanceDB source checkout. Add a default-off `test-fixtures` feature that exposes `lancedb::test_fixtures::FUNCTION_ARROW_TYPES_JSON`, so consumers can enable it on their existing LanceDB dev-dependency and use the golden from the same revision. The golden stays in its existing location with unchanged bytes. LanceDB's Rust test reads the exported constant; Python tests and release/versioning workflows remain unchanged. --- rust/lancedb/Cargo.toml | 2 ++ rust/lancedb/src/lib.rs | 4 ++++ rust/lancedb/src/table/computed_columns.rs | 6 ++---- rust/lancedb/src/test_fixtures.rs | 21 +++++++++++++++++++++ 4 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 rust/lancedb/src/test_fixtures.rs diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index cdc575e69..34e91dbfd 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -140,6 +140,8 @@ pprof = { version = "0.14", features = ["flamegraph"] } [features] default = [] +# Shared golden data for downstream compatibility tests. +test-fixtures = [] # Local SQL computed columns and materialized-view creation/refresh. # Remote clients and shared server primitives do not require this feature. experimental-functions = [] diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 9f800d593..de555f709 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -48,6 +48,8 @@ //! Install any `metrics`-compatible recorder to collect them. //! - `metrics-otel` - Add a pull-based adapter (the `metrics_otel` module) over //! the `metrics` facade for bridging metrics into OpenTelemetry or similar. +//! - `test-fixtures` - Expose shared golden data through `test_fixtures` for +//! downstream compatibility tests. Disabled by default. //! //! ### Quick Start //! @@ -220,6 +222,8 @@ pub mod server_info; pub mod sql; pub mod storage_integration; pub mod table; +#[cfg(any(test, feature = "test-fixtures"))] +pub mod test_fixtures; #[cfg(test)] pub mod test_utils; pub mod utils; diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 7348e659d..a87c38f3c 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -2906,10 +2906,8 @@ mod tests { #[test] fn output_arrow_type_grammar_matches_the_shared_golden() { - let golden: serde_json::Value = serde_json::from_str(include_str!( - "../../tests/fixtures/first_class_functions/v1/arrow_types.json" - )) - .unwrap(); + let golden: serde_json::Value = + serde_json::from_str(crate::test_fixtures::FUNCTION_ARROW_TYPES_JSON).unwrap(); let valid = golden["valid"].as_array().unwrap().iter(); for case in valid.chain(golden["server_only"].as_array().unwrap()) { let raw = case["arrow_type"].as_str().unwrap(); diff --git a/rust/lancedb/src/test_fixtures.rs b/rust/lancedb/src/test_fixtures.rs new file mode 100644 index 000000000..71ea8c6e8 --- /dev/null +++ b/rust/lancedb/src/test_fixtures.rs @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Shared golden data for downstream compatibility tests. +//! +//! Enable the `test-fixtures` feature to access these fixtures from another crate. + +/// The version 1 Function Arrow type golden as UTF-8 JSON. +/// +/// Contains supported declaration spellings, their canonical JSON Arrow types, +/// and declarations that must be rejected. The contents match the golden used by +/// LanceDB's Rust and Python tests; parsing is left to the consumer. +/// +/// ``` +/// let golden: serde_json::Value = +/// serde_json::from_str(lancedb::test_fixtures::FUNCTION_ARROW_TYPES_JSON).unwrap(); +/// assert!(golden["valid"].is_array()); +/// assert!(golden["invalid"].is_array()); +/// ``` +pub const FUNCTION_ARROW_TYPES_JSON: &str = + include_str!("../tests/fixtures/first_class_functions/v1/arrow_types.json"); From ff9dc7a2bed199176dfeb3cb19b675a38328e7ed Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 17 Nov 2026 13:48:13 +0800 Subject: [PATCH 144/203] feat(function): expose descriptor refresh plan in terminal result (#5064) ## Summary Add the terminal plan shape for Function-backed refresh results: - `FunctionRefreshPlan` describes the descriptor-derived size tiers, selected worker classes, batch bytes, row counts, and batch counts. - `FunctionRefreshTier` describes one byte-bounded tier. - `RefreshColumnResult.plan` carries the plan in the public terminal result, optional and omitted when absent. This is the SDK prerequisite for descriptor-first Function refresh planning. It only exposes the shared result shape; it does not compute the plan or change refresh execution. ## Compatibility Existing terminal payloads and callers are unchanged: the new field is `#[serde(default, skip_serializing_if = "Option::is_none")]`, so absent plans stay absent and old payloads decode to `None`. ## Validation - `git diff --check` - Unit tests cover absent-plan serialization and plan round-trip. - Repository CI on this PR. --- rust/lancedb/src/function.rs | 86 +++++++++++++++++++++++++++++++ rust/lancedb/src/table/refresh.rs | 1 + 2 files changed, 87 insertions(+) diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index d0ef6570d..4e7157c37 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1261,6 +1261,46 @@ impl FunctionBinding { } } +/// One byte-bounded size tier of a Function refresh plan. +/// +/// A row belongs to the first tier whose `max_row_bytes` admits its total +/// descriptor payload size. The final tier has no upper bound and carries the +/// largest configured worker class. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionRefreshTier { + /// Inclusive upper bound of the rows this tier admits. `None` on the last + /// tier, which also serves rows larger than every configured class. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_row_bytes: Option, + /// Worker resource class selected for this tier. + pub worker_class: String, + /// Worker container memory limit for `worker_class`. + pub worker_memory_bytes: u64, + /// Logical UDF executor budget derived from the worker limit. + pub executor_budget_bytes: u64, + /// Byte target for one materialized Blob input batch on this tier. + pub batch_bytes: u64, + /// Rows assigned to this tier. + pub rows: u64, + /// Byte-bounded batches the assigned rows form at `batch_bytes`. + pub batches: u64, +} + +/// Descriptor-derived tier plan for one Function refresh. +/// +/// The plan is computed from Blob descriptor sizes before any payload read. It +/// names the same worker classes the refresh supervisor uses for routing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionRefreshPlan { + /// Worker class the supervisor starts ordinary work on. + pub default_worker_class: String, + /// Row cap supplied through the `batch_size` override, when present. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + /// Tiers ordered from the smallest to the largest worker class. + pub tiers: Vec, +} + /// Stable terminal result of an expression-backed or Function-backed column /// refresh [`crate::Job`]. /// @@ -1279,6 +1319,10 @@ pub struct RefreshColumnResult { /// Table version made visible by the refresh, when one was published. #[serde(default, skip_serializing_if = "Option::is_none")] pub published_version: Option, + /// Descriptor-derived tier plan, when the refresh is Function-backed and + /// its inputs expose Blob descriptor sizes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, } /// Which per-row errors [`crate::Table::function_errors`] lists. Every @@ -1409,6 +1453,48 @@ impl RefreshColumnResult { impl_json!(RefreshColumnResult); +#[cfg(test)] +mod refresh_result_tests { + use super::{FunctionRefreshPlan, FunctionRefreshTier, RefreshColumnResult}; + + fn result(plan: Option) -> RefreshColumnResult { + RefreshColumnResult { + rows_assigned: 3, + rows_failed: 0, + rows_remaining: 0, + source_version: 7, + published_version: Some(8), + plan, + } + } + + #[test] + fn absent_plan_stays_out_of_the_terminal_payload() { + let encoded = serde_json::to_value(result(None)).unwrap(); + assert!(encoded.get("plan").is_none()); + } + + #[test] + fn descriptor_plan_round_trips_through_the_terminal_payload() { + let plan = FunctionRefreshPlan { + default_worker_class: "medium".to_string(), + batch_size: Some(1), + tiers: vec![FunctionRefreshTier { + max_row_bytes: None, + worker_class: "large".to_string(), + worker_memory_bytes: 16 << 30, + executor_budget_bytes: 11 << 30, + batch_bytes: 1 << 20, + rows: 3, + batches: 2, + }], + }; + let encoded = serde_json::to_value(result(Some(plan.clone()))).unwrap(); + let decoded: RefreshColumnResult = serde_json::from_value(encoded).unwrap(); + assert_eq!(decoded.plan, Some(plan)); + } +} + #[cfg(test)] mod conda_environment_tests { use super::{PythonEnvironmentSpec, PythonRuntimeSpec}; diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index f38509002..879527f24 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -782,6 +782,7 @@ pub(crate) async fn execute_refresh_column_async( rows_remaining: 0, source_version: execution.source_version, published_version: execution.published_version, + plan: None, }) }))) } From e61252f4dc99dc90c13f1f25a50a180056157b22 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 17 Nov 2026 00:10:59 -0800 Subject: [PATCH 145/203] feat(python): capture Arrow and structured Function globals (#5044) Function source packaging inlined only scalar literals and tuples of them. A module-level PyArrow type shared by `output_schema=` and the Function body, a label map, or a small NumPy weight vector failed at decoration with an "unsupported global value" error and had to be redefined inside the body. These globals are now captured: ```python import numpy as np import pyarrow as pa from lancedb import function OUT_TYPE = pa.struct([pa.field("label", pa.string()), pa.field("score", pa.int32())]) LABELS = {"pick": 0, "place": 1} WEIGHTS = np.array([0.25, 0.75]) @function( input_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]), output_schema=pa.field("out", OUT_TYPE, nullable=False), pip=["numpy"], ) def judge(x: pa.Array) -> pa.Array: score = int(WEIGHTS.sum() * 10) rows = [{"label": "pick", "score": LABELS["pick"] + score}] * len(x) return pa.array(rows, type=OUT_TYPE) ``` | Captured global | Rebuilt in the artifact as | | --- | --- | | `None`, `bool`, `int`, `str`, `bytes`, finite `float` | a literal (unchanged) | | tuple, list, dict, set, frozenset of supported values | a literal; dicts keep insertion order, set elements are sorted by their source | | PyArrow `DataType`, `Field`, `Schema` | `pa.ipc.read_schema` over the value's IPC schema bytes, which keeps nullability, metadata, and nested fields | | NumPy array or scalar of a bool, integer, float16, float32, or float64 dtype | `np.array(, dtype=)` or `np.dtype().type()` | - Each value is a copy taken when the decorator runs and rebuilt per worker process, so values that share an object become separate copies. Packaging does not depend on hash randomization. - Each value is limited to 1 MiB of source and 32 levels of nesting. Cycles and Python-defined Arrow extension types are rejected. The size limit also applies to the existing literal captures. - Unsupported values keep the error that names the global, its type, the supported captures, and the remedy. - `pyarrow` and `numpy` are imported under private aliases ahead of the captured globals. The builtins used for empty sets and frozensets are claimed, so a module that rebinds them fails packaging instead of silently shadowing them. Empty NumPy arrays are encoded directly from dtype and shape, so even `(500_000, 0)` stays compact without expanding nested Python lists. --- docs/src/python/python.md | 35 ++- python/python/lancedb/functions.py | 237 ++++++++++++++-- .../python/tests/test_function_packaging.py | 267 +++++++++++++++++- 3 files changed, 502 insertions(+), 37 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b0425e1f7..b64940e39 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -517,11 +517,36 @@ def probe_library(name: str) -> str: return native_diagnostics.find_library(name) ``` -Captured literal globals support `None`, booleans, integers, strings, bytes, -finite floats, and tuples of these values. Construct other objects, including -PyArrow types and schemas, inside the Function or helper module instead. Values -used only in the decorator's `input_schema` or `output_schema` are not captured -globals and can be defined outside the Function. +Captured globals are copied into the Function's source. They can be `None`, +booleans, integers, strings, bytes, and finite floats; tuples, lists, dicts, +sets, and frozensets of supported values; PyArrow data types, fields, and +schemas; and NumPy arrays and scalars of bool, integer, `float16`, `float32`, +and `float64` dtypes. The copy is taken when the decorator runs and rebuilt in +each worker process, so later changes on either side are not shared. NumPy +values need `numpy` in the remote environment; declare it with `pip=` or +`conda=`. Each value is limited to 1 MiB of source and 32 levels of nesting; +load larger data inside the Function, for example from a table or a package +resource shipped with `code=`. Construct other objects inside the Function or +helper module instead. Values used only in the decorator's `input_schema` or +`output_schema` are not captured globals and can be defined outside the +Function. + +```python +import pyarrow as pa +from lancedb import function + +LABELS = {"pick": 0, "place": 1} +RESULT = pa.struct([pa.field("label", pa.string()), pa.field("id", pa.int32())]) + + +@function( + input_schema=pa.schema([pa.field("action", pa.string(), nullable=False)]), + output_schema=pa.field("result", RESULT, nullable=False), +) +def label(action: pa.Array) -> pa.Array: + rows = [{"label": name, "id": LABELS[name]} for name in action.to_pylist()] + return pa.array(rows, type=RESULT) +``` Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or with `bytes` to materialize its contents before the Function runs. Reader diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index f57a114dc..9178d5194 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1859,24 +1859,42 @@ def _is_function_decorator(node: ast.expr) -> bool: ) -def _literal_source(value: Any, name: str) -> str: - if value is None or type(value) in (bool, int, str, bytes): - return repr(value) - if type(value) is float and math.isfinite(value): - return repr(value) - if type(value) is tuple: - children = ", ".join(_literal_source(child, name) for child in value) - if len(value) == 1: - children += "," - return f"({children})" - raise TypeError( +# A captured value is inlined into the artifact source; larger data belongs in a +# table or a package resource. +_MAX_CAPTURED_SOURCE = 1024 * 1024 +# Far below CPython's parser nesting limit. +_MAX_CAPTURED_DEPTH = 32 +_CAPTURE_REMEDY = "Define this value inside the function or class body instead." + + +def _unsupported_capture(name: str, kind: str) -> TypeError: + return TypeError( "Function source references an unsupported global value of type " - f"{type(value).__name__} in {name!r}. Only None, bool, int, str, bytes, " - "finite float, and tuples of these literals can be captured. " - "Define this value inside the function or class body instead." + f"{kind} in {name!r}. Captured globals can be None, bool, int, str, " + "bytes, or finite float values; tuples, lists, dicts, sets, or frozensets " + "of supported values; PyArrow data types, fields, or schemas; or NumPy " + "arrays or scalars of bool, integer, float16, float32, or float64 dtypes. " + + _CAPTURE_REMEDY ) +def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType]: + """The first extension type within `data_type` whose class is defined in + Python. IPC carries only its name, so it deserializes as the storage type + wherever that class is not registered.""" + if isinstance(data_type, pa.ExtensionType): + return data_type + if isinstance(data_type, pa.BaseExtensionType): + return _python_extension_type(data_type.storage_type) + if isinstance(data_type, pa.DictionaryType): + return _python_extension_type(data_type.value_type) + for index in range(data_type.num_fields): + found = _python_extension_type(data_type.field(index).type) + if found is not None: + return found + return None + + _DYNAMIC_NAMESPACE_ACCESS = frozenset( {"globals", "locals", "vars", "eval", "exec", "compile", "__import__"} ) @@ -2175,7 +2193,7 @@ class _SourcePackager: The module holds the definition plus exactly the module-level names it references: modules as imports, importable classes and functions as - imports, literals inline, and functions and classes defined in + imports, captured values inline, and functions and classes defined in ``__main__`` by source, recursively, dependencies first. """ @@ -2183,6 +2201,7 @@ class _SourcePackager: self._code_modules = code_modules self._requirements = requirements self._imports: dict[str, str] = {} + self._support_imports: dict[str, str] = {} self._definitions: list[str] = [] self._packaged: set[int] = set() self._names: dict[str, Any] = {} @@ -2191,8 +2210,13 @@ class _SourcePackager: 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))]) + # Captured values are rebuilt with the support modules, so those come first. + imports = [ + *(self._support_imports[alias] for alias in sorted(self._support_imports)), + *(self._imports[name] for name in sorted(self._imports)), + ] + if imports: + parts.extend(["", *imports]) for definition in self._definitions: parts.extend(["", definition]) parts.extend(["", entry, ""]) @@ -2313,8 +2337,8 @@ class _SourcePackager: def _global_source(self, name: str, value: Any) -> str: """One module-level line that rebinds `name` to `value` in the artifact: - an import for modules and importable classes/functions, a literal - otherwise.""" + an import for modules and importable classes/functions, a captured + copy otherwise.""" if value is BlobReader: return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): @@ -2347,7 +2371,149 @@ class _SourcePackager: if imported is value: self._require_importable(module_name) return f"from {module_name} import {qualname} as {name}" - return f"{name} = {_literal_source(value, name)}" + return f"{name} = {self._captured_source(name, value)}" + + def _captured_source(self, name: str, value: Any) -> str: + """An expression that rebuilds a copy of the global `name`. + + Literals and containers are written as Python literals, with set + elements sorted by their source so the artifact does not depend on hash + randomization. Arrow values are rebuilt from Arrow's IPC schema encoding + and NumPy values from their dtype and elements. + """ + remaining = _MAX_CAPTURED_SOURCE + enclosing: set[int] = set() + + def too_large() -> ValueError: + return ValueError( + f"Function global {name!r} is too large to capture: its source " + f"exceeds {_MAX_CAPTURED_SOURCE} characters. Load large data inside " + "the function or class body instead, for example from a table or a " + "package resource shipped with code=." + ) + + def charge(source: str, nested: Sequence[str] = ()) -> str: + nonlocal remaining + remaining -= len(source) - sum(map(len, nested)) + if remaining < 0: + raise too_large() + return source + + def emit(value: Any) -> str: + if value is None or type(value) in (bool, int, str, bytes): + return charge(repr(value)) + if type(value) is float and math.isfinite(value): + return charge(repr(value)) + if isinstance(value, (pa.DataType, pa.Field, pa.Schema)): + return charge(self._arrow_source(name, value)) + numpy = sys.modules.get("numpy") + if numpy is not None and ( + type(value) is numpy.ndarray or isinstance(value, numpy.generic) + ): + return emit_numpy(numpy, value) + if type(value) in (tuple, list, dict, set, frozenset): + return emit_container(value) + raise _unsupported_capture(name, type(value).__name__) + + def emit_numpy(numpy: types.ModuleType, value: Any) -> str: + # These convert to exact Python values; longdouble stays a NumPy scalar. + if value.dtype.kind not in "biuf" or value.dtype.type is numpy.longdouble: + raise _unsupported_capture( + name, f"{type(value).__name__} with dtype {value.dtype}" + ) + # Every element takes at least one character; check before tolist(). + if value.size > remaining: + raise too_large() + alias = self._support_module("numpy") + dtype = repr(value.dtype.str) + if isinstance(value, numpy.generic): + item = emit(value.item()) + return charge(f"{alias}.dtype({dtype}).type({item})", (item,)) + if value.size == 0: + return charge( + f"{alias}.array([], dtype={dtype}).reshape({value.shape!r})" + ) + elements = emit(value.tolist()) + source = f"{alias}.array({elements}, dtype={dtype})" + return charge(source, (elements,)) + + def emit_container(value: Any) -> str: + if id(value) in enclosing: + raise ValueError( + f"Function global {name!r} contains itself and cannot be " + "captured. " + _CAPTURE_REMEDY + ) + if len(enclosing) == _MAX_CAPTURED_DEPTH: + raise ValueError( + f"Function global {name!r} nests containers more than " + f"{_MAX_CAPTURED_DEPTH} levels deep and cannot be captured. " + + _CAPTURE_REMEDY + ) + enclosing.add(id(value)) + if type(value) is dict: + entries = [(emit(key), emit(child)) for key, child in value.items()] + children = [part for entry in entries for part in entry] + listed = ", ".join(f"{key}: {child}" for key, child in entries) + source = f"{{{listed}}}" + else: + children = [emit(child) for child in value] + if type(value) in (set, frozenset): + listed = ", ".join(sorted(children)) + else: + listed = ", ".join(children) + if type(value) is tuple: + source = f"({listed},)" if len(children) == 1 else f"({listed})" + elif type(value) is list: + source = f"[{listed}]" + elif type(value) is set: + source = ( + f"{{{listed}}}" if children else f"{self._builtin('set')}()" + ) + else: + items = f"{{{listed}}}" if children else "" + source = f"{self._builtin('frozenset')}({items})" + enclosing.remove(id(value)) + return charge(source, children) + + return emit(value) + + def _arrow_source( + self, name: str, value: Union[pa.DataType, pa.Field, pa.Schema] + ) -> str: + if isinstance(value, pa.Schema): + schema, suffix = value, "" + elif isinstance(value, pa.Field): + schema, suffix = pa.schema([value]), ".field(0)" + else: + schema, suffix = pa.schema([pa.field("", value)]), ".field(0).type" + for data_type in schema.types: + extension = _python_extension_type(data_type) + if extension is not None: + raise TypeError( + f"Function global {name!r} uses the Arrow extension type " + f"{extension.extension_name!r}, which is defined in Python and " + "cannot be captured. " + _CAPTURE_REMEDY + ) + alias = self._support_module("pyarrow") + # Schema IPC keeps nullability, metadata, and nested fields exactly. + data = schema.serialize().to_pybytes() + return f"{alias}.ipc.read_schema({alias}.py_buffer({data!r})){suffix}" + + def _support_module(self, module: str) -> str: + """The artifact's private alias for a module that rebuilds captured + values.""" + alias = f"_lancedb_{module}" + if alias not in self._support_imports: + self._require_importable(module) + self._claim(alias, ("support", module)) + self._support_imports[alias] = f"import {module} as {alias}" + return alias + + def _builtin(self, name: str) -> str: + """A builtin called by captured source, which the artifact must not + rebind.""" + self._claim(name, ("builtin", name)) + return name def _require_importable(self, module_name: str) -> None: """Warn about an import the Function's environment may not be able to @@ -3015,8 +3181,11 @@ def function( - modules, and classes and functions importable from an installed package, become imports; the package must be declared in ``pip`` or ``conda``; - - literals (``None``, ``bool``, ``int``, ``str``, ``bytes``, finite - ``float``, and tuples containing only these literals) are inlined; + - values are copied into the source: ``None``, ``bool``, ``int``, + ``str``, ``bytes``, and finite ``float``; tuples, lists, dicts, sets, + and frozensets of supported values; PyArrow data types, fields, and + schemas; and NumPy arrays and scalars of ``bool``, integer, + ``float16``, ``float32``, and ``float64`` dtypes; - functions and classes defined in ``__main__``, such as notebook cells, are packaged by source, together with what they reference; - modules and packages listed in ``code`` are shipped as Python source and @@ -3034,13 +3203,27 @@ def function( image. Warnings follow normal Python warning filters and may be promoted to errors. Declare every third-party import in ``pip`` or ``conda`` even when it happens to be installed on the registration host. - Other global values, including Arrow types and schemas, lists, dictionaries, - sets, and NumPy arrays, cannot be captured as literals. Define them inside - the function or class body instead. - Closures, lambdas, nested definitions, mutable module-level objects, and a - non-standard ``__builtins__`` are rejected where they can be seen and + Closures, lambdas, nested definitions, other mutable module-level objects, + and a non-standard ``__builtins__`` are rejected where they can be seen and otherwise unsupported. + **Captured values.** A captured value is copied when the decorator runs + and rebuilt in every worker process. Later changes on the client do not + reach the Function, changes a worker makes stay in that process, and + globals that share an object on the client become separate copies. + Dictionaries keep their insertion order and set elements are written in a + canonical order, so the same values always package to the same source. + Floats, including NumPy elements, must be finite. Arrow values are rebuilt + from Arrow's IPC schema encoding, which preserves nullability, metadata, + and nested fields; extension types defined in Python cannot be captured. + NumPy values keep their dtype and shape and need ``numpy`` in the remote + environment, so declare it in ``pip`` or ``conda``. Each captured value is + limited to 1 MiB of source and 32 levels of nesting, and cannot contain + itself. Load larger data inside the function or class body, for example + from a table or a package resource shipped with ``code``. Define other + values, such as instances of your own classes, inside the function or + class body as well. + **Namespace restrictions.** The packaged source cannot import ``sys``, ``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``, including submodules such as ``ctypes.util`` and ``importlib.metadata``. diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index fcefc9110..ae74cc8cd 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -9,6 +9,7 @@ import base64 import importlib import hashlib import json +import os import subprocess import sys import textwrap @@ -17,6 +18,7 @@ import warnings from pathlib import Path from typing import Annotated, Optional, get_type_hints +import numpy as np import pyarrow as pa import pytest @@ -234,10 +236,15 @@ def test_function_can_return_a_list_from_a_generator_expression(): @pytest.mark.parametrize( ("global_value", "value_type"), [ - ("pa.struct([('label', pa.string())])", "StructType"), - ("(1, (pa.int64(),))", "DataType"), - ("{'label': 1}", "dict"), ("float('inf')", "float"), + ("{'label': float('nan')}", "float"), + ("[1, (2, object())]", "object"), + ("{'labels': range(2)}", "range"), + ("pa.array([1])", "Int64Array"), + ("np.array(['label'])", "ndarray with dtype pa.Array:\n" + + textwrap.indent(body, " ") + if kind == "class" + else "def judge(x: pa.Array) -> pa.Array:\n" + body + ) + module = helper_package( + "fx_structured_global", + { + "__init__.py": textwrap.dedent(""" + import numpy as np + import pyarrow as pa + + OUT_TYPE = pa.struct( + [pa.field("label", pa.string()), pa.field("score", pa.int32())] + ) + LABELS = { + "pick": 0, + "place": 1, + "nested": [None, (1.5, b"x"), {"deep": frozenset({"b", "a"})}], + } + EMPTY = ([], {}, set(), frozenset(), ()) + ARROW = { + "field": pa.field( + "score", pa.int32(), nullable=False, metadata={"unit": "pts"} + ), + "schema": pa.schema( + [pa.field("label", pa.dictionary(pa.int8(), pa.utf8(), True))], + metadata={"version": "1"}, + ), + "tensor": pa.fixed_shape_tensor(pa.float32(), [2, 2]), + } + WEIGHTS = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=np.float32) + NUMPY = ( + np.float32(0.5), + np.True_, + np.uint64(2**64 - 1), + np.array(1.5), + np.zeros((0, 3), dtype=np.int16), + np.array([1.0, -0.0], dtype=">f8"), + ) + """) + + definition + }, + ) + out_type = module.OUT_TYPE + packaged = function( + input_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]), + output_schema=pa.field("out", out_type, nullable=False), + )(module.judge) + source = artifact(packaged).decode() + assert "import numpy as _lancedb_numpy" in source + assert "import pyarrow as _lancedb_pyarrow" in source + + namespace = {} + exec(compile(source, "user_function.py", "exec"), namespace) + call = namespace["judge"]() if kind == "class" else namespace["judge"] + result = call(pa.array([1, 2])) + assert result.type == out_type + assert result.to_pylist() == [{"label": "pick", "score": 0}] * 2 + assert namespace["OUT_TYPE"] == out_type + + assert namespace["LABELS"] == module.LABELS + assert list(namespace["LABELS"]) == list(module.LABELS) + assert namespace["EMPTY"] == module.EMPTY + assert [type(value) for value in namespace["EMPTY"]] == [ + type(value) for value in module.EMPTY + ] + for key, value in module.ARROW.items(): + assert namespace["ARROW"][key].equals(value, check_metadata=True) + assert type(namespace["ARROW"][key]) is type(value) + + weights = namespace["WEIGHTS"] + assert weights.dtype == module.WEIGHTS.dtype + assert np.array_equal(weights, module.WEIGHTS) + for captured, original in zip(namespace["NUMPY"], module.NUMPY, strict=True): + assert type(captured) is type(original) + assert captured.dtype == original.dtype + assert np.shape(captured) == np.shape(original) + assert np.array_equal(captured, original) + assert np.signbit(namespace["NUMPY"][-1][1]) + + +@pytest.mark.parametrize("kind", ["function", "class"]) +@pytest.mark.parametrize("shape", [(0,), (0, 3), (2, 0, 3), (500_000, 0)]) +def test_empty_numpy_captures_preserve_shape_without_expanding( + helper_package, kind, shape +): + definition = ( + "class empty_size:\n def __call__(self, value: int) -> int:\n" + " return value + EMPTY.size\n" + if kind == "class" + else "def empty_size(value: int) -> int:\n return value + EMPTY.size\n" + ) + module = helper_package( + "fx_empty_numpy_global", + { + "__init__.py": "import numpy as np\n" + f"EMPTY = np.empty({shape!r}, dtype='>i2')\n" + definition + }, + ) + source = artifact(function(module.empty_size)) + assert len(source) < 1024 + namespace = {} + exec(compile(source, "user_function.py", "exec"), namespace) + captured = namespace["EMPTY"] + assert captured.shape == shape + assert captured.dtype == module.EMPTY.dtype + assert captured.size == 0 + call = namespace["empty_size"]() if kind == "class" else namespace["empty_size"] + assert call(7) == 7 + + +def test_captured_containers_are_copied_when_decorated(helper_package): + module = helper_package( + "fx_captured_copy", + { + "__init__.py": """ + SHARED = [1, 2] + CONFIG = {"shared": SHARED, "again": SHARED} + + def uses_config(value: int) -> int: + return value + len(CONFIG["shared"]) + len(SHARED) + """ + }, + ) + definition = function(module.uses_config) + module.SHARED.append(3) + + namespace = {} + exec(compile(artifact(definition), "user_function.py", "exec"), namespace) + assert namespace["SHARED"] == [1, 2] + assert namespace["CONFIG"] == {"shared": [1, 2], "again": [1, 2]} + assert namespace["CONFIG"]["shared"] is not namespace["CONFIG"]["again"] + assert namespace["CONFIG"]["shared"] is not namespace["SHARED"] + assert namespace["uses_config"](1) == 5 + + +def test_captured_sets_package_deterministically(tmp_path): + script = tmp_path / "sets.py" + script.write_text( + textwrap.dedent( + """ + import json + + from lancedb import function + + WORDS = {f"word{index}" for index in range(20)} + MIXED = frozenset({("pair", 1), b"bytes", None, 2.5, "text"}) + + @function + def known(word: str) -> bool: + return word in WORDS or word in MIXED + + print(json.dumps([ + known.registration_request.artifact.digest, + list(WORDS), + ])) + """ + ) + ) + runs = [] + for seed in ("0", "1", "2", "3"): + result = subprocess.run( + [sys.executable, str(script)], + capture_output=True, + text=True, + env={**os.environ, "PYTHONHASHSEED": seed}, + ) + assert result.returncode == 0, result.stderr + runs.append(json.loads(result.stdout)) + # Hash randomization reorders the client's set; the artifact must not change. + assert len({tuple(order) for _, order in runs}) > 1 + assert len({digest for digest, _ in runs}) == 1 + + +@pytest.mark.parametrize( + ("global_value", "message"), + [ + ("list(range(300_000))", "too large to capture"), + ("np.zeros(2_000_000)", "too large to capture"), + ("'x' * (1024 * 1024)", "too large to capture"), + ("functools.reduce(lambda inner, _: [inner], range(40), [])", "32 levels"), + ("_cycle()", "contains itself"), + ("pa.schema([pa.field('x', pa.list_(_Extension()))])", "defined in Python"), + ], +) +def test_captured_value_limits_name_the_global(helper_package, global_value, message): + module = helper_package( + "fx_captured_limits", + { + "__init__.py": textwrap.dedent(""" + import functools + + import numpy as np + import pyarrow as pa + + class _Extension(pa.ExtensionType): + def __init__(self): + super().__init__(pa.int64(), "fx.extension") + + def __arrow_ext_serialize__(self): + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return cls() + + def _cycle(): + value = [] + value.append(value) + return value + """) + + f"CAPTURED_VALUE = {global_value}\n" + "def uses_global(value: int) -> int:\n" + " return value if CAPTURED_VALUE else 0\n" + }, + ) + with pytest.raises((TypeError, ValueError)) as error: + function(module.uses_global) + assert "CAPTURED_VALUE" in str(error.value) + assert message in str(error.value) + assert "inside the function or class body" in str(error.value) + + +def test_captured_sets_keep_their_builtins(helper_package): + module = helper_package( + "fx_captured_builtins", + { + "__init__.py": """ + STOP = frozenset({"a"}) + frozenset = ("shadowed",) + + def uses_sets(word: str) -> bool: + return word in STOP or word in frozenset + """ + }, + ) + with pytest.raises(ValueError, match="cannot package 'frozenset'"): + function(module.uses_sets) + + @pytest.mark.parametrize("annotation", ["Array", "RecordBatch"]) @pytest.mark.parametrize("kind", ["function", "class"]) def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package): From 1a216989063a07f1fed003c6dcfd46a351662bc3 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 17 Nov 2026 16:55:26 +0800 Subject: [PATCH 146/203] chore: update lance dependency to v15.0.0-beta.25 (#5069) Update the Rust workspace, Java core dependency and Python test dependency to [Lance v15.0.0-beta.25](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.25). Mark computed-column refresh replacements as data changes using Lance's new explicit flag so refreshed values retain the existing index invalidation and row-update behavior. Rust API compatibility: the re-exported `CompactionOptions` adds `max_data_files_per_fragment` and `scope`. Callers using exhaustive struct literals must include the new fields or use `..Default::default()`. Configure macOS Rust tests with an explicit Python 3.13 interpreter and runner/Python-specific caches so doctests do not link against an absent Python framework. --- .github/workflows/rust.yml | 7 +++ Cargo.lock | 96 +++++++++++++++---------------- Cargo.toml | 30 +++++----- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 18 +++--- rust/lancedb/src/table/refresh.rs | 5 +- 7 files changed, 85 insertions(+), 75 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 9bbc4d581..636c1a7bf 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -311,10 +311,16 @@ jobs: with: fetch-depth: 0 lfs: true + - uses: actions/setup-python@v6 + id: python + with: + python-version: "3.13" - name: CPU features run: sysctl -a | grep cpu - uses: Swatinem/rust-cache@v2 with: + # PyO3 caches the interpreter library path; runner images can differ. + key: ${{ matrix.mac-runner }}-python-${{ steps.python.outputs.python-version }} # 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. @@ -323,6 +329,7 @@ jobs: run: brew install protobuf - name: Run tests env: + PYO3_PYTHON: ${{ steps.python.outputs.python-path }} CARGO_TEST_TARGETS: ${{ matrix.phase == 'doc' && '--doc' || '--lib --tests' }} run: | # Don't run the s3 integration tests since docker isn't available diff --git a/Cargo.lock b/Cargo.lock index 906577f07..bed68cb73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3836,8 +3836,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5315,8 +5315,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arc-swap", "arrow", @@ -5391,8 +5391,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-buffer", @@ -5414,7 +5414,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-buffer", @@ -5428,7 +5428,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-schema", @@ -5437,8 +5437,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrayref", "crunchy", @@ -5448,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-buffer", @@ -5487,8 +5487,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow", "arrow-array", @@ -5519,8 +5519,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow", "arrow-array", @@ -5545,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow", "arrow-array", @@ -5563,8 +5563,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "proc-macro2", "quote", @@ -5573,8 +5573,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-arith", "arrow-array", @@ -5608,8 +5608,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-arith", "arrow-array", @@ -5640,8 +5640,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-schema", @@ -5672,8 +5672,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arc-swap", "arrow", @@ -5746,8 +5746,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-schema", @@ -5770,8 +5770,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow", "arrow-array", @@ -5816,8 +5816,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "byteorder", "ethnum", @@ -5834,8 +5834,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5850,8 +5850,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow", "async-trait", @@ -5865,8 +5865,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arc-swap", "arrow", @@ -5920,8 +5920,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-buffer", @@ -5935,8 +5935,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow", "arrow-array", @@ -5977,8 +5977,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "arrow-array", "arrow-schema", @@ -5991,8 +5991,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.23" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908" +version = "15.0.0-beta.25" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.25#f5dbd55dd79f1f0412f897ed1917128300fb8c1a" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 6a8450cf7..1b277c625 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.25", default-features = false, "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.25", "tag" = "v15.0.0-beta.25", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index 43b70e500..4ccbc59e4 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.23 + 15.0.0-beta.25 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 201e9fd07..ff64d9772 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b23", + "pylance==15.0.0b25", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 0cbcea617..6b1a96c2e 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2147,7 +2147,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.0b23" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b25" }, { 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" }, @@ -4301,7 +4301,7 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b23" +version = "15.0.0b25" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,13 +4312,13 @@ dependencies = [ { name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_ldwuz/pylance-15.0.0b23-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:b7980c606424e63e9be645536dbcaff75b479886a53abdae3aef64684c9a6fc4" }, - { url = "https://pypi.fury.io/lance-format/-/ver_5wKzE/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a6d887bc81d5f79b8a23d5cbc840cb56dbea4d8b0a9d2c2edf063dea48bcf741" }, - { url = "https://pypi.fury.io/lance-format/-/ver_FKuk6/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1424bd48cac2160b7745c9b87cd24d81c7cf2b0a89f342ea46ecd2a473ea74e6" }, - { url = "https://pypi.fury.io/lance-format/-/ver_SVglj/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:09de71b60ac6b8b91fdd73207f71c74bc521626de7e437102ebfe4f2c1f78fa0" }, - { url = "https://pypi.fury.io/lance-format/-/ver_SgTr6/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d9385471578bec51ae546f7bd7ea638e20bd12d687082d43ed465017dfd992e7" }, - { url = "https://pypi.fury.io/lance-format/-/ver_wyipY/pylance-15.0.0b23-cp310-abi3-win_amd64.whl", hash = "sha256:7b98b0d78564c5acea3693334c41dc3ced20484fb2c8e738113eeb078281a109" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1v2uEn/pylance-15.0.0b23-cp310-abi3-win_arm64.whl", hash = "sha256:0f4d2645143d44c11237e6ea00772c169a3c6ed23a7c36beaeaef9a18d1be14d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2hpc2R/pylance-15.0.0b25-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:2a0bb8d6b0c55b7a821989759fc0f8f62cb4da621f89eae232cef49bb7ef341e" }, + { url = "https://pypi.fury.io/lance-format/-/ver_4LUKQ/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9b73e6e9373c4d5af3fea51e63c3e55873f470aa1a6d0412c22916f88ff5df88" }, + { url = "https://pypi.fury.io/lance-format/-/ver_11CcHk/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8090d403b2a38cd4ac8eb09de0327bc404cb3bc965d905f2b6a8479891273fae" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1S87Ih/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7f0a20e8ed41d3e49cd5e0bbba97d18ad684cf337e053641321404c9db34f1a1" }, + { url = "https://pypi.fury.io/lance-format/-/ver_13KmLJ/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:079385a6816a10d42f57bc467d9c822c7207cd31d9a6f768bbf522c0a3007229" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1bTDlQ/pylance-15.0.0b25-cp310-abi3-win_amd64.whl", hash = "sha256:d9b1d713b0d03043a3f5596e909405787f85219f54c427b14437367f0ea7acb9" }, + { url = "https://pypi.fury.io/lance-format/-/ver_j7adN/pylance-15.0.0b25-cp310-abi3-win_arm64.whl", hash = "sha256:4a1c18176ffd6a860c6e66b0deb39fcc9ac1434dba57ee66559b7638ad4a200a" }, ] [[package]] diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 879527f24..f6bab98f5 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -653,7 +653,10 @@ async fn execute_refresh_column_with_source( let session = dataset.session(); let new_dataset = Dataset::commit( WriteDestination::Dataset(dataset.clone()), - Operation::DataReplacement { replacements }, + Operation::DataReplacement { + replacements, + data_change: true, + }, Some(source_version), None, None, From 57b20fb11d907fd8948827370e7c4032d396c205 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 17 Nov 2026 08:56:28 +0000 Subject: [PATCH 147/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.17=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.18?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 9ddd23172..8f10d67f0 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.17" +current_version = "0.42.0-beta.18" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index bed68cb73..6a23569a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 4aa029baf..1a8347ad5 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.42.0-beta.17 + 0.42.0-beta.18 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 2301b9e1d..c15bc0774 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.17 + 0.42.0-beta.18 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 4ccbc59e4..dce3deba3 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.17 + 0.42.0-beta.18 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index c0bf9ca9b..e523c1138 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" 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 924ff3967..d603a2c8f 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.42.0-beta.17", + "version": "0.42.0-beta.18", "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 b265cd7f1..8115e27f9 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.42.0-beta.17", + "version": "0.42.0-beta.18", "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 031d20477..f3cdd7253 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.42.0-beta.17", + "version": "0.42.0-beta.18", "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 6c71adeee..4d165c4de 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.42.0-beta.17", + "version": "0.42.0-beta.18", "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 2d05ddca1..d884605b6 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.42.0-beta.17", + "version": "0.42.0-beta.18", "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 013568ae2..2b6bdc8da 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.42.0-beta.17", + "version": "0.42.0-beta.18", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index fec9adb4f..1402f5bee 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.42.0-beta.17", + "version": "0.42.0-beta.18", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index cd8dd8be7..a0cf05acb 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.17", + "version": "0.42.0-beta.18", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 189950963..9ba87dcd5 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 34e91dbfd..28e8c501b 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index ff16ccb7b..689200452 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.17" +version = "0.42.0-beta.18" edition = "2021" license.workspace = true repository.workspace = true From ba4e3ef3f9dccb9e94623783120af04166cc2239 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 17 Nov 2026 02:54:18 -0800 Subject: [PATCH 148/203] feat: expose Function worker stack inspection (#5043) Adds `Job::stack(worker_id)` in Rust and `Job.stack(worker_id)` / `AsyncJob.stack(worker_id)` in Python for server-side Function jobs. The response preserves capture availability, timestamps, truncation, and session details; unsupported local or query handles retain their existing unsupported-operation behavior. Refresh wrappers forward the request to their tracked server job. ```python evidence = job.stack("worker-id") for session in evidence["stacks"]: print(session["status"], session["stack"]) ``` Requires a server implementing `/v1/jobs/stack` and system operate privilege. The API propagates authorization and transport errors without waiting for job completion. Existing progress snapshots already preserve server warning fields. Includes mocked request/response and synchronous/asynchronous Python coverage. Local builds and tests were intentionally skipped as requested. --- docs/web/basics/jobs.mdx | 30 ++++++++++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/job.py | 41 +++++++++++++ python/python/tests/test_job.py | 45 +++++++++++++++ python/src/job.rs | 7 +++ rust/lancedb/src/job.rs | 32 ++++++++++ rust/lancedb/src/remote/job.rs | 93 ++++++++++++++++++++++++++++++ rust/lancedb/src/remote/table.rs | 8 +++ 8 files changed, 257 insertions(+) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index db5b49ab5..30d48e93e 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -332,6 +332,36 @@ by the jobs API. `estimated_remaining_time_millis` is a best-effort client-side estimate. It is omitted while a job is initializing, queued, or paused, and when there is no positive progress rate from two compatible samples. + +### Inspect a slow Function worker + +On a supported Enterprise server, Python's `Job.stack(worker_id)` and +`await AsyncJob.stack(worker_id)` capture Python thread stacks from a running +Function refresh worker. Rust provides `job.stack(worker_id).await?`. +TypeScript does not yet expose this method. Stack inspection requires the +system operate privilege. + +Select a worker ID from the job's progress warnings or recorded events. For +example, inspect a worker named in the current no-progress or slow-split warnings: + +```python +job = db.open_job(job_id) +snapshot = job.progress() or {} +warnings = snapshot.get("warnings", []) +if warnings: + evidence = job.stack(warnings[0]["worker_id"]) + print(evidence["status"], evidence["omitted_sessions"]) + for session in evidence["stacks"]: + print(session["status"], session["captured_at_millis"]) + print(session["stack"], session["truncated"]) +``` + +`unavailable` and `unsupported` are explicit capture statuses; missing frames +do not establish that a worker is healthy or finished. Captures are bounded and +may reuse a recent sample. They contain Python frames without source text, +locals or native frames. Local operations and SQL-backed query handles do not +support stack inspection. For a worker that already timed out, inspect the +recorded failure events for retained traceback evidence. */} ## Embedded and Enterprise execution {#in-process} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 63d442703..2273e8628 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -449,6 +449,7 @@ class Job: async def cancel(self) -> None: ... async def refresh(self) -> None: ... async def timeline(self) -> str: ... + async def stack(self, worker_id: str) -> str: ... async def stats(self) -> Optional[str]: ... async def events( self, diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index e49609e1f..dab6d5903 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -4,6 +4,7 @@ """Handles to asynchronous registry jobs, SQL queries, and local operations.""" import asyncio +import json import logging import reprlib import time @@ -486,6 +487,30 @@ class AsyncJob(Generic[T]): description = self._inner._description if self._inner is not None else None return getattr(description, name) if description is not None else None + async def stack(self, worker_id: str) -> dict[str, Any]: + """Capture Python thread stacks from a running Function worker. + + Requires server support and system operate privilege. The response has + ``status``, ``worker_id``, ``execution_epoch`` and ``stacks``. Each session + reports its status, capture timestamp, Python frames and truncation. + ``omitted_sessions`` counts sessions beyond the server's capture limit. + Captures exclude source text, locals and native frames; a recent capture + may be reused to bound overhead. Unsupported or unavailable captures + have an explicit status. Transport and authorization errors propagate. + Local operations and SQL query handles raise ``NotImplementedError``. + Timeout stack evidence remains in the job's failure events. + + Examples + -------- + >>> evidence = await job.stack("worker-id") # doctest: +SKIP + >>> print(evidence["stacks"]) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "worker stacks require a server-side Function job" + ) + return json.loads(await self._inner.stack(worker_id)) + async def stats(self) -> Optional[str]: """Return a printable run report for this Function job. @@ -736,6 +761,22 @@ class Job(Generic[T]): def _field(self, name: str) -> Optional[Any]: return getattr(self._inner, name) if self._inner is not None else None + def stack(self, worker_id: str) -> dict[str, Any]: + """Capture Python thread stacks from a running Function worker. + + See [AsyncJob.stack][lancedb.job.AsyncJob.stack] for availability, + permissions and response fields. + + Examples + -------- + >>> print(job.stack("worker-id")["stacks"]) # doctest: +SKIP + """ + if self._inner is None: + raise NotImplementedError( + "worker stacks require a server-side Function job" + ) + return LOOP.run(self._inner.stack(worker_id)) + def stats(self) -> Optional[str]: """Return a printable Function job run report. diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index e71945b7f..59e2fc3a8 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -1027,3 +1027,48 @@ async def test_export_timeline_reports_filesystem_errors(tmp_path): ) with pytest.raises(FileNotFoundError): await job.export_timeline(tmp_path / "missing" / "trace.json") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stack_preserves_evidence_and_does_not_wait(sync): + evidence = { + "worker_id": "worker", + "status": "unavailable", + "execution_epoch": 1, + "stacks": [], + "omitted_sessions": 0, + } + inner = SimpleNamespace( + stack=AsyncMock(return_value=json.dumps(evidence)), + wait=AsyncMock(), + cancel=AsyncMock(), + ) + job = AsyncJob(inner) + actual = ( + await asyncio.to_thread(Job(job).stack, "worker") + if sync + else await job.stack("worker") + ) + assert actual == evidence + inner.stack.assert_awaited_once_with("worker") + inner.wait.assert_not_awaited() + inner.cancel.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_stack_propagates_errors_and_rejects_local_handles(sync): + error = RuntimeError("system operate privilege required") + job = AsyncJob(SimpleNamespace(stack=AsyncMock(side_effect=error))) + with pytest.raises(RuntimeError) as failure: + if sync: + await asyncio.to_thread(Job(job).stack, "worker") + else: + await job.stack("worker") + assert failure.value is error + with pytest.raises(NotImplementedError): + if sync: + Job(None).stack("worker") + else: + await AsyncJob(None).stack("worker") diff --git a/python/src/job.rs b/python/src/job.rs index 08f6440ab..7e4c13f41 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -159,6 +159,13 @@ impl Job { }) } + pub fn stack(self_: PyRef<'_, Self>, worker_id: String) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + Ok(inner.stack(worker_id).await.infer_error()?.to_string()) + }) + } + pub fn stats(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { inner.stats().await.infer_error() }) diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index b1e3c1bbf..39fee38d6 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -90,6 +90,10 @@ pub(crate) trait JobHandle: Send + Sync { job_detail_not_supported("job timeline export") } + async fn stack(&self, _worker_id: &str) -> Result { + job_detail_not_supported("worker stack capture") + } + /// A printable report of recorded Function job metrics. async fn stats(&self) -> Result> { job_detail_not_supported("job statistics") @@ -536,6 +540,34 @@ where } } + /// Capture Python thread stacks from a running Function worker. + /// + /// Requires a server supporting stack inspection and system operate privilege. + /// The JSON response reports capture availability per session, timestamps and + /// truncation. Stacks exclude source text, locals and native frames. A server + /// may reuse a recent capture to bound sampling overhead. Unsupported local + /// operations return [`crate::Error::NotSupported`]. + /// + /// ```no_run + /// # async fn inspect(job: &lancedb::job::Job) -> Result<(), Box> { + /// let evidence = job.stack("worker-id").await?; + /// println!("{evidence}"); + /// # Ok(()) + /// # } + /// ``` + pub async fn stack(&self, worker_id: impl AsRef) -> Result { + let worker_id = worker_id.as_ref(); + if worker_id.is_empty() || worker_id.len() > 256 { + return Err(Error::InvalidInput { + message: "worker_id must contain 1 to 256 bytes".into(), + }); + } + match &self.inner { + JobInner::Handle { handle, .. } => handle.stack(worker_id).await, + JobInner::Completed(_) => job_detail_not_supported("worker stack capture"), + } + } + /// Fetch a printable run report for a server-side Function job. /// /// The server report includes recorded phase timings, finishing-supervisor diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 7e59834d0..f233d4026 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -261,6 +261,46 @@ impl JobHandle for RemoteJob { Ok(trace) } + async fn stack(&self, worker_id: &str) -> Result { + let request = self + .client + .post("/v1/jobs/stack") + .json(&serde_json::json!({"job_id": self.job_id, "worker_id": worker_id})); + let (request_id, response) = self.client.send(request).await?; + let response = self.client.check_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let evidence: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse worker stack response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if evidence + .get("worker_id") + .and_then(serde_json::Value::as_str) + != Some(worker_id) + || !matches!( + evidence.get("status").and_then(serde_json::Value::as_str), + Some("captured" | "unavailable" | "unsupported") + ) + || !evidence + .get("stacks") + .is_some_and(serde_json::Value::is_array) + || !evidence + .get("execution_epoch") + .is_some_and(serde_json::Value::is_i64) + { + return Err(Error::Http { + source: + "server response is not worker stack evidence; capture requires server support" + .into(), + request_id, + status_code: None, + }); + } + Ok(evidence) + } + async fn stats(&self) -> Result> { let request = self .client @@ -401,6 +441,59 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test] + async fn stack_preserves_availability_and_uses_the_selected_worker() { + for status in ["captured", "unsupported", "unavailable"] { + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/stack"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!( + body, + serde_json::json!({"job_id":"job-1", "worker_id":"worker-1"}) + ); + http::Response::builder().status(200).body(serde_json::json!({ + "worker_id":"worker-1", "status":status, "execution_epoch":1, "stacks":[], "omitted_sessions":0 + }).to_string()).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "job-1".into()))); + assert_eq!(job.stack("worker-1").await.unwrap()["status"], status); + } + } + + #[tokio::test] + async fn stack_rejects_unrelated_responses_and_preserves_authorization_errors() { + for body in [ + "{}", + r#"{"worker_id":"other","status":"captured","execution_epoch":1,"stacks":[]}"#, + ] { + let client = client_with_handler(move |_| { + http::Response::builder().status(200).body(body).unwrap() + }); + assert!(matches!( + RemoteJob::new(client, "job-1".into()) + .stack("worker-1") + .await + .unwrap_err(), + crate::Error::Http { .. } + )); + } + let client = client_with_handler(|_| { + http::Response::builder() + .status(403) + .body("access denied") + .unwrap() + }); + assert!( + RemoteJob::new(client, "job-1".into()) + .stack("worker-1") + .await + .unwrap_err() + .to_string() + .contains("403") + ); + } + #[tokio::test] async fn stats_reads_report_verbatim_and_preserves_unavailable_without_waiting() { let requests = Arc::new(AtomicUsize::new(0)); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 1394f1ab0..f89be7e69 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -324,6 +324,10 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::timeline(&self.inner).await } + async fn stack(&self, worker_id: &str) -> Result { + crate::job::JobHandle::stack(&self.inner, worker_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, @@ -409,6 +413,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::timeline(&self.inner).await } + async fn stack(&self, worker_id: &str) -> Result { + crate::job::JobHandle::stack(&self.inner, worker_id).await + } + async fn events( &self, request: crate::job::JobEventsRequest, From fb34b1c7837b525b4ebb27b71800d63efa2026fc Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 17 Nov 2026 03:26:45 -0800 Subject: [PATCH 149/203] feat(functions): add row failure recovery APIs (#5048) Function failures currently require callers to assemble row predicates and manage retry/version/quarantine state themselves. Add exact failed-row retry and Function upgrades through the Rust and Python refresh APIs, plus Python helpers for grouped causes, failing input rows, quarantine, and per-row producing-version metadata. ```python errors = table.function_errors(column="sharpness") errors.summary() errors.rows(columns=["frame_index", "frame"]) table.retry_failed("sharpness", function_version="2").wait() table.quarantine_failed("sharpness", after_attempts=3) table.retry_failed("sharpness", include_quarantined=True).wait() table.function_provenance("sharpness") ``` `upgrade_column(..., recompute="failed" | "all" | "none")` keeps the column available while selecting the intended work. `history=True` reads retained past errors. Capability checks reject these operations on servers that cannot honor the workflow, before any refresh is submitted. Includes synchronous/asynchronous API and older-server compatibility coverage. Formatting applied; local builds and tests were not run. --- docs/src/python/python.md | 10 +- docs/web/management/function-failures.mdx | 133 +++++++- nodejs/src/table.rs | 1 + python/python/lancedb/__init__.py | 11 +- python/python/lancedb/_lancedb.pyi | 35 ++ python/python/lancedb/functions.py | 221 +++++++++++++ python/python/lancedb/remote/table.py | 60 +++- python/python/lancedb/table.py | 370 ++++++++++++++++++++-- python/python/tests/test_remote_db.py | 211 +++++++++++- python/src/table.rs | 115 ++++++- rust/lancedb/src/function.rs | 106 +++++++ rust/lancedb/src/remote/table.rs | 104 ++++++ rust/lancedb/src/table.rs | 105 ++++++ rust/lancedb/src/table/refresh.rs | 85 +++++ 14 files changed, 1540 insertions(+), 27 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b64940e39..d3713b634 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -640,7 +640,15 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.RefreshColumnResult -::: lancedb.FunctionErrors +::: lancedb.functions.FunctionErrorGroup + +::: lancedb.functions.FunctionProvenance + +::: lancedb.functions.FunctionValueProvenance + +::: lancedb.functions.AsyncFunctionErrors + +::: lancedb.functions.FunctionErrors ::: lancedb.FunctionErrorRecord diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 4546129fa..131204382 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -10,8 +10,137 @@ availability: A Function refresh can encounter a bad row, fail to initialize a model, lose a worker, or fail while publishing results. These need different remedies. -This guide uses the existing [refresh error policy](/sql/dml/refresh-column#options) -and Python error records; it does not require a new retry or quarantine API. +The native workflow below is draft guidance for an unreleased SDK and a +matching Enterprise server. The recipes that follow it remain available for +older deployments. + +## Draft native workflow: server contract version 1 {#native} + +This section requires the SDK changes in [PR #5048](https://github.com/lancedb/lancedb/pull/5048) +and an Enterprise deployment advertising `workflow_version >= 1` in its +Function error response. No released SDK or Enterprise version is implied by +this draft. The SDK checks this capability before submitting native retry, +upgrade, quarantine, history or provenance requests, and rejects unsupported +servers before changing the column. + +New Function refreshes default to `error_policy="skip"` with a 5% failed-row +ceiling. Successful outputs are published before a threshold failure is +reported; failed rows and grouped causes remain available. Explicit `fail` +still stops on a row error. Initialization, infrastructure and publication +failures remain job failures. External effects can repeat during recovery. + +Read current unresolved failures, group their causes and inspect their inputs: + +```python +errors = table.function_errors(column="embedding") +print(errors.summary()) +inputs = errors.rows(columns=["text"]) +print(inputs) # Includes a __function_error struct for each failed column. + +history = table.function_errors(column="embedding", history=True) +print(history.records) # Retained attempts, including repaired failures. +``` + +The default listing deduplicates failures by row and Function column, retaining +attempt counts and first/last failure times. `summary()` and `rows()` refuse +incomplete selections; narrow a truncated request before inspecting it. +Historical records cannot be joined to current inputs through `rows()`. +Stable row IDs survive compaction; older physical-only records are rejected +for exact retry if their fragments have been rewritten. + +Select retry rows on the server, optionally by exception class or job: + +```python +retry_job = table.retry_failed("embedding", error_type="ValueError") +retry_job.wait() +``` + +Upgrade the existing Function binding and choose which values to recompute: + +```python +upgrade_job = table.upgrade_column("embedding", version="2", recompute="failed") +upgrade_job.wait() +provenance = table.function_provenance("embedding") +if not provenance.truncated: + print(provenance.records) +``` + +The immutable target version must already exist for the same Function. +`recompute="failed"` selects current failures; `"all"` recomputes all live rows; +`"none"` changes the binding while preserving existing values. The default is +`"all"`. New and changed inputs use the new version. Producing-version records +identify successful values written by this workflow; older values without +recorded provenance do not acquire an invented producing version. + +Quarantine failures that need input repair, then explicitly include them when +they are ready to retry: + +```python +table.quarantine_failed("embedding", after_attempts=3) +retry_job = table.retry_failed("embedding", include_quarantined=True) +retry_job.wait() +``` + +Ordinary and automatic refreshes exclude quarantined rows, including during +an `"all"` upgrade. Explicit inclusion releases quarantine before the retry. +Async tables expose the same operations with `await`; `function_errors()` +returns `AsyncFunctionErrors`, and its `rows()` method is also awaited. +These native recovery APIs are available in Python and Rust. TypeScript does +not yet expose them; its SDK support is tracked as a separate follow-up. + +The equivalent Rust operations use explicit request options: + +```rust +use lancedb::{Table, table::RefreshColumnOptions}; +use lancedb::function::{ + FunctionProvenanceOptions, FunctionQuarantineOptions, FunctionRecompute, +}; + +async fn recover(table: &Table) -> lancedb::Result<()> { + let retry = table.refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default() + .retry_errors(true) + .retry_error_type("ValueError"), + ).await?; + retry.wait().await?; + + let upgrade = table.refresh_column_async_with_options( + "embedding", + RefreshColumnOptions::default().upgrade("2", FunctionRecompute::Failed), + ).await?; + upgrade.wait().await?; + + table.quarantine_function_errors( + "embedding", + FunctionQuarantineOptions { + after_attempts: Some(3), + ..Default::default() + }, + ).await?; + let provenance = table.function_provenance( + "embedding", FunctionProvenanceOptions::default(), + ).await?; + if !provenance.truncated { + println!("{:?}", provenance.records); + } + Ok(()) +} +``` + +Set `include_quarantined(true)` on a Rust failed-row retry to explicitly +release quarantine before recomputing those failures. + +The native contract also applies skip/5% defaults to newly created materialized +views, with errors identified by Function invocation and source input. Column +retry and upgrade helpers apply to Function columns; use the materialized-view +refresh reference for view refresh options. + +## Older-deployment recipes {#older-deployments} + +The following sections describe deployments without workflow version 1. Their +legacy defaults, error-history semantics and application-managed quarantine +remain unchanged. ## Choose a row-error policy {#policy} diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index a0a220e24..c9e03b2a3 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -581,6 +581,7 @@ impl Table { }) .transpose()?; let request = lancedb::function::FunctionErrorsRequest { + history: false, job_id: options.job_id, column: options.column, limit, diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index acf25d35c..129a4b1c5 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -29,7 +29,6 @@ from ._lancedb import ( ) from ._lancedb import FunctionErrorFragment as FunctionErrorFragment from ._lancedb import FunctionErrorRecord as FunctionErrorRecord -from ._lancedb import FunctionErrors as FunctionErrors from ._lancedb import GpuClass as GpuClass from ._lancedb import RTEWriteSpec from ._lancedb import tokenize as _tokenize @@ -46,6 +45,11 @@ from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery from .sql import QueryDescription from .functions import ( + FunctionErrors as FunctionErrors, + AsyncFunctionErrors as AsyncFunctionErrors, + FunctionErrorGroup as FunctionErrorGroup, + FunctionProvenance as FunctionProvenance, + FunctionValueProvenance as FunctionValueProvenance, AssignmentMapping as AssignmentMapping, FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, @@ -678,6 +682,11 @@ __all__ = [ "FunctionColumnLastRefreshJob", "FunctionColumnStatus", "FunctionColumnVersionStatus", + "FunctionErrors", + "AsyncFunctionErrors", + "FunctionErrorGroup", + "FunctionProvenance", + "FunctionValueProvenance", "col", "Expr", "func", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 2273e8628..19454790a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -694,6 +694,12 @@ class Table: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> RefreshColumnResult: ... async def refresh_column_async( self, @@ -716,13 +722,36 @@ class Table: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job: ... async def function_errors( self, job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> FunctionErrors: ... + async def quarantine_function_errors( + self, + column: str, + *, + quarantined: bool = True, + job_id: Optional[str] = None, + error_type: Optional[str] = None, + after_attempts: Optional[int] = None, + ) -> int: ... + async def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> str: ... async def column_statuses( self, column: Optional[str] = None ) -> list[FunctionColumnStatus]: ... @@ -1128,6 +1157,10 @@ class RefreshColumnResult: version: int class FunctionErrorRecord: + first_seen_at_millis: Optional[int] + last_seen_at_millis: Optional[int] + quarantined: bool + input: Optional[str] attempts: Optional[int] job_id: str fragment_id: int @@ -1151,6 +1184,8 @@ class FunctionErrorFragment: rows_recorded: int class FunctionErrors: + workflow_version: Optional[int] + error_groups_json: str records: list[FunctionErrorRecord] fragments: list[FunctionErrorFragment] truncated: bool diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 9178d5194..5ea45a6a6 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1132,6 +1132,220 @@ class FunctionBinding(_RemoteValue): return reader.read_all().to_pylist()[0] +class FunctionErrorGroup(_RemoteValue): + """A grouped cause among returned Function failures.""" + + column: str + error_type: str + error_message: str + rows_failed: _UInt64 + + +class FunctionValueProvenance(_RemoteValue): + """The Function version and job that produced one stored value.""" + + column: str + job_id: str + function_name: str + function_version: str + row_id: Optional[_UInt64] = None + row_address: Optional[_UInt64] = None + source_version: _UInt64 + published_version: _UInt64 + + +class FunctionProvenance(_RemoteValue): + """A bounded per-row producing-version listing for a table snapshot.""" + + records: tuple[FunctionValueProvenance, ...] + truncated: bool = False + + +class _FunctionErrors: + """Current Function failures, with grouped causes and source-row lookup. + + Check ``truncated`` and ``fragments`` before treating a listing as complete. + ``history=True`` on ``table.function_errors`` returns retained past records. + """ + + def __init__(self, raw: Any, table: Any, *, history: bool = False): + self._raw = raw + self._table = table + self._history = history + self.records = raw.records + self.fragments = raw.fragments + self.truncated = raw.truncated + + def __repr__(self) -> str: + return repr(self._raw) + + def as_sync(self, table: Any) -> FunctionErrors: + return FunctionErrors(self._raw, table, history=self._history) + + def summary(self) -> list[FunctionErrorGroup]: + """Group returned failures by column, exception class, and message. + + Raises when records are incomplete, so sampled counts cannot be mistaken + for totals. Narrow the request by column or job, or raise its limit. + """ + if (getattr(self._raw, "workflow_version", None) or 0) < 1: + raise NotImplementedError( + "The server does not support the current Function failure workflow" + ) + if ( + self.truncated + or self.fragments + or any( + record.row_offset is None and record.input is None + for record in self.records + ) + ): + raise ValueError( + "Function errors are incomplete; narrow the request or raise limit" + ) + groups: dict[tuple[str, str, str], int] = {} + for record in self.records: + if record.row_offset is None and record.input is None: + continue + message = record.error_message + if record.input is not None: + message = message.split("\nSource input: ", 1)[0].split( + "\nFunction input ", 1 + )[0] + key = (record.column, record.error_type, message) + groups[key] = groups.get(key, 0) + 1 + return [ + FunctionErrorGroup( + column=column, error_type=kind, error_message=message, rows_failed=count + ) + for (column, kind, message), count in sorted(groups.items()) + ] + + def _identities(self) -> dict[tuple[str, int], list[Any]]: + if (getattr(self._raw, "workflow_version", None) or 0) < 1: + raise NotImplementedError( + "The server does not support the current Function failure workflow" + ) + if self._history: + raise ValueError( + "Source-row lookup requires current failures; " + "read retained history through records" + ) + if self.truncated or self.fragments: + raise ValueError( + "Function errors are incomplete; narrow the request or raise limit" + ) + result = {} + for record in self.records: + if record.input is not None or record.row_offset is None: + raise ValueError( + "This error names a Function invocation; " + "inspect its input source identities" + ) + identity = ( + record.row_id if record.row_id is not None else record.row_address + ) + if identity is None: + raise ValueError("This error has no source row identity") + key = ("_rowid" if record.row_id is not None else "_rowaddr", identity) + result.setdefault(key, []).append(record) + return result + + def _predicate(self, identities: dict[tuple[str, int], list[Any]]) -> str: + clauses = [] + for field in ("_rowid", "_rowaddr"): + selected = [identity for (kind, identity) in identities if kind == field] + if selected: + clauses.append(field + " IN (" + ",".join(map(str, selected)) + ")") + return " OR ".join(clauses) if clauses else "false" + + def _join_rows( + self, rows: pa.Table, identities: dict[tuple[str, int], list[Any]] + ) -> pa.Table: + matches = [] + indices = [] + found = set() + for index, (row_id, address) in enumerate( + zip(rows.column("_rowid").to_pylist(), rows.column("_rowaddr").to_pylist()) + ): + for key in (("_rowid", row_id), ("_rowaddr", address)): + for record in identities.get(key, []): + found.add(key) + indices.append(index) + matches.append(record) + if found != identities.keys(): + raise ValueError( + "Some failed inputs are no longer addressable in this snapshot; " + "refresh the error listing or use a historical snapshot" + ) + rows = rows.take(pa.array(indices, type=pa.int64())) + fields = [ + "column", + "error_type", + "error_message", + "attempts", + "function_version", + "job_id", + "first_seen_at_millis", + "last_seen_at_millis", + "quarantined", + ] + arrays = [ + pa.array([getattr(record, field) for record in matches]) for field in fields + ] + if "__function_error" in rows.column_names: + raise ValueError("Source columns already contain __function_error") + return rows.append_column( + "__function_error", pa.StructArray.from_arrays(arrays, names=fields) + ) + + +class FunctionErrors(_FunctionErrors): + """Current failures with grouped causes and synchronous source-row lookup.""" + + def rows(self, columns: Optional[list[str]] = None) -> pa.Table: + """Return current failing inputs with a ``__function_error`` struct. + + Row IDs come from the error records. The server joins stable identities + correctly after compaction; callers need no physical-address arithmetic. + """ + identities = self._identities() + predicate = self._predicate(identities) + query = ( + self._table.search() + .where(predicate) + .with_row_id(True) + .with_row_address() + .limit(max(1, len(identities))) + ) + selected = list(self._table.schema.names if columns is None else columns) + selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected) + query = query.select(selected) + return self._join_rows(query.to_arrow(), identities) + + +class AsyncFunctionErrors(_FunctionErrors): + """Current Function failures returned by an asynchronous table.""" + + async def rows(self, columns: Optional[list[str]] = None) -> pa.Table: + """Return current failing inputs with their ``__function_error`` metadata.""" + identities = self._identities() + predicate = self._predicate(identities) + query = ( + self._table.query() + .where(predicate) + .with_row_id() + .with_row_address() + .limit(max(1, len(identities))) + ) + selected = list( + (await self._table.schema()).names if columns is None else columns + ) + selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected) + query = query.select(selected) + return self._join_rows(await query.to_arrow(), identities) + + class RefreshColumnResult(_RemoteValue): """Terminal result of an expression-backed or Function-backed refresh Job. @@ -1169,6 +1383,8 @@ class RefreshColumnResult(_RemoteValue): """Exact table version the refresh read.""" published_version: Optional[_UInt64] = None + error_groups: tuple[FunctionErrorGroup, ...] = () + error_groups_truncated: bool = False """Table version made visible by the refresh, when one was published.""" @property @@ -3487,6 +3703,11 @@ __all__ = [ "ResolvedEnvironmentProvenance", "ResolvedPackage", "RefreshColumnResult", + "FunctionErrors", + "AsyncFunctionErrors", + "FunctionErrorGroup", + "FunctionProvenance", + "FunctionValueProvenance", "FunctionDefinition", ] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 2d068536e..19e7ff454 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -50,6 +50,7 @@ from lancedb.index import ( ) from lancedb.job import Job from lancedb.functions import ( + FunctionProvenance, FunctionApplication, FunctionRetryPolicy, RefreshColumnResult, @@ -1185,6 +1186,12 @@ class RemoteTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ): return LOOP.run( self._table.refresh_column( @@ -1206,6 +1213,12 @@ class RemoteTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) @@ -1230,6 +1243,12 @@ class RemoteTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnResult]: return Job( LOOP.run( @@ -1252,6 +1271,12 @@ class RemoteTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) ) @@ -1261,9 +1286,42 @@ class RemoteTable(Table): job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ): return LOOP.run( - self._table.function_errors(job_id=job_id, column=column, limit=limit) + self._table.function_errors( + job_id=job_id, column=column, limit=limit, history=history + ) + ).as_sync(self) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + return LOOP.run( + self._table.quarantine_failed( + column, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + quarantined=quarantined, + ) + ) + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + return LOOP.run( + self._table.function_provenance(column, limit=limit, version=version) ) def column_statuses( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 7f378a34c..8d996d32e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -84,6 +84,9 @@ from .index import ( ) from .expr import Expr from .functions import ( + FunctionErrors, + AsyncFunctionErrors, + FunctionProvenance, FunctionRetryPolicy, FunctionApplication, RefreshColumnResult as RefreshColumnJobResult, @@ -300,7 +303,6 @@ if TYPE_CHECKING: CompactionStats, Tag, AddColumnsResult, - FunctionErrors, RefreshColumnResult, AddResult, AlterColumnsResult, @@ -3290,6 +3292,12 @@ class Table(ABC): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> "RefreshColumnResult": """ Fill the rows of a computed column that hold no value yet. @@ -3365,6 +3373,9 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -3382,6 +3393,23 @@ class Table(ABC): max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -3412,6 +3440,12 @@ class Table(ABC): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -3486,6 +3520,9 @@ class Table(ABC): error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -3503,6 +3540,23 @@ class Table(ABC): max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -3525,22 +3579,104 @@ class Table(ABC): 'finished' """ + def retry_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + **options: Any, + ) -> Job[RefreshColumnJobResult]: + """Start a job for exactly the current failed rows. + + Stable row identities survive compaction. Set ``function_version`` to + upgrade and retry failures atomically. ``include_quarantined=True`` + explicitly releases quarantined rows before retrying them. + + >>> job = table.retry_failed("sharpness") # doctest: +SKIP + >>> result = job.wait() # doctest: +SKIP + """ + return self.refresh_column_async( + column, + retry_errors=True, + retry_error_type=error_type, + retry_job_id=job_id, + include_quarantined=include_quarantined, + function_version=function_version, + recompute="failed" if function_version is not None else None, + **options, + ) + + def upgrade_column( + self, + column: str, + *, + version: str, + recompute: Literal["failed", "all", "none"] = "all", + **options: Any, + ) -> Job[RefreshColumnJobResult]: + """Upgrade a Function binding while keeping its columns available. + + ``failed`` recomputes current failures, ``all`` recomputes all live rows, + and ``none`` preserves existing values. New and changed rows use the new + version; ``function_provenance`` identifies each value's producing version. + """ + return self.refresh_column_async( + column, function_version=version, recompute=recompute, **options + ) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + """Quarantine current failures, or release them with ``quarantined=False``. + + Normal and automatic refreshes skip quarantined rows. ``after_attempts`` + restricts the selection to rows with at least that many failed calls. + Returns the number of selected rows. LanceDB Enterprise only. + """ + raise NotImplementedError("Function quarantine requires LanceDB Enterprise") + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + """Read each returned row's producing Function version and job. + + ``version`` selects a table snapshot. Check ``truncated`` before treating + the returned records as a complete snapshot. LanceDB Enterprise only. + """ + raise NotImplementedError("Function provenance requires LanceDB Enterprise") + @abstractmethod def function_errors( self, job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> "FunctionErrors": """ 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 Enterprise only; reading errors - needs read access to the table, since a message carries the value - that failed. + A refresh running under a skip policy records each row it skipped. + On servers advertising workflow version 1 or later, the default lists + current unresolved failures, deduplicated by row and Function column, + with attempt counts and first/last failure times. ``history=True`` + returns retained observations, including repaired failures. Older servers + keep their legacy listing behavior and reject explicit history requests. + LanceDB Enterprise only; reading errors needs table read access because + messages can include the input that failed. Parameters ---------- @@ -3550,6 +3686,10 @@ class Table(ABC): Only errors on this column. limit: int, optional At most this many records (server default 10000, cap 100000). + history: bool, default False + Include retained historical errors instead of current failures. + Requires Enterprise workflow version 1 or later. Historical records + cannot be used with the current-input ``rows()`` helper. Returns ------- @@ -5706,6 +5846,12 @@ class LanceTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> "RefreshColumnResult": """Fill a computed column's unfilled rows and recompute those whose inputs changed. See @@ -5730,6 +5876,12 @@ class LanceTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) @@ -5754,6 +5906,12 @@ class LanceTable(Table): init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> Job[RefreshColumnJobResult]: """Fill a computed column's unfilled rows and recompute those whose inputs changed, returning a handle to the refresh job. See @@ -5780,6 +5938,12 @@ class LanceTable(Table): init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ) ) ) @@ -5789,11 +5953,44 @@ class LanceTable(Table): job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, + history: bool = False, ) -> "FunctionErrors": """The per-row errors Function refreshes recorded on this table. See [`Table.function_errors`][lancedb.table.Table.function_errors].""" return LOOP.run( - self._table.function_errors(job_id=job_id, column=column, limit=limit) + self._table.function_errors( + job_id=job_id, column=column, limit=limit, history=history + ) + ).as_sync(self) + + def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + return LOOP.run( + self._table.quarantine_failed( + column, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + quarantined=quarantined, + ) + ) + + def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + return LOOP.run( + self._table.function_provenance(column, limit=limit, version=version) ) def column_statuses( @@ -8221,6 +8418,12 @@ class AsyncTable: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> RefreshColumnResult: """ Fill the rows of a computed column that hold no value yet. @@ -8296,6 +8499,9 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -8313,6 +8519,23 @@ class AsyncTable: max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -8340,6 +8563,77 @@ class AsyncTable: init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, + ) + + async def retry_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + **options: Any, + ) -> AsyncJob[RefreshColumnJobResult]: + """Start an exact failed-row retry; see ``Table.retry_failed``.""" + return await self.refresh_column_async( + column, + retry_errors=True, + retry_error_type=error_type, + retry_job_id=job_id, + include_quarantined=include_quarantined, + function_version=function_version, + recompute="failed" if function_version is not None else None, + **options, + ) + + async def upgrade_column( + self, + column: str, + *, + version: str, + recompute: Literal["failed", "all", "none"] = "all", + **options: Any, + ) -> AsyncJob[RefreshColumnJobResult]: + """Upgrade the Function and choose which rows to recompute.""" + return await self.refresh_column_async( + column, function_version=version, recompute=recompute, **options + ) + + async def quarantine_failed( + self, + column: str, + *, + error_type: Optional[str] = None, + job_id: Optional[str] = None, + after_attempts: Optional[int] = None, + quarantined: bool = True, + ) -> int: + """Quarantine current failures or release them for later refreshes.""" + return await self._inner.quarantine_function_errors( + column, + quarantined=quarantined, + error_type=error_type, + job_id=job_id, + after_attempts=after_attempts, + ) + + async def function_provenance( + self, + column: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + ) -> FunctionProvenance: + """Read per-row producing versions at a table snapshot.""" + return FunctionProvenance.from_json( + await self._inner.function_provenance(column, limit=limit, version=version) ) async def function_errors( @@ -8347,16 +8641,19 @@ class AsyncTable: job_id: Optional[str] = None, column: Optional[str] = None, limit: Optional[int] = None, - ) -> "FunctionErrors": + history: bool = False, + ) -> "AsyncFunctionErrors": """ 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 Enterprise only; reading errors - needs read access to the table, since a message carries the value - that failed. + A refresh running under a skip policy records each row it skipped. + On servers advertising workflow version 1 or later, the default lists + current unresolved failures, deduplicated by row and Function column, + with attempt counts and first/last failure times. ``history=True`` + returns retained observations, including repaired failures. Older servers + keep their legacy listing behavior and reject explicit history requests. + LanceDB Enterprise only; reading errors needs table read access because + messages can include the input that failed. Parameters ---------- @@ -8366,10 +8663,14 @@ class AsyncTable: Only errors on this column. limit: int, optional At most this many records (server default 10000, cap 100000). + history: bool, default False + Include retained historical errors instead of current failures. + Requires Enterprise workflow version 1 or later. Historical records + cannot be used with the current-input ``rows()`` helper. Returns ------- - FunctionErrors + AsyncFunctionErrors ``records``, ``fragments`` and ``truncated``, the last saying whether the listing stopped at its limit. @@ -8427,9 +8728,10 @@ class AsyncTable: >>> if errors.truncated: # doctest: +SKIP ... print("listing stopped at the limit") """ - return await self._inner.function_errors( - job_id=job_id, column=column, limit=limit + raw = await self._inner.function_errors( + job_id=job_id, column=column, limit=limit, history=history ) + return AsyncFunctionErrors(raw, self, history=history) async def column_statuses( self, column: Optional[str] = None @@ -8478,6 +8780,12 @@ class AsyncTable: init_timeout_seconds: Optional[float] = None, num_workers: Optional[int] = None, max_executor_processes_per_worker: Optional[int] = None, + retry_errors: bool = False, + retry_job_id: Optional[str] = None, + retry_error_type: Optional[str] = None, + include_quarantined: bool = False, + function_version: Optional[str] = None, + recompute: Optional[Literal["failed", "all", "none"]] = None, ) -> AsyncJob[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job @@ -8552,6 +8860,9 @@ class AsyncTable: error_policy: {"fail", "skip"}, optional Action after failure or retry exhaustion. Skip records the error and attempt count, subject to the server's failure limits. + Workflow version 1 servers default to skip with a 5% failure ceiling + and publish successful output before reporting a threshold failure. + Older deployments retain their existing defaults. max_failed_fraction: float, optional Under a skip policy, fail the job once more than this share of rows (0 to 1) has failed. LanceDB Enterprise only. @@ -8569,6 +8880,23 @@ class AsyncTable: max_executor_processes_per_worker: int, optional Cap on executor processes per Function worker. LanceDB Enterprise only. + retry_errors: bool, default False + Select current failed rows on the server. Cannot be combined with + ``where``. Requires Enterprise workflow version 1 or later. + retry_job_id: str, optional + Restrict a failed-row retry to errors recorded by this job. + retry_error_type: str, optional + Restrict a failed-row retry to this exception class. + include_quarantined: bool, default False + Explicitly release and include quarantined rows in a failed-row retry. + function_version: str, optional + Atomically rebind this column's Function to the specified immutable + version. Requires Enterprise workflow version 1 or later. + recompute: {"failed", "all", "none"}, optional + Which rows to recompute during an upgrade. Requires + ``function_version``; the default is ``all``. ``failed`` selects + current failures, and ``none`` preserves existing values. Quarantined + rows stay excluded unless explicitly included in a failed-row retry. Returns ------- @@ -8613,6 +8941,12 @@ class AsyncTable: init_timeout_seconds=init_timeout_seconds, num_workers=num_workers, max_executor_processes_per_worker=max_executor_processes_per_worker, + retry_errors=retry_errors, + retry_job_id=retry_job_id, + retry_error_type=retry_error_type, + include_quarantined=include_quarantined, + function_version=function_version, + recompute=recompute, ), RefreshColumnJobResult.from_json, ) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 587e2d587..2cacc4716 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -21,6 +21,7 @@ import threading import time from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch +from types import SimpleNamespace import uuid import warnings from packaging.version import Version @@ -2382,7 +2383,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result( result = job.wait(timeout=timedelta(seconds=30)) assert isinstance(result, lancedb.RefreshColumnResult) - assert result.model_dump() == terminal_result + assert result.model_dump(exclude_defaults=True) == terminal_result assert result.rows_filled == 12 assert result.version == 8 @@ -7845,3 +7846,211 @@ def test_remote_fts_and_rejects_legacy_server(): with query_test_table(handler, vector_columns={}) as table: with pytest.raises(NotImplementedError, match="server version 0.3.0"): table.search("gripper closed", query_type="fts", operator="AND").to_list() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_table", [False, True]) +async def test_function_failure_workflow_uses_exact_retry_and_upgrade_apis(async_table): + received = [] + result = { + "rows_assigned": 1000, + "rows_failed": 100, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + "error_groups": [ + { + "column": "derived", + "error_type": "RowTimeoutError", + "error_message": "timeout", + "rows_failed": 100, + } + ], + "error_groups_truncated": False, + } + + def handler(request): + length = int(request.headers.get("Content-Length", 0)) + body = json.loads(request.rfile.read(length)) if length else {} + received.append((request.path, body)) + status = 200 + if request.path == "/v1/table/test/describe/": + response = {"version": 8, "schema": {"fields": []}} + elif request.path == "/v1/table/test/backfill_column": + status = 202 + response = {"job_id": "refresh-1"} + elif request.path == "/v1/jobs/describe": + response = { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": result, + } + elif request.path == "/v1/table/test/errors/quarantine": + response = {"rows_affected": 100} + elif request.path == "/v1/table/test/function_provenance": + response = { + "records": [ + { + "column": "derived", + "job_id": "refresh-1", + "function_name": "check", + "function_version": "2", + "row_id": 42, + "source_version": 7, + "published_version": 8, + } + ], + "truncated": False, + } + elif request.path == "/v1/table/test/errors": + response = { + "records": [], + "fragments": [], + "truncated": False, + "workflow_version": 1, + } + else: + status = 404 + response = {} + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + retry_options = dict( + error_type="ValueError", + job_id="first", + include_quarantined=True, + function_version="2", + max_failed_fraction=1.0, + ) + if async_table: + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + job = await table.retry_failed("derived", **retry_options) + terminal = await job.wait() + await table.upgrade_column("derived", version="3", recompute="none") + affected = await table.quarantine_failed("derived", after_attempts=3) + provenance = await table.function_provenance("derived") + errors = await table.function_errors(column="derived", history=True) + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + terminal = table.retry_failed("derived", **retry_options).wait() + table.upgrade_column("derived", version="3", recompute="none") + affected = table.quarantine_failed("derived", after_attempts=3) + provenance = table.function_provenance("derived") + errors = table.function_errors(column="derived", history=True) + + refreshes = [body for path, body in received if path.endswith("backfill_column")] + assert refreshes == [ + { + "column": "derived", + "retry_errors": True, + "retry_job_id": "first", + "retry_error_type": "ValueError", + "include_quarantined": True, + "function_version": "2", + "recompute": "failed", + "max_failed_fraction": 1.0, + }, + {"column": "derived", "function_version": "3", "recompute": "none"}, + ] + assert terminal.rows_assigned == 1000 + assert terminal.error_groups[0].rows_failed == 100 + assert affected == 100 + assert provenance.records[0].function_version == "2" + assert provenance.records[0].row_id == 42 + assert errors.summary() == [] + assert ("/v1/table/test/errors", {"column": "derived", "history": True}) in received + + +def test_function_error_rows_returns_all_inputs_and_preserves_multiple_column_errors( + tmp_path, +): + db = lancedb.connect(tmp_path) + table = db.create_table("inputs", [{"id": index} for index in range(16)]) + inputs = table.search().select(["id", "_rowid", "_rowaddr"]).limit(16).to_arrow() + records = [ + SimpleNamespace( + column="first", + row_id=row_id, + row_address=999999, + row_offset=0, + input=None, + error_type="ValueError", + error_message="corrupt", + attempts=3, + function_version="1", + job_id="first", + first_seen_at_millis=100, + last_seen_at_millis=200, + quarantined=False, + ) + for row_id in inputs.column("_rowid").to_pylist() + ] + duplicate = copy.copy(records[0]) + duplicate.column = "second" + records.append(duplicate) + errors = lancedb.FunctionErrors( + SimpleNamespace( + records=records, fragments=[], truncated=False, workflow_version=1 + ), + table, + ) + rows = errors.rows(columns=["id"]) + assert rows.num_rows == 17 + assert sorted(set(rows.column("id").to_pylist())) == list(range(16)) + assert rows.column("__function_error").type.field("column").name == "column" + assert [group.rows_failed for group in errors.summary()] == [16, 1] + legacy = copy.copy(records[0]) + legacy.row_id = None + legacy.row_address = inputs.column("_rowaddr")[0].as_py() + legacy_errors = lancedb.FunctionErrors( + SimpleNamespace( + records=[legacy], fragments=[], truncated=False, workflow_version=1 + ), + table, + ) + assert legacy_errors.rows(columns=["id"]).column("id").to_pylist() == [0] + + incomplete = lancedb.FunctionErrors( + SimpleNamespace( + records=records, fragments=[], truncated=True, workflow_version=1 + ), + table, + ) + with pytest.raises(ValueError, match="incomplete"): + incomplete.rows() + + +def test_exact_function_retries_fail_before_writing_to_older_servers(): + writes = [] + + def handler(request): + length = int(request.headers.get("Content-Length", 0)) + body = request.rfile.read(length) if length else b"" + if request.path == "/v1/table/test/describe/": + response = {"version": 1, "schema": {"fields": []}} + elif request.path == "/v1/table/test/errors": + response = {"records": [], "fragments": [], "truncated": False} + else: + writes.append((request.path, body)) + response = {} + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + with pytest.raises(NotImplementedError, match="server does not support"): + table.retry_failed("derived") + with pytest.raises(NotImplementedError, match="server does not support"): + table.upgrade_column("derived", version="2", recompute="failed") + with pytest.raises(NotImplementedError, match="server does not support"): + table.function_errors(history=True) + with pytest.raises(NotImplementedError, match="server does not support"): + table.function_errors().summary() + assert writes == [] diff --git a/python/src/table.rs b/python/src/table.rs index 25a99e5db..3bc23ec95 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -48,6 +48,12 @@ mod scannable; /// Keyword arguments shared by `refresh_column` and `refresh_column_async`. struct RefreshColumnArgs { + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, where_clause: Option, batch_size: Option, max_concurrency: Option, @@ -259,6 +265,12 @@ fn parse_planning_workers( fn refresh_column_options(args: RefreshColumnArgs) -> PyResult { let RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause, batch_size, max_concurrency, @@ -278,6 +290,17 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult for RefreshColumnResult { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrorRecord { + pub first_seen_at_millis: Option, + pub last_seen_at_millis: Option, + pub quarantined: bool, + pub input: Option, pub attempts: Option, pub job_id: String, pub fragment_id: u64, @@ -915,6 +942,10 @@ impl FunctionErrorRecord { impl From for FunctionErrorRecord { fn from(record: lancedb::function::FunctionErrorRecord) -> Self { Self { + first_seen_at_millis: record.first_seen_at_millis, + last_seen_at_millis: record.last_seen_at_millis, + quarantined: record.quarantined, + input: record.input.map(|value| value.to_string()), attempts: record.attempts, job_id: record.job_id, fragment_id: record.fragment_id, @@ -968,6 +999,8 @@ impl From for FunctionErrorFragment { #[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FunctionErrors { + pub workflow_version: Option, + pub error_groups_json: String, pub records: Vec, pub fragments: Vec, pub truncated: bool, @@ -988,6 +1021,9 @@ impl FunctionErrors { impl From for FunctionErrors { fn from(errors: lancedb::function::FunctionErrors) -> Self { Self { + workflow_version: errors.workflow_version, + error_groups_json: serde_json::to_string(&errors.error_groups) + .expect("serializable Function error groups"), records: errors.records.into_iter().map(Into::into).collect(), fragments: errors.fragments.into_iter().map(Into::into).collect(), truncated: errors.truncated, @@ -2599,7 +2635,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column<'py>( self_: PyRef<'py, Self>, @@ -2621,8 +2657,20 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause: r#where, batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, @@ -2651,7 +2699,7 @@ impl Table { }) } - #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))] + #[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None, retry_errors=false, retry_job_id=None, retry_error_type=None, include_quarantined=false, function_version=None, recompute=None))] #[allow(clippy::too_many_arguments)] pub fn refresh_column_async<'py>( self_: PyRef<'py, Self>, @@ -2673,8 +2721,20 @@ impl Table { init_timeout_seconds: Option, num_workers: Option, max_executor_processes_per_worker: Option, + retry_errors: bool, + retry_job_id: Option, + retry_error_type: Option, + include_quarantined: bool, + function_version: Option, + recompute: Option, ) -> PyResult> { let options = refresh_column_options(RefreshColumnArgs { + retry_errors, + retry_job_id, + retry_error_type, + include_quarantined, + function_version, + recompute, where_clause: r#where, batch_size, max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?, @@ -2703,18 +2763,20 @@ impl Table { }) } - #[pyo3(signature = (job_id=None, column=None, limit=None))] + #[pyo3(signature = (job_id=None, column=None, limit=None, history=false))] pub fn function_errors( self_: PyRef<'_, Self>, job_id: Option, column: Option, limit: Option, + history: bool, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let request = lancedb::function::FunctionErrorsRequest { job_id, column, limit, + history, }; future_into_py(self_.py(), async move { let errors = inner.function_errors(request).await.infer_error()?; @@ -2722,6 +2784,53 @@ impl Table { }) } + #[pyo3(signature = (column, *, quarantined=true, job_id=None, error_type=None, after_attempts=None))] + pub fn quarantine_function_errors( + self_: PyRef<'_, Self>, + column: String, + quarantined: bool, + job_id: Option, + error_type: Option, + after_attempts: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + inner + .quarantine_function_errors( + &column, + lancedb::function::FunctionQuarantineOptions { + quarantined, + job_id, + error_type, + after_attempts, + }, + ) + .await + .infer_error() + }) + } + + #[pyo3(signature = (column, *, limit=None, version=None))] + pub fn function_provenance( + self_: PyRef<'_, Self>, + column: String, + limit: Option, + version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let result = inner + .function_provenance( + &column, + lancedb::function::FunctionProvenanceOptions { limit, version }, + ) + .await + .infer_error()?; + serde_json::to_string(&result) + .map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) + } + #[pyo3(signature = (column=None))] pub fn column_statuses( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 4e7157c37..e4fff29c5 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1308,6 +1308,12 @@ pub struct FunctionRefreshPlan { /// Enterprise decodes the same value from the durable job's terminal payload. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshColumnResult { + /// Grouped row failures, when the server reports them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub error_groups: Vec, + /// Whether the grouped counts omit any failures. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub error_groups_truncated: bool, /// Rows assigned a value by this refresh. pub rows_assigned: u64, /// Rows whose computation failed. @@ -1330,6 +1336,8 @@ pub struct RefreshColumnResult { /// covers every refresh of every column. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct FunctionErrorsRequest { + /// Include retained historical errors, including repaired rows. + pub history: bool, /// Only errors recorded by this job. pub job_id: Option, /// Only errors on this column. @@ -1340,6 +1348,11 @@ pub struct FunctionErrorsRequest { } impl FunctionErrorsRequest { + /// Include retained historical records instead of current failures. + pub fn history(mut self, history: bool) -> Self { + self.history = history; + self + } /// A request with no filter. pub fn new() -> Self { Self::default() @@ -1369,6 +1382,18 @@ impl FunctionErrorsRequest { /// read access to the table. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrorRecord { + /// Earliest retained failure time for this current failure. + #[serde(default)] + pub first_seen_at_millis: Option, + /// Most recent failure time. + #[serde(default)] + pub last_seen_at_millis: Option, + /// Whether normal refreshes skip this row until explicitly retried. + #[serde(default)] + pub quarantined: bool, + /// Source identities for a materialized-view Function invocation. + #[serde(default)] + pub input: Option, /// Number of user-code calls for this failed invocation, when recorded. #[serde(default, skip_serializing_if = "Option::is_none")] pub attempts: Option, @@ -1429,6 +1454,12 @@ pub struct FunctionErrorFragment { /// A table's per-row Function errors; see [`crate::Table::function_errors`]. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionErrors { + /// Version of the server's current-failure, retry, upgrade, and quarantine contract. + #[serde(default)] + pub workflow_version: Option, + /// Grouped causes for the returned records. Counts are bounded by the listing. + #[serde(default)] + pub error_groups: Vec, /// The recorded rows, newest job first. pub records: Vec, /// Fragments whose detail was capped. @@ -1439,6 +1470,79 @@ pub struct FunctionErrors { pub truncated: bool, } +/// Which existing rows to recompute when upgrading a Function column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FunctionRecompute { + /// Recompute exactly the current failures. + Failed, + /// Recompute all live rows. + All, + /// Preserve existing values; new and changed rows use the new Function. + None, +} + +/// One cause in a Function failure listing or refresh result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionErrorGroup { + pub column: String, + pub error_type: String, + pub error_message: String, + pub rows_failed: u64, +} + +/// Selection and state for explicitly quarantining or releasing failed rows. +#[derive(Debug, Clone, Serialize)] +pub struct FunctionQuarantineOptions { + pub quarantined: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub job_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub after_attempts: Option, +} + +impl Default for FunctionQuarantineOptions { + fn default() -> Self { + Self { + quarantined: true, + job_id: None, + error_type: None, + after_attempts: None, + } + } +} + +/// Which snapshot and how much producing-version metadata to read. +#[derive(Debug, Clone, Default, Serialize)] +pub struct FunctionProvenanceOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// The Function and job that produced one stored value. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionValueProvenance { + pub job_id: String, + pub column: String, + pub function_name: String, + pub function_version: String, + pub row_id: Option, + pub row_address: Option, + pub source_version: u64, + pub published_version: u64, +} + +/// A bounded set of per-row producing-version records. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionProvenance { + pub records: Vec, + pub truncated: bool, +} + impl RefreshColumnResult { /// Deprecated compatibility alias for `rows_assigned`. pub fn rows_filled(&self) -> u64 { @@ -1465,6 +1569,8 @@ mod refresh_result_tests { source_version: 7, published_version: Some(8), plan, + error_groups: Vec::new(), + error_groups_truncated: false, } } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f89be7e69..ad53f8722 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -969,6 +969,33 @@ impl RemoteTable { } } + async fn require_function_failure_workflow(&self) -> Result<()> { + let mut body = serde_json::json!({"limit": 1}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id, + status_code: None, + })?; + if value + .get("workflow_version") + .and_then(serde_json::Value::as_u64) + .is_some_and(|version| version >= 1) + { + Ok(()) + } else { + Err(Error::NotSupported { message: "The server does not support the Function row-failure workflow; upgrade the server before retrying, upgrading, or quarantining rows".into() }) + } + } + async fn describe(&self) -> Result { self.describe_read_snapshot(self.snapshot_read_state().await) .await @@ -4322,6 +4349,9 @@ impl BaseTable for RemoteTable { ) -> Result> { options.validate()?; self.check_mutable().await?; + if options.retry_errors == Some(true) || options.function_version.is_some() { + self.require_function_failure_workflow().await?; + } let mut body = serde_json::to_value(&options).map_err(|e| Error::Runtime { message: format!("failed to serialize refresh options: {e}"), })?; @@ -4363,7 +4393,13 @@ impl BaseTable for RemoteTable { &self, request: &crate::function::FunctionErrorsRequest, ) -> Result { + if request.history { + self.require_function_failure_workflow().await?; + } let mut body = serde_json::json!({}); + if request.history { + body["history"] = serde_json::json!(true); + } if let Some(job_id) = &request.job_id { body["job_id"] = serde_json::json!(job_id); } @@ -4388,6 +4424,70 @@ impl BaseTable for RemoteTable { }) } + async fn quarantine_function_errors( + &self, + column: &str, + options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + self.check_mutable().await?; + if options.after_attempts == Some(0) { + return Err(Error::InvalidInput { + message: "after_attempts must be at least 1".into(), + }); + } + let mut body = serde_json::json!({"column": column, "quarantined": options.quarantined, + "job_id": options.job_id, "error_type": options.error_type, "after_attempts": options.after_attempts}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/errors/quarantine", self.identifier)) + .json(&body); + let (request_id, response) = self.send(request, false).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let value: serde_json::Value = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id: request_id.clone(), + status_code: None, + })?; + value + .get("rows_affected") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| Error::Http { + source: "Function quarantine response has no rows_affected".into(), + request_id, + status_code: None, + }) + } + + async fn function_provenance( + &self, + column: &str, + options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + self.require_function_failure_workflow().await?; + let mut body = serde_json::json!({"column": column, "limit": options.limit, + "version": match options.version { Some(version) => version, None => self.version().await? }}); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!( + "/v1/table/{}/function_provenance", + self.identifier + )) + .json(&body); + let (request_id, response) = self.send(request, true).await?; + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + serde_json::from_str(&body).map_err(|error| Error::Http { + source: error.into(), + request_id, + status_code: None, + }) + } + async fn function_column_statuses( &self, column: Option<&str>, @@ -12925,6 +13025,10 @@ mod tests { assert_eq!( errors.records, [FunctionErrorRecord { + first_seen_at_millis: None, + last_seen_at_millis: None, + quarantined: false, + input: None, attempts: Some(3), job_id: "j-7".into(), fragment_id: 3, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 00505220b..f247a386f 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -980,6 +980,28 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { .append_to("per-row Function errors are recorded only in LanceDB Enterprise"), }) } + /// Change the quarantine state of current failed rows. + async fn quarantine_function_errors( + &self, + _column: &str, + _options: &crate::function::FunctionQuarantineOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function quarantine requires LanceDB Enterprise".into(), + }) + } + + /// Read per-row producing Function versions from LanceDB Enterprise. + async fn function_provenance( + &self, + _column: &str, + _options: &crate::function::FunctionProvenanceOptions, + ) -> Result { + Err(Error::NotSupported { + message: "Function provenance requires LanceDB Enterprise".into(), + }) + } + /// Exact four-way freshness status for Function-backed output columns. /// /// `column` filters to one user-visible output; `None` returns every @@ -2285,6 +2307,30 @@ impl Table { /// refreshes ignore the batch-size and GPU options, and reject resource /// budgets, publication thresholds, and other Enterprise-only options. /// + /// Native failed-row retry and upgrades require Enterprise workflow version + /// 1 or later. The SDK checks the server capability before submitting them. + /// An upgrade targets an existing immutable version of the same Function. + /// + /// ``` + /// # use lancedb::{Table, table::RefreshColumnOptions}; + /// use lancedb::function::FunctionRecompute; + /// # async fn retry_and_upgrade(table: &Table) -> lancedb::Result<()> { + /// let retry = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default() + /// .retry_errors(true) + /// .retry_error_type("ValueError"), + /// ).await?; + /// retry.wait().await?; + /// let upgrade = table.refresh_column_async_with_options( + /// "embedding", + /// RefreshColumnOptions::default().upgrade("2", FunctionRecompute::Failed), + /// ).await?; + /// upgrade.wait().await?; + /// # Ok(()) + /// # } + /// ``` + /// /// ``` /// # use lancedb::{Table, table::RefreshColumnOptions}; /// # async fn refresh(table: &Table) -> Result<(), Box> { @@ -2388,6 +2434,9 @@ impl Table { /// A record carries a stable `row_id` when the refresh source used stable /// row IDs. Prefer it over the physical `row_address` for retries: /// compaction and rewrite can change the address. + /// With Enterprise workflow version 1, the default lists current failures; + /// [`FunctionErrorsRequest::history`] selects retained historical attempts. + /// Earlier servers retain their existing default behavior. /// /// LanceDB Enterprise only, and the caller needs read access /// to the table, since a message carries the value that failed. @@ -2413,6 +2462,62 @@ impl Table { self.inner.function_errors(&request).await } + /// Quarantine current failures, or release them with `quarantined=false`. + /// Normal and automatic Function refreshes skip quarantined rows. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionQuarantineOptions; + /// # async fn quarantine(table: &Table) -> lancedb::Result<()> { + /// let count = table.quarantine_function_errors( + /// "embedding", + /// FunctionQuarantineOptions { + /// after_attempts: Some(3), + /// ..Default::default() + /// }, + /// ).await?; + /// println!("quarantined {count} rows"); + /// # Ok(()) + /// # } + /// ``` + pub async fn quarantine_function_errors( + &self, + column: &str, + options: crate::function::FunctionQuarantineOptions, + ) -> Result { + self.inner + .quarantine_function_errors(column, &options) + .await + } + + /// Read the producing Function version and job for each returned row. + /// Inspect `truncated` before treating this as a complete snapshot. + /// Requires Enterprise workflow version 1 or later. + /// + /// ``` + /// # use lancedb::Table; + /// use lancedb::function::FunctionProvenanceOptions; + /// # async fn provenance(table: &Table) -> lancedb::Result<()> { + /// let values = table.function_provenance( + /// "embedding", FunctionProvenanceOptions::default(), + /// ).await?; + /// if !values.truncated { + /// for value in values.records { + /// println!("{:?}: {}", value.row_id, value.function_version); + /// } + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn function_provenance( + &self, + column: &str, + options: crate::function::FunctionProvenanceOptions, + ) -> Result { + self.inner.function_provenance(column, &options).await + } + /// Change a column's name, data type, or nullability. /// /// Each alteration must specify at least one of `rename`, `data_type`, or diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index f6bab98f5..78530497f 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -212,6 +212,24 @@ impl FunctionRefreshPlanningConfig { #[derive(Debug, Clone, Default, Serialize)] #[non_exhaustive] pub struct RefreshColumnOptions { + /// Select exactly the current failed rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_errors: Option, + /// Restrict retry selection to this job. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_job_id: Option, + /// Restrict retry selection to this exception class. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub retry_error_type: Option, + /// Explicitly release and retry quarantined rows. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_quarantined: Option, + /// Upgrade the bound Function to this exact version. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub function_version: Option, + /// Rows recomputed by a Function upgrade. Enterprise only. + #[serde(skip_serializing_if = "Option::is_none")] + pub recompute: Option, /// Only refresh the rows matching this SQL filter. Enterprise only. #[serde(rename = "where", skip_serializing_if = "Option::is_none")] pub where_clause: Option, @@ -290,6 +308,40 @@ pub struct RefreshColumnOptions { } impl RefreshColumnOptions { + /// Retry only current failures, using the server's row identities. + pub fn retry_errors(mut self, enabled: bool) -> Self { + self.retry_errors = Some(enabled); + self + } + + /// Restrict a failed-row retry to one recorded job. + pub fn retry_job_id(mut self, job_id: impl Into) -> Self { + self.retry_job_id = Some(job_id.into()); + self + } + + /// Restrict a failed-row retry to one exception class. + pub fn retry_error_type(mut self, error_type: impl Into) -> Self { + self.retry_error_type = Some(error_type.into()); + self + } + + /// Release quarantine when explicitly retrying failures. + pub fn include_quarantined(mut self, include: bool) -> Self { + self.include_quarantined = Some(include); + self + } + + /// Change the Function version and select the upgrade's recomputation policy. + pub fn upgrade( + mut self, + version: impl Into, + recompute: crate::function::FunctionRecompute, + ) -> Self { + self.function_version = Some(version.into()); + self.recompute = Some(recompute); + self + } /// Only refresh the rows matching `filter`. pub fn where_clause(mut self, filter: impl Into) -> Self { self.where_clause = Some(filter.into()); @@ -399,6 +451,12 @@ impl RefreshColumnOptions { /// The first set option a LanceDB Embedded refresh cannot honor, if any. pub fn enterprise_only_option(&self) -> Option<&'static str> { [ + ("retry_errors", self.retry_errors.is_some()), + ("retry_job_id", self.retry_job_id.is_some()), + ("retry_error_type", self.retry_error_type.is_some()), + ("include_quarantined", self.include_quarantined.is_some()), + ("function_version", self.function_version.is_some()), + ("recompute", self.recompute.is_some()), ("where", self.where_clause.is_some()), ("retry_policy", self.retry_policy.is_some()), ("error_policy", self.error_policy.is_some()), @@ -426,6 +484,31 @@ impl RefreshColumnOptions { /// Validate client-side constraints before any request is sent. pub fn validate(&self) -> Result<()> { + let retry = self.retry_errors == Some(true); + if (retry || self.function_version.is_some()) && self.where_clause.is_some() { + return Err(Error::InvalidInput { + message: "retry_errors and Function upgrades cannot be combined with where".into(), + }); + } + if !retry + && (self.retry_job_id.is_some() + || self.retry_error_type.is_some() + || self.include_quarantined == Some(true)) + { + return Err(Error::InvalidInput { + message: "retry filters require retry_errors=true".into(), + }); + } + if self + .function_version + .as_ref() + .is_some_and(|version| version.is_empty()) + || (self.recompute.is_some() && self.function_version.is_none()) + { + return Err(Error::InvalidInput { + message: "recompute requires a nonempty function_version".into(), + }); + } if self .where_clause .as_deref() @@ -780,6 +863,8 @@ pub(crate) async fn execute_refresh_column_async( let execution = execute_refresh_column_with_source(&table, &column).await?; table.bump_freshness(); Ok(crate::function::RefreshColumnResult { + error_groups: Vec::new(), + error_groups_truncated: false, rows_assigned: execution.result.rows_filled, rows_failed: 0, rows_remaining: 0, From 1670859327d5503e8bf7e02c58f93260da4881b4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 17 Nov 2026 20:58:43 +0800 Subject: [PATCH 150/203] fix(deps): ignore unmaintained chrono family advisories (#5073) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo deny` fails on main because RUSTSEC-2026-0543 (`chrono`), RUSTSEC-2026-0555 (`chrono-tz`) and RUSTSEC-2026-0542 (`humantime`) mark the chrono family unmaintained. Add exceptions reviewed on 2026-11-17, with the advisory links and the upstream migration constraint; none of the three is a vulnerability and RustSec lists no patched version for any of them (chrono recommends jiff/time). Dependency paths (from `cargo tree -i` at version fb34b1c7 of main): - `chrono` 0.4.45: arrow 59 / datafusion 55 and the lance stack, across the workspace. - `chrono-tz` 0.10.4: arrow-array → arrow → datafusion/lance. - `humantime` 2.3.0: lance, object_store (through datafusion), and xet-runtime. Clearing the advisories requires the arrow/datafusion/lance ecosystem to migrate off chrono; no upstream fix exists to consume. Also remove the RUSTSEC-2026-0441 `pin-utils` ignore, which the current lockfile no longer needs. Validation on commit 04259a04 (cargo-deny 0.21.0, the version the CI action installs): - Before: `cargo deny check advisories` failed on the three chrono-family advisories, and warned that the pin-utils ignore was not encountered. - After: `cargo deny check advisories bans licenses sources` passes all four checks, matching the Rust CI deny job. - `git diff --check` passes. --- deny.toml | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/deny.toml b/deny.toml index 458559936..b10550a54 100644 --- a/deny.toml +++ b/deny.toml @@ -132,13 +132,31 @@ ignore = [ { 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" }, - # pin-utils: unmaintained; reviewed 2026-11-05. Transitive via - # aws-smithy-http/runtime/types, including aws-config -> lance-io. - # No safe upgrade exists; clearing requires AWS Smithy to migrate to - # core::pin::pin!, pin-project, or pin-project-lite. Revisit on AWS updates. + # pin-utils: unmaintained; reviewed 2026-11-05, removed 2026-11-17 after + # the lockfile dropped the aws-smithy pins that carried it. # https://rustsec.org/advisories/RUSTSEC-2026-0441 - # https://github.com/rustsec/advisory-db/issues/3314 - { id = "RUSTSEC-2026-0441", reason = "pin-utils unmaintained via AWS Smithy; no safe upgrade, awaiting upstream migration" }, + + # chrono: unmaintained; reviewed 2026-11-17. Informational notice, not a + # vulnerability. Transitive via arrow 59 / datafusion 55 and the lance + # stack throughout the workspace. RustSec lists no patched version and + # recommends jiff/time; clearing it requires the arrow/datafusion/lance + # ecosystem to migrate. + # https://rustsec.org/advisories/RUSTSEC-2026-0543 + { id = "RUSTSEC-2026-0543", reason = "chrono unmaintained via arrow/datafusion/lance; no fixed upstream release, awaiting ecosystem migration" }, + + # chrono-tz: unmaintained; reviewed 2026-11-17. Informational notice, not + # a vulnerability. Transitive via arrow-array → arrow → datafusion/lance. + # No patched version exists; clearing it needs the same ecosystem + # migration off chrono as RUSTSEC-2026-0543. + # https://rustsec.org/advisories/RUSTSEC-2026-0555 + { id = "RUSTSEC-2026-0555", reason = "chrono-tz unmaintained via arrow/datafusion/lance; no fixed upstream release" }, + + # humantime: unmaintained; reviewed 2026-11-17. Informational notice, not + # a vulnerability. Transitive via lance, object_store (through datafusion) + # and xet-runtime. No patched version exists; the advisory follows chrono's + # maintenance status. + # https://rustsec.org/advisories/RUSTSEC-2026-0542 + { id = "RUSTSEC-2026-0542", reason = "humantime unmaintained via lance/object_store/xet-runtime; no fixed upstream release" }, ] From 961a4518fd67677779e751de698c2815a6c318c3 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 17 Nov 2026 22:49:40 +0800 Subject: [PATCH 151/203] fix(remote): forward job statistics through refresh handles (#5071) A Function refresh submitted through the LanceDB SDK returns a handle wrapped for read-freshness tracking. lancedb/lancedb#5016 added canonical `Job::stats()` on the server-job handle, but the refresh wrapper did not forward `stats`. The returned handle therefore reported `job statistics is only available for server-side jobs`, while `db.open_job().stats()` returned the server report. Forward `stats` through the refresh wrapper and cover it at the public refresh entry point. The regression submits with `refresh_column_async`, then reads `stats` from that returned handle without reopening the job. With the forwarding removed, the test fails with the same `NotSupported` error; with the change, it passes. Validation on `57b20fb11`: the targeted Rust test passed, `cargo fmt --check` passed, and `cargo clippy -p lancedb --features remote --lib --tests -- -D warnings` passed. Part of ENT-3974. --- rust/lancedb/src/remote/table.rs | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index ad53f8722..2ed46147d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -335,6 +335,10 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::events(&self.inner, request).await } + async fn stats(&self) -> Result> { + crate::job::JobHandle::stats(&self.inner).await + } + async fn wait(&self) -> Result { crate::job::JobHandle::wait_with_progress(self, None).await } @@ -424,6 +428,10 @@ impl crate::job::JobHandle for MaterializedViewRefreshJob { crate::job::JobHandle::events(&self.inner, request).await } + async fn stats(&self) -> Result> { + crate::job::JobHandle::stats(&self.inner).await + } + async fn wait(&self) -> Result { crate::job::JobHandle::wait_with_progress(self, None).await } @@ -11601,6 +11609,19 @@ mod tests { .to_string(), ) .unwrap(), + "/v1/jobs/stats" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "job-1"); + http::Response::builder() + .status(200) + .body( + r#"{"job_id":"job-1","profile":{},"report":"Function job: finished\nRows: 1600\n"}"# + .to_string(), + ) + .unwrap() + } "/v1/table/ns$view/describe/" => http::Response::builder() .status(200) .body(r#"{"version":42,"schema":{"fields":[]}}"#.to_string()) @@ -11623,6 +11644,10 @@ mod tests { })); assert_eq!(job.id(), Some("job-1")); + assert_eq!( + job.stats().await.unwrap().as_deref(), + Some("Function job: finished\nRows: 1600\n") + ); let observations = Arc::new(Mutex::new(Vec::new())); let observed = observations.clone(); let result: RefreshMaterializedViewResult = if with_progress { @@ -13142,6 +13167,20 @@ mod tests { .body(events.clone()) .unwrap() } + "/v1/jobs/stats" => { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["job_id"], "j-42"); + http::Response::builder() + .status(200) + .body( + r#"{"job_id":"j-42","profile":{},"report":"Function job: finished\nRows: 1600\n"}"# + .as_bytes() + .to_vec(), + ) + .unwrap() + } "/v1/jobs/timeline" => http::Response::builder().status(200) .body(br#"{"traceEvents":[],"metadata":{"partial":true}}"#.to_vec()).unwrap(), other => panic!("unexpected path {other}"), @@ -13149,6 +13188,10 @@ mod tests { }); let job = table.refresh_column_async("doubled").await.unwrap(); + assert_eq!( + job.stats().await.unwrap().as_deref(), + Some("Function job: finished\nRows: 1600\n") + ); job.refresh().await.unwrap(); assert_eq!(job.state().as_deref(), Some("running")); assert_eq!(job.job_type().as_deref(), Some("refresh_column")); From e3a0a29bdbe4cdc39f6f4eeb0c45e3e57fdf6b19 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 17 Nov 2026 14:51:33 +0000 Subject: [PATCH 152/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.18=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.19?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 8f10d67f0..6efd2bf48 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.18" +current_version = "0.42.0-beta.19" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 6a23569a8..7b43449a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1a8347ad5..f6e7497d0 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.42.0-beta.18 + 0.42.0-beta.19 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index c15bc0774..5a49a1a60 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.18 + 0.42.0-beta.19 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index dce3deba3..46d5fac54 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.18 + 0.42.0-beta.19 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index e523c1138..d0ccd2efd 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" 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 d603a2c8f..4f6851519 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.42.0-beta.18", + "version": "0.42.0-beta.19", "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 8115e27f9..a4027033a 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.42.0-beta.18", + "version": "0.42.0-beta.19", "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 f3cdd7253..49a50f33f 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.42.0-beta.18", + "version": "0.42.0-beta.19", "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 4d165c4de..8f9f3ec18 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.42.0-beta.18", + "version": "0.42.0-beta.19", "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 d884605b6..bc32a415f 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.42.0-beta.18", + "version": "0.42.0-beta.19", "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 2b6bdc8da..7e7db948b 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.42.0-beta.18", + "version": "0.42.0-beta.19", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 1402f5bee..e1cd2879e 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.42.0-beta.18", + "version": "0.42.0-beta.19", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a0cf05acb..e040cb2b8 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.18", + "version": "0.42.0-beta.19", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 9ba87dcd5..1b9c44290 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 28e8c501b..97d2e732b 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 689200452..8e0348a2b 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.18" +version = "0.42.0-beta.19" edition = "2021" license.workspace = true repository.workspace = true From 16af729792240195e503af986c0d338036f466d5 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Tue, 17 Nov 2026 10:57:56 -0800 Subject: [PATCH 153/203] feat(sdk)!: add typed SQL job handles for compaction and data prewarm (#5056) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remote data prewarm used REST even though SQL supported filters and concurrency, and both maintenance APIs returned after acceptance without exposing a consistent typed completion handle. Compaction's legacy statistics therefore could not describe the work committed by its durable job. This PR adds job-returning compaction and data-prewarm methods across Rust, Python sync/async and TypeScript, and moves data-prewarm submission to SQL. Legacy methods retain return-after-acceptance behavior; data prewarm now requires a compatible SQL PREWARM server and Flight SQL connectivity. This consolidates #5037, #5055 and #4906. This was accomplished with the following changes: - Added `compact_async()` / `compactAsync()` and `prewarm_data_async()` / `prewarmDataAsync()`, retaining the command receipt's durable job ID. - Added `PrewarmDataOptions` for columns, a metadata-pruning filter and concurrency; both operations inherit database, namespace and branch from the table handle. - Added filter/concurrency arguments to legacy Python `prewarm_data()` and a TypeScript `prewarmData(options)` overload, preserving the columns-array form and discarding the handle after acceptance. - Added typed `CompactionResult` and `PrewarmDataResult` decoding, including reopened jobs; missing result payloads fail explicitly and omitted measurements remain unknown. - Reused the shared Job lifecycle for status, refresh, progress callbacks, cancellation and events; Python maintenance progress bars display rewritten rows or completed executors. - Added TypeScript `wait({ timeoutMs, onProgress })` and Rust `wait_with_options(JobWaitOptions)`, complementing Python's existing timeout argument without cancelling the durable job. - Validated single unambiguous receipts, preserved compaction option presence/default inheritance, and returned actionable unsupported-server errors without dropping options or falling back to REST. - Updated native bindings, API references and maintenance documentation with job methods, result semantics, tuning and compatibility requirements. ### Usage and behaviour **New** = added here; **Enhanced** = existing support extended; **Existing** = already on main. This table describes remote SDK behavior; server-side SQL/CLI capabilities are prerequisites, not additions made by this SDK PR. | Surface | Capability | Compact | Data prewarm | Assessment | | --- | --- | --- | --- | --- | | Rust / Python sync+async / TypeScript | Submission transport | Existing SQL OPTIMIZE | **New:** REST → SQL PREWARM | Both now submit through SQL | | All SDKs | Durable job-returning API | **New:** `compact_async` / `compactAsync` | **New:** `prewarm_data_async` / `prewarmDataAsync` | Same lifecycle model | | All SDKs | Options and target scope | **New handle:** four existing compaction overrides, with omitted fields inherited | **New options:** columns/filter/concurrency | Namespace and branch preserved for both | | Python / TypeScript | Legacy convenience calls | Existing optimize acceptance behavior preserved | **Enhanced:** legacy methods accept filter/concurrency and use SQL | Return after acceptance; no completion wait | | All SDKs | Typed successful result | **New:** committed rows, file/fragment changes, partial commit and `more_work` | **New:** pinned version, fragments and executor outcomes | Different measurements are intentional | | All SDKs | Status / refresh / progress | Existing Job APIs reused by **new** maintenance handle | Existing Job APIs reused by **new** maintenance handle | HTTP monitoring remains | | Python / TypeScript | Progress presentation | **Enhanced:** rewrite rows/groups | **Enhanced:** executor progress | Shared callbacks; Python bars use operation counters | | All SDKs | Bounded wait | Python existing; **new** TS/Rust timeout controls | Same shared timeout support | Timeout stops this wait; job continues | | All SDKs | Reopen and await typed outcome | **New:** compaction result decoding on reopened handle | **New:** prewarm result decoding on reopened handle | Rust selects the typed result explicitly | | All SDKs | Cancel / events | Existing shared APIs available on **new** handle | Same | HTTP underneath; permissions unchanged | | All SDKs | Typed preview helper | Unavailable | Unavailable | General SQL where exposed; no helper added | | Authorization | Submission | Existing table Ownership plus parent Usage | SQL path uses Select plus parent Usage | Intentional difference | | All SDKs | Local / historical handles | New durable API rejects them | New durable API rejects them | Remote current-branch jobs only | ```python from datetime import timedelta # Legacy convenience call: returns None after acceptance. table.prewarm_data(["payload"], filter="id >= 1000", concurrency=4) warm = table.prewarm_data_async(["payload"], filter="id >= 1000", concurrency=4) warmed = warm.wait(timeout=timedelta(minutes=10), progress=print) print(warmed.table_version, warmed.executors_completed) compact = table.compact_async(compaction_options={"max_source_rows": 1000000}) committed = compact.wait(timeout=timedelta(minutes=10), progress=print) print(committed.rows_succeeded, committed.fragments_removed, committed.more_work) reopened_result = db.open_job(compact.id).wait() ``` ```typescript await table.prewarmData({ columns: ["payload"], filter: "id >= 1000", concurrency: 4 }); const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= 1000", concurrency: 4, }); const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); ``` ```rust use std::time::Duration; use lancedb::job::JobWaitOptions; let job = table.compact_async(Default::default()).await?; let result = job.wait_with_options( JobWaitOptions::new().timeout(Duration::from_secs(600)), ).await?; ``` Python async tables await both submission and Job methods. Rust's legacy `prewarm_data(columns)` keeps its columns-only signature; use `PrewarmDataOptions` on the new job-returning method for filtering/concurrency. Wait deadlines cover pending status requests and polling delays. Existing `wait()`, TypeScript `wait(callback)` and Rust `wait_with_progress(callback)` remain supported. Status/progress/refresh/cancel/events still use generic HTTP job APIs; those endpoints and their read/event/cancel permissions must remain available. Cancelling or timing out does not roll back committed work. Compaction results describe committed rewrites and include deletion files in file counts. Prewarm results describe work against a pinned snapshot, with partial executors included in completed executors; nonempty byte/range measurements remain unknown. Missing results require compatible server/worker support rather than placeholder zero statistics. Filtering uses conservative metadata pruning, not an exact row-filter scan. ### Testing Six checked-in live Python sync/async cases pass against matching server/worker builds for compaction, job-returning prewarm and legacy filtered submission. Ten additional live Node scenarios pass for legacy/default/options forms, filters/concurrency, empty plans, validation, persisted specifications and readback. Targeted regressions pass: Python remote maintenance (80), shared jobs (82), local prewarm rejection (4); Node remote (107) and prewarm API cases (28), plus the previously exercised Rust remote regressions. Tests cover receipt parsing, typed results, reopening, unknown measurements, timeouts, and legacy calls returning None/undefined without polling. Dependency pins are unchanged. Azure account-hint acknowledgment was verified locally with filesystem storage; real Azure-backed storage still needs deployment-specific validation. --- Cargo.lock | 1 + docs/src/js/classes/Connection.md | 20 +- docs/src/js/classes/Job.md | 23 +- docs/src/js/classes/Table.md | 137 +++++- docs/src/js/globals.md | 4 + docs/src/js/interfaces/CompactionResult.md | 99 +++++ docs/src/js/interfaces/JobProgress.md | 98 +++++ docs/src/js/interfaces/JobWaitOptions.md | 31 ++ docs/src/js/interfaces/PrewarmDataOptions.md | 39 ++ docs/src/js/interfaces/PrewarmDataResult.md | 79 ++++ docs/src/python/python.md | 4 + docs/web/basics/embedded-vs-enterprise.mdx | 29 +- docs/web/basics/jobs.mdx | 27 +- .../advanced-conflict-resolution.mdx | 12 +- docs/web/enterprise/cache-prewarm.mdx | 151 ++++++- .../web/enterprise/distributed-compaction.mdx | 8 + .../intelligent-auto-maintenance.mdx | 14 +- docs/web/indexing/incremental-indexing.mdx | 7 +- docs/web/indexing/scalar-index.mdx | 7 +- docs/web/indexing/vector-index.mdx | 4 +- docs/web/maintenance/cleanup.mdx | 6 +- docs/web/maintenance/compaction.mdx | 268 +++++++++++- docs/web/management/table.mdx | 5 +- docs/web/sql/ddl/job.mdx | 20 +- docs/web/sql/ddl/table.mdx | 54 ++- docs/web/tools/cli.mdx | 6 + nodejs/Cargo.toml | 1 + nodejs/__test__/remote.test.ts | 267 ++++++++++++ nodejs/__test__/table.test.ts | 105 ++++- nodejs/lancedb/compaction.ts | 41 ++ nodejs/lancedb/connection.ts | 6 +- nodejs/lancedb/index.ts | 7 +- nodejs/lancedb/job.ts | 116 ++++- nodejs/lancedb/prewarm.ts | 35 ++ nodejs/lancedb/table.ts | 145 ++++++- nodejs/src/connection.rs | 14 +- nodejs/src/job.rs | 82 +++- nodejs/src/table.rs | 60 +++ python/python/lancedb/_lancedb.pyi | 10 + python/python/lancedb/compaction.py | 37 ++ python/python/lancedb/job.py | 25 +- python/python/lancedb/prewarm.py | 32 ++ python/python/lancedb/remote/table.py | 48 +- python/python/lancedb/table.py | 199 ++++++++- python/python/tests/test_e2e_remote_db.py | 128 ++++++ python/python/tests/test_job.py | 92 ++++ python/python/tests/test_remote_db.py | 374 +++++++++++++++- python/python/tests/test_table.py | 19 + python/src/connection.rs | 8 + python/src/table.rs | 51 +++ rust/lancedb/src/job.rs | 181 +++++++- rust/lancedb/src/remote/db.rs | 29 +- rust/lancedb/src/remote/job.rs | 110 ++++- rust/lancedb/src/remote/sql.rs | 52 ++- rust/lancedb/src/remote/sql_test.rs | 410 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 170 ++++---- rust/lancedb/src/remote/table/optimize.rs | 77 ++++ rust/lancedb/src/remote/table/prewarm.rs | 248 +++++++++++ rust/lancedb/src/table.rs | 93 +++- rust/lancedb/src/table/optimize.rs | 45 +- rust/lancedb/src/table/prewarm.rs | 118 +++++ 61 files changed, 4339 insertions(+), 249 deletions(-) create mode 100644 docs/src/js/interfaces/CompactionResult.md create mode 100644 docs/src/js/interfaces/JobWaitOptions.md create mode 100644 docs/src/js/interfaces/PrewarmDataOptions.md create mode 100644 docs/src/js/interfaces/PrewarmDataResult.md create mode 100644 nodejs/lancedb/compaction.ts create mode 100644 nodejs/lancedb/prewarm.ts create mode 100644 python/python/lancedb/compaction.py create mode 100644 python/python/lancedb/prewarm.py create mode 100644 rust/lancedb/src/remote/table/prewarm.rs create mode 100644 rust/lancedb/src/table/prewarm.rs diff --git a/Cargo.lock b/Cargo.lock index 7b43449a0..923b7e94e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6179,6 +6179,7 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "serde", "serde_json", ] diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 4876e3a52..83c182cf2 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -456,7 +456,7 @@ Rejects a table that exists but is not a materialized view. ### dropMaterializedViewAsync() ```ts -abstract dropMaterializedViewAsync(name, namespacePath?): Promise +abstract dropMaterializedViewAsync(name, namespacePath?): Promise> ``` Start dropping the materialized view named `name` and return its job. @@ -473,7 +473,7 @@ Rejects a table that exists but is not a materialized view. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -532,7 +532,7 @@ Drop an existing table. ### dropTableAsync() ```ts -abstract dropTableAsync(name, namespacePath?): Promise +abstract dropTableAsync(name, namespacePath?): Promise> ``` Start dropping a table and return its cleanup job. @@ -548,7 +548,7 @@ on the returned job to know when cleanup has finished. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -579,7 +579,7 @@ catalog removal; physical cleanup continues in the background. ### dropViewAsync() ```ts -abstract dropViewAsync(name, namespacePath?): Promise +abstract dropViewAsync(name, namespacePath?): Promise> ``` Drop a view and return its SQL query job. @@ -594,7 +594,7 @@ catalog removal; physical cleanup continues in the background. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -729,7 +729,7 @@ state and error behavior; options control page size and the starting token. ### openJob() ```ts -abstract openJob(jobId): Promise +abstract openJob(jobId): Promise> ``` Open a server-side job by id, returning a handle with its record already @@ -740,13 +740,17 @@ The returned [Job](Job.md) answers for its own state, specification, result, failure and event history, so there is no separate connection-level call for any of them. +#### Type Parameters + +• **T** = `void` + #### Parameters * **jobId**: `string` #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`T`>> *** diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 8fd59c964..43d532cdd 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -4,7 +4,7 @@ [@lancedb/lancedb](../globals.md) / Job -# Class: Job +# Class: Job<T> A handle to an operation that may still be running. @@ -20,6 +20,10 @@ extra round trip on every call: - Registry details are null until one of those runs. Query handles report jobType "query" immediately. +## Type Parameters + +• **T** = `void` + ## Accessors ### creationMs @@ -241,7 +245,7 @@ printing it. ### wait() ```ts -wait(progressCallback?): Promise +wait(optionsOrProgress?): Promise ``` Wait until the operation reaches a terminal state. @@ -253,10 +257,21 @@ synchronous observer: its return value is ignored and not awaited. If it throws, the error is logged with `console.warn` and waiting continues; a callback exception does not reject `wait`. +Pass an options object to set a client-side timeout. Expiry rejects with an +error and stops this wait, including pending status requests and backoff. +The operation continues; use the same handle to wait again. Registry jobs +can also be reopened with `Connection.openJob`; query IDs cannot. + #### Parameters -* **progressCallback?**: [`JobProgressCallback`](../type-aliases/JobProgressCallback.md) +* **optionsOrProgress?**: [`JobWaitOptions`](../interfaces/JobWaitOptions.md) \| [`JobProgressCallback`](../type-aliases/JobProgressCallback.md) #### Returns -`Promise`<`void`> +`Promise`<`T`> + +#### Example + +```ts +const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log }); +``` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index f93c1b7cd..0a230ac94 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -305,6 +305,40 @@ It is a no-op when no writers are cached. *** +### compactAsync() + +```ts +compactAsync(_options?): Promise> +``` + +Submit remote compaction and return its durable job after acceptance. + +Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires +a compatible remote server and table Ownership plus parent Usage. Local and +historical-version handles are unsupported. Existing optimize() behavior is unchanged. +Waiting tracks the rewrite itself and returns actual row/file statistics. +Missing result payloads are errors; older workers can omit file counts. +Status, progress, events and cancellation reuse the generic HTTP job APIs. +Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + +#### Parameters + +* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`CompactionResult`](../interfaces/CompactionResult.md)>> + +#### Example + +```ts +const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); +const result = await job.wait(); +console.log(result.rowsSucceeded, result.fragmentsRemoved); +``` + +*** + ### compactRTE() ```ts @@ -423,7 +457,7 @@ await table.createIndex("my_float_col"); ### createIndexAsync() ```ts -abstract createIndexAsync(column, options?): Promise +abstract createIndexAsync(column, options?): Promise> ``` Create an index, returning a handle to the indexing job. @@ -444,7 +478,7 @@ account for the replacement caveat described in [Table.createIndex](Table.md#cre #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> *** @@ -1047,29 +1081,98 @@ retrying with the settings removed. ### prewarmData() +#### prewarmData(options) + ```ts -abstract prewarmData(columns?): Promise +abstract prewarmData(options?): Promise ``` Prewarm one or more columns of data in the table. -#### Parameters +This will load the column data into the page cache so that future queries that +read those columns avoid the initial cold-start latency. This call initiates +prewarming and returns once the request is accepted; the warming itself may +continue in the background. Submission uses SQL PREWARM and needs Flight +SQL connectivity. Use [prewarmDataAsync](Table.md#prewarmdataasync) to retain the job handle. + +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 in LanceDB Enterprise. + +##### Parameters + +* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md) + Columns, a metadata-pruning filter, and per-executor concurrency. + Omitted or empty columns warm every column. + +##### Returns + +`Promise`<`void`> + +##### Example + +```ts +await table.prewarmData({ + columns: ["payload"], filter: "quality > 0.7", concurrency: 4, +}); +``` + +#### prewarmData(columns) + +```ts +abstract prewarmData(columns?): Promise +``` + +Submit data prewarm using the columns-array form and return after acceptance. + +##### Parameters * **columns?**: `string`[] - The columns to prewarm. If undefined, all columns are prewarmed. - This will load the column data into the page cache so that future queries that - read those columns avoid the initial cold-start latency. This call initiates - prewarming and returns once the request is accepted; the warming itself may - continue in the background. Calling it on already-prewarmed columns is a - no-op on the server. - 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 in LanceDB Enterprise. + Columns to warm; omitted or empty means every column. + +##### Returns + +`Promise`<`void`> + +*** + +### prewarmDataAsync() + +```ts +abstract prewarmDataAsync(options?): Promise> +``` + +Submit data prewarm through SQL and return its durable warming-job handle. + +The table handle supplies the branch and namespace. Requires a compatible +SQL PREWARM server and Flight SQL connectivity. Standard authorization +requires table Select and database/namespace Usage. Status/wait use generic +HTTP job APIs; events and cancellation retain their own privileges. +No REST fallback or option-dropping retry is performed. Historical-version +handles are unsupported; call `checkoutLatest()` first. + +Submission returns after acceptance. Use `job.wait()` for completion, or +save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel +the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. + +#### Parameters + +* **options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md) #### Returns -`Promise`<`void`> +`Promise`<[`Job`](Job.md)<[`PrewarmDataResult`](../interfaces/PrewarmDataResult.md)>> + +#### Example + +```ts +const job = await table.prewarmDataAsync({ + columns: ["video"], filter: "quality > 0.7", concurrency: 4, +}); +await job.wait(); +``` *** @@ -1200,7 +1303,7 @@ number of rows filled and the new version number of the table. ### refreshColumnAsync() ```ts -abstract refreshColumnAsync(column, options?): Promise +abstract refreshColumnAsync(column, options?): Promise> ``` Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh @@ -1253,7 +1356,7 @@ LanceDB Enterprise it is the server's backfill job. #### Returns -`Promise`<[`Job`](Job.md)> +`Promise`<[`Job`](Job.md)<`void`>> #### Example diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 23e576877..3893f9a7e 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -75,6 +75,7 @@ - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) - [CompactionOptions](interfaces/CompactionOptions.md) +- [CompactionResult](interfaces/CompactionResult.md) - [CompactionStats](interfaces/CompactionStats.md) - [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md) - [ConnectionOptions](interfaces/ConnectionOptions.md) @@ -119,6 +120,7 @@ - [JobFailureInfo](interfaces/JobFailureInfo.md) - [JobInfo](interfaces/JobInfo.md) - [JobProgress](interfaces/JobProgress.md) +- [JobWaitOptions](interfaces/JobWaitOptions.md) - [ListingOptions](interfaces/ListingOptions.md) - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) - [MemtableStats](interfaces/MemtableStats.md) @@ -128,6 +130,8 @@ - [OpenTableOptions](interfaces/OpenTableOptions.md) - [OptimizeOptions](interfaces/OptimizeOptions.md) - [OptimizeStats](interfaces/OptimizeStats.md) +- [PrewarmDataOptions](interfaces/PrewarmDataOptions.md) +- [PrewarmDataResult](interfaces/PrewarmDataResult.md) - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) diff --git a/docs/src/js/interfaces/CompactionResult.md b/docs/src/js/interfaces/CompactionResult.md new file mode 100644 index 000000000..623dfe453 --- /dev/null +++ b/docs/src/js/interfaces/CompactionResult.md @@ -0,0 +1,99 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CompactionResult + +# Interface: CompactionResult + +Actual committed outcome of one remote compaction job. + +## Properties + +### completionPercentage + +```ts +completionPercentage: number; +``` + +Percentage of planned live rows committed, from 0 to 100. + +*** + +### filesAdded + +```ts +filesAdded: null | number; +``` + +Files added, including deletion files; null if an older worker omitted it. + +*** + +### filesRemoved + +```ts +filesRemoved: null | number; +``` + +Files removed, including deletion files; null if an older worker omitted it. + +*** + +### fragmentsAdded + +```ts +fragmentsAdded: null | number; +``` + +Fragments added by committed rewrites; null if an older worker omitted it. + +*** + +### fragmentsRemoved + +```ts +fragmentsRemoved: null | number; +``` + +Fragments removed by committed rewrites; null if an older worker omitted it. + +*** + +### moreWork + +```ts +moreWork: boolean; +``` + +A bounded run left eligible work for another invocation. + +*** + +### partialCommit + +```ts +partialCommit: boolean; +``` + +Some planned groups were not committed. + +*** + +### rowsFailed + +```ts +rowsFailed: number; +``` + +Planned live rows not committed by this job. + +*** + +### rowsSucceeded + +```ts +rowsSucceeded: number; +``` + +Live source rows in committed rewrite groups. diff --git a/docs/src/js/interfaces/JobProgress.md b/docs/src/js/interfaces/JobProgress.md index dde202794..6c9bc5466 100644 --- a/docs/src/js/interfaces/JobProgress.md +++ b/docs/src/js/interfaces/JobProgress.md @@ -17,6 +17,14 @@ different counters. A missing counter is unknown; it is not zero. ## Properties +### bytes\_read? + +```ts +optional bytes_read: null | number; +``` + +*** + ### estimated\_remaining\_time\_millis? ```ts @@ -37,6 +45,72 @@ Execution identity and sample time used for client-side ETA derivation. *** +### executors\_active? + +```ts +optional executors_active: null | number; +``` + +*** + +### executors\_completed? + +```ts +optional executors_completed: null | number; +``` + +*** + +### executors\_failed? + +```ts +optional executors_failed: null | number; +``` + +*** + +### executors\_partial? + +```ts +optional executors_partial: null | number; +``` + +*** + +### executors\_targeted? + +```ts +optional executors_targeted: null | number; +``` + +*** + +### fragments\_selected? + +```ts +optional fragments_selected: null | number; +``` + +*** + +### groups\_completed? + +```ts +optional groups_completed: null | number; +``` + +*** + +### groups\_planned? + +```ts +optional groups_planned: null | number; +``` + +Maintenance work observations; rewritten rows are not committed rows. + +*** + ### paused? ```ts @@ -57,6 +131,22 @@ Coarse server-derived phase, including phases from newer servers. *** +### ranges\_completed? + +```ts +optional ranges_completed: null | number; +``` + +*** + +### ranges\_planned? + +```ts +optional ranges_planned: null | number; +``` + +*** + ### rows\_computed? ```ts @@ -92,6 +182,14 @@ optional rows_remaining: null | number; *** +### rows\_rewritten? + +```ts +optional rows_rewritten: null | number; +``` + +*** + ### rows\_skipped? ```ts diff --git a/docs/src/js/interfaces/JobWaitOptions.md b/docs/src/js/interfaces/JobWaitOptions.md new file mode 100644 index 000000000..38f1795f5 --- /dev/null +++ b/docs/src/js/interfaces/JobWaitOptions.md @@ -0,0 +1,31 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / JobWaitOptions + +# Interface: JobWaitOptions + +Client-side controls for waiting without cancelling the underlying job. + +## Properties + +### onProgress? + +```ts +optional onProgress: JobProgressCallback; +``` + +Observe progress using the same poller that waits for completion. + +*** + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Maximum wait in milliseconds, including status requests and polling backoff. +Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows +only an immediately ready result. diff --git a/docs/src/js/interfaces/PrewarmDataOptions.md b/docs/src/js/interfaces/PrewarmDataOptions.md new file mode 100644 index 000000000..def1eb822 --- /dev/null +++ b/docs/src/js/interfaces/PrewarmDataOptions.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmDataOptions + +# Interface: PrewarmDataOptions + +Settings for submitting a durable remote data-cache prewarm job. + +## Properties + +### columns? + +```ts +optional columns: string[]; +``` + +Lance field paths to warm; omitted or empty means every column. + +*** + +### concurrency? + +```ts +optional concurrency: number; +``` + +Positive per-executor concurrency, at most 4294967295. + +*** + +### filter? + +```ts +optional filter: string; +``` + +A single SQL predicate for conservative metadata pruning. diff --git a/docs/src/js/interfaces/PrewarmDataResult.md b/docs/src/js/interfaces/PrewarmDataResult.md new file mode 100644 index 000000000..ce43b927c --- /dev/null +++ b/docs/src/js/interfaces/PrewarmDataResult.md @@ -0,0 +1,79 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmDataResult + +# Interface: PrewarmDataResult + +Reported executor work for a pinned snapshot; unavailable measurements stay null. + +## Properties + +### bytesRead + +```ts +bytesRead: null | number; +``` + +Reported bytes read, or null when unavailable. + +*** + +### executorsCompleted + +```ts +executorsCompleted: null | number; +``` + +Executors that finished successfully or partially, or null when unavailable. + +*** + +### executorsPartial + +```ts +executorsPartial: null | number; +``` + +Subset of completed executors reporting partial warming, or null when unavailable. + +*** + +### executorsTargeted + +```ts +executorsTargeted: null | number; +``` + +Reported executors targeted, or null when unavailable. + +*** + +### fragmentsSelected + +```ts +fragmentsSelected: null | number; +``` + +Reported fragments selected, or null when unavailable. + +*** + +### rangesCompleted + +```ts +rangesCompleted: null | number; +``` + +Reported ranges completed, or null when unavailable. + +*** + +### tableVersion + +```ts +tableVersion: number; +``` + +The source snapshot captured by submission. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index d3713b634..b7859c2f7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1494,3 +1494,7 @@ that accepts `python_bundle.resources`. Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or `conda=` for platform-specific dependencies and `models=` for large model snapshots. + +::: lancedb.compaction.CompactionResult + +::: lancedb.prewarm.PrewarmDataResult diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index a4e00040b..7d30a0e92 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -19,7 +19,7 @@ file format, so moving data from one edition to the other does not require a dat | **Mode** | Single process | Distributed fleet | LanceDB Embedded runs on one host, so scale is limited to what it can provide. Enterprise spreads work across nodes, adds capacity by adding nodes, and keeps serving even if one node fails. | | **Query serving** | Uses the resources of your application process | Adds independently scaled query compute | Size the Enterprise cluster for your workload and latency target. See the expected-performance sections on [vector search](/search/vector-search#expected-performance) and [full-text search](/search/full-text-search#expected-performance) for representative measurements. | | **Cache** | In-process index and metadata caches | Adds a distributed NVMe data cache | LanceDB Embedded caches indexes and metadata in your application's memory. Enterprise also keeps hot table data near compute on NVMe and avoids repeated S3 calls -- see the [Data Page Cache](/enterprise/data-page-cache). | -| **Indexing & compaction** | Manual | Platform-managed workflows | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). | +| **Indexing & compaction** | Manual | Platform-managed workflows and explicit compaction | LanceDB Embedded requires application-managed maintenance; Enterprise schedules it in the background. See [Indexing in LanceDB](/indexing/). | | **Data format** | Lance | Lance | Both use the same open table format. Plan catalog registration, access and transfer when moving existing data. | | **Deployment** | Embedded in your code | BYOC or Managed | Enterprise adds deployment operations and support for shared workloads. | | **SQL analytics** | Not available | Arrow Flight SQL | Enterprise runs joins, grouping, sampling and [curation](/curation) over SQL. See [SQL reference](/sql). | @@ -137,15 +137,26 @@ Instead, materialize results through query/search builders, for example ### 4\. Maintenance lifecycle {#4-maintenance-lifecycle} -In LanceDB Embedded, you run maintenance yourself: `optimize()` compacts data files, adds new rows to -existing indexes, and removes old table versions. In Enterprise, the cluster runs this work -- along with -async write and reindexing workflows -- as background jobs, and the SDK's maintenance calls do not trigger -it. On an Enterprise table, the synchronous Python `optimize()`, `compact_files()`, and -`cleanup_old_versions()` only emit a warning, and the asynchronous Python, TypeScript, and Rust clients -reject `optimize()` as not supported. +In LanceDB Embedded, `optimize()` compacts data files, adds new rows to existing +indexes, and removes old table versions. LanceDB Enterprise schedules that work +through separate background jobs and also accepts explicit compaction requests +with compatible releases. -That means maintenance is managed by platform behavior and cluster configuration, not by explicit -per-table maintenance calls in your application code. +Python sync/async `compact_async()`, TypeScript `compactAsync()`, and Rust +`Table::compact_async(CompactionOverrides)` return durable compaction job handles; +waiting returns the committed rewrite statistics. Legacy remote `optimize()` +and Rust `Table::compact()` return after submission with placeholder counts. +Remote optimize does not prune versions or optimize indexes; +explicit requests for those unsupported operations are rejected. The synchronous +Python `compact_files()` and `cleanup_old_versions()` helpers remain warning-only +no-ops in LanceDB Enterprise. + +Manual compaction accepts four invocation options and inherits omitted fields +from the selected branch's table tuning, then deployment/built-in defaults. +Automatic-compaction enablement gates background scheduling while explicit +manual jobs can still run. See +[manual Enterprise compaction](/maintenance/compaction#enterprise-manual-compaction) +for CLI, SQL, and SDK examples and rollout requirements. ### 5\. Guardrails and limits {#5-guardrails-and-limits} diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 30d48e93e..7761ab07c 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -95,7 +95,7 @@ In Python, `job.status()` returns the current state: It returns `failed` or `cancelled` for unsuccessful jobs. Use `job.wait()` to wait for completion and raise if the job fails or is -cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection +cancelled. Python's `Job.wait()` and `AsyncJob.wait()` retry transient connection and read errors with capped exponential backoff within the caller's timeout. Without a timeout, retries continue indefinitely. @@ -123,8 +123,33 @@ except ConnectionError as exc: except TimeoutError: print(f"still running: {job.status()}") ``` +```typescript TypeScript +const result = await job.wait({ + timeoutMs: 600_000, + onProgress: progress => console.log(progress), +}); +``` +```rust Rust +use std::time::Duration; +use lancedb::job::JobWaitOptions; + +let result = job.wait_with_options( + JobWaitOptions::new() + .timeout(Duration::from_secs(600)) + .progress(|description| println!("{}", description.progress_snapshot())), +).await?; +``` +TypeScript's `timeoutMs` and Rust's `JobWaitOptions::timeout` bound the existing +wait poller, including pending status requests and retry/polling delays. +Expiry rejects the TypeScript promise or returns Rust's `Error::Timeout`; +the operation is not cancelled. Calling `wait()` without options still waits +indefinitely. TypeScript's existing `wait(callback)` and Rust's +`wait_with_progress(callback)` remain available. A zero timeout only permits +an immediately ready result. TypeScript timeouts use nonnegative safe-integer +milliseconds; Rust uses `std::time::Duration`. + After connectivity returns, reopen an Enterprise registry job by its saved ID and continue waiting on the existing operation: diff --git a/docs/web/enterprise/advanced-conflict-resolution.mdx b/docs/web/enterprise/advanced-conflict-resolution.mdx index 3826de8a5..a48d23952 100644 --- a/docs/web/enterprise/advanced-conflict-resolution.mdx +++ b/docs/web/enterprise/advanced-conflict-resolution.mdx @@ -20,11 +20,13 @@ independently: `optimize()` compacts and remaps affected indexes in the same call, before returning. Compaction's `defer_index_remap` option opts out of that -- the call returns once compaction itself commits, leaving the remap for later -- which is what lets a custom remapper or a -stable-row-ID table skip the synchronous step. LanceDB Enterprise runs -compaction and indexing as separate, independently scheduled -background jobs -- a table can compact while an index build is still -catching up from an earlier compaction -- so it needs a way to keep an index -correct without forcing every compaction to wait for a synchronous remap. +stable-row-ID table skip the synchronous step. LanceDB Enterprise schedules +automatic compaction and indexing independently, so an eligible table can compact +while an index build is still catching up from earlier compaction. Deferred +remapping keeps indexes correct without making every automatic compaction wait +for a synchronous remap. Explicit +[manual compaction](/maintenance/compaction#enterprise-manual-compaction) uses one +worker with atomic execution and inline index remapping instead. ## The fragment reuse index {#fri} diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index 3ce773d73..c2a5347f1 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -1,23 +1,25 @@ --- title: "Cache Prewarm" sidebarTitle: "Cache Prewarm" -description: "Populate the tiered index cache ahead of a request, instead of filling it lazily on first read." +description: "Warm indexes at executor startup or submit on-demand jobs to populate the data page cache." icon: "fire" -keywords: ["prewarm", "cache", "index cache", "startup"] +keywords: ["prewarm", "cache", "index cache", "data page cache", "startup"] availability: embedded: unavailable enterprise: available --- -Cache Prewarm loads the [tiered index cache](/enterprise/tiered-index-cache) -a plan executor keeps as part of Enterprise's serving layer, instead of -leaving it to fill lazily on first read. You configure which tables to -prewarm; on startup, each plan executor loads those tables' indexes into -cache before it joins the fleet. The executor does not accept queries until -prewarming finishes, so it never serves a request against a cold cache. +Enterprise supports two kinds of cache prewarm: startup index prewarm fills +the [tiered index cache](/enterprise/tiered-index-cache), and +[on-demand data prewarm](#on-demand-data-prewarm) fills the +[data page cache](/enterprise/data-page-cache) through a durable job. -LanceDB Embedded has no such cache, so there is nothing for it to warm -there. Embedded does have its own, separate `prewarm_index()` on a table -- +For startup index prewarm, you configure which tables to warm. Each plan +executor loads those tables' indexes before it joins the fleet. The executor +does not accept queries until startup prewarming finishes. + +These Enterprise caches are not available in LanceDB Embedded. +Embedded does have its own, separate `prewarm_index()` on a table -- an idempotent hint that loads a built index into memory ahead of a query.
@@ -72,14 +74,139 @@ and rollouts instead of dipping right after each one. [Contact us](https://www.lancedb.com/contact) to learn more about how prewarming is configured for your deployment. +## On-demand data prewarm {#on-demand-data-prewarm} + +On compatible Enterprise deployments, the SDK submits data prewarm through +SQL. Flight SQL connectivity is required; the existing generic HTTP job API is +used to inspect or wait for the durable warming job. Under Standard +authorization, submission requires table Select plus Usage on the database +and namespace hierarchy. Job events require System Usage and cancellation +requires System Operate. + +The table handle determines the database, namespace, and branch in every SDK. + + + +```python +from datetime import timedelta + +job = table.prewarm_data_async( + ["video"], filter="quality > 0.7", concurrency=4 +) +print(job.id) +result = job.wait(timeout=timedelta(minutes=10), progress=print) +print(result.table_version, result.executors_completed, result.fragments_selected) + +# Reattach in a later process using the same database connection settings. +db.open_job(job.id).wait() +``` + + +```typescript +const job = await table.prewarmDataAsync({ + columns: ["video"], + filter: "quality > 0.7", + concurrency: 4, +}); +console.log(job.id); +const result = await job.wait({ timeoutMs: 600_000, onProgress: console.log }); +console.log(result.tableVersion, result.executorsCompleted); + +// Reattach using the same database connection settings. +if (job.id !== null) { + await (await db.openJob(job.id)).wait(); +} +``` + + +```rust +use std::time::Duration; +use lancedb::job::JobWaitOptions; +use lancedb::table::{PrewarmDataOptions, PrewarmDataResult}; + +let job = table + .prewarm_data_async( + PrewarmDataOptions::new() + .columns(["video"]) + .filter("quality > 0.7") + .concurrency(4), + ) + .await?; +println!("{:?}", job.id()); +let result = job.wait_with_options( + JobWaitOptions::new().timeout(Duration::from_secs(600)), +).await?; +println!("Snapshot {}: {:?} executors completed", result.table_version, result.executors_completed); + +// Reattach using the same database connection settings. +if let Some(id) = job.id() { + db.open_job(id).await?.into_typed::()?.wait().await?; +} +``` + + + +The method returns when the job is accepted. Waiting finishes when warming +reaches a terminal state; a timeout does not cancel the job. Use +`job.refresh()` and `job.spec["table_version"]` to inspect the captured source +version. In Python's asynchronous API, await submission and `job.wait()`. +Node exposes `table.prewarmDataAsync({ columns, filter, concurrency })` with +the same lifecycle. + +Waiting returns a typed `PrewarmDataResult`: the pinned source version, +selected fragment count, targeted/completed executor counts, and partial +executor count when reported. Completed executors include partial completions; +`executors_partial` is that subset, which can reflect cache pressure. These are observations of executor work, not a guarantee that every +page remains resident. Counters omitted by older workers stay unknown. + +The current executor status protocol does not report byte/range measurements +for nonempty prewarms, so `bytes_read` and `ranges_completed` are None/null there. +A new worker performing an empty plan reports known zero work. Progress exposes +planning/dispatch phases, selected fragments, executor fan-out, and the latest +active/completed/partial/failed executor counts without inventing percentages. +In Python, `job.wait(progress=True)` displays completed executors. Pass a +callback instead to inspect the full structured snapshots. + +The Enterprise administrative CLI supports the same lifecycle: + +```bash +lancedb admin cache prewarm data --profile production --table events \ + --column payload --filter 'id >= 1000' --concurrency 4 \ + --wait --wait-timeout-seconds 600 --poll-interval-seconds 5 +``` + +SQL submission and preview use the same options. Submission returns a job ID +and pinned source version; preview creates no job: + +```sql +PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; +EXPLAIN PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; +DESCRIBE JOB '' FORMAT JSON; +``` + +The filter is a single SQL predicate used for conservative metadata pruning. +Unknown or unavailable metadata keeps data eligible for warming. Omitted +columns warm all fields; concurrency must be a positive integer. Historical +version checkouts are unsupported: use the latest version of the selected +branch. The server never needs to scan rows merely to evaluate the predicate. + +`prewarm_data(columns, filter=..., concurrency=...)` and +`prewarmData({ columns, filter, concurrency })` accept the same options as the +job-returning methods but return after acceptance without retaining the handle. +The existing TypeScript `prewarmData(columns)` array form remains supported. +These methods require SQL PREWARM support and Flight SQL connectivity. +Unsupported servers fail without a REST fallback or silently +dropping options. Repeated submissions may create distinct jobs; warming +already-cached data is safe. Index prewarm keeps its existing behavior. + ## What to read next {#next} - The raw-data-page cache -- a separate cache from the one prewarm fills. + The raw-data-page cache populated by on-demand data prewarm jobs. - The deserialized-index cache prewarm fills. + The deserialized-index cache populated by startup index prewarm. Where plan executors and query nodes sit in the serving fleet. diff --git a/docs/web/enterprise/distributed-compaction.mdx b/docs/web/enterprise/distributed-compaction.mdx index 8d1fb4191..30d8a8863 100644 --- a/docs/web/enterprise/distributed-compaction.mdx +++ b/docs/web/enterprise/distributed-compaction.mdx @@ -76,6 +76,14 @@ rest of the job's tasks commit without waiting on it. See [Advanced Conflict Resolution](/enterprise/advanced-conflict-resolution) for when compaction defers a remap at all. +Automatic compaction can use this distributed path when table state and index +safety permit it. Explicit CLI, SQL, and SDK compaction jobs use one worker with +atomic execution and inline index remapping. Their tuning resolves from the +invocation, then table settings, then deployment/built-in defaults. Automatic +jobs use table settings before those defaults. See +[manual compaction](/maintenance/compaction#enterprise-manual-compaction) for +submission, the four tuning fields, and job completion checks. + ## Compaction interfaces {#compaction-interfaces} - [Compaction](/maintenance/compaction) for triggering and configuring a compaction. diff --git a/docs/web/enterprise/intelligent-auto-maintenance.mdx b/docs/web/enterprise/intelligent-auto-maintenance.mdx index 38cbdd2a5..cabac3643 100644 --- a/docs/web/enterprise/intelligent-auto-maintenance.mdx +++ b/docs/web/enterprise/intelligent-auto-maintenance.mdx @@ -112,13 +112,21 @@ a compaction and a cleanup are unrelated and can both launch together -- but some gate each other where running them at the same time would be unsafe, like index operations waiting on a compaction that can't defer its remap. +Compaction's four tuning fields can be set per table. Automatic jobs use table +tuning before deployment/built-in defaults; explicit manual invocation values +take precedence over both. Automatic enablement still gates background jobs, +while manual compaction can run with it disabled. Resolved tuning is captured in +each job. See [table compaction defaults](/maintenance/compaction#table-compaction-defaults) +for the fields, precedence, source-budget planning failures, and compatible-version requirements. + ### When cleanup is due {#cleanup} [Cleanup](/maintenance/cleanup) prunes old table versions and the files only they referenced. In LanceDB Embedded, that always happens because you asked -for it -- a call to `optimize()`. LanceDB Enterprise does not support a -manual `optimize()` call at all; cleanup there is entirely this planner's own -decision, off by default unless the deployment sets a minimum version age -- +for it, through a call to `optimize()`. In LanceDB Enterprise, a +[manual `optimize()` call](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only. Cleanup remains this planner's own decision, off by +default unless the deployment sets a minimum version age: with no minimum age configured, nothing is ever old enough to clean up automatically, and old versions simply accumulate until an operator enables it. A table can also disable it individually even when the deployment allows diff --git a/docs/web/indexing/incremental-indexing.mdx b/docs/web/indexing/incremental-indexing.mdx index 42c864ae9..6c79102f0 100644 --- a/docs/web/indexing/incremental-indexing.mdx +++ b/docs/web/indexing/incremental-indexing.mdx @@ -41,10 +41,11 @@ default. The name says which algorithm is building, not a separate feature. ## Triggering an incremental update {#incremental-reindexing} In the embedded library, you trigger an incremental indexing operation on -updated data with the `optimize()` method on a table. A deployment does this -for you and does not support `optimize()`, as described below. +updated data with the `optimize()` method on a table. LanceDB Enterprise updates +indexes in the background. Its [manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only and does not trigger incremental index updates. -Table optimization performs three maintenance operations: +In LanceDB Embedded, table optimization performs three maintenance operations: 1. **Compaction**: merges small fragments into larger ones to improve read performance 2. **Pruning/Cleanup**: removes files from versions older than a retention window (7 days by default) -- see [Cleanup](/maintenance/cleanup) for how retention works diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index fbd818b64..3d7b3a864 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -90,7 +90,12 @@ Updating the table data (adding, deleting, or modifying records) requires that y -New data added after creating the scalar index will still appear in search results if optimize is not used, but with increased latency due to a flat search on the unindexed portion. LanceDB Enterprise does not support `optimize()`; instead it adds new rows to `BTREE`, `BITMAP` and `LABEL_LIST` indexes in the background once enough have accumulated. It does not update `FM` indexes automatically. +New data added after creating the scalar index remains searchable through a +slower flat scan of the unindexed rows. LanceDB Enterprise adds new rows to +`BTREE`, `BITMAP`, and `LABEL_LIST` indexes in the background once enough have +accumulated. It does not update `FM` indexes automatically. The Enterprise +[manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only and does not trigger this index maintenance. ### 4\. Run Indexed Searches diff --git a/docs/web/indexing/vector-index.mdx b/docs/web/indexing/vector-index.mdx index 33fc802fa..2800463af 100644 --- a/docs/web/indexing/vector-index.mdx +++ b/docs/web/indexing/vector-index.mdx @@ -301,7 +301,9 @@ fallback and searches only indexed rows. **Operational checks** In the embedded library, use `optimize()` after appends or other writes to fold new rows into existing indexes. -A deployment does this in the background, and `optimize()` is not available there. +LanceDB Enterprise does this in the background. Its +[manual `optimize()` path](/maintenance/compaction#enterprise-manual-compaction) +submits compaction only and does not add unindexed rows to the vector index. #### Check Index Status diff --git a/docs/web/maintenance/cleanup.mdx b/docs/web/maintenance/cleanup.mdx index 21ba079f9..8ccf4e242 100644 --- a/docs/web/maintenance/cleanup.mdx +++ b/docs/web/maintenance/cleanup.mdx @@ -96,8 +96,10 @@ maintenance workers to a version that understands Managed blobs before using them, and reopen handles created before that upgrade. For LanceDB Embedded tables, `optimize()` performs compaction and cleanup. -Enterprise runs these as background jobs; Python tables connected to Enterprise -do not support `optimize()`. +Enterprise schedules them as separate background jobs. With compatible releases, +remote `optimize()` also submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction), +but does not prune versions or remove their files. Cleanup remains governed by +the deployment's separate policy. See [Intelligent Auto-Maintenance](/enterprise/intelligent-auto-maintenance#cleanup) 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 e7b79f768..d8638419e 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -13,8 +13,10 @@ import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompac Every write commits a new table version, and versions accumulate: small files from frequent appends, superseded files from updates and deletes, and rows added since an index was built. In the embedded library, `optimize()` addresses all -three. Enterprise handles maintenance in the background and also supports -on-demand compaction through `optimize()` on compatible servers. +three. LanceDB Enterprise schedules maintenance in the background and also +supports explicit compaction jobs through the CLI, SQL, and compatible SDKs. +[Manual Enterprise compaction](#enterprise-manual-compaction) rewrites data files; +cleanup and index optimization remain separate operations. Run optimization as regular table maintenance, particularly after many small writes or a large ingest. @@ -37,7 +39,7 @@ optimize. Rebuilding with the default IVF partitioning can also choose enough partitions. */} -## Optimize a table {#what-it-does} +## Optimize an Embedded table {#what-it-does} ```python Python icon="python" @@ -63,6 +65,266 @@ separately from [`cleanup`](/maintenance/cleanup). The two are distinct jobs even though `optimize()` bundles both in one LanceDB Embedded call. +## Track on-demand Enterprise compaction {#compaction-jobs} + +On compatible Enterprise deployments, `compact_async()` / `compactAsync()` +submits SQL `OPTIMIZE ... REWRITE DATA` and returns a durable job handle. +The table handle supplies the namespace and branch. The existing remote +`optimize()` call keeps returning after submission with placeholder statistics; +use the job-returning API to wait for the actual rewrite and obtain its result. + + +```python Python +from datetime import timedelta + +job = table.compact_async( + compaction_options={"target_rows_per_fragment": 1000, "batch_size": 128} +) +result = job.wait(timeout=timedelta(minutes=10)) +print(result.rows_succeeded, result.fragments_removed, result.fragments_added) + +# Resume from another process with the same connection settings. +result = db.open_job(job.id).wait() +``` +```typescript TypeScript +import type { CompactionResult } from "@lancedb/lancedb"; + +const job = await table.compactAsync({ + targetRowsPerFragment: 1000, batchSize: 128, +}); +const result = await job.wait({ timeoutMs: 600_000 }); +console.log(result.rowsSucceeded, result.fragmentsRemoved, result.fragmentsAdded); + +if (job.id !== null) { + await (await db.openJob(job.id)).wait(); +} +``` +```rust Rust +use std::time::Duration; +use lancedb::job::JobWaitOptions; +use lancedb::table::{CompactionResult, optimize::CompactionOverrides}; + +let job = table.compact_async(CompactionOverrides { + target_rows_per_fragment: Some(1000), + batch_size: Some(128), + ..Default::default() +}).await?; +let result = job.wait_with_options( + JobWaitOptions::new().timeout(Duration::from_secs(600)), +).await?; +println!("Committed {} rows", result.rows_succeeded); + +if let Some(id) = job.id() { + db.open_job(id).await?.into_typed::()?.wait().await?; +} +``` + + +The result describes this job's committed rewrites, not a comparison of table +versions that could include concurrent writes. `partial_commit` identifies an +incomplete commit; `rows_failed` counts planned rows left uncommitted. +`more_work` means a bounded run left eligible work for another invocation. +A genuine no-op reports zero file/fragment counts; counts omitted by an older +worker are `None` in Python/Rust or `null` in TypeScript. A server that publishes +no compaction result raises an error when waiting, rather than fabricating zero +statistics. + +Submission requires Flight SQL connectivity and, under Standard authorization, +table Ownership plus Usage on the database and namespace hierarchy. Status, +progress, events, and cancellation use the generic HTTP job APIs and their +existing permissions. A wait timeout or dropping the handle does not cancel +the job. Local tables and historical-version checkouts are unsupported by the +job-returning API; ordinary embedded `optimize()` remains available. + +## Submit Enterprise compaction {#enterprise-manual-compaction} + +Use an existing Enterprise table and a connection configured for its database. +The `lancedb admin ...` and `lancedb job ...` examples on this page require the +**Enterprise administrative CLI**, available from your deployment administrator. +Check that `lancedb --help` lists `admin` and `job`. It needs Flight SQL +connectivity to submit the job and REST connectivity to read table settings and +job progress. + +The [public CLI installation](/tools/cli#install) supplies the client commands +`auth`, `profile`, and `sql`, without the administrative commands. You can use +that client for the SQL alternative below or submit through an SDK. Ask your +deployment administrator for the Enterprise CLI when you need the administrative +examples. + + +Use versions of the SDK, query nodes, agents, and workers that support these +options. +Older agents or workers can silently discard new job fields and run without the +requested source-row cap. Older-server errors propagate through the SDK without +retrying after dropping the settings. Manual submission requires a deployment +with SQL job submission enabled. Targets are resolved through the service +catalog, including PostgreSQL-backed SaaS catalogs. + + +Submit the same four invocation settings through any of these interfaces: + + +```bash CLI icon="terminal" +lancedb admin table optimize --table events \ + --target-rows-per-fragment 100000 \ + --max-source-rows 1000000 \ + --io-buffer-size 67108864 \ + --batch-size 1024 \ + --wait --wait-timeout-seconds 600 --poll-interval-seconds 5 +``` +```sql SQL icon="database" +OPTIMIZE events REWRITE DATA WITH ( + target_rows_per_fragment = 100000, + max_source_rows = 1000000, + io_buffer_size = 67108864, + batch_size = 1024 +); +``` + + +With the public CLI, execute SQL directly using a profile configured for the +same database and Flight SQL endpoint: + +```bash +lancedb sql --profile production --command \ + 'OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000);' +``` + +Add `--branch exp` to the Enterprise CLI's `admin table optimize` command or +`branch = 'exp'` to SQL's `WITH` clause to target a branch. SDK calls use the table handle's selected branch. +Without a branch, the job targets main. CLI and SQL validate the table and branch +through the service catalog before creating a job. + +SQL and the CLI without `--wait` return after durable submission. The +job-returning SDK methods above preserve the ID and return committed statistics +when waiting completes. The CLI's `--wait` polls the same durable job and prints +its result. A timeout leaves the job running. Legacy remote `optimize()` still +returns after acceptance with placeholder statistics. + +Find earlier submissions with a table-scoped list, replacing `DATABASE` with +the database name: + +```bash +lancedb job list --db-name DATABASE --table-name events --job-type compact +``` + +For a namespaced table or branch, also pass `--namespace` or `--branch-name`. +Correlate the job's submission time and stored specification, then inspect +completion and worker events with a CLI profile for that deployment: + +```bash +lancedb job describe --job-id JOB_ID +lancedb job events --job-id JOB_ID +``` + +Under Standard authorization, submission requires table Ownership. `job describe` +accepts system Usage or, for a table job, Usage on its database and every namespace +in its path. `job list` and `job events` require system Usage; `job cancel` +requires system Operate. An unauthorized describe request returns 404 to hide +the job's existence; denied list/events requests return 403. Submission does not +grant system-level access to job lists or events. + +Manual compaction uses one worker with atomic execution and inline index +remapping. Remote `optimize` does not prune old versions or optimize indexes; +explicit pruning, index optimization, and unsupported non-default compaction +settings are rejected. Cleanup continues through the deployment's separate +[cleanup policy](/maintenance/cleanup). + +### Preview and inspect a run + +```sql +EXPLAIN OPTIMIZE events REWRITE DATA WITH ( + target_rows_per_fragment = 100000, + max_source_rows = 1000000 +); + +DESCRIBE JOB '' FORMAT JSON; +``` + +The preview uses the execution planner to report the source version, resolved +options, planned groups/fragments/rows, and whether more eligible work remains. +It creates no job. Submission plans against its own snapshot, so concurrent +writes can change the work after a preview. `EXPLAIN ANALYZE` is unsupported. + +JSON job diagnostics include reported maintenance progress and the completed +operation result alongside the existing time profile. While a job runs, its +result is null. SDK progress callbacks and CLI `--wait` expose the same worker +observations: rewritten groups/rows are execution progress, not proof of a +successful commit. Repeated task reports are counted once within an execution. +Python's `job.wait(progress=True)` displays rewritten rows; read the completion +result for committed statistics. + +### Choose invocation settings {#compaction-invocation-options} + +| SQL / Python / Rust | TypeScript | Meaning | +| --- | --- | --- | +| `target_rows_per_fragment` | `targetRowsPerFragment` | Positive target rows per output fragment; also affects candidate selection. This is a target, not an exact output-size guarantee. | +| `max_source_rows` | `maxSourceRows` | Positive live-source-row budget across whole planned tasks. Selection stops before a task would exceed the remaining budget. If the first useful task exceeds the budget, worker planning fails with the required live rows and source fragment count. | +| `io_buffer_size` | `ioBufferSize` | Nonnegative I/O read-ahead budget in bytes. Zero disables byte-based I/O backpressure; a positive value limits read-ahead. It is not a total-memory limit. | +| `batch_size` | `batchSize` | Positive scanner input-batch size in rows. | + +These settings do not impose a runtime limit. Values must be integers in the +interface's supported range. Python and TypeScript fragment targets and batch +sizes are limited to `u32::MAX`; TypeScript additionally requires safe integers. + +### Set table defaults {#table-compaction-defaults} + +Table tuning supports the same four fields under `job_types.compaction`: + +```bash +lancedb admin table overrides get --table events +lancedb admin table overrides set --table events \ + '{"job_types":{"compaction":{"enabled":false,"target_rows_per_fragment":100000,"max_source_rows":1000000,"io_buffer_size":67108864,"batch_size":1024}}}' +``` + +`set` replaces the whole overrides object. The example assumes no other settings +need preserving; read the current object and retain unrelated fields when +editing an existing policy. Use the same namespace and branch for policy reads, +writes, and compaction submission. + +Each manual field resolves as **invocation option → table tuning → +deployment/built-in default**. Automatic jobs resolve **table tuning → +deployment/built-in default**. The fragment target has a shared deployment +default. Automatic atomic jobs also use the deployment +`agent.jobTypes.compaction.atomicMaxSourceRows` when the table has no source-row +override; manual and deferred-remap jobs do not inherit that agent-only fallback. +Otherwise, an omitted source-row budget is unbounded. Unset I/O and batch settings +use the existing Lance/scanner defaults. + +The table's `enabled` flag controls automatic scheduling and admission. An +explicit manual job can run while table or deployment automatic compaction is +disabled. For example, inherit the table's target, source budget, and batch size +while overriding I/O backpressure for one run: + +```bash +lancedb admin table optimize --table events --io-buffer-size 0 +``` + +```sql +OPTIMIZE events REWRITE DATA WITH (io_buffer_size = 0); +``` + +Resolved tuning is stored with the durable job. A later table-policy change +affects future jobs and does not rewrite an existing job's settings. If the +budget cannot admit the first useful task, automatic preflight reports an error +without launching a compaction worker. A submitted manual job fails in worker +planning. Raise the budget to the reported requirement or review a smaller +fragment target; the target alone does not guarantee that a whole task fits. +Genuinely empty plans are still skipped by automatic preflight. + +Successful bounded automatic atomic runs record whether work remains, allowing +later runs below the normal fragment-count threshold. Run intervals, index +readiness, refresh, and failure-backoff gates still apply. Failed or timed-out +attempts retain pending continuation; explicit cancellation clears it. Changing +the effective source-row budget re-arms automatic failures recorded under a +different budget; toggling automatic enablement alone does not reset backoff. + +SDKs forward supplied fields and leave inheritance to the server. An explicitly +supplied SDK-default fragment target still overrides table tuning. Rust callers +should use `Table::compact_async(CompactionOverrides)` for that distinction: the legacy +`OptimizeAction::Compact` path treats its default-valued Lance fragment target +as unspecified because the options type has no presence bit. + ## Retraining indexes {#retrain} Folding new rows into an index preserves the structure the index was trained on. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index facb9bdfe..ff56aff10 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1790,7 +1790,10 @@ mixing in lower-level Lance file operations. System operations like `optimize()`, index updates, and table compaction also increment table version numbers. 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. +when its configuration enables [cleanup](/maintenance/cleanup). With compatible +releases, Enterprise `optimize()` submits [manual compaction](/maintenance/compaction#enterprise-manual-compaction) +only; it does not prune old versions. Submission returns before workers finish, +so observe the completed job and resulting table state before expecting a new version. **Tagged versions are never pruned.** A version with a tag pointing at it is retained regardless of age. When a tagged version is older than the retention window and diff --git a/docs/web/sql/ddl/job.mdx b/docs/web/sql/ddl/job.mdx index a4cf13490..8b507e6bc 100644 --- a/docs/web/sql/ddl/job.mdx +++ b/docs/web/sql/ddl/job.mdx @@ -67,9 +67,23 @@ DESC JOB '' [FORMAT TEXT | TABLE | JSON] ``` -Both spellings show a finished root job's timing profile. `TEXT` is the -default; `TABLE` returns typed phase/step rows and `JSON` returns the -profile as one document. A running job has no profile rows. +`TEXT` is the default and shows a finished root job's timing profile; +`TABLE` returns typed phase/step rows. These formats have no profile rows +while a job runs. + +On compatible deployments, `JSON` returns one document in the `profile` +column with `job_id`, `job_type`, `job_state`, reported `progress`, and the +successful operation's `result`, alongside any timing profile. It works +while the job runs, when `result` is null. Compaction counters describe +committed work only in the result; progress counters describe observed +execution work. Data prewarm results identify the pinned table version and +reported executor work. Unavailable measurements remain absent or null. + +```sql +DESCRIBE JOB '' FORMAT JSON; +``` + +Older deployments return only the timing profile. ## SHOW ERRORS {#errors} diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index d2196b93a..e2b50168a 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -1,9 +1,9 @@ --- title: "Table" sidebarTitle: "Table" -description: "CREATE, DESCRIBE, ALTER, CLONE and DROP TABLE." +description: "CREATE, DESCRIBE, ALTER, OPTIMIZE, CLONE and DROP TABLE." icon: table -keywords: ["create table", "alter table", "drop table", "describe", "clone", "ddl"] +keywords: ["create table", "alter table", "drop table", "describe", "clone", "optimize", "ddl"] availability: embedded: unavailable enterprise: available @@ -258,6 +258,56 @@ deployment stores its catalog. See [Object teardown](/basics/jobs#teardown). +## OPTIMIZE REWRITE DATA {#optimize} + +Submit a durable manual compaction job on a compatible Enterprise deployment: + +```sql +OPTIMIZE events REWRITE DATA WITH ( + target_rows_per_fragment = 100000, + max_source_rows = 1000000, + io_buffer_size = 67108864, + batch_size = 1024 +); +``` + +Write the table name immediately after `OPTIMIZE`, without a `TABLE` keyword. +All four settings are optional. Add `branch = 'exp'` in the same `WITH (...)` +clause to select a branch; an omitted branch targets main. Row targets, +source-row budgets, and scanner batch sizes must be positive integers. The I/O +budget is in bytes and accepts zero to disable byte-based I/O backpressure. +Unknown or duplicate options and invalid numbers are rejected before submission. + +Each field uses its invocation value, then that branch's table tuning, then +deployment/built-in defaults. The automatic-compaction `enabled` flags do not +block an explicit manual job. Tuning is captured in the durable specification; +later table changes affect future jobs. + +The statement returns a `job_id` after submission, before worker completion. +It runs atomic compaction on one worker with inline index remapping, without +pruning versions or optimizing indexes. The source-row budget admits whole +tasks; if the first useful task exceeds it, worker planning fails with the +required live rows and source fragment count. The table and branch are validated +through the service catalog before creating a job. + +See [manual compaction](/maintenance/compaction#enterprise-manual-compaction) +for the option meanings, supported deployment and version requirements, +authorization, job inspection, table defaults, and equivalent CLI/SDK examples. + + +### Preview manual compaction + +```sql +EXPLAIN OPTIMIZE events REWRITE DATA WITH (max_source_rows = 1000000); +DESCRIBE JOB '' FORMAT JSON; +``` + +The preview reports the selected source version, effective options, planned +work and continuation using the worker's planner without submitting a job. +`EXPLAIN ANALYZE` is unsupported. The JSON diagnostic includes reported progress +and a successful job's committed result. See [Compaction](/maintenance/compaction#compaction-jobs) +for durable SDK handles and CLI waiting. + ## What to read next {#next} diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index 2d5104322..0259bf9fb 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -10,6 +10,12 @@ 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). +This public client exposes `auth`, `profile`, and `sql`. Commands such as +`lancedb admin ...` and `lancedb job ...` require the Enterprise administrative +CLI from your deployment administrator; the public client archive and source +installation below do not include them. Use `lancedb sql --command` for SQL +statements supported by your deployment. + ## Install Download a CLI archive and `SHA256SUMS` from the diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index d0ccd2efd..d0d000e10 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -30,6 +30,7 @@ napi = { version = "3.15.0", default-features = false, features = [ "serde-json", ] } chrono.workspace = true +serde.workspace = true serde_json.workspace = true napi-derive = "3.6.13" # Prevent dynamic linking of lzma, which comes from datafusion diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 9baa51292..c5f81391a 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2662,3 +2662,270 @@ describe("lazy resource listings", () => { }); } }); + +describe("remote compaction job results", () => { + test.each([true, false])( + "reopens typed compaction result (counts=%s)", + async (counts) => { + await withMockDatabase( + (request, response) => { + expect(request.url).toBe("/v1/jobs/describe"); + const result = JSON.parse(`{ + "partial_commit": false, + "rows_succeeded": 12, + "rows_failed": 0, + "completion_percentage": 100 + }`); + if (counts) { + Object.assign( + result, + JSON.parse(`{ + "files_added": 1, + "files_removed": 3, + "fragments_added": 1, + "fragments_removed": 3 + }`), + ); + } + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + `{"job_id":"compacting-job","job_type":"compact","job_state":"DONE","result":${JSON.stringify(result)}}`, + ); + }, + async (db) => { + const job = + await db.openJob( + "compacting-job", + ); + const result = await job.wait(); + expect(result.rowsSucceeded).toBe(12); + expect(result.moreWork).toBe(false); + expect(result.fragmentsRemoved).toBe(counts ? 3 : null); + }, + ); + }, + ); +}); + +describe("data prewarm typed results", () => { + test.each([null, {}])( + "rejects a missing typed outcome (%p)", + async (result) => { + await withMockDatabase( + (_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + `{"job_id":"warming-job","job_type":"prewarm_page_cache","job_state":"DONE","result":${JSON.stringify(result)}}`, + ); + }, + async (db) => { + const job = await db.openJob("warming-job"); + await expect(job.wait()).rejects.toThrow(); + }, + ); + }, + ); + + test.each([true, false])( + "reopens a result (counters=%s)", + async (counters) => { + await withMockDatabase( + (_request, response) => { + const result = JSON.parse( + counters + ? '{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}' + : '{"table_version":42}', + ); + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + ["job_id"]: "warming-job", + ["job_type"]: "prewarm_page_cache", + ["job_state"]: "DONE", + progress: null, + ["operation_progress"]: { + phase: "reading", + ["executors_completed"]: 2, + }, + result, + }), + ); + }, + async (db) => { + const job = + await db.openJob( + "warming-job", + ); + const result = await job.wait(); + expect(result.tableVersion).toBe(42); + expect(result.executorsCompleted).toBe(counters ? 2 : null); + expect(result.bytesRead).toBeNull(); + expect((await job.progress())?.executors_completed).toBe(2); + }, + ); + }, + ); +}); + +describe("job wait deadlines", () => { + function response(kind: string, done: boolean) { + const result = + kind === "compact" + ? '{"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100}' + : kind === "prewarm_page_cache" + ? '{"table_version":42,"executors_targeted":2,"executors_completed":2}' + : "null"; + return `{"job_id":"bounded-job","job_type":"${kind}","job_state":"${done ? "DONE" : "IN_PROGRESS"}","result":${done ? result : "null"}}`; + } + + test.each(["compact", "prewarm_page_cache", "create_index"])( + "%s stops polling at timeout, resumes, and reopens", + async (kind) => { + let done = false; + let describes = 0; + const progress: JobProgress[] = []; + await withMockDatabase( + (request, res) => { + expect(request.url).toBe("/v1/jobs/describe"); + describes++; + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response(kind, done)); + }, + async (db) => { + const fallback = setTimeout(() => { + done = true; + }, 1000); + try { + const job = await db.openJob("bounded-job"); + await expect( + job.wait({ timeoutMs: 50, onProgress: (p) => progress.push(p) }), + ).rejects.toThrow(/bounded-job.*continues/); + expect(job.state).toBe("running"); + await new Promise((resolve) => setImmediate(resolve)); + const requestsAtTimeout = describes; + const updatesAtTimeout = progress.length; + await new Promise((resolve) => setTimeout(resolve, 350)); + expect(describes).toBe(requestsAtTimeout); + expect(progress).toHaveLength(updatesAtTimeout); + done = true; + const result = await job.wait({ + timeoutMs: 1000, + onProgress: (p) => progress.push(p), + }); + await new Promise((resolve) => setImmediate(resolve)); + expect(progress.some((p) => p.state === "finished")).toBe(true); + expect(job.state).toBe("finished"); + expect(result).toEqual( + kind === "compact" + ? expect.objectContaining({ rowsSucceeded: 12 }) + : kind === "prewarm_page_cache" + ? expect.objectContaining({ tableVersion: 42 }) + : undefined, + ); + // Existing callback-only and argument-free calls remain supported. + expect(await job.wait((p) => progress.push(p))).toEqual(result); + expect(await job.wait()).toEqual(result); + const reopened = await db.openJob("bounded-job"); + expect(await reopened.wait({ timeoutMs: 1000 })).toEqual(result); + } finally { + clearTimeout(fallback); + } + }, + ); + }, + ); + + it("bounds a pending HTTP response and permits a later wait", async () => { + let slow = false; + let requests = 0; + await withMockDatabase( + (request, res) => { + expect(request.url).toBe("/v1/jobs/describe"); + requests++; + const send = () => { + if (!res.destroyed) { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response("prewarm_page_cache", slow)); + } + }; + if (slow) setTimeout(send, 300); + else send(); + }, + async (db) => { + const job = await db.openJob("bounded-job"); + slow = true; + await expect(job.wait({ timeoutMs: 50 })).rejects.toThrow("continues"); + expect(job.state).toBe("running"); + const stoppedAt = requests; + await new Promise((resolve) => setTimeout(resolve, 350)); + expect(requests).toBe(stoppedAt); + const result = await job.wait({ timeoutMs: 1000 }); + expect(result).toEqual(expect.objectContaining({ tableVersion: 42 })); + }, + ); + }); + + it("accepts zero timeout and validates options before polling", async () => { + let requests = 0; + let done = false; + await withMockDatabase( + (_request, res) => { + requests++; + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(response("compact", done)); + }, + async (db) => { + const fallback = setTimeout(() => { + done = true; + }, 1000); + try { + const job = await db.openJob("bounded-job"); + for (const timeoutMs of [ + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER + 1, + "10", + true, + ]) { + await expect( + job.wait({ timeoutMs: timeoutMs as number }), + ).rejects.toThrow("nonnegative safe integer"); + } + await expect(job.wait({ timeout: 10 } as never)).rejects.toThrow( + "Unknown job wait option", + ); + await expect(job.wait({ onProgress: 7 } as never)).rejects.toThrow( + "onProgress must be a function", + ); + await expect(job.wait(10 as never)).rejects.toThrow("options object"); + expect(requests).toBe(1); + await expect(job.wait({ timeoutMs: 0 })).rejects.toThrow("Timeout"); + } finally { + clearTimeout(fallback); + } + }, + ); + }); + + test.each(["FAILED", "CANCELLED"])( + "preserves a %s outcome when a timeout is configured", + async (state) => { + await withMockDatabase( + (_request, res) => { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end( + `{"job_id":"bounded-job","job_type":"compact","job_state":"${state}"}`, + ); + }, + async (db) => { + const job = await db.openJob("bounded-job"); + await expect(job.wait({ timeoutMs: 1000 })).rejects.toThrow( + state === "FAILED" ? /failed/i : /cancelled/i, + ); + }, + ); + }, + ); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 99c58a8c9..7a103d2c9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4678,15 +4678,94 @@ describe.each(arrowVersions)( ]; const table = await db.createTable("prewarm_data_test", data); - // prewarmData is only supported in LanceDB Enterprise. 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 in LanceDB Enterprise", + "only supported on remote tables", ); await expect(table.prewarmData(["text"])).rejects.toThrow( - "prewarm_data is currently only supported in LanceDB Enterprise", + "only supported on remote tables", ); + await expect( + table.prewarmData({ + columns: ["text"], + filter: "text = 'alpha'", + concurrency: 2, + }), + ).rejects.toThrow("only supported on remote tables"); + }); + + test("prewarmData preserves argument forms and returns after submission", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_submission", [{ id: 1 }]); + const wait = jest.fn(); + const submit = jest + .spyOn(table, "prewarmDataAsync") + .mockResolvedValue({ wait } as unknown as Awaited< + ReturnType + >); + const options = { columns: ["id"], filter: "id > 0", concurrency: 2 }; + try { + await expect(table.prewarmData(options)).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith(options); + await expect(table.prewarmData(["id"])).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith({ columns: ["id"] }); + await expect(table.prewarmData([])).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith({ columns: [] }); + await expect(table.prewarmData()).resolves.toBeUndefined(); + expect(submit).toHaveBeenLastCalledWith(undefined); + expect(wait).not.toHaveBeenCalled(); + } finally { + submit.mockRestore(); + } + }); + + test("prewarmData validates options before submission", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_options", [{ id: 1 }]); + await expect( + table.prewarmData({ unsupported: 1 } as never), + ).rejects.toThrow("Unsupported data prewarm option: unsupported"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 4294967296, + ]) { + await expect(table.prewarmData({ concurrency })).rejects.toThrow( + "concurrency must be an integer", + ); + } + }); + + test("prewarmDataAsync validates options and rejects local tables", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("prewarm_job", [{ id: 1 }]); + await expect(table.prewarmDataAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.prewarmDataAsync({ + columns: ["id"], + filter: "id > 0", + concurrency: 2, + }), + ).rejects.toThrow("only supported on remote tables"); + await expect( + table.prewarmDataAsync({ unsupported: 1 } as never), + ).rejects.toThrow("Unsupported data prewarm option: unsupported"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 4294967296, + ]) { + await expect(table.prewarmDataAsync({ concurrency })).rejects.toThrow( + "concurrency must be an integer", + ); + } }); test("full text index on list", async () => { @@ -5791,3 +5870,19 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([10, 2]); }); }); + +describe("durable compaction validation", () => { + test("rejects local tables and unknown options", async () => { + const db = await connect(`memory://compaction-job-${Date.now()}`); + const table = await db.createTable("test", [{ id: 1 }]); + await expect(table.compactAsync()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.compactAsync({ unrecognizedLimit: 1 } as never), + ).rejects.toThrow("Unsupported compaction option"); + await expect( + table.compactAsync({ targetRowsPerFragment: 0 }), + ).rejects.toThrow("safe integer"); + }); +}); diff --git a/nodejs/lancedb/compaction.ts b/nodejs/lancedb/compaction.ts new file mode 100644 index 000000000..3aaf3907c --- /dev/null +++ b/nodejs/lancedb/compaction.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Actual committed outcome of one remote compaction job. */ +export interface CompactionResult { + /** A bounded run left eligible work for another invocation. */ + moreWork: boolean; + /** Some planned groups were not committed. */ + partialCommit: boolean; + /** Live source rows in committed rewrite groups. */ + rowsSucceeded: number; + /** Planned live rows not committed by this job. */ + rowsFailed: number; + /** Percentage of planned live rows committed, from 0 to 100. */ + completionPercentage: number; + /** Files added, including deletion files; null if an older worker omitted it. */ + filesAdded: number | null; + /** Files removed, including deletion files; null if an older worker omitted it. */ + filesRemoved: number | null; + /** Fragments added by committed rewrites; null if an older worker omitted it. */ + fragmentsAdded: number | null; + /** Fragments removed by committed rewrites; null if an older worker omitted it. */ + fragmentsRemoved: number | null; +} + +/** @internal */ +export function decodeCompactionResult(value: unknown): CompactionResult { + // The Rust typed-job decoder validates the wire payload before it reaches JS. + const result = value as Record; + return { + moreWork: result.more_work as boolean, + partialCommit: result.partial_commit as boolean, + rowsSucceeded: result.rows_succeeded as number, + rowsFailed: result.rows_failed as number, + completionPercentage: result.completion_percentage as number, + filesAdded: (result.files_added as number | null) ?? null, + filesRemoved: (result.files_removed as number | null) ?? null, + fragmentsAdded: (result.fragments_added as number | null) ?? null, + fragmentsRemoved: (result.fragments_removed as number | null) ?? null, + }; +} diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 9c83d833f..ce71c4e89 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -583,7 +583,7 @@ export abstract class Connection { * result, failure and event history, so there is no separate * connection-level call for any of them. */ - abstract openJob(jobId: string): Promise; + abstract openJob(jobId: string): Promise>; /** * Iterate lazily over server-side jobs across the database's tables. @@ -1017,8 +1017,8 @@ export class LocalConnection extends Connection { ); } - async openJob(jobId: string): Promise { - return new Job(await this.inner.openJob(jobId)); + async openJob(jobId: string): Promise> { + return new Job(await this.inner.openJob(jobId)); } listJobs(options: ListingOptions = {}): Listing { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index a6bcd68f5..3f0aed61f 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -118,7 +118,7 @@ export { Job, JobEventsOptions, } from "./job"; -export type { JobProgress, JobProgressCallback } from "./job"; +export type { JobProgress, JobProgressCallback, JobWaitOptions } from "./job"; export { AutoQuery, @@ -175,6 +175,7 @@ export { UpdateOptions, OptimizeOptions, CompactionOptions, + PrewarmDataOptions, Version, WriteProgress, FtsToken, @@ -664,3 +665,7 @@ export { } from "./catalog"; export { Listing, ListingOptions } from "./listing"; + +export type { CompactionResult } from "./compaction"; + +export type { PrewarmDataResult } from "./prewarm"; diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts index f38d8d7fa..40c27365e 100644 --- a/nodejs/lancedb/job.ts +++ b/nodejs/lancedb/job.ts @@ -2,7 +2,9 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; +import { decodeCompactionResult } from "./compaction"; import { JobFailureInfo, Job as NativeJob } from "./native"; +import { decodePrewarmDataResult } from "./prewarm"; /** Which of a job's events {@link Job.events} returns. */ export interface JobEventsOptions { @@ -39,6 +41,31 @@ export interface JobProgress { rows_remaining?: number | null; // biome-ignore lint/style/useNamingConvention: server wire format rows_failed?: number | null; + /** Maintenance work observations; rewritten rows are not committed rows. */ + // biome-ignore lint/style/useNamingConvention: server wire format + groups_planned?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + groups_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + rows_rewritten?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_targeted?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_partial?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_active?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + executors_failed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + fragments_selected?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + ranges_completed?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + ranges_planned?: number | null; + // biome-ignore lint/style/useNamingConvention: server wire format + bytes_read?: number | null; /** Execution identity and sample time used for client-side ETA derivation. */ // biome-ignore lint/style/useNamingConvention: server wire format execution_epoch?: number | null; @@ -54,6 +81,18 @@ export interface JobProgress { /** Callback for progress snapshots observed while waiting for a job. */ export type JobProgressCallback = (progress: JobProgress) => void; +/** Client-side controls for waiting without cancelling the underlying job. */ +export interface JobWaitOptions { + /** + * Maximum wait in milliseconds, including status requests and polling backoff. + * Must be a nonnegative safe integer. Omit to wait indefinitely; zero allows + * only an immediately ready result. + */ + timeoutMs?: number; + /** Observe progress using the same poller that waits for completion. */ + onProgress?: JobProgressCallback; +} + /** * A handle to an operation that may still be running. * @@ -71,11 +110,20 @@ export type JobProgressCallback = (progress: JobProgress) => void; * * @hideconstructor */ -export class Job { +export class Job { private readonly inner: NativeJob; - constructor(inner: NativeJob) { + private readonly resultDecoder?: (value: unknown) => T; + + constructor(inner: NativeJob, resultDecoder?: (value: unknown) => T) { this.inner = inner; + this.resultDecoder = + resultDecoder ?? + (inner.jobType === "prewarm_page_cache" + ? (decodePrewarmDataResult as (value: unknown) => T) + : inner.jobType === "compact" + ? (decodeCompactionResult as (value: unknown) => T) + : undefined); } /** @@ -161,18 +209,64 @@ export class Job { * synchronous observer: its return value is ignored and not awaited. If it * throws, the error is logged with `console.warn` and waiting continues; a * callback exception does not reject `wait`. + * + * Pass an options object to set a client-side timeout. Expiry rejects with an + * error and stops this wait, including pending status requests and backoff. + * The operation continues; use the same handle to wait again. Registry jobs + * can also be reopened with `Connection.openJob`; query IDs cannot. + * + * @example + * ```ts + * const result = await job.wait({ timeoutMs: 60_000, onProgress: console.log }); + * ``` */ - async wait(progressCallback?: JobProgressCallback): Promise { - if (progressCallback === undefined) { - return this.inner.wait(); + async wait( + optionsOrProgress?: JobWaitOptions | JobProgressCallback, + ): Promise { + const options: JobWaitOptions = + typeof optionsOrProgress === "function" + ? { onProgress: optionsOrProgress } + : (optionsOrProgress ?? {}); + if (typeof options !== "object" || Array.isArray(options)) { + throw new TypeError( + "wait expects an options object or a progress callback", + ); } - return this.inner.wait((progress) => { - try { - progressCallback(this.enrichProgress(progress)); - } catch (error) { - console.warn("Job progress callback threw:", error); + for (const key of Object.keys(options)) { + if (key !== "timeoutMs" && key !== "onProgress") { + throw new TypeError(`Unknown job wait option: ${key}`); } - }); + } + const { timeoutMs, onProgress: progressCallback } = options; + if ( + timeoutMs !== undefined && + (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) + ) { + throw new RangeError("timeoutMs must be a nonnegative safe integer"); + } + if ( + progressCallback !== undefined && + typeof progressCallback !== "function" + ) { + throw new TypeError("onProgress must be a function"); + } + const callback = + progressCallback === undefined + ? undefined + : (progress: Record) => { + try { + progressCallback(this.enrichProgress(progress)); + } catch (error) { + console.warn("Job progress callback threw:", error); + } + }; + if (this.resultDecoder !== undefined) { + return this.resultDecoder( + await this.inner.waitResult(callback, timeoutMs), + ); + } + await this.inner.wait(callback, timeoutMs); + return undefined as T; } /** Request cancellation. Cancelling a finished operation is a no-op. */ diff --git a/nodejs/lancedb/prewarm.ts b/nodejs/lancedb/prewarm.ts new file mode 100644 index 000000000..942e0a19f --- /dev/null +++ b/nodejs/lancedb/prewarm.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +/** Reported executor work for a pinned snapshot; unavailable measurements stay null. */ +export interface PrewarmDataResult { + /** The source snapshot captured by submission. */ + tableVersion: number; + /** Reported executors targeted, or null when unavailable. */ + executorsTargeted: number | null; + /** Executors that finished successfully or partially, or null when unavailable. */ + executorsCompleted: number | null; + /** Subset of completed executors reporting partial warming, or null when unavailable. */ + executorsPartial: number | null; + /** Reported fragments selected, or null when unavailable. */ + fragmentsSelected: number | null; + /** Reported ranges completed, or null when unavailable. */ + rangesCompleted: number | null; + /** Reported bytes read, or null when unavailable. */ + bytesRead: number | null; +} + +/** @internal */ +export function decodePrewarmDataResult(value: unknown): PrewarmDataResult { + // Rust validates the typed wire result before handing it to JavaScript. + const result = value as Record; + return { + tableVersion: result.table_version as number, + executorsTargeted: result.executors_targeted ?? null, + executorsCompleted: result.executors_completed ?? null, + executorsPartial: result.executors_partial ?? null, + fragmentsSelected: result.fragments_selected ?? null, + rangesCompleted: result.ranges_completed ?? null, + bytesRead: result.bytes_read ?? null, + }; +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index f949bd00a..2fff63108 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1,6 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import { CompactionResult, decodeCompactionResult } from "./compaction"; +import { PrewarmDataResult, decodePrewarmDataResult } from "./prewarm"; + import { Table as ArrowTable, Data, @@ -165,6 +168,16 @@ export interface UpdateOptions { where: string; } +/** Settings for submitting a durable remote data-cache prewarm job. */ +export interface PrewarmDataOptions { + /** Lance field paths to warm; omitted or empty means every column. */ + columns?: string[]; + /** A single SQL predicate for conservative metadata pruning. */ + filter?: string; + /** Positive per-executor concurrency, at most 4294967295. */ + concurrency?: number; +} + /** Per-invocation compaction settings. Values must be safe integers. */ export interface CompactionOptions { /** Positive target rows per output fragment; also affects candidate selection. */ @@ -562,22 +575,58 @@ export abstract class Table { /** * Prewarm one or more columns of data in the table. * - * @param columns The columns to prewarm. If undefined, all columns are prewarmed. - * * This will load the column data into the page cache so that future queries that * read those columns avoid the initial cold-start latency. This call initiates * prewarming and returns once the request is accepted; the warming itself may - * continue in the background. Calling it on already-prewarmed columns is a - * no-op on the server. + * continue in the background. Submission uses SQL PREWARM and needs Flight + * SQL connectivity. Use {@link prewarmDataAsync} to retain the job handle. * * 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 in LanceDB Enterprise. + * + * @param options Columns, a metadata-pruning filter, and per-executor concurrency. + * Omitted or empty columns warm every column. + * + * @example + * await table.prewarmData({ + * columns: ["payload"], filter: "quality > 0.7", concurrency: 4, + * }); + */ + abstract prewarmData(options?: PrewarmDataOptions): Promise; + + /** + * Submit data prewarm using the columns-array form and return after acceptance. + * @param columns Columns to warm; omitted or empty means every column. */ abstract prewarmData(columns?: string[]): Promise; + /** + * Submit data prewarm through SQL and return its durable warming-job handle. + * + * The table handle supplies the branch and namespace. Requires a compatible + * SQL PREWARM server and Flight SQL connectivity. Standard authorization + * requires table Select and database/namespace Usage. Status/wait use generic + * HTTP job APIs; events and cancellation retain their own privileges. + * No REST fallback or option-dropping retry is performed. Historical-version + * handles are unsupported; call `checkoutLatest()` first. + * + * Submission returns after acceptance. Use `job.wait()` for completion, or + * save `job.id` and reopen it with `db.openJob(id)`. A timeout does not cancel + * the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. + * + * @example + * const job = await table.prewarmDataAsync({ + * columns: ["video"], filter: "quality > 0.7", concurrency: 4, + * }); + * await job.wait(); + */ + abstract prewarmDataAsync( + options?: PrewarmDataOptions, + ): Promise>; + /** * Waits for asynchronous indexing to complete on the table. * @@ -1209,6 +1258,28 @@ export abstract class Table { * out state and the read_consistency_interval, if any, will apply. */ abstract restore(): Promise; + /** + * Submit remote compaction and return its durable job after acceptance. + * + * Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires + * a compatible remote server and table Ownership plus parent Usage. Local and + * historical-version handles are unsupported. Existing optimize() behavior is unchanged. + * Waiting tracks the rewrite itself and returns actual row/file statistics. + * Missing result payloads are errors; older workers can omit file counts. + * Status, progress, events and cancellation reuse the generic HTTP job APIs. + * Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + * + * @example + * const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); + * const result = await job.wait(); + * console.log(result.rowsSucceeded, result.fragmentsRemoved); + */ + async compactAsync( + _options?: CompactionOptions, + ): Promise> { + throw new Error("compaction jobs are only supported on remote tables"); + } + /** * Optimize the on-disk data and indices for better performance. * @@ -1505,8 +1576,30 @@ export class LocalTable extends Table { await this.inner.prewarmIndex(name); } - async prewarmData(columns?: string[]): Promise { - await this.inner.prewarmData(columns); + async prewarmData(options?: PrewarmDataOptions): Promise; + async prewarmData(columns?: string[]): Promise; + async prewarmData( + columnsOrOptions?: string[] | PrewarmDataOptions, + ): Promise { + await this.prewarmDataAsync( + Array.isArray(columnsOrOptions) + ? { columns: columnsOrOptions } + : columnsOrOptions, + ); + } + + async prewarmDataAsync( + options?: PrewarmDataOptions, + ): Promise> { + for (const key of Object.keys(options ?? {})) { + if (!["columns", "filter", "concurrency"].includes(key)) { + throw new Error(`Unsupported data prewarm option: ${key}`); + } + } + return new Job( + await this.inner.prewarmDataAsync(options), + decodePrewarmDataResult, + ); } async waitForIndex( @@ -1884,20 +1977,18 @@ export class LocalTable extends Table { return this.inner.currentBranch() ?? null; } + async compactAsync( + options?: CompactionOptions, + ): Promise> { + validateCompactionOptions(options); + return new Job( + await this.inner.compactAsync(options), + decodeCompactionResult, + ); + } + async optimize(options?: Partial): Promise { - // JavaScript callers can supply extra keys that TypeScript would reject. - // Refuse them before the native binding can silently discard a work limit. - const supported = new Set([ - "targetRowsPerFragment", - "maxSourceRows", - "ioBufferSize", - "batchSize", - ]); - for (const key of Object.keys(options?.compactionOptions ?? {})) { - if (!supported.has(key)) { - throw new Error(`Unsupported compaction option: ${key}`); - } - } + validateCompactionOptions(options?.compactionOptions); return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, @@ -2197,3 +2288,19 @@ function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] { return BigInt(id); }); } + +function validateCompactionOptions(options?: CompactionOptions): void { + // JavaScript callers can supply extra keys that TypeScript would reject. + // Refuse them before the native binding can silently discard a work limit. + const supported = new Set([ + "targetRowsPerFragment", + "maxSourceRows", + "ioBufferSize", + "batchSize", + ]); + for (const key of Object.keys(options ?? {})) { + if (!supported.has(key)) { + throw new Error(`Unsupported compaction option: ${key}`); + } + } +} diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 914f9e4c9..fa1c289b1 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -567,7 +567,19 @@ impl Connection { #[napi(catch_unwind)] pub async fn open_job(&self, job_id: String) -> napi::Result { let job = self.get_inner()?.open_job(&job_id).await.default_error()?; - Ok(crate::job::Job::new(job)) + if job.job_type().as_deref() == Some("prewarm_page_cache") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else if job.job_type().as_deref() == Some("compact") { + Ok(crate::job::Job::new_typed( + job.into_typed::() + .default_error()?, + )) + } else { + Ok(crate::job::Job::new(job)) + } } /// List server-side jobs across the database's tables. diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 09b245f97..15e95caad 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use std::sync::Arc; +use std::{sync::Arc, time::Duration}; use arrow_array::RecordBatch; -use lancedb::job::JobEventsRequest; +use lancedb::job::{JobEventsRequest, JobWaitOptions}; use napi::bindgen_prelude::Buffer; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; @@ -17,7 +17,7 @@ type JobProgressFn = /// A handle to an operation that may still be running. #[napi] pub struct Job { - inner: Arc, + inner: Arc, String>>>, } impl Job { @@ -26,7 +26,19 @@ impl Job { T: Clone + Send + Sync + 'static, { Self { - inner: Arc::new(inner.map(|_| ())), + inner: Arc::new(inner.map(|_| Ok(None))), + } + } + pub(crate) fn new_typed(inner: lancedb::Job) -> Self + where + T: Clone + serde::Serialize + Send + Sync + 'static, + { + Self { + inner: Arc::new(inner.map(|result| { + serde_json::to_value(result) + .map(Some) + .map_err(|error| format!("failed to serialize typed job result: {error}")) + })), } } } @@ -67,22 +79,56 @@ impl Job { /// backend poller without starting another polling loop. #[napi( catch_unwind, - ts_args_type = "progressCallback?: (progress: Record) => void" + ts_args_type = "progressCallback?: (progress: Record) => void, timeoutMs?: number" )] - pub async fn wait(&self, progress_callback: Option) -> napi::Result<()> { - if let Some(progress_callback) = progress_callback { - self.inner - .wait_with_progress(move |description| { - progress_callback.call( - description.progress_snapshot(), - ThreadsafeFunctionCallMode::NonBlocking, - ); - }) - .await - .default_error() - } else { - self.inner.wait().await.default_error() + pub async fn wait( + &self, + progress_callback: Option, + timeout_ms: Option, + ) -> napi::Result<()> { + self.wait_result(progress_callback, timeout_ms) + .await + .map(|_| ()) + } + + /// The typed terminal value used by result-returning SDK operations. + #[napi( + catch_unwind, + ts_args_type = "progressCallback?: (progress: Record) => void, timeoutMs?: number" + )] + pub async fn wait_result( + &self, + progress_callback: Option, + timeout_ms: Option, + ) -> napi::Result> { + let mut options = JobWaitOptions::new(); + if let Some(timeout_ms) = timeout_ms { + const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + if !timeout_ms.is_finite() + || timeout_ms.fract() != 0.0 + || !(0.0..=MAX_SAFE_INTEGER).contains(&timeout_ms) + { + return Err(napi::Error::new( + napi::Status::InvalidArg, + "timeoutMs must be a nonnegative safe integer", + )); + } + options = options.timeout(Duration::from_millis(timeout_ms as u64)); } + if let Some(progress_callback) = progress_callback { + options = options.progress(move |description| { + progress_callback.call( + description.progress_snapshot(), + ThreadsafeFunctionCallMode::NonBlocking, + ); + }); + } + let result = self + .inner + .wait_with_options(options) + .await + .default_error()?; + result.map_err(napi::Error::from_reason) } /// Request cancellation. Cancelling a finished operation is a no-op. diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index c9e03b2a3..3a9b8be72 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -27,6 +27,32 @@ use crate::merge::NativeMergeInsertBuilder; use crate::query::{Query, TakeQuery, VectorQuery}; use crate::util::schema_to_buffer; +/// Settings for durable data-cache prewarm submission. +#[napi(object)] +pub struct PrewarmDataOptions { + pub columns: Option>, + pub filter: Option, + pub concurrency: Option, +} + +impl PrewarmDataOptions { + fn into_options(self) -> napi::Result { + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default()); + options.filter = self.filter; + if let Some(value) = self.concurrency { + if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64 + { + return Err(napi::Error::from_reason( + "concurrency must be an integer between 1 and 4294967295", + )); + } + options.concurrency = Some(value as u32); + } + Ok(options) + } +} + /// Per-invocation file-compaction settings. All numbers must be safe integers. #[napi(object)] pub struct CompactionOptions { @@ -298,6 +324,23 @@ impl Table { .default_error() } + #[napi(catch_unwind)] + pub async fn prewarm_data_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(PrewarmDataOptions::into_options) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .prewarm_data_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + #[napi(catch_unwind)] pub async fn wait_for_index(&self, index_names: Vec, timeout_s: i64) -> Result<()> { let timeout = std::time::Duration::from_secs(timeout_s.try_into().unwrap()); @@ -894,6 +937,23 @@ impl Table { Ok(self.inner_ref()?.current_branch()) } + #[napi(catch_unwind)] + pub async fn compact_async( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(); + let job = self + .inner_ref()? + .compact_async(options) + .await + .default_error()?; + Ok(crate::job::Job::new_typed(job)) + } + #[napi(catch_unwind)] pub async fn optimize( &self, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 19454790a..b4b97ff38 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -645,6 +645,13 @@ class Table: async def restore(self, version: Optional[Union[int, str]] = None): ... async def prewarm_index(self, index_name: str) -> None: ... async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ... + async def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job: ... async def list_indices(self) -> list[IndexConfig]: ... async def tokenize( self, @@ -787,6 +794,9 @@ class Table: async def update_field_metadata( self, updates: list[dict[str, Any]] ) -> UpdateFieldMetadataResult: ... + async def compact_async( + self, compaction_options: Optional[Dict[str, Any]] = None + ) -> Job: ... async def optimize( self, *, diff --git a/python/python/lancedb/compaction.py b/python/python/lancedb/compaction.py new file mode 100644 index 000000000..823b0a281 --- /dev/null +++ b/python/python/lancedb/compaction.py @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Results of durable remote compaction jobs.""" + +from dataclasses import dataclass, fields +import json +from typing import Optional + + +@dataclass(frozen=True) +class CompactionResult: + """Actual committed outcome of one remote compaction invocation. + + ``rows_failed`` counts planned live rows that were not committed, including + partial progress. ``more_work`` means a bounded run left eligible work for + another invocation. File/fragment counts are None if an older worker did + not report them; they are never inferred from unrelated table versions. + File counts include deletion files as well as data files. + """ + + partial_commit: bool + rows_succeeded: int + rows_failed: int + completion_percentage: float + more_work: bool = False + files_added: Optional[int] = None + files_removed: Optional[int] = None + fragments_added: Optional[int] = None + fragments_removed: Optional[int] = None + + @classmethod + def from_json(cls, raw: str) -> "CompactionResult": + """Decode a server result, ignoring additive fields from newer servers.""" + value = json.loads(raw) + names = {field.name for field in fields(cls)} + return cls(**{key: item for key, item in value.items() if key in names}) diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index dab6d5903..9191bf497 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -21,6 +21,8 @@ from lancedb.background_loop import LOOP from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url from .functions import RefreshColumnResult +from .compaction import CompactionResult +from .prewarm import PrewarmDataResult from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -148,6 +150,19 @@ def _job_progress_callback(progress, enrich): planned = snapshot.get("rows_planned") remaining = snapshot.get("rows_remaining") computed = snapshot.get("rows_computed") + job_type = snapshot.get("job_type") + maintenance = job_type in ("compact", "prewarm_page_cache") + if job_type == "compact": + computed = snapshot.get("rows_rewritten") + remaining = None + if hasattr(progress, "unit"): + progress.unit = " rows" + elif job_type == "prewarm_page_cache": + planned = snapshot.get("executors_targeted") + computed = snapshot.get("executors_completed") + remaining = None + if hasattr(progress, "unit"): + progress.unit = " executors" if isinstance(planned, int): epoch = snapshot.get("execution_epoch") reset = (isinstance(last_planned, int) and planned < last_planned) or ( @@ -173,7 +188,7 @@ def _job_progress_callback(progress, enrich): if completed is not None: if isinstance(planned, int): completed = min(completed, planned) - if first_snapshot and completed < last_rows: + if (first_snapshot or maintenance) and completed < last_rows: # The server may have started a new execution while a # caller-owned bar retained its old position. last_rows = completed @@ -287,6 +302,10 @@ class AsyncJob(Generic[T]): a caller-owned bar with the server's current completed rows and total; later observations in a stable execution epoch use a high-water mark. A new execution epoch or smaller plan resets the bar to that plan. + Maintenance jobs display reported rewritten rows or completed executors; + revised maintenance counters replace earlier retry observations. Totals + remain unknown until the server reports them. Rewritten rows describe + execution work, not committed compaction results. ``False`` preserves the original wait behavior. For SQL-backed Function registration, progress shows the query's @@ -841,4 +860,8 @@ def _typed_job( def _opened_job(inner: "_lancedb.Job") -> AsyncJob: if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"): return _typed_job(inner, RefreshColumnResult.from_json) + if inner.job_type == "prewarm_page_cache": + return _typed_job(inner, PrewarmDataResult.from_json) + if inner.job_type == "compact": + return _typed_job(inner, CompactionResult.from_json) return AsyncJob(inner) diff --git a/python/python/lancedb/prewarm.py b/python/python/lancedb/prewarm.py new file mode 100644 index 000000000..c21bd6cfd --- /dev/null +++ b/python/python/lancedb/prewarm.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Results of remote data-cache prewarm jobs.""" + +from dataclasses import dataclass, fields +import json +from typing import Optional + + +@dataclass(frozen=True) +class PrewarmDataResult: + """Reported executor work for a pinned snapshot, not guaranteed cache residency. + + Counts omitted by older workers remain None. I/O counts are unknown when + executors do not report them. Partial completions are a subset of completed + executors and may reflect cache pressure. + """ + + table_version: int + executors_targeted: Optional[int] = None + executors_completed: Optional[int] = None + executors_partial: Optional[int] = None + fragments_selected: Optional[int] = None + ranges_completed: Optional[int] = None + bytes_read: Optional[int] = None + + @classmethod + def from_json(cls, raw: str) -> "PrewarmDataResult": + value = json.loads(raw) + names = {field.name for field in fields(cls)} + return cls(**{key: item for key, item in value.items() if key in names}) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 19e7ff454..ac936ebd9 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -48,6 +48,7 @@ from lancedb.index import ( Bitmap, LabelList, ) +from lancedb.prewarm import PrewarmDataResult from lancedb.job import Job from lancedb.functions import ( FunctionProvenance, @@ -78,6 +79,7 @@ from ..table import ( BlobMode, Branches, CompactionOptions, + CompactionResult, IndexStatistics, Query, Table, @@ -1105,6 +1107,13 @@ class RemoteTable(Table): ) pass + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + return Job( + LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + ) + def optimize( self, *, @@ -1433,7 +1442,13 @@ class RemoteTable(Table): """ return LOOP.run(self._table.prewarm_index(name)) - def prewarm_data(self, columns: Optional[List[str]] = None) -> None: + def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: """Prewarm data for the table. This is a hint to the database that the given columns will be accessed @@ -1441,7 +1456,8 @@ class RemoteTable(Table): Currently only supported in LanceDB Enterprise. This call initiates prewarming and returns once the request is accepted. - It is idempotent and safe to call from multiple clients concurrently. + Uses SQL PREWARM and requires Flight SQL connectivity. To track the + durable warming job, use ``prewarm_data_async()``. This operation has a large upfront cost but can speed up future queries that need to fetch the given columns. Large columns such as embeddings @@ -1452,8 +1468,34 @@ class RemoteTable(Table): ---------- columns: list of str, optional The columns to prewarm. If None, all columns are prewarmed. + filter: str, optional + A single SQL predicate for conservative metadata pruning. + concurrency: int, optional + Positive per-executor warming concurrency; omitted uses the server default. + + Examples + -------- + >>> table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) """ - return LOOP.run(self._table.prewarm_data(columns)) + return LOOP.run( + self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + ) + + def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job[PrewarmDataResult]: + return Job( + LOOP.run( + self._table.prewarm_data_async( + columns, filter=filter, concurrency=concurrency + ) + ) + ) def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 8d996d32e..8c3d30170 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -48,7 +48,9 @@ from ._blob import ( from .types import BlobMode from lancedb.arrow import peek_reader from lancedb.background_loop import LOOP, embedding_executor +from lancedb.prewarm import PrewarmDataResult from lancedb.job import AsyncJob, Job, _typed_job +from lancedb.compaction import CompactionResult from .dependencies import ( _check_for_hugging_face, _check_for_lance, @@ -2011,6 +2013,69 @@ class Table(ABC): """ raise NotImplementedError("create_index is not supported for this table type") + def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: + """Submit remote data prewarm and return after acceptance. + + Omitted or empty ``columns`` warm all fields. ``filter`` is a single + SQL predicate for conservative metadata pruning; ``concurrency`` is + a positive per-executor integer, or omitted for the server default. + The table handle supplies the namespace and branch. Requires a + compatible SQL PREWARM server and Flight SQL connectivity. + + The operation continues in the background. Use + [prewarm_data_async][lancedb.table.Table.prewarm_data_async] to retain + the job handle and wait for completion. + + Examples + -------- + >>> table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) + """ + self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + + def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job[PrewarmDataResult]: + """Submit a remote data-cache prewarm and return its durable job. + + Requires a compatible SQL PREWARM server and Flight SQL connectivity. + The table handle supplies the branch and namespace. ``columns`` uses + Lance field paths; an omitted/empty list warms all columns. ``filter`` + is one SQL predicate for conservative metadata pruning, not a row scan. + ``concurrency`` is a positive per-executor integer. Historical-version + handles are unsupported; call ``checkout_latest()`` first. + + Submission requires table Select and database/namespace Usage under + Standard authorization. Status/wait use the generic HTTP job API; + events and cancellation have their own privileges. Unsupported servers + are not retried through REST or with settings removed. + + Returns once accepted. ``job.wait()`` waits for warming to finish and + returns [PrewarmDataResult][lancedb.prewarm.PrewarmDataResult]. + Save ``job.id`` to resume with ``db.open_job(id)``. A wait timeout does + not cancel the operation. After ``job.refresh()``, + ``job.spec["table_version"]`` identifies the pinned source version. + + Examples + -------- + >>> job = table.prewarm_data_async( # doctest: +SKIP + ... ["video"], filter="quality > 0.7", concurrency=4) + >>> job.wait() # doctest: +SKIP + """ + raise NotImplementedError( + "data prewarm jobs are only supported on remote tables" + ) + def create_index_async( self, column: str, @@ -3024,6 +3089,33 @@ class Table(ABC): compaction for you automatically. """ + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + """Submit remote compaction and return a durable job after acceptance. + + Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports + the four per-job settings in + [CompactionOptions][lancedb.table.CompactionOptions]. + Requires a compatible remote server, table Ownership and parent Usage. + Local and historical-version handles are unsupported. Existing + ``optimize()`` retains its return-on-submission behavior remotely. + + ``job.wait()`` waits for the actual rewrite and returns + [CompactionResult][lancedb.compaction.CompactionResult]. Partial/bounded + runs report uncommitted rows and ``more_work``; unknown file statistics + are None. Servers without a result payload raise an error rather than + returning fabricated zero statistics. Wait timeouts do not cancel work. + Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and + cancellation use generic HTTP job APIs and their existing permissions. + + >>> job = table.compact_async( # doctest: +SKIP + ... compaction_options={"target_rows_per_fragment": 1000}) + >>> result = job.wait() # doctest: +SKIP + >>> print(result.rows_succeeded) # doctest: +SKIP + """ + raise NotImplementedError("compaction jobs are only supported on remote tables") + @abstractmethod def optimize( self, @@ -4843,7 +4935,13 @@ class LanceTable(Table): """ return LOOP.run(self._table.prewarm_index(name)) - def prewarm_data(self, columns: Optional[List[str]] = None) -> None: + def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: """ Prewarm data for the table. @@ -4852,7 +4950,8 @@ class LanceTable(Table): Currently only supported in LanceDB Enterprise. This call initiates prewarming and returns once the request is accepted. - It is idempotent and safe to call from multiple clients concurrently. + Uses SQL PREWARM and requires Flight SQL connectivity. To track the + durable warming job, use ``prewarm_data_async()``. This operation has a large upfront cost but can speed up future queries that need to fetch the given columns. Large columns such as embeddings @@ -4863,8 +4962,34 @@ class LanceTable(Table): ---------- columns: list of str, optional The columns to prewarm. If None, all columns are prewarmed. + filter: str, optional + A single SQL predicate for conservative metadata pruning. + concurrency: int, optional + Positive per-executor warming concurrency; omitted uses the server default. + + Examples + -------- + >>> table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) """ - return LOOP.run(self._table.prewarm_data(columns)) + return LOOP.run( + self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + ) + + def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> Job[PrewarmDataResult]: + return Job( + LOOP.run( + self._table.prewarm_data_async( + columns, filter=filter, concurrency=concurrency + ) + ) + ) def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) @@ -5683,6 +5808,13 @@ class LanceTable(Table): self.checkout_latest() return stats + def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> Job[CompactionResult]: + return Job( + LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + ) + def optimize( self, *, @@ -7324,7 +7456,13 @@ class AsyncTable: """ await self._inner.prewarm_index(name) - async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: + async def prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> None: """ Prewarm data for the table. @@ -7333,7 +7471,8 @@ class AsyncTable: Currently only supported in LanceDB Enterprise. This call initiates prewarming and returns once the request is accepted. - It is idempotent and safe to call from multiple clients concurrently. + Uses SQL PREWARM and requires Flight SQL connectivity. To track the + durable warming job, use ``prewarm_data_async()``. This operation has a large upfront cost but can speed up future queries that need to fetch the given columns. Large columns such as embeddings @@ -7344,8 +7483,43 @@ class AsyncTable: ---------- columns: list of str, optional The columns to prewarm. If None, all columns are prewarmed. + filter: str, optional + A single SQL predicate for conservative metadata pruning. + concurrency: int, optional + Positive per-executor warming concurrency; omitted uses the server default. + + Examples + -------- + >>> await table.prewarm_data( # doctest: +SKIP + ... ["payload"], filter="quality > 0.7", concurrency=4) """ - await self._inner.prewarm_data(columns) + await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + + async def prewarm_data_async( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> AsyncJob[PrewarmDataResult]: + """Submit data prewarm and return a durable handle after acceptance. + + See [Table.prewarm_data_async][lancedb.table.Table.prewarm_data_async] + for options, permissions, and compatibility. Awaiting this method does + not wait for warming; use ``await job.wait()`` for completion. + + Examples + -------- + >>> job = await table.prewarm_data_async( # doctest: +SKIP + ... ["video"], filter="quality > 0.7", concurrency=4) + >>> await job.wait() # doctest: +SKIP + """ + return _typed_job( + await self._inner.prewarm_data_async( + columns, filter=filter, concurrency=concurrency + ), + PrewarmDataResult.from_json, + ) async def wait_for_index( self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300) @@ -9273,6 +9447,19 @@ class AsyncTable: """The branch this table handle is scoped to, or ``None`` for ``main``.""" return self._inner.current_branch() + async def compact_async( + self, *, compaction_options: Optional[CompactionOptions] = None + ) -> AsyncJob[CompactionResult]: + """Submit remote compaction; await the returned job for actual results. + + See [Table.compact_async][lancedb.table.Table.compact_async] for options, + permissions, completion semantics and compatibility requirements. + """ + return _typed_job( + await self._inner.compact_async(compaction_options), + CompactionResult.from_json, + ) + async def optimize( self, *, diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index 8b06943da..f09581bff 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -11,11 +11,139 @@ import numpy as np import pyarrow as pa import pytest from lancedb import LanceDBConnection, function +from lancedb.compaction import CompactionResult from lancedb.index import FTS +from lancedb.prewarm import PrewarmDataResult # TODO: setup integ test mark and script +@pytest.fixture +def maintenance_connection_options(): + uri = os.environ.get("LANCEDB_URI") + if not uri: + pytest.skip( + "Set LANCEDB_URI to a server supporting SQL maintenance job results" + ) + assert uri.startswith("db://") + return { + "uri": uri, + "api_key": os.environ.get("LANCEDB_API_KEY"), + "region": os.environ.get("LANCEDB_REGION", "us-east-1"), + "host_override": os.environ.get("LANCEDB_HOST_OVERRIDE"), + "sql_host_override": os.environ.get("LANCEDB_SQL_HOST_OVERRIDE"), + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("operation", ["compact", "prewarm", "prewarm_legacy"]) +async def test_maintenance_job_result_and_reopen_against_server( + maintenance_connection_options, asynchronous, operation +): + """Exercise real SQL receipts, workers and HTTP job results with matching versions. + + Configure LANCEDB_URI, LANCEDB_API_KEY and the REST/Flight SQL endpoint + overrides for a writable database. Workers must publish maintenance results; + an unsupported server fails the contract rather than silently skipping it. + """ + if asynchronous: + connection = await lancedb.connect_async(**maintenance_connection_options) + else: + connection = lancedb.connect(**maintenance_connection_options) + + async def call(method, *args, **kwargs): + result = method(*args, **kwargs) + return await result if asynchronous else result + + name = f"maintenance_{uuid4().hex}" + created = False + expected = [{"id": i, "payload": i * 10} for i in range(16)] + timeout = timedelta(minutes=5) + try: + table = await call( + connection.create_table, name, pa.Table.from_pylist(expected[:4]) + ) + created = True + for start in (4, 8, 12): + await call(table.add, pa.Table.from_pylist(expected[start : start + 4])) + version = await table.version() if asynchronous else table.version + if operation == "compact": + job = await call( + table.compact_async, + compaction_options={ + "target_rows_per_fragment": 100, + "batch_size": 128, + "io_buffer_size": 0, + }, + ) + elif operation == "prewarm_legacy": + assert ( + await call( + table.prewarm_data, + ["payload"], + filter="id >= 8", + concurrency=2, + ) + is None + ) + reader = await call( + connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"' + ) + batches = await call(reader.read_all) + jobs = pa.Table.from_batches(batches) if asynchronous else batches + ids = [ + row["job_id"] + for row in jobs.to_pylist() + if row["job_type"] == "prewarm_page_cache" + ] + assert len(ids) == 1, jobs.to_pylist() + job = await call(connection.open_job, ids[0]) + else: + job = await call( + table.prewarm_data_async, + ["payload"], + filter="id >= 8", + concurrency=2, + ) + assert job.id + progress = [] + result = await call(job.wait, timeout=timeout, progress=progress.append) + assert any(snapshot["state"] == "finished" for snapshot in progress) + await call(job.refresh) + assert await call(job.status) == "finished" + if operation == "compact": + assert isinstance(result, CompactionResult) + assert job.job_type == "compact" + assert not result.partial_commit and result.rows_failed == 0 + assert result.completion_percentage == 100 + assert 0 <= result.rows_succeeded <= len(expected) + assert result.files_added is not None and result.files_removed is not None + else: + assert isinstance(result, PrewarmDataResult) + assert job.job_type == "prewarm_page_cache" + assert result.table_version == version == job.spec["table_version"] + assert job.spec["columns"] == ["payload"] + assert job.spec["concurrency"] == 2 + assert result.fragments_selected > 0 + assert result.executors_completed == result.executors_targeted + assert result.executors_partial == 0 + assert result.bytes_read is None and result.ranges_completed is None + reopened = await call(connection.open_job, job.id) + assert await call(reopened.wait, timeout=timeout) == result + query = table.query() if asynchronous else table.search() + actual = await call( + query.select(["id", "payload"]).limit(len(expected) + 1).to_arrow + ) + assert sorted(actual.to_pylist(), key=lambda row: row["id"]) == expected + finally: + try: + if created: + await call(connection.drop_table, name) + finally: + connection.close() + + @pytest.mark.skipif( not os.environ.get("LANCEDB_URI"), reason="Set LANCEDB_URI to a JSON FTS server" ) diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 59e2fc3a8..809105102 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -1072,3 +1072,95 @@ async def test_stack_propagates_errors_and_rejects_local_handles(sync): Job(None).stack("worker") else: await AsyncJob(None).stack("worker") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "kind,planned_key,completed_key,unit", + [ + ("compact", "rows_planned", "rows_rewritten", " rows"), + ( + "prewarm_page_cache", + "executors_targeted", + "executors_completed", + " executors", + ), + ], +) +async def test_maintenance_progress_bar_uses_operation_counters_and_handles_retry( + monkeypatch, kind, planned_key, completed_key, unit +): + tqdm_module = pytest.importorskip("tqdm.auto") + + class Bar: + total = None + n = 0 + unit = " rows" + closed = False + + def update(self, delta): + self.n += delta + + def close(self): + self.closed = True + + bar = Bar() + monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar) + + class MaintenanceJob: + id = "maintenance-job" + job_type = kind + + async def wait(self, progress): + progress({"job_type": kind, "phase": "planning"}) + assert bar.total is None + progress({"job_type": kind, planned_key: 4, completed_key: 2}) + assert bar.n == 2 + # Older responses can omit an epoch; revised observations still + # replace the previous attempt's displayed work. + progress({"job_type": kind, planned_key: 4, completed_key: 1}) + assert bar.n == 1 + progress({"job_type": kind, planned_key: 4, completed_key: 4}) + + assert await AsyncJob(MaintenanceJob()).wait(progress=True) is None + assert bar.n == 4 + assert bar.total == 4 + assert bar.unit == unit + assert bar.closed + + +@pytest.mark.asyncio +@pytest.mark.parametrize("known_empty", [False, True]) +async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals( + monkeypatch, known_empty +): + tqdm_module = pytest.importorskip("tqdm.auto") + + class Bar: + total = None + n = 0 + unit = " rows" + + def update(self, delta): + self.n += delta + + def close(self): + pass + + bar = Bar() + monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar) + + class PrewarmJob: + id = "prewarm-job" + job_type = "prewarm_page_cache" + + async def wait(self, progress): + snapshot = {"job_type": self.job_type, "phase": "succeeded"} + if known_empty: + snapshot.update(executors_targeted=0, executors_completed=0) + progress(snapshot) + + assert await AsyncJob(PrewarmJob()).wait(progress=True) is None + assert bar.n == 0 + assert bar.total == (0 if known_empty else None) + assert bar.unit == " executors" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 2cacc4716..eff207230 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -7408,10 +7408,10 @@ def _create_table_handler(request): @contextlib.contextmanager -def _mock_remote_sql_connection(flight_server): +def _mock_remote_sql_connection(flight_server, handler=_create_table_handler): """Connection arguments for mock REST and Flight SQL servers.""" with http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), make_mock_http_handler(_create_table_handler) + ("127.0.0.1", 0), make_mock_http_handler(handler) ) as rest_server: rest_port = rest_server.server_address[1] handle = start_server_thread(rest_server) @@ -8054,3 +8054,373 @@ def test_exact_function_retries_fail_before_writing_to_older_servers(): with pytest.raises(NotImplementedError, match="server does not support"): table.function_errors().summary() assert writes == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("mode", ["job", "columns", "filtered", "defaults"]) +async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mode): + flight = pytest.importorskip("pyarrow.flight") + polls = [] + + class PrewarmServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream( + pa.table( + { + "job_id": ["warming-job"], + "table_version": pa.array([42], pa.uint64()), + } + ) + ) + + def handler(request): + if request.path == "/v1/jobs/describe": + body = json.loads( + request.rfile.read(int(request.headers["Content-Length"])) + ) + assert body == {"job_id": "warming-job"} + polls.append(body) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "warming-job", + "job_type": "prewarm_page_cache", + "job_state": "DONE", + "creation_ms": 1, + "spec": {"table_version": 42}, + "result": { + "table_version": 42, + "executors_targeted": 2, + "executors_completed": 2, + "fragments_selected": 4, + }, + "operation_progress": { + "phase": "reading", + "executors_completed": 2, + "fragments_selected": 4, + }, + } + ).encode() + ) + else: + # No operation-specific REST prewarm endpoint is accepted. + _create_table_handler(request) + + server = PrewarmServer() + with _mock_remote_sql_connection(server, handler) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + if mode == "columns": + assert await table.prewarm_data(["payload"]) is None + elif mode == "filtered": + assert ( + await table.prewarm_data( + columns=["attrs.score"], filter="id >= 8", concurrency=4 + ) + is None + ) + elif mode == "defaults": + assert await table.prewarm_data() is None + else: + job = await table.prewarm_data_async( + ["attrs.score"], filter="id >= 8", concurrency=4 + ) + assert job.id == "warming-job" + assert not polls + assert (await job.wait()).table_version == 42 + await job.refresh() + assert job.spec["table_version"] == 42 + reopened = await db.open_job(job.id) + assert (await reopened.wait()).executors_completed == 2 + assert (await job.progress())["executors_completed"] == 2 + assert (await job.wait()).bytes_read is None + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + if mode == "columns": + assert table.prewarm_data(["payload"]) is None + elif mode == "filtered": + assert ( + table.prewarm_data( + columns=["attrs.score"], filter="id >= 8", concurrency=4 + ) + is None + ) + elif mode == "defaults": + assert table.prewarm_data() is None + else: + job = table.prewarm_data_async( + ["attrs.score"], filter="id >= 8", concurrency=4 + ) + assert job.id == "warming-job" + assert not polls + assert job.wait().table_version == 42 + job.refresh() + assert job.spec["table_version"] == 42 + assert db.open_job(job.id).wait().executors_completed == 2 + assert job.progress()["executors_completed"] == 2 + assert job.wait().bytes_read is None + assert len(server.tickets) == 1 + assert b"PREWARM" in server.tickets[0] + if mode != "job": + assert not polls + if mode == "columns": + assert b'"payload"' in server.tickets[0] + elif mode == "defaults": + assert b"SELECT *" in server.tickets[0] + else: + assert b'"attrs"."score"' in server.tickets[0] + assert b"concurrency = 4" in server.tickets[0] + assert b"id >= 8" in server.tickets[0] + + +@pytest.mark.parametrize( + "options", + [ + {"filter": ""}, + {"filter": "id > 0; DROP TABLE test"}, + {"filter": "id > 0 LIMIT 1"}, + {"concurrency": 0}, + {"concurrency": -1}, + {"concurrency": 2**32}, + {"concurrency": True}, + {"concurrency": 1.5}, + ], +) +@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +def test_remote_data_prewarm_validates_before_submission(options, method): + flight = pytest.importorskip("pyarrow.flight") + + class UnusedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + raise AssertionError("invalid options must not submit SQL") + + server = UnusedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(ValueError): + getattr(table, method)(**options) + assert not server.tickets + + +def test_remote_data_prewarm_malformed_receipt_is_not_retried(): + flight = pytest.importorskip("pyarrow.flight") + + class MalformedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"job_id": ["warming-job"]})) + + server = MalformedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(Exception, match="inspect jobs before retrying"): + table.prewarm_data_async() + assert len(server.tickets) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "outcome", + [ + "counts", + "legacy", + "partial", + "bounded", + "no_op", + "missing", + "FAILED", + "CANCELLED", + ], +) +async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): + flight = pytest.importorskip("pyarrow.flight") + polls = [] + result = { + "partial_commit": False, + "rows_succeeded": 12, + "rows_failed": 0, + "completion_percentage": 100.0, + } + if outcome == "counts": + result.update( + files_added=1, files_removed=3, fragments_added=1, fragments_removed=3 + ) + + if outcome == "partial": + result.update( + partial_commit=True, + rows_succeeded=8, + rows_failed=4, + completion_percentage=100 * 8 / 12, + ) + if outcome == "bounded": + result.update(more_work=True) + if outcome == "no_op": + result.update( + rows_succeeded=0, + files_added=0, + files_removed=0, + fragments_added=0, + fragments_removed=0, + ) + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"job_id": ["compacting-job"]})) + + def handler(request): + if request.path != "/v1/jobs/describe": + return _create_table_handler(request) + body = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert body == {"job_id": "compacting-job"} + polls.append(body) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "compacting-job", + "job_type": "compact", + "job_state": outcome + if outcome in ("FAILED", "CANCELLED") + else "DONE", + "result": None if outcome == "missing" else result, + } + ).encode() + ) + + server = Server() + with _mock_remote_sql_connection(server, handler) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + job = await table.compact_async( + compaction_options={"target_rows_per_fragment": 100} + ) + assert job.id == "compacting-job" and not polls + if outcome in ("missing", "FAILED", "CANCELLED"): + with pytest.raises( + Exception, + match={ + "missing": "did not contain a result", + "FAILED": "failed", + "CANCELLED": "cancel", + }[outcome], + ): + await job.wait() + else: + stats = await job.wait() + reopened = await db.open_job(job.id) + assert await reopened.wait() == stats + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + job = table.compact_async( + compaction_options={"target_rows_per_fragment": 100} + ) + assert job.id == "compacting-job" and not polls + if outcome in ("missing", "FAILED", "CANCELLED"): + with pytest.raises( + Exception, + match={ + "missing": "did not contain a result", + "FAILED": "failed", + "CANCELLED": "cancel", + }[outcome], + ): + job.wait() + else: + stats = job.wait() + assert db.open_job(job.id).wait() == stats + if outcome in ("counts", "legacy", "partial", "bounded", "no_op"): + from lancedb.compaction import CompactionResult + + assert isinstance(stats, CompactionResult) + assert stats.rows_succeeded == ( + 0 if outcome == "no_op" else 8 if outcome == "partial" else 12 + ) + assert stats.rows_failed == (4 if outcome == "partial" else 0) + assert stats.partial_commit == (outcome == "partial") + assert stats.more_work == (outcome == "bounded") + assert stats.fragments_removed == ( + 3 if outcome == "counts" else 0 if outcome == "no_op" else None + ) + assert len(server.tickets) == 1 + assert b"OPTIMIZE" in server.tickets[0] + assert b"target_rows_per_fragment = 100" in server.tickets[0] + + +@pytest.mark.parametrize("ids", [[], [None], [""], ["a", "b"]]) +def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids): + flight = pytest.importorskip("pyarrow.flight") + + class Server(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + return flight.RecordBatchStream( + pa.table({"job_id": pa.array(ids, pa.string())}) + ) + + server = Server() + with _mock_remote_sql_connection(server) as kwargs: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + with pytest.raises(Exception, match="inspect jobs before retrying"): + table.compact_async() + assert server.calls == 1 + + +@pytest.mark.parametrize("method", ["compact_async", "optimize"]) +@pytest.mark.parametrize( + "option", + ["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"], +) +@pytest.mark.parametrize("value", [False, True]) +def test_remote_compaction_rejects_boolean_budgets_without_submitting( + method, option, value +): + flight = pytest.importorskip("pyarrow.flight") + + class UnusedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + raise AssertionError("boolean compaction settings must not submit SQL") + + server = UnusedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(ValueError, match="must be an integer, not a bool"): + getattr(table, method)(compaction_options={option: value}) + assert server.calls == 0 diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 4b26a9003..ebc3c3006 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6414,3 +6414,22 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db): table.create_index("`body-text`", config=FTS(), exist_ok=True) assert table.version == before assert len(table.list_indices()) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method): + if asynchronous: + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("prewarm", [{"id": 1}]) + with pytest.raises( + NotImplementedError, match="only supported on remote tables" + ): + await getattr(table, method)(filter="id > 0", concurrency=2) + else: + table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}]) + with pytest.raises( + NotImplementedError, match="only supported on remote tables" + ): + getattr(table, method)(filter="id > 0", concurrency=2) diff --git a/python/src/connection.rs b/python/src/connection.rs index 2d65a0459..ce41589cc 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -902,6 +902,14 @@ impl Connection { job.into_typed::().infer_error()?, )) } + Some("prewarm_page_cache") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), + Some("compact") => Ok(crate::job::Job::new_typed( + job.into_typed::() + .infer_error()?, + )), _ => Ok(crate::job::Job::new(job)), } }) diff --git a/python/src/table.rs b/python/src/table.rs index 3bc23ec95..e421c939d 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -495,6 +495,16 @@ fn parse_compaction_options(options: Option<&Bound<'_, PyDict>>) -> PyResult() + { + return Err(PyValueError::new_err(format!( + "{key} must be an integer, not a bool" + ))); + } match key.as_str() { "target_rows_per_fragment" => { parsed.target_rows_per_fragment = positive_u32(&value, &key)? @@ -1885,6 +1895,24 @@ impl Table { }) } + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + pub fn prewarm_data_async<'py>( + self_: PyRef<'py, Self>, + columns: Option>, + filter: Option, + concurrency: Option<&Bound<'py, PyAny>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); + options.filter = filter; + options.concurrency = positive_u32_integer(concurrency, "concurrency")?; + future_into_py(self_.py(), async move { + let job = inner.prewarm_data_async(options).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { @@ -2245,6 +2273,29 @@ impl Table { }) } + /// Submit remote compaction and retain its durable job and actual result. + #[pyo3(signature = (compaction_options=None))] + pub fn compact_async<'py>( + self_: PyRef<'py, Self>, + compaction_options: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let target_specified = compaction_options + .map(|options| options.contains("target_rows_per_fragment")) + .transpose()? + .unwrap_or(false); + let options = parse_compaction_options(compaction_options)?; + let mut overrides = + lancedb::table::optimize::CompactionOverrides::try_from(options).infer_error()?; + if !target_specified { + overrides.target_rows_per_fragment = None; + } + future_into_py(self_.py(), async move { + let job = inner.compact_async(overrides).await.infer_error()?; + Ok(crate::job::Job::new_typed(job)) + }) + } + /// Optimize the on-disk data by compacting and pruning old data, for better performance. #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))] pub fn optimize<'py>( diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 39fee38d6..14170d43c 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -6,6 +6,7 @@ use std::future::Future; use std::pin::Pin; use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; +use std::time::Duration; use arrow_array::RecordBatch; use async_trait::async_trait; @@ -24,6 +25,48 @@ use crate::error::{Error, JobFailure, Result}; /// retry loop just to render progress. pub type JobProgressCallback = Arc>; +/// Client-side controls for waiting on a job. A timeout stops this wait without +/// cancelling the operation; keep the handle to wait again. +#[derive(Clone, Default)] +#[non_exhaustive] +pub struct JobWaitOptions { + /// Maximum time to wait, including HTTP requests and polling backoff. + /// `None` waits indefinitely. Zero only permits an immediately ready result. + pub timeout: Option, + progress: Option, +} + +impl std::fmt::Debug for JobWaitOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("JobWaitOptions") + .field("timeout", &self.timeout) + .field("progress", &self.progress.is_some()) + .finish() + } +} + +impl JobWaitOptions { + /// Wait indefinitely without a progress callback. + pub fn new() -> Self { + Self::default() + } + + /// Bound this wait without cancelling the underlying job. + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } + + /// Observe the backend's existing poller. The callback should return promptly. + pub fn progress(mut self, progress: F) -> Self + where + F: FnMut(&JobDescription) + Send + 'static, + { + self.progress = Some(Arc::new(Mutex::new(progress))); + self + } +} + /// Which of a job's events [`Job::events`] returns. /// /// The handle already knows which job to ask about, so this narrows the @@ -598,7 +641,7 @@ where /// Returns [`crate::Error::JobFailed`] if the operation failed and /// [`crate::Error::JobCancelled`] if it was cancelled. pub async fn wait(&self) -> Result { - self.wait_with_progress_opt(None).await + self.wait_with_options(JobWaitOptions::default()).await } /// Wait for the operation while observing progress from the backend's @@ -609,10 +652,58 @@ where where F: FnMut(&JobDescription) + Send + 'static, { - self.wait_with_progress_opt(Some(Arc::new(Mutex::new(progress)))) + self.wait_with_options(JobWaitOptions::new().progress(progress)) .await } + /// Wait with a client-side deadline and an optional progress callback. + /// + /// Returns [`Error::Timeout`] when the deadline expires, including while a + /// status request or polling backoff is pending. This drops the wait future; + /// it does not cancel the operation or mark it failed. The same handle can + /// wait again. Registry jobs can also be reopened by ID; query IDs remain + /// connection-scoped and cannot be reopened as registry jobs. + /// + /// ```no_run + /// # async fn example(job: &lancedb::Job) -> lancedb::Result<()> { + /// use std::time::Duration; + /// use lancedb::job::JobWaitOptions; + /// job.wait_with_options(JobWaitOptions::new() + /// .timeout(Duration::from_secs(60)) + /// .progress(|description| println!("{}", description.state))) + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn wait_with_options(&self, options: JobWaitOptions) -> Result { + let Some(timeout) = options.timeout else { + return self.wait_with_progress_opt(options.progress).await; + }; + let deadline = tokio::time::Instant::now() + .checked_add(timeout) + .ok_or_else(|| Error::InvalidInput { + message: "job wait timeout is too large".to_string(), + })?; + tokio::time::timeout_at(deadline, self.wait_with_progress_opt(options.progress)) + .await + .map_err(|_| { + let operation = self + .id() + .map(|id| format!("job {id:?}")) + .unwrap_or_else(|| "operation".to_string()); + let resume = if self.id().is_some() && self.job_type().as_deref() != Some("query") { + "continue waiting on this handle or reattach with Connection::open_job" + } else { + "keep this handle to continue waiting" + }; + Error::Timeout { + message: format!( + "{operation} still running after {timeout:?}; the operation continues; {resume}" + ), + } + })? + } + async fn wait_with_progress_opt(&self, progress: Option) -> Result { match &self.inner { JobInner::Handle { handle, decode } => { @@ -838,6 +929,92 @@ mod tests { use super::*; + #[tokio::test(start_paused = true)] + async fn wait_timeout_preserves_local_task_and_typed_result() { + let job = Job::spawned(tokio::spawn(async { + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(41_u64) + })) + .map(|value| value + 1); + let error = job + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10))) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert!(error.to_string().contains("keep this handle")); + assert!(!error.to_string().contains("Connection::open_job")); + assert_eq!(job.state(), None); + assert_eq!(job.status().await.unwrap(), "running"); + assert_eq!( + job.wait_with_options(JobWaitOptions::new()).await.unwrap(), + 42 + ); + } + + #[tokio::test(start_paused = true)] + async fn wait_timeout_keeps_query_handle_without_requesting_cancellation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let cancellations = Arc::new(AtomicUsize::new(0)); + let observed = cancellations.clone(); + let id = Uuid::new_v4(); + let job = Job::from_query_task( + id, + tokio::spawn(async { + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(42_u64) + }), + move || { + observed.fetch_add(1, Ordering::SeqCst); + async { Ok(()) } + }, + ); + let error = job + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(10))) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout { .. })); + assert!(error.to_string().contains(&id.to_string())); + assert!(!error.to_string().contains("Connection::open_job")); + assert_eq!(cancellations.load(Ordering::SeqCst), 0); + assert_eq!(job.wait().await.unwrap(), 42); + } + + #[tokio::test] + async fn wait_options_handle_zero_and_unrepresentable_deadlines() { + let job = Job::new_done(); + job.wait_with_options(JobWaitOptions::new().timeout(Duration::ZERO)) + .await + .unwrap(); + assert!(matches!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::MAX)) + .await, + Err(Error::InvalidInput { .. }) + )); + } + + #[tokio::test] + async fn wait_options_preserve_operation_errors() { + let failed = Job::::spawned(tokio::spawn(async { + Err(Error::Runtime { + message: "original failure".into(), + }) + })); + let error = failed + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await + .unwrap_err(); + assert!(matches!(error, Error::JobFailed { .. })); + assert!(error.to_string().contains("original failure")); + let cancelled = Job::::spawned(tokio::spawn(pending())); + cancelled.cancel().await.unwrap(); + assert!(matches!( + cancelled + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await, + Err(Error::JobCancelled { .. }) + )); + } + #[test] fn local_typed_result_decode_errors_are_runtime_errors() { assert!(matches!( diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 125930cb7..b36d3cd03 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -411,14 +411,6 @@ impl RemoteDatabase { read_consistency_interval: Option, parsed: super::client::ParsedDbUrl, ) -> Result { - let sql_client = SqlClient::new( - parsed.db_name.clone(), - parsed.db_prefix.clone(), - api_key.to_string(), - host_overrides.rest.clone(), - host_overrides.sql, - client_config.clone(), - ); let header_map = RestfulLanceDbClient::::default_headers( api_key, region, @@ -429,6 +421,27 @@ impl RemoteDatabase { &client_config, )?; + // Preserve the resolved source-account hint when table operations use SQL. + let mut sql_config = client_config.clone(); + if let Some(account) = header_map.get("x-azure-storage-account-name") { + sql_config.extra_headers.insert( + "x-azure-storage-account-name".into(), + account + .to_str() + .map_err(|error| Error::InvalidInput { + message: error.to_string(), + })? + .into(), + ); + } + let sql_client = SqlClient::new( + parsed.db_name.clone(), + parsed.db_prefix.clone(), + api_key.to_string(), + host_overrides.rest.clone(), + host_overrides.sql, + sql_config, + ); let namespace_headers: HashMap = header_map .iter() .filter_map(|(k, v)| { diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index f233d4026..c60fa46ec 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -116,6 +116,8 @@ pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) progress: Option, #[serde(default)] + pub(super) operation_progress: Option, + #[serde(default)] pub(super) phase: Option, #[serde(default)] pub(super) queue_reason: Option, @@ -160,7 +162,7 @@ impl DescribeJobResponse { job_type: self.job_type, state: JobState::from(self.job_state.as_str()).client_label(), creation_ms: self.creation_ms, - progress: self.progress, + progress: self.operation_progress.or(self.progress), phase: self.phase, queue_reason: self.queue_reason, waiting_for_job_id: self.waiting_for_job_id, @@ -420,7 +422,7 @@ impl JobHandle for RemoteJob { #[cfg(test)] mod tests { - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -428,7 +430,7 @@ mod tests { use crate::Result; use crate::function::{FunctionVersion, RefreshColumnResult}; - use crate::job::{Job, JobHandle, JobProgressCallback, TerminalResult}; + use crate::job::{Job, JobHandle, JobProgressCallback, JobWaitOptions, TerminalResult}; use crate::remote::client::test_utils::client_with_handler; use super::{DescribeJobResponse, RemoteJob}; @@ -441,6 +443,108 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + #[tokio::test(start_paused = true)] + async fn timed_wait_stops_polling_and_can_resume_or_reopen_typed_maintenance_jobs() { + for job_type in ["compact", "prewarm_page_cache"] { + let done = Arc::new(AtomicBool::new(false)); + let describes = Arc::new(AtomicUsize::new(0)); + let complete = done.clone(); + let seen = describes.clone(); + let expected = if job_type == "compact" { + serde_json::json!({"partial_commit":false,"rows_succeeded":12,"rows_failed":0,"completion_percentage":100}) + } else { + serde_json::json!({"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}) + }; + let payload = expected.clone(); + let client = + client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + seen.fetch_add(1, Ordering::SeqCst); + let finished = complete.load(Ordering::SeqCst); + http::Response::builder().status(200).body(serde_json::json!({ + "job_id":"bounded-job", "job_type":job_type, + "job_state":if finished {"DONE"} else {"IN_PROGRESS"}, + "result":if finished {payload.clone()} else {serde_json::Value::Null}, + }).to_string()).unwrap() + }); + let handle = RemoteJob::new(client.clone(), "bounded-job".into()); + let description = handle.describe().await.unwrap(); + let job = Job::opened(Box::new(handle), description) + .into_typed::() + .unwrap(); + let observations = Arc::new(Mutex::new(Vec::new())); + let updates = observations.clone(); + let options = JobWaitOptions::new() + .timeout(Duration::from_millis(50)) + .progress(move |description| { + updates.lock().unwrap().push(description.state.clone()) + }); + // Bound a regression that accidentally ignores the wait deadline. + let eventual_completion = done.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(1)).await; + eventual_completion.store(true, Ordering::SeqCst); + }); + let error = job.wait_with_options(options.clone()).await.unwrap_err(); + assert!(matches!(error, crate::Error::Timeout { .. })); + assert!(error.to_string().contains("bounded-job")); + assert!(error.to_string().contains("Connection::open_job")); + assert_eq!(job.state().as_deref(), Some("running")); + assert_eq!(describes.load(Ordering::SeqCst), 2); + tokio::time::advance(Duration::from_secs(2)).await; + tokio::task::yield_now().await; + assert_eq!( + describes.load(Ordering::SeqCst), + 2, + "timed-out poller must stop" + ); + assert_eq!(*observations.lock().unwrap(), ["running"]); + done.store(true, Ordering::SeqCst); + let result = job + .wait_with_options(options.timeout(Duration::from_secs(1))) + .await + .unwrap(); + assert_eq!(result, expected); + assert_eq!(*observations.lock().unwrap(), ["running", "finished"]); + let handle = RemoteJob::new(client, "bounded-job".into()); + let description = handle.describe().await.unwrap(); + let reopened = Job::opened(Box::new(handle), description) + .into_typed::() + .unwrap(); + assert_eq!( + reopened + .wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))) + .await + .unwrap(), + result + ); + } + } + + #[tokio::test(start_paused = true)] + async fn one_wait_timeout_does_not_interrupt_another_waiter() { + let done = Arc::new(AtomicBool::new(false)); + let complete = done.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + http::Response::builder().status(200).body(serde_json::json!({ + "job_state":if complete.load(Ordering::SeqCst) {"DONE"} else {"IN_PROGRESS"}, + }).to_string()).unwrap() + }); + let job = Job::new(Box::new(RemoteJob::new(client, "shared-job".into()))); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(100)).await; + done.store(true, Ordering::SeqCst); + }); + let (short, long) = tokio::join!( + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_millis(50))), + job.wait_with_options(JobWaitOptions::new().timeout(Duration::from_secs(1))), + ); + assert!(matches!(short, Err(crate::Error::Timeout { .. }))); + long.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + #[tokio::test] async fn stack_preserves_availability_and_uses_the_selected_worker() { for status in ["captured", "unsupported", "unavailable"] { diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 9c34f8f90..f5e053f9f 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -12,7 +12,6 @@ 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, @@ -44,6 +43,8 @@ pub(super) use secret::SecretWriteOperation; mod stream; mod view; +const PREWARM_AZURE_HINT_CAPABILITY: &str = "lancedb.prewarm.azure_storage_account_name"; + use stream::{StreamingQuery, StreamingQueryHandle, Submission}; const DEFAULT_SQL_PORT: u16 = 10025; @@ -217,6 +218,55 @@ impl SqlClient { } } + /// Unknown headers are otherwise silently ignored by older SQL servers. + /// Probe only when a source-account hint is present, before submitting work. + pub(super) async fn execute_prewarm(&self, request: ExecuteQueryRequest) -> Result { + with_overall_timeout( + self.inner.overall_timeout()?, + "prewarm submission", + async { + validate_namespace_path(&request.default_namespace_path)?; + let request_id = Uuid::new_v4().to_string(); + let headers = self + .inner + .headers(&request.default_namespace_path, &request_id) + .await?; + if headers.contains_key("x-azure-storage-account-name") { + let connection = self.inner.connection(&request_id).await?; + let mut client = client_with_headers(connection.client.clone(), &headers)?; + let command = CommandStatementQuery { + query: request.query.clone(), + transaction_id: None, + }; + let descriptor = FlightDescriptor::new_cmd(command.as_any().encode_to_vec()); + let read_timeout = resolve_timeout( + self.inner.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", Some(DEFAULT_READ_TIMEOUT), + )?.unwrap(); + let info = tokio::time::timeout(read_timeout, client.get_flight_info(descriptor)) + .await.map_err(|_| Error::Runtime { message: format!("SQL PREWARM capability check timed out (request_id={request_id})") })? + .map_err(|error| sql_flight_error(&request_id, &error))?; + let supported = info.try_decode_schema().ok().is_some_and(|schema| { + schema + .metadata() + .get(PREWARM_AZURE_HINT_CAPABILITY) + .map(String::as_str) + == Some("true") + }); + if !supported { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM server cannot acknowledge the Azure storage-account hint (request_id={request_id}); upgrade the server. No execution request was sent." + ), + }); + } + } + self.execute(request).await + }, + ) + .await + } + pub(super) async fn execute(&self, request: ExecuteQueryRequest) -> Result { Ok(self .execute_with_materialized_view_job_handle(request, false) diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d7249da9b..a80e26ad9 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -143,6 +143,8 @@ struct TestSqlService { result_overrides: Arc>>, materialized_view_job_handle_supported: bool, optimize_error: Option, + prewarm_error: Option, + prewarm_azure_supported: bool, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, @@ -318,6 +320,8 @@ impl Default for TestSqlService { result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), materialized_view_job_handle_supported: false, optimize_error: None, + prewarm_error: None, + prewarm_azure_supported: false, exchange_drops: Arc::new(AtomicUsize::new(0)), result, large_result, @@ -352,9 +356,30 @@ impl FlightService for TestSqlService { async fn get_flight_info( &self, - _request: Request, + request: Request, ) -> std::result::Result, Status> { - Err(Status::unimplemented("get_flight_info")) + self.capture_headers(request.metadata()); + assert!( + request + .metadata() + .get("x-azure-storage-account-name") + .is_some() + ); + let schema = if self.prewarm_azure_supported { + self.result + .schema() + .as_ref() + .clone() + .with_metadata(HashMap::from([( + "lancedb.prewarm.azure_storage_account_name".into(), + "true".into(), + )])) + } else { + self.result.schema().as_ref().clone() + }; + Ok(Response::new( + FlightInfo::new().try_with_schema(&schema).unwrap(), + )) } async fn poll_flight_info( @@ -493,6 +518,11 @@ impl FlightService for TestSqlService { { return Err(error.clone()); } + if command.query.starts_with("PREWARM") + && let Some(error) = &self.prewarm_error + { + return Err(error.clone()); + } if command.query == "SELECT rejected" { return Err(Status::invalid_argument("invalid statement")); } @@ -4445,3 +4475,379 @@ async fn remote_optimize_branch_options_are_not_dropped() { ); shutdown.send(()).unwrap(); } + +fn prewarm_result() -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(vec!["warming-job"])) as ArrayRef, + ), + ( + "table_version", + Arc::new(arrow_array::UInt64Array::from(vec![42])) as ArrayRef, + ), + ]) + .unwrap() +} + +#[tokio::test] +async fn remote_prewarm_data_returns_the_durable_job_without_polling() { + use crate::table::PrewarmDataOptions; + for branch in [None, Some("experiment"), Some("o'brien")] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| -> http::Response { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let value: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(value["job_id"], "warming-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job", "job_type":"prewarm_page_cache", "job_state":"DONE", + "creation_ms":1,"spec":{"table_version":42}, + "result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}, + "operation_progress":{"phase":"reading","executors_completed":2}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clip\"name".into(), + vec!["team".into(), "inner".into()], + "team$inner$clip\"name".into(), + Default::default(), + Some(sql), + ) + .with_branch(branch.map(str::to_string)); + let job = table + .prewarm_data_async( + PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7") + .concurrency(4), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("warming-job")); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "acceptance must not eagerly poll HTTP" + ); + let branch_sql = branch + .map(|b| format!("branch = '{}', ", b.replace('\'', "''"))) + .unwrap_or_default(); + assert_eq!( + *statements.lock().unwrap(), + [format!( + "PREWARM WITH ({branch_sql}concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7" + )] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team$inner" && h.database == "analytics") + ); + job.wait().await.unwrap(); + assert_eq!(polls.load(Ordering::SeqCst), 1); + job.refresh().await.unwrap(); + assert_eq!(job.spec().unwrap()["table_version"], 42); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_legacy_prewarm_data_submits_sql_and_returns_on_acceptance() { + for columns in [None, Some(vec![]), Some(vec!["payload".into()])] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!( + "legacy prewarm must neither submit nor poll REST: {}", + r.url() + ); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.prewarm_data(columns.clone()).await.unwrap(); + let projection = if columns.as_ref().is_some_and(|c| !c.is_empty()) { + "\"payload\"" + } else { + "*" + }; + assert_eq!( + *statements.lock().unwrap(), + [format!("PREWARM AS SELECT {projection} FROM \"clips\"")] + ); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_data_rejects_bad_receipts_without_resubmission() { + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry malformed receipt through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(error.to_string().contains("inspect jobs before retrying")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_prewarm_errors_preserve_diagnostics_and_never_fall_back() { + for (status, unsupported) in [ + ( + Status::invalid_argument("Unknown PREWARM option 'branch'"), + true, + ), + (Status::permission_denied("source Select denied"), false), + ( + Status::invalid_argument("ParserError: expected expression, found invalid_filter"), + false, + ), + ] { + let service = TestSqlService { + adaptive: true, + prewarm_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not retry through REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let error = table.prewarm_data(None).await.unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error}" + ); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_requires_azure_ack_before_execution() { + for supported in [false, true] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + prewarm_azure_supported: supported, + ..Default::default() + }; + let statements = service.statements.clone(); + let mut config = ClientConfig::default(); + config.extra_headers.insert( + "x-azure-storage-account-name".into(), + "sourceaccount".into(), + ); + let (sql, shutdown) = start_sql_service(service, config).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!("must not use REST: {}", r.url()); + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let result = table.prewarm_data(None).await; + assert_eq!(result.is_ok(), supported, "{result:?}"); + assert_eq!(statements.lock().unwrap().len(), usize::from(supported)); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_wait_surfaces_warming_job_failure_or_cancellation() { + for state in ["FAILED", "CANCELLED"] { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(move |r| -> http::Response { + assert_eq!(r.url().path(), "/v1/jobs/describe"); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"warming-job","job_type":"prewarm_page_cache","job_state":state, + "creation_ms":1,"spec":{"table_version":42}, + "result":{"table_version":42,"executors_targeted":2,"executors_completed":2,"fragments_selected":4}, + "operation_progress":{"phase":"reading","executors_completed":2}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + let job = table.prewarm_data_async(Default::default()).await.unwrap(); + assert_eq!(job.id(), Some("warming-job")); + let error = job.wait().await.unwrap_err(); + if state == "FAILED" { + assert!(matches!(error, Error::JobFailed { .. }), "{error}"); + } else { + assert!(matches!(error, Error::JobCancelled { .. }), "{error}"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_rejects_historical_checkout_without_submitting() { + let service = TestSqlService { + adaptive: true, + result: prewarm_result(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + assert_eq!(r.url().path(), "/v1/table/clips/describe/"); + http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }), + "analytics".into(), + "clips".into(), + vec![], + "clips".into(), + Default::default(), + Some(sql), + ); + table.checkout(7).await.unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("historical version 7")); + assert!(statements.lock().unwrap().is_empty()); + shutdown.send(()).unwrap(); +} + +#[tokio::test] +async fn remote_compaction_tracks_registry_job_and_real_result() { + use crate::table::optimize::CompactionOverrides; + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([( + "job_id", + Arc::new(StringArray::from(vec!["compacting-job"])) as ArrayRef, + )]) + .unwrap(), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let polls = Arc::new(AtomicUsize::new(0)); + let observed = polls.clone(); + let client = client_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/jobs/describe"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["job_id"], "compacting-job"); + observed.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "job_id":"compacting-job","job_type":"compact","job_state":"DONE", + "result":{"partial_commit":false,"rows_succeeded":12,"rows_failed":0, + "completion_percentage":100.0,"files_added":1,"files_removed":3, + "fragments_added":1,"fragments_removed":3}}) + .to_string(), + ) + .unwrap() + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec!["team".into(), "inner".into()], + "team$inner$events".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("experiment".into())); + let job = table + .compact_async(CompactionOverrides { + target_rows_per_fragment: Some(100), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(job.id(), Some("compacting-job")); + assert_eq!(polls.load(Ordering::SeqCst), 0); + let result = job.wait().await.unwrap(); + assert_eq!(result.rows_succeeded, 12); + assert_eq!(result.fragments_removed, Some(3)); + assert!(!result.more_work); + assert_eq!( + *statements.lock().unwrap(), + [ + "OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'experiment', target_rows_per_fragment = 100)" + ] + ); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2ed46147d..2e116dd87 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5,6 +5,7 @@ pub mod blobs; pub mod insert; mod ipc_stream; mod optimize; +mod prewarm; #[cfg(test)] mod write_tests; @@ -4098,19 +4099,10 @@ impl BaseTable for RemoteTable { options: crate::table::optimize::CompactionOverrides, ) -> Result { self.check_mutable().await?; - let compaction_options = optimize::compaction_sql_options(&options)?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; let sql_client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { message: "SQL is unavailable for this remote table client".to_string(), })?; - let mut statement = format!("OPTIMIZE {} REWRITE DATA", quote_sql_identifier(&self.name)); - let mut sql_options = Vec::new(); - if let Some(branch) = &self.branch { - sql_options.push(format!("branch = {}", quote_sql_string(branch))); - } - sql_options.extend(compaction_options); - if !sql_options.is_empty() { - statement.push_str(&format!(" WITH ({})", sql_options.join(", "))); - } // `OptimizeStats` carries `lance::dataset::optimize` metric types that // are not `Serialize`/`Deserialize`/`Clone`, which `Job` requires, // so the job itself only signals completion; the real (placeholder) @@ -4127,6 +4119,42 @@ impl BaseTable for RemoteTable { prune: None, }) } + async fn compact_async( + &self, + options: crate::table::optimize::CompactionOverrides, + ) -> Result> { + self.check_mutable().await?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "compaction jobs require a Flight SQL endpoint".into(), + })?; + let query = client + .execute(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(optimize::map_optimize_error)?; + let mut reader = query.reader().await.map_err(optimize::map_optimize_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader + .try_next() + .await + .map_err(optimize::map_optimize_error)? + { + batches.push(batch); + } + let job_id = optimize::receipt(&batches)?; + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn add_columns( &self, transforms: NewColumnTransform, @@ -4728,20 +4756,53 @@ impl BaseTable for RemoteTable { } async fn prewarm_data(&self, columns: Option>) -> Result<()> { - let mut request = self.client.post(&format!( - "/v1/table/{}/page_cache/prewarm/", - self.identifier - )); - let mut body = serde_json::json!({ - "columns": columns.unwrap_or_default(), - }); - self.apply_branch_body(&mut body); - request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; - self.check_table_response(&request_id, response).await?; + self.prewarm_data_async( + crate::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()), + ) + .await?; Ok(()) } + async fn prewarm_data_async( + &self, + options: crate::table::PrewarmDataOptions, + ) -> Result> { + if let Some(version) = *self.version.read().await { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM does not support historical version {version}; use checkout_latest() to prewarm the current branch" + ), + }); + } + let statement = prewarm::statement(&self.name, self.branch.as_deref(), &options)?; + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "data prewarm requires a Flight SQL endpoint and SQL PREWARM support" + .into(), + })?; + let query = client + .execute_prewarm(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(prewarm::map_error)?; + let mut reader = query.reader().await.map_err(prewarm::map_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader.try_next().await.map_err(prewarm::map_error)? { + batches.push(batch); + } + let (job_id, _table_version) = prewarm::receipt(&batches)?; + // Construct lazily: submission must not require an HTTP status round trip. + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + async fn table_definition(&self) -> Result { let schema = self.schema().await?; TableDefinition::try_from_rich_schema(schema) @@ -13718,67 +13779,16 @@ mod tests { } #[tokio::test] - async fn test_prewarm_data() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" + async fn test_prewarm_data_requires_sql_without_rest_fallback() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!( + "data prewarm must not submit through REST: {}", + request.url() ); - http::Response::builder().status(200).body("{}").unwrap() }); - table.prewarm_data(None).await.unwrap(); - } - - #[tokio::test] - async fn test_prewarm_data_with_columns() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!( - request.url().path(), - "/v1/table/my_table/page_cache/prewarm/" - ); - let body = request.body().unwrap().as_bytes().unwrap(); - let body: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!(body["columns"], serde_json::json!(["col_a", "col_b"])); - http::Response::builder().status(200).body("{}").unwrap() - }); - table - .prewarm_data(Some(vec!["col_a".into(), "col_b".into()])) - .await - .unwrap(); - } - - #[tokio::test] - async fn test_prewarm_data_sends_the_checked_out_branch() { - use lance::dataset::refs::Ref; - - let table = - Table::new_with_handler_version("my_table", semver::Version::new(0, 5, 0), |request| { - match request.url().path() { - "/v1/table/my_table/branches/create/" => { - http::Response::builder().status(200).body("{}").unwrap() - } - "/v1/table/my_table/page_cache/prewarm/" => { - let body = request_body_json(&request); - assert_eq!(body["branch"], "dev"); - assert_eq!(body["columns"], json!(["payload"])); - http::Response::builder() - .status(202) - .body(r#"{"job_id":"prewarm-job"}"#) - .unwrap() - } - path => panic!("unexpected request path: {path}"), - } - }); - let branch = table - .create_branch("dev", Ref::Version(None, None)) - .await - .unwrap(); - branch - .prewarm_data(Some(vec!["payload".into()])) - .await - .unwrap(); + let error = table.prewarm_data(None).await.unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("SQL")); } #[tokio::test] diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 6f4b7f7e8..80d4d9639 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -4,6 +4,49 @@ //! Compaction options supported by the remote SQL submission protocol. use crate::error::{Error, Result}; +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &crate::table::optimize::CompactionOverrides, +) -> Result { + let mut settings = compaction_sql_options(options)?; + if let Some(branch) = branch { + settings.insert(0, format!("branch = {}", super::quote_sql_string(branch))); + } + let mut sql = format!( + "OPTIMIZE {} REWRITE DATA", + super::quote_sql_identifier(table) + ); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + Ok(sql) +} + +/// Submission can already have created work: reject ambiguous receipts without +/// retrying or confusing the SQL query's identity with the compaction job. +pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result { + use arrow_array::{Array, StringArray}; + let invalid = || { + Error::Runtime { message: "OPTIMIZE did not return a single nonempty job_id receipt; inspect jobs before retrying because compaction may already have been submitted".into() } + }; + if batches.iter().map(|batch| batch.num_rows()).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let ids = batch + .column_by_name("job_id") + .and_then(|a| a.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if ids.is_null(0) || ids.value(0).is_empty() { + return Err(invalid()); + } + Ok(ids.value(0).into()) +} + pub(super) fn compaction_sql_options( options: &crate::table::optimize::CompactionOverrides, ) -> Result> { @@ -258,3 +301,37 @@ mod tests { } } } + +#[cfg(test)] +mod receipt_tests { + use super::*; + use arrow_array::{ArrayRef, RecordBatch, StringArray}; + use std::sync::Arc; + + #[test] + fn compaction_receipt_requires_one_unambiguous_registry_id() { + let batch = |ids: Vec>| { + RecordBatch::try_from_iter([("job_id", Arc::new(StringArray::from(ids)) as ArrayRef)]) + .unwrap() + }; + assert_eq!( + receipt(&[batch(vec![Some("compacting-job")])]).unwrap(), + "compacting-job" + ); + for batches in [ + vec![], + vec![batch(vec![])], + vec![batch(vec![None])], + vec![batch(vec![Some("")])], + vec![batch(vec![Some("a"), Some("b")])], + vec![batch(vec![Some("a")]), batch(vec![Some("b")])], + ] { + assert!( + receipt(&batches) + .unwrap_err() + .to_string() + .contains("inspect jobs before retrying") + ); + } + } +} diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs new file mode 100644 index 000000000..8388b6350 --- /dev/null +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! SQL submission and receipt validation for data-cache prewarm jobs. + +use arrow_array::{Array, RecordBatch, StringArray, UInt64Array}; +use datafusion_sql::sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Token}; + +use super::{quote_sql_identifier, quote_sql_string}; +use crate::{Error, Result, table::PrewarmDataOptions}; + +pub(super) fn statement( + table: &str, + branch: Option<&str>, + options: &PrewarmDataOptions, +) -> Result { + let invalid = |message: &str| Error::InvalidInput { + message: message.into(), + }; + if options.concurrency == Some(0) { + return Err(invalid("prewarm concurrency must be greater than 0")); + } + if let Some(filter) = &options.filter { + if filter.trim().is_empty() { + return Err(invalid("prewarm filter must not be empty")); + } + let dialect = GenericDialect {}; + let mut parser = Parser::new(&dialect) + .try_with_sql(filter) + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + parser + .parse_expr() + .map_err(|error| invalid(&format!("invalid prewarm filter: {error}")))?; + if parser.peek_token().token != Token::EOF { + return Err(invalid("prewarm filter must be a single SQL expression")); + } + } + let mut settings = Vec::new(); + if let Some(branch) = branch { + if branch.trim().is_empty() { + return Err(invalid("prewarm branch must not be empty")); + } + settings.push(format!("branch = {}", quote_sql_string(branch))); + } + if let Some(concurrency) = options.concurrency { + settings.push(format!("concurrency = {concurrency}")); + } + let mut sql = "PREWARM".to_string(); + if !settings.is_empty() { + sql.push_str(&format!(" WITH ({})", settings.join(", "))); + } + let mut columns = Vec::new(); + for column in &options.columns { + let parts = lance::datatypes::parse_field_path(column)?; + let column = parts + .iter() + .map(|part| quote_sql_identifier(part)) + .collect::>() + .join("."); + if !columns.contains(&column) { + columns.push(column); + } + } + let projection = if columns.is_empty() { + "*".into() + } else { + columns.join(", ") + }; + sql.push_str(&format!( + " AS SELECT {projection} FROM {}", + quote_sql_identifier(table) + )); + if let Some(filter) = &options.filter { + sql.push_str(&format!(" WHERE {filter}")); + } + Ok(sql) +} + +pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> { + let invalid = || { + Error::Runtime { + message: "PREWARM did not return a single (job_id, table_version) receipt; inspect jobs before retrying because work may already have been submitted".into(), + } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let id = batch + .column_by_name("job_id") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + let version = batch + .column_by_name("table_version") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if id.is_null(0) || id.value(0).is_empty() || version.is_null(0) { + return Err(invalid()); + } + Ok((id.value(0).into(), version.value(0))) +} + +pub(super) fn map_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<&Error> { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let diagnostic = message.to_ascii_lowercase(); + (*grpc_code == tonic::Code::Unimplemented as i32 + || (*grpc_code == tonic::Code::InvalidArgument as i32 + && (diagnostic.contains("found: prewarm") + || diagnostic.contains("supported syntax: prewarm") + || diagnostic.contains("unknown prewarm option")))) + .then_some(error) + } + Error::JobFailed { failure, .. } => failure.source.as_deref().and_then(unsupported), + _ => None, + } + } + if let Some(source) = unsupported(&error) { + let diagnostic = if matches!(error, Error::Sql { .. }) { + error.to_string() + } else { + format!("{error}; {source}") + }; + Error::NotSupported { + message: format!( + "Data prewarm requires a compatible SQL PREWARM server; upgrade the server. Requested options will not be removed and submission will not fall back to REST. Server diagnostic: {diagnostic}" + ), + } + } else { + error + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + #[test] + fn quotes_paths_branch_and_filter_without_changing_options() { + let options = PrewarmDataOptions::new() + .columns(["attrs.score", "`caption.text`", "attrs.score"]) + .filter("quality > 0.7 AND caption = 'it''s ready'") + .concurrency(4); + assert_eq!( + statement("clip\"name", Some("o'brien"), &options).unwrap(), + "PREWARM WITH (branch = 'o''brien', concurrency = 4) AS SELECT \"attrs\".\"score\", \"caption.text\" FROM \"clip\"\"name\" WHERE quality > 0.7 AND caption = 'it''s ready'" + ); + assert_eq!( + statement("clips", None, &Default::default()).unwrap(), + "PREWARM AS SELECT * FROM \"clips\"" + ); + assert!(statement("clips", None, &PrewarmDataOptions::new().filter("-1 < id")).is_ok()); + } + + #[test] + fn rejects_invalid_inputs_before_submission() { + for options in [ + PrewarmDataOptions::new().filter(""), + PrewarmDataOptions::new().filter("id > 0; DROP TABLE clips"), + PrewarmDataOptions::new().filter("id > 0 LIMIT 1"), + PrewarmDataOptions::new().filter("id >"), + PrewarmDataOptions::new().columns(["attrs..score"]), + PrewarmDataOptions::new().concurrency(0), + ] { + assert!(statement("clips", None, &options).is_err(), "{options:?}"); + } + } + + fn batch(ids: Vec>, versions: Vec>) -> RecordBatch { + RecordBatch::try_from_iter([ + ( + "job_id", + Arc::new(StringArray::from(ids)) as arrow_array::ArrayRef, + ), + ( + "table_version", + Arc::new(UInt64Array::from(versions)) as arrow_array::ArrayRef, + ), + ]) + .unwrap() + } + + #[test] + fn receipt_requires_one_non_null_job_and_version() { + assert_eq!( + receipt(&[batch(vec![Some("job-1")], vec![Some(42)])]).unwrap(), + ("job-1".into(), 42) + ); + for batches in [ + vec![], + vec![batch(vec![], vec![])], + vec![batch(vec![None], vec![Some(42)])], + vec![batch(vec![Some("")], vec![Some(42)])], + vec![batch(vec![Some("job")], vec![None])], + vec![batch(vec![Some("a"), Some("b")], vec![Some(1), Some(2)])], + vec![ + batch(vec![Some("a")], vec![Some(1)]), + batch(vec![Some("b")], vec![Some(2)]), + ], + vec![RecordBatch::new_empty(Arc::new(Schema::new(vec![ + Field::new("wrong", DataType::Utf8, false), + ])))], + ] { + let error = receipt(&batches).unwrap_err().to_string(); + assert!(error.contains("inspect jobs before retrying"), "{error}"); + } + } + + #[test] + fn compatibility_errors_preserve_permission_and_predicate_diagnostics() { + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError: found: PREWARM", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown PREWARM option 'branch'", + true, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + ( + tonic::Code::InvalidArgument, + "ParserError: expected expression, found unsupported_filter", + false, + ), + ] { + let error = map_error(Error::Sql { + message: message.into(), + request_id: "prewarm-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }); + assert_eq!(matches!(error, Error::NotSupported { .. }), unsupported); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("prewarm-request")); + } + } +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index f247a386f..e7f8062e4 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -86,6 +86,9 @@ pub mod freshness; pub mod function_column_status; pub mod merge; pub mod optimize; +pub use optimize::CompactionResult; +mod prewarm; +pub use prewarm::{PrewarmDataOptions, PrewarmDataResult}; pub(crate) mod primary_key; pub mod query; pub mod refresh; @@ -688,6 +691,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Currently only supported in LanceDB Enterprise. /// If `columns` is `None`, all columns are prewarmed. async fn prewarm_data(&self, columns: Option>) -> Result<()>; + + /// Submit a data-cache prewarm and return its durable job handle. + async fn prewarm_data_async( + &self, + _options: PrewarmDataOptions, + ) -> Result> { + Err(Error::NotSupported { + message: "data prewarm jobs are only supported on remote tables".into(), + }) + } /// Get statistics about the index. async fn index_stats(&self, index_name: &str) -> Result>; /// Merge insert new records into the table. @@ -881,6 +894,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn tags(&self) -> Result>; /// Optimize the dataset. async fn optimize(&self, action: OptimizeAction) -> Result; + /// Submit remote compaction and retain its durable job and actual outcome. + async fn compact_async( + &self, + _options: optimize::CompactionOverrides, + ) -> Result> { + Err(Error::NotSupported { + message: "compaction jobs are only supported on remote tables".into(), + }) + } /// Compact with optional fields, preserving remote policy inheritance. async fn compact(&self, options: optimize::CompactionOverrides) -> Result { self.optimize(OptimizeAction::Compact { @@ -2065,6 +2087,37 @@ impl Table { self.inner.compact(options).await } + /// Submit remote compaction and return its durable job after acceptance. + /// + /// Uses SQL `OPTIMIZE ... REWRITE DATA` with the table handle's namespace + /// and branch. The four fields of [`optimize::CompactionOverrides`] retain + /// server defaults when omitted. Requires a compatible remote SQL server + /// and table Ownership plus database/namespace Usage under Standard authorization. + /// Historical-version and local handles are unsupported. + /// + /// Unlike [`Self::optimize`], waiting on this handle waits for compaction + /// itself and returns actual [`CompactionResult`] values. Status, progress, + /// events, and cancellation use the generic HTTP job APIs. A timeout or + /// dropping the handle does not cancel work. Missing result payloads are + /// errors, never placeholder zero statistics. An older worker may omit + /// file counts, represented as `None`. Reopen with + /// `connection.open_job(id).await?.into_typed::()?`. + /// + /// ```no_run + /// # async fn compact(table: &lancedb::Table) -> lancedb::Result<()> { + /// let job = table.compact_async(Default::default()).await?; + /// let result = job.wait().await?; + /// println!("Committed {} rows", result.rows_succeeded); + /// # Ok(()) + /// # } + /// ``` + pub async fn compact_async( + &self, + options: optimize::CompactionOverrides, + ) -> Result> { + self.inner.compact_async(options).await + } + /// Language-binding entry point retaining optional compaction fields. #[doc(hidden)] pub async fn optimize_full_with_overrides( @@ -3090,8 +3143,9 @@ impl Table { /// supported in LanceDB Enterprise. /// /// This call initiates prewarming and returns once the request is accepted. - /// It is idempotent and safe to call from multiple clients concurrently — - /// calling it on already-prewarmed columns is a no-op on the server. + /// Remote tables use SQL PREWARM and require Flight SQL connectivity. + /// Use [`Self::prewarm_data_async`] to retain the durable job handle. + /// Repeated submissions can create distinct jobs; warming cached data is safe. /// /// This operation has a large upfront cost but can speed up future queries /// that need to fetch the given columns. Large columns such as embeddings @@ -3103,6 +3157,41 @@ impl Table { self.inner.prewarm_data(columns).await } + /// Submit a durable data-cache prewarm job through SQL and return when accepted. + /// + /// The handle tracks the warming job, rather than the SQL submission. Use + /// [`Job::wait`] to wait for warming to finish, or save [`Job::id`] and + /// reopen it through [`crate::Connection::open_job`]. A wait timeout or + /// dropping the handle does not cancel the job. Waiting returns the reported + /// [`PrewarmDataResult`]; unavailable measurements remain `None`. + /// + /// Requires a compatible remote server with SQL PREWARM support and Flight + /// SQL connectivity. Under Standard authorization, submission requires + /// Select on the table and Usage on its database and namespace hierarchy. + /// Status and waiting use the generic HTTP job APIs; events and cancellation + /// retain their separate privileges. Unsupported servers are not retried + /// through REST or with requested settings removed. Local tables are unsupported. + /// Historical-version checkouts are unsupported; use `checkout_latest()` first. + /// After [`Job::refresh`], the pinned source version is in [`Job::spec`]. + /// + /// ```no_run + /// # async fn warm(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::PrewarmDataOptions; + /// let job = table.prewarm_data_async(PrewarmDataOptions::new() + /// .columns(["video"]) + /// .filter("quality > 0.7") + /// .concurrency(4)).await?; + /// job.wait().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn prewarm_data_async( + &self, + options: PrewarmDataOptions, + ) -> Result> { + self.inner.prewarm_data_async(options).await + } + /// Poll until the columns are fully indexed. Will return Error::Timeout if the columns /// are not fully indexed within the timeout. pub async fn wait_for_index( diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index ab34e05c6..0888ca4c4 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -32,6 +32,35 @@ pub use lance::dataset::optimize::{CompactionMode, CompactionOptions, IndexRemap const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64; +/// Actual outcome of one remote compaction job, returned by its job handle. +/// +/// A successful bounded run can leave more work for another invocation. A +/// partial commit reports uncommitted rows rather than inventing file counts. +/// File/fragment counts are unknown (`None`) when an older worker omitted them. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct CompactionResult { + /// A complete bounded plan left eligible work for a later invocation. + #[serde(default)] + pub more_work: bool, + /// Some planned groups were not committed. + pub partial_commit: bool, + /// Live source rows in committed rewrite groups. + pub rows_succeeded: u64, + /// Planned live rows not committed by this job. + pub rows_failed: u64, + /// Percentage of planned live rows committed, from 0 to 100. + pub completion_percentage: f64, + /// Files added by committed rewrites, including deletion files, when reported. + pub files_added: Option, + /// Files removed by committed rewrites, including deletion files, when reported. + pub files_removed: Option, + /// Fragments added by committed rewrites, when reported by the server. + pub fragments_added: Option, + /// Fragments removed by committed rewrites, when reported by the server. + pub fragments_removed: Option, +} + struct PrecomputedCompactionPlanner { plan: Mutex>, } @@ -261,8 +290,11 @@ pub enum OptimizeAction { /// options and custom `remap_options` return [`crate::Error::NotSupported`] /// before submission. The server must support these SQL options; errors /// from older servers are returned without dropping the settings. - /// The source-row budget admits whole tasks and may perform no work when - /// the first task exceeds it. Zero I/O buffer size disables byte-based I/O + /// The source-row budget admits whole tasks. On current Enterprise servers, + /// worker planning fails if the budget cannot admit the first useful task, + /// reporting its required live rows and source fragment count. Older servers + /// may instead finish without rewriting data in this case. + /// Zero I/O buffer size disables byte-based I/O /// backpressure. Use a positive size to limit I/O read-ahead; this is not a /// total-memory limit. Row targets, source-row budgets, and batch sizes must /// be positive. @@ -298,10 +330,11 @@ pub enum OptimizeAction { /// # } /// ``` /// - /// A branch-scoped table handle compacts that branch. The branch is not - /// validated to exist before the job is submitted, so a nonexistent - /// branch fails the compaction job asynchronously rather than failing - /// this call. + /// A branch-scoped table handle compacts that branch. Current Enterprise + /// servers validate the table and branch through the service catalog before + /// creating the compaction job, so a nonexistent branch fails submission. + /// Older servers may accept submission and fail the compaction job + /// asynchronously instead. Compact { options: CompactionOptions, remap_options: Option>, diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs new file mode 100644 index 000000000..1d0f8c002 --- /dev/null +++ b/rust/lancedb/src/table/prewarm.rs @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Options for submitting a durable data-cache prewarm job. + +/// Data prewarm settings for [`super::Table::prewarm_data_async`]. +/// +/// The table handle supplies the database, namespace, and branch. Omitted +/// columns warm all fields. The filter selects conservative metadata ranges; +/// it does not execute a row-filter scan or change the source data. +#[derive(Debug, Clone, Default)] +#[non_exhaustive] +pub struct PrewarmDataOptions { + /// Lance field paths, including nested paths such as `attrs.score`. + pub columns: Vec, + /// An optional SQL predicate for metadata pruning. + pub filter: Option, + /// Positive per-executor warming concurrency. Omit for the server default. + pub concurrency: Option, +} + +impl PrewarmDataOptions { + /// Use server defaults and warm every column. + pub fn new() -> Self { + Self::default() + } + + /// Select fields to warm. An empty collection selects all columns. + pub fn columns(mut self, columns: impl IntoIterator>) -> Self { + self.columns = columns.into_iter().map(Into::into).collect(); + self + } + + /// Restrict warming using a single SQL predicate for metadata pruning. + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + /// Set positive per-executor warming concurrency. + pub fn concurrency(mut self, concurrency: u32) -> Self { + self.concurrency = Some(concurrency); + self + } +} + +/// Reported outcome of a remote data-prewarm job. Counts describe executor work; +/// absent measurements remain unknown rather than being inferred as zero. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmDataResult { + /// Source snapshot captured by the submitted prewarm. + pub table_version: u64, + /// Reported executors targeted; unknown on older workers. + pub executors_targeted: Option, + /// Executors that reached a successful or partial terminal state. + pub executors_completed: Option, + /// Subset of completed executors that reported partial warming. + pub executors_partial: Option, + /// Reported fragments selected; unknown on older workers. + pub fragments_selected: Option, + /// Reported ranges completed; unknown on older workers. + pub ranges_completed: Option, + /// Reported bytes read; unknown on older workers. + pub bytes_read: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::Arc; + + #[test] + fn result_preserves_zero_partial_and_unknown_measurements() { + let result: PrewarmDataResult = serde_json::from_value(serde_json::json!({ + "table_version":42,"executors_targeted":2,"executors_completed":2, + "executors_partial":1,"ranges_completed":0,"extra":"ignored", + })) + .unwrap(); + assert_eq!(result.executors_partial, Some(1)); + assert_eq!(result.ranges_completed, Some(0)); + assert_eq!(result.bytes_read, None); + assert!(serde_json::from_value::(serde_json::json!({})).is_err()); + assert!( + serde_json::from_value::( + serde_json::json!({"table_version":42,"bytes_read":-1}) + ) + .is_err() + ); + } + + #[tokio::test] + async fn local_table_rejects_durable_data_prewarm() { + let db = crate::connect(&format!("memory://prewarm-{}", uuid::Uuid::new_v4())) + .execute() + .await + .unwrap(); + let table = db + .create_empty_table( + "items", + Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])), + ) + .execute() + .await + .unwrap(); + let error = table + .prewarm_data_async(PrewarmDataOptions::new().filter("id > 0")) + .await + .unwrap_err(); + assert!(matches!(error, crate::Error::NotSupported { .. })); + assert!( + error + .to_string() + .contains("only supported on remote tables") + ); + } +} From e29ec0e0847b696b8ebb83a6cc0027c316a257b0 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Tue, 17 Nov 2026 13:58:48 -0800 Subject: [PATCH 154/203] docs: publish the CLI page (#5079) The compaction guide links to `/tools/cli#install`, but `tools/cli.mdx` was listed in `docs/web/.mintignore`, so the link had no target and failed the broken-links check in the docs site build. This removes the page from `.mintignore` and restores its nav entry and the link from `basics/sql.mdx`, both dropped when the page was hidden in #4859. --- docs/web/.mintignore | 1 - docs/web/basics/sql.mdx | 2 +- docs/web/docs.json | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/web/.mintignore b/docs/web/.mintignore index 8fea3d17d..b6f13bcdc 100644 --- a/docs/web/.mintignore +++ b/docs/web/.mintignore @@ -1,4 +1,3 @@ -tools/cli.mdx # Branching is Beta; not documented until early access. tables/branching.mdx # stays reachable (out of the nav only): SDK error messages link to it. # To restore: docs.json Tutorials > Feature Engineering, after tutorials/feature-engineering/materialized-views. diff --git a/docs/web/basics/sql.mdx b/docs/web/basics/sql.mdx index 31e3af1f3..89f465e65 100644 --- a/docs/web/basics/sql.mdx +++ b/docs/web/basics/sql.mdx @@ -80,7 +80,7 @@ endpoint, returning results as Arrow record batches: does 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. -3. **The LanceDB CLI.** Open an interactive SQL shell, or run a +3. **The [LanceDB CLI](/tools/cli).** Open an interactive SQL shell, or run a statement or file, directly from the command line with no code at all. The [SQL reference](/sql#connecting) shows a query from Python. See diff --git a/docs/web/docs.json b/docs/web/docs.json index 0b26a7fc0..4f5d247b3 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -387,6 +387,7 @@ "quickstart", "basics/sdk", "basics/sql", + "tools/cli", "basics/agentic-skills", "deployment/support" ] From ee671533f9994504c46285f1940eb114f92df038 Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Tue, 17 Nov 2026 19:06:45 -0800 Subject: [PATCH 155/203] docs: say the Tables page covers schema changes and field metadata (#5080) The docs index lists each page by its title and description. The Tables page holds the guide to field metadata, but its description only mentioned creating, renaming and dropping tables. In local runs of the agent evals, two of three docs-only agents searched the index for "metadata", landed on the REST reference, and never found the convention. This adds schema changes and field metadata to the description and keywords, so that search finds the guide. --- docs/web/management/table.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index ff56aff10..cfe363176 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1,9 +1,9 @@ --- title: "Tables" sidebarTitle: "Table" -description: "The object most operations act on: creating, opening, renaming, cloning and dropping one." +description: "The object most operations act on: creating, opening, renaming, cloning and dropping one, changing its schema, and documenting its columns with field metadata." icon: table -keywords: ["table", "create_table", "open_table", "clone", "rename", "drop"] +keywords: ["table", "create_table", "open_table", "clone", "rename", "drop", "schema", "field metadata", "update_field_metadata", "column description", "tags"] availability: embedded: available enterprise: available From 13453ae5f83826bf0438ecc5a4a2f4918b69a6fe Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Tue, 17 Nov 2026 19:17:37 -0800 Subject: [PATCH 156/203] docs: serve Attach Database at ingestion/attach-database (#5078) The Attach Database page was renamed in the docs rework but kept its old URL, `ingestion/migrate-from-embedded`. That reads like the wrong page when we share the link. This renames the file to `ingestion/attach-database`, updates its nav entry and the two pages that link to it, and adds a redirect from the old URL so existing links keep working. --- docs/web/basics/embedded-vs-enterprise.mdx | 2 +- docs/web/docs.json | 6 +++++- .../{migrate-from-embedded.mdx => attach-database.mdx} | 0 docs/web/ingestion/define-storage-integration.mdx | 4 ++-- 4 files changed, 8 insertions(+), 4 deletions(-) rename docs/web/ingestion/{migrate-from-embedded.mdx => attach-database.mdx} (100%) diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index 7d30a0e92..430d26885 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -33,7 +33,7 @@ file format, so moving data from one edition to the other does not require a dat | **Data Ingestion** | [Insert data](/ingestion/insert) | ✅ | ✅ | | | [RTE Write (Upsert)](/ingestion/realtime-write) | ✅ | ✅ | | | [Distributed RTE Write](/enterprise/distributed-real-time-write) | ❌ | ✅ | -| | [Attach Database](/ingestion/migrate-from-embedded) | ❌ | ✅ | +| | [Attach Database](/ingestion/attach-database) | ❌ | ✅ | | | [Import Datasets](/ingestion/import) | ❌ | ✅ | | | [Distributed Write](/enterprise/distributed-write) | ❌ | ✅ | | **Search** | [Vector search](/search/vector-search) | ✅ | ✅ | diff --git a/docs/web/docs.json b/docs/web/docs.json index 4f5d247b3..4c800d65a 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -27,6 +27,10 @@ }, "favicon": "/static/favicon.ico", "redirects": [ + { + "source": "/ingestion/migrate-from-embedded", + "destination": "/ingestion/attach-database" + }, { "source": "/enterprise/expected-performance", "destination": "/search/vector-search#expected-performance" @@ -415,7 +419,7 @@ "ingestion/delete", "ingestion/realtime-write", "ingestion/define-storage-integration", - "ingestion/migrate-from-embedded", + "ingestion/attach-database", "ingestion/import", "enterprise/distributed-write", "enterprise/distributed-real-time-write" diff --git a/docs/web/ingestion/migrate-from-embedded.mdx b/docs/web/ingestion/attach-database.mdx similarity index 100% rename from docs/web/ingestion/migrate-from-embedded.mdx rename to docs/web/ingestion/attach-database.mdx diff --git a/docs/web/ingestion/define-storage-integration.mdx b/docs/web/ingestion/define-storage-integration.mdx index 446d47d22..96e137601 100644 --- a/docs/web/ingestion/define-storage-integration.mdx +++ b/docs/web/ingestion/define-storage-integration.mdx @@ -10,7 +10,7 @@ availability: --- Before you can [import data](/ingestion/import) from external storage or -[attach an existing database](/ingestion/migrate-from-embedded), define a +[attach an existing database](/ingestion/attach-database), define a storage integration once per location. It is a namespace-scoped catalog object that stores the credential -- neither operation names the integration directly, LanceDB matches the URI you read against whichever @@ -166,7 +166,7 @@ for the Python and SQL CRUD operations at a glance. Read or import through the integration once it exists. - + Attach an existing database at a location the integration covers. From 4cab7d0b6f5b9b8c5bd1034887ab3ba87d862389 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 18 Nov 2026 16:14:01 +0800 Subject: [PATCH 157/203] docs: show how to read and copy filtered blob rows (#5086) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The table guide starts with two tasks using the same `photos` table: read the bytes of filtered images with the LanceDB Python SDK and copy those images into another Enterprise table with `INSERT INTO … SELECT`. The examples distinguish SDK descriptors, independent row-ID fetches, Function readers and Enterprise 1.12.0 SQL results. The Enterprise support page covers SDK, server and proxy compatibility when query-bound reads fail. --- docs/web/deployment/support.mdx | 19 +++ docs/web/management/table.mdx | 231 ++++++++++---------------------- 2 files changed, 93 insertions(+), 157 deletions(-) diff --git a/docs/web/deployment/support.mdx b/docs/web/deployment/support.mdx index 09b2892c3..d97546932 100644 --- a/docs/web/deployment/support.mdx +++ b/docs/web/deployment/support.mdx @@ -38,3 +38,22 @@ post in Discord or email: Talk to your account executive, file a support ticket, or reach the LanceDB support and engineering team directly for dedicated assistance. + +### Python blob queries raise `NotImplementedError` {#blob-query-bytes} + +If a Blob v2 query works in `"descriptions"` mode but fails in `"bytes"` mode, +check that the Python SDK and every serving node support snapshot-bound reads. +Enterprise 1.12.0 supports separate row-ID fetches. For query-bound reads, +upgrade the serving path before enabling the feature in clients. + +- On the query response, the proxy must preserve `x-lancedb-query-version` + and `x-lancedb-query-snapshot`. The legacy `x-lancedb-version` watermark + or Arrow metadata alone cannot identify the snapshot that produced the rows. +- On each payload request, forward the selected version and the + `x-lancedb-query-snapshot` header. The server checks the identity against + the dataset it opens and echoes it in the response. The proxy must preserve + that echo so the SDK can verify it before returning bytes. + +If the version was deleted or the table was recreated, repeat the query to +select a current snapshot. To finish reading the original selection, retain +its table version until the last batch has been read. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index cfe363176..c24b08b4a 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -384,8 +384,8 @@ file, up to 64 KiB by default, and larger values are stored outside it. Early access -A `blob` column keeps metadata separate from the payload bytes, so queries can -filter rows without loading the blobs. +Filter rows by their metadata first. Then read the matching blob bytes in +Python, or copy the matching rows to another table with Enterprise SQL. {/* Draft for Blob v2 GA. Confirm release status before removing Early access. @@ -393,15 +393,62 @@ Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled are outside the GA support scope. */} -SDK queries return descriptors by default, which contain metadata about the -blob instead of its bytes. Enterprise SQL queries return payload bytes by -default; use `blob_descriptor(column)` to select metadata instead. With an SDK, -you can -[read the bytes in the query results](#multimodal-blob-query-results) or -[fetch them by row ID](#multimodal-read-blobs). +Suppose your Enterprise database has a `photos` table with an integer `id` and a +Blob v2 column named `image`. Set `LANCEDB_URI`, `LANCEDB_API_KEY`, and +`LANCEDB_HOST_OVERRIDE` to your database URI, API key, and HTTPS endpoint. +See [Connect to LanceDB Enterprise](/basics/catalog#enterprise). -In Python, plain `to_pandas()` scans can also return `BlobFile` handles when -`pylance` is installed. +An SDK query normally returns a descriptor with the blob's location and size. +Pass `blob_mode="bytes"` to get the actual image in the same query. Each result +contains Python `bytes`, or `None` for a null image. + +```python +import os +import lancedb + +db = lancedb.connect( + os.environ["LANCEDB_URI"], + api_key=os.environ["LANCEDB_API_KEY"], + host_override=os.environ["LANCEDB_HOST_OVERRIDE"], +) +rows = ( + db.open_table("photos").search() + .where("id < 100") + .select(["id", "image"]) + .limit(10) + .to_list(blob_mode="bytes") +) +for row in rows: + image = row["image"] + print(row["id"], len(image) if image is not None else None) +``` + +Use this mode with a Python SDK and Enterprise deployment that support +snapshot-bound blob reads. The bytes come from the same table version as the +filtered rows. Keep that version available until the read finishes. On +Enterprise 1.12.0, or when you already have row IDs, use `fetch_blobs()`. +Keep the source unchanged between selecting the IDs and fetching their bytes. +Inside a LanceDB Function, a parameter annotated with `lancedb.BlobReader` +lets the function seek and read the input on demand. +[Fetch blobs by row ID](#multimodal-read-blobs) · [Troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes) + +#### Copy a subset of blob rows {#multimodal-copy-subset} + +To copy images within the same Enterprise database, run the filter on the +server. This example appends matching rows to an existing `photo_subset` +table with the same `id` and blob `image` columns. + +```sql +INSERT INTO photo_subset (id, image) +SELECT id, image FROM photos WHERE id < 100; +``` + +In Enterprise 1.12.0, selecting a Blob v2 column directly in SQL returns the +payload as `large_binary`. Use `blob_descriptor(image)` when you want storage +metadata. For a copy, select `image` itself. +[SQL blob descriptors](/sql/dql/blob-descriptor) + +#### Blob storage layouts {#blob-storage-layouts} 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: @@ -500,141 +547,23 @@ methods `to_pandas()`, `to_arrow()`, `to_list()`, and `to_batches()` accept a | `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`. | +| `"lazy"` | Default. Local plain scans return seekable `BlobFile` handles; local vector, full-text, hybrid, and ordered queries return descriptor dicts. Enterprise queries raise `NotImplementedError`. | 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. | -For supported local v2 blob projections, `to_pandas(blob_mode="bytes")` and +For supported v2 blob projections, `to_pandas(blob_mode="bytes")` and `to_pandas(blob_mode="descriptions")` use native Arrow conversion without pylance. Eligible local plain scans also convert row-addressable legacy blob bytes without pylance. Pandas conversions that need the Lance scanner, -including plain-scan `"lazy"` handles and scanner-only options, still require -pylance. `to_arrow()`, `to_list()`, `to_batches()`, and the fetch methods do -not require pylance for supported local queries. +including local plain-scan `"lazy"` handles and scanner-only options, still +require pylance. `to_arrow()`, `to_list()`, `to_batches()`, and the fetch +methods do not require pylance for supported queries. -`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 -`fetch_blob_files`. - -{/* Draft for the Enterprise Python bytes release. Replace the released instructions above only after SDK and serving-node rollout. - -`blob_mode="bytes"` also supports Enterprise queries. The SDK locks all blob -fetches, including streaming batches, to both the version in -`x-lancedb-query-version` and the incarnation/revision identity in -`x-lancedb-query-snapshot`, captured from the same query response. Every payload -request verifies that identity against the actual opened dataset before reading -rows. Concurrent writes therefore preserve the selected payloads. Dropping and -recreating a table, even at the same location and version, cannot substitute the -replacement's bytes: the original snapshot is served or the read fails explicitly. - -Upgrade the SDK and every serving node to support snapshot identities. A server -that reports only a numeric query version, a legacy `x-lancedb-version` watermark, -or Arrow schema metadata does not enable deferred bytes. Missing or unsupported -identities raise `NotImplementedError`; use `"descriptions"` until the upgrade is -complete. Ordinary queries, descriptors, and independent `fetch_blobs` calls keep -working. Old SDKs keep their existing behavior and do not gain this protection -from a server-only upgrade. Realtime/MemWAL and historical manifests without a -native transaction identity do not support deferred bytes. Snapshot identities -do not retain old versions; deleting the selected version still fails explicitly. -In-memory tables and namespace `QueryTable` pushdown do not support bytes mode. -On an Enterprise table, sync `Table.to_pandas()` and `Table.to_arrow()` are not -supported; use `table.search()` instead. A query's `to_pandas()` also raises in -the default `"lazy"` mode because remote lazy handles are not supported. -*/} - -###### Copy a subset of blob rows {#multimodal-copy-subset} - -SDK descriptors identify stored payloads; materialize the bytes before inserting -them into another table. These APIs return different values: - -| Read path | Value | -| --- | --- | -| Enterprise SQL | Raw payload bytes by default. | -| An SDK Arrow query in `"descriptions"` mode | Descriptor struct identifying the stored blob. Treat it as opaque. | -| `table.fetch_blobs(column, row_ids)` | Arrow `large_binary` array; `.to_pylist()` gives `bytes` or `None` in the requested order. | -| A Function parameter annotated `lancedb.BlobReader` | Lazy, seekable reader over the input blob, available inside the Function. | - -For an Enterprise source table, select the rows and fetch their bytes explicitly. -The following example copies up to 100 rows from an existing `images` table with -an integer `id` and a blob `image` column. Keep the source unchanged during this -operation: selection and fetching are separate requests. - -```python -import lancedb -import pyarrow as pa - -source = db.open_table("images") -hits = ( - source.search() - .where("id < 100") - .select(["id"]) - .with_row_id(True) - .limit(100) - .to_arrow() -) -payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist() -subset = db.create_table( - "image_subset", - schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), -) -if hits.num_rows: - subset.add([ - {"id": image_id, "image": payload} - for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True) - ]) -``` - -Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches -for larger subsets; `fetch_blobs` materializes all requested bytes in memory. -For incremental decoding, use `fetch_blob_files` instead. - -{/* Draft for the Enterprise Python bytes release. Replace the copy example above when snapshot-bound remote bytes are released. - -For Enterprise tables, prefer server-side `CREATE TABLE AS SELECT` or -`INSERT INTO ... SELECT` to copy blobs without a client round trip: - -```sql -CREATE TABLE image_subset AS SELECT id, image FROM images WHERE id < 100; --- To append to an existing destination: -INSERT INTO image_subset SELECT id, image FROM images WHERE id >= 100 AND id < 200; -``` - -For SDK copies, query with `blob_mode="bytes"` to bind selection and payload -reads to one snapshot. The following example copies up to 100 rows from an -existing `images` table with an integer `id` and a blob `image` column. - -```python -import lancedb -import pyarrow as pa - -source = db.open_table("images") -hits = ( - source.search() - .where("id < 100") - .select(["id", "image"]) - .limit(100) - .to_arrow(blob_mode="bytes") -) -subset = db.create_table( - "image_subset", - schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]), -) -if hits.num_rows: - subset.add(hits) -``` - -Empty blobs remain `b""` and null blobs remain `None`. Fetch bounded batches -for larger subsets; `fetch_blobs` materializes all requested bytes in memory. -For incremental decoding, use `fetch_blob_files` instead. - -Remote bytes mode requires a server that supports snapshot-bound Blob reads. -Older servers and Realtime/MemWAL tables can still return descriptors, but -bytes mode raises an explicit unsupported-operation error before fetching payloads. -*/} +On Enterprise tables, call `table.search()` for `blob_mode="bytes"`. The sync +`Table.to_pandas()` and `Table.to_arrow()` conversions are unsupported. For +Realtime/MemWAL tables or historical versions without a native transaction +identity, request descriptors. In-memory tables and namespace `QueryTable` +pushdown do not support bytes mode. `blob_mode="bytes"` materializes top-level and struct-nested blob columns. It raises `ValueError` when the selected columns include blobs @@ -663,25 +592,13 @@ 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 blobs inside lists, Enterprise tables, namespace `QueryTable` -pushdown, or query shapes that cannot preserve their row results. Legacy v1 -bytes are limited to eligible local plain scans. 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`. - -{/* Draft for the Enterprise Python bytes release. Replace the streaming restrictions above after release. - -Bytes mode has the same restrictions as `to_arrow(blob_mode="bytes")`, -including no blobs inside lists, namespace `QueryTable` pushdown, or query -shapes that cannot preserve their row results. Enterprise queries require a -valid `x-lancedb-query-version` and `x-lancedb-query-snapshot` response headers. -Legacy v1 bytes are limited to -eligible local plain scans. For local queries, 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`. -*/} +including no blobs inside lists, in-memory tables, namespace `QueryTable` +pushdown, or query shapes that cannot preserve their row results. Each Enterprise +batch reads blob bytes from the snapshot that produced the rows. Legacy v1 +bytes are limited to eligible local plain scans. For +local queries, 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} From a653d861ecb2cfa6d7ce37d5dab5e1e4fa213cb1 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 18 Nov 2026 16:15:42 +0800 Subject: [PATCH 158/203] fix(python): allow static diagnostic imports in Functions (#5084) Functions previously rejected every `sys` or `importlib` import even when the source only used a statically visible diagnostic. Allow exactly `sys.stderr`, `sys.version_info`, and `importlib.metadata.version`, with direct imports, `from` imports, and aliases treated identically whether they appear at module level or inside the function or class body. Every other use of a namespace-access module still fails at decoration. The error now names the rejected operation, such as `sys.modules`, and lists the supported diagnostic operations. Tests package and execute the artifact offline for each import form, and reject unsupported attributes, submodules, dynamic attribute access, and rebinding. ENT-3918. --- docs/src/python/python.md | 46 +++- docs/web/management/function.mdx | 19 ++ python/python/lancedb/functions.py | 247 +++++++++++++++--- .../python/tests/test_function_packaging.py | 142 +++++++++- 4 files changed, 407 insertions(+), 47 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b7859c2f7..04f315e1c 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -481,19 +481,41 @@ scaler.close() ### Function packaging restrictions The decorator snapshots the Function's source and referenced globals into a new -module. It conservatively rejects imports of `sys`, `builtins`, `importlib`, -`inspect`, `gc`, `ctypes`, and `types`, including submodules such as `ctypes.util` -and `importlib.metadata`. This applies to imports inside function or class bodies -and references to module-level aliases. Even ordinary uses such as `sys.version` -and `ctypes.util.find_library` are blocked: these modules can reach names outside -the reconstructed Function namespace. References to `globals`, `locals`, `vars`, -`eval`, `exec`, `compile`, and `__import__` are rejected as dynamic namespace access. -These restrictions also apply to the deprecated `@udf` alias. +module. It supports three statically recognizable diagnostic operations: +`sys.stderr`, `sys.version_info`, and `importlib.metadata.version`. Direct +imports, `from` imports, and aliases are treated the same way, whether the +import appears inside a function or class body or at module level. -For legitimate uses, move the code into an importable helper module and ship it -with `code=`, or install its package with `pip=` or `conda=`. Imported helpers keep -their own namespace; the packager does not scan their bodies. Helpers defined in -`__main__` are copied by source and have the same restrictions as the Function. +Other imports of `sys`, `builtins`, `importlib`, `inspect`, `gc`, `ctypes`, and +`types`, including submodules such as `ctypes.util` and `importlib.resources`, +remain blocked. This applies to imports inside function or class bodies and +references to module-level aliases. Even ordinary uses such as `sys.version` +and `ctypes.util.find_library` are blocked: these modules can reach names +outside the reconstructed Function namespace. References to `globals`, `locals`, +`vars`, `eval`, `exec`, `compile`, and `__import__` are rejected as dynamic +namespace access. These restrictions also apply to the deprecated `@udf` alias. + +For example, a diagnostic Function can report its Python version and NumPy +version without a helper module: + +```python +import importlib.metadata +import sys + +from lancedb import function + + +@function(pip=["numpy"]) +def report(value: int) -> str: + print("diagnostic", file=sys.stderr) + return f"numpy {importlib.metadata.version('numpy')} on {sys.version_info}" +``` + +For other restricted uses, move the code into an importable helper module and +ship it with `code=`, or install its package with `pip=` or `conda=`. Imported +helpers keep their own namespace; the packager does not scan their bodies. +Helpers defined in `__main__` are copied by source and have the same +restrictions as the Function. For example, put this helper in `native_diagnostics/__init__.py`: diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 562de05c6..bc237d79e 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -767,6 +767,25 @@ seen and unsupported where it cannot: `globals()`, `eval`, `sys.modules`, `builtins`. Closures and a non-standard `__builtins__` are rejected outright. +Three statically recognizable diagnostic operations are supported: `sys.stderr`, +`sys.version_info`, and `importlib.metadata.version`. Direct imports, `from` +imports, and aliases work the same way. Any other use of `sys`, `builtins`, +`importlib`, `inspect`, `gc`, `ctypes`, or `types` is rejected; move it into an +importable helper module. + +```python +import importlib.metadata +import sys + +from lancedb import function + + +@function(pip=["numpy"]) +def report(value: int) -> str: + print("diagnostic", file=sys.stderr) + return f"numpy {importlib.metadata.version('numpy')} on {sys.version_info}" +``` + 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. diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 5ea45a6a6..2d369e3ec 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -16,6 +16,7 @@ import builtins import base64 import functools import hashlib +import importlib.metadata import importlib.util import inspect import symtable @@ -2114,6 +2115,17 @@ def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType] _DYNAMIC_NAMESPACE_ACCESS = frozenset( {"globals", "locals", "vars", "eval", "exec", "compile", "__import__"} ) +# Static diagnostic operations the packager can reconstruct. Anything else that +# reaches through a namespace-access module remains unrepresentable. +_APPROVED_NAMESPACE_ATTRIBUTES = { + "sys": frozenset({"stderr", "version_info"}), + "importlib.metadata": frozenset({"version"}), +} +_APPROVED_NAMESPACE_OPERATIONS = ( + "sys.stderr", + "sys.version_info", + "importlib.metadata.version", +) # Modules that hand out namespaces (`sys.modules`, `builtins`, importers, # introspection). The artifact's module namespace holds only the names it was # packaged with, so reaching around it cannot be represented. @@ -2128,28 +2140,170 @@ _NAMESPACE_HELPER_HINT = ( ) +_APPROVED_NAMESPACE_HINT = ( + "The supported diagnostic operations are " + + ", ".join(_APPROVED_NAMESPACE_OPERATIONS) + + ". " +) + + +def _namespace_operation_error(operations: Sequence[str]) -> ValueError: + label = operations[0] if len(operations) == 1 else list(operations) + return ValueError( + f"@function cannot package namespace operation {label!r}. " + "The artifact's module namespace holds only the names it was packaged " + "with, so references that reach around it cannot be represented. " + + _APPROVED_NAMESPACE_HINT + + _NAMESPACE_HELPER_HINT + ) + + def _namespace_import_error(modules: Sequence[str]) -> ValueError: return ValueError( f"@function cannot package imports from namespace-access modules: {modules!r}. " f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) " "are blocked because they can access names outside the packaged " - "Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT + "Function's reconstructed module namespace. " + + _APPROVED_NAMESPACE_HINT + + _NAMESPACE_HELPER_HINT ) -def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]: - found: set[str] = set() +def _namespace_import_bindings( + definition: Union[ast.FunctionDef, ast.ClassDef], +) -> tuple[dict[str, frozenset[str]], list[str], list[str]]: + """Return approved diagnostic bindings and rejected imports. + + A binding maps the local name an import creates to the attribute paths + that may be read through it. Rejected modules and operations are kept + separate so each error names the relevant rule. + """ + bindings: dict[str, frozenset[str]] = {} + blocked_modules: set[str] = set() + blocked_operations: set[str] = set() for node in ast.walk(definition): if isinstance(node, ast.Import): - found.update( - alias.name - for alias in node.names - if alias.name.split(".")[0] in _NAMESPACE_MODULES - ) - elif isinstance(node, ast.ImportFrom) and node.module: - if node.module.split(".")[0] in _NAMESPACE_MODULES: - found.add(node.module) - return sorted(found) + for alias in node.names: + root = alias.name.split(".")[0] + if root not in _NAMESPACE_MODULES: + continue + attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(alias.name) + if attributes is None: + blocked_modules.add(alias.name) + continue + if alias.asname: + name = alias.asname + bases = frozenset(f"{name}.{attribute}" for attribute in attributes) + else: + name = root + module = alias.name if "." in alias.name else name + bases = frozenset( + f"{module}.{attribute}" for attribute in attributes + ) + bindings[name] = bindings.get(name, frozenset()) | bases + elif ( + isinstance(node, ast.ImportFrom) + and node.level == 0 + and node.module + and node.module.split(".")[0] in _NAMESPACE_MODULES + ): + if node.module == "importlib": + for alias in node.names: + if alias.name == "metadata": + name = alias.asname or "metadata" + bindings[name] = bindings.get(name, frozenset()) | frozenset( + {f"{name}.version"} + ) + else: + blocked_modules.add("importlib") + continue + attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(node.module) + if attributes is None: + blocked_modules.add(node.module) + continue + for alias in node.names: + if alias.name in attributes: + name = alias.asname or alias.name + bindings[name] = bindings.get(name, frozenset()) | frozenset({name}) + else: + blocked_operations.add(f"{node.module}.{alias.name}") + return bindings, sorted(blocked_modules), sorted(blocked_operations) + + +def _namespace_binding_errors( + definition: Union[ast.FunctionDef, ast.ClassDef], + bindings: Mapping[str, frozenset[str]], +) -> list[str]: + """Operations that read a diagnostic binding outside its approved paths.""" + if not bindings: + return [] + parents: dict[ast.AST, ast.AST] = {} + for node in ast.walk(definition): + for child in ast.iter_child_nodes(node): + parents[child] = node + invalid: set[str] = set() + for node in ast.walk(definition): + if not isinstance(node, ast.Name): + continue + allowed = bindings.get(node.id) + if allowed is None: + continue + if not isinstance(node.ctx, ast.Load): + invalid.add(node.id) + continue + path = node.id + current: ast.AST = node + while True: + parent = parents.get(current) + if isinstance(parent, ast.Attribute) and parent.value is current: + path = f"{path}.{parent.attr}" + current = parent + continue + break + if not any(path == base or path.startswith(f"{base}.") for base in allowed): + invalid.add(path) + continue + if any(part.startswith("__") for part in path.split(".")[1:]): + invalid.add(path) + return sorted(invalid) + + +def _approved_global_namespace_binding( + definition: Optional[Union[ast.FunctionDef, ast.ClassDef]], + name: str, + value: Any, +) -> Optional[str]: + """The artifact import for an approved diagnostic global, if any.""" + if definition is None: + return None + if isinstance(value, types.ModuleType): + if value is sys: + bases = frozenset({f"{name}.stderr", f"{name}.version_info"}) + line = f"import sys as {name}" + elif value is importlib.metadata: + bases = frozenset({f"{name}.version"}) + line = f"import importlib.metadata as {name}" + elif value is importlib and name == "importlib": + # ``import importlib.metadata`` binds the top-level package name. + bases = frozenset({"importlib.metadata.version"}) + line = "import importlib.metadata" + else: + return None + elif value is sys.stderr: + bases = frozenset({name}) + line = f"from sys import stderr as {name}" + elif value is sys.version_info: + bases = frozenset({name}) + line = f"from sys import version_info as {name}" + elif value is importlib.metadata.version: + bases = frozenset({name}) + line = f"from importlib.metadata import version as {name}" + else: + return None + invalid = _namespace_binding_errors(definition, {name: bases}) + if invalid: + raise _namespace_operation_error(invalid) + return line def _module_references(module_source: str) -> set[str]: @@ -2462,14 +2616,21 @@ class _SourcePackager: "Function's reconstructed module namespace. Reference dependencies " "explicitly. " + _NAMESPACE_HELPER_HINT ) - namespace_imports = _namespace_imports(definition) - if namespace_imports: - raise _namespace_import_error(namespace_imports) + namespace_bindings, blocked_modules, blocked_operations = ( + _namespace_import_bindings(definition) + ) + if blocked_modules: + raise _namespace_import_error(blocked_modules) + if blocked_operations: + raise _namespace_operation_error(blocked_operations) + invalid_operations = _namespace_binding_errors(definition, namespace_bindings) + if invalid_operations: + raise _namespace_operation_error(invalid_operations) self._warn_unshipped_direct_imports(definition) self._packaged.add(id(target)) self._claim(target.__name__, ("definition", id(target))) if reader_name is not None: - self._bind(reader_name, BlobReader) + self._bind(reader_name, BlobReader, definition=definition) unresolved = [] for name in sorted(references): if name == target.__name__: @@ -2481,7 +2642,7 @@ class _SourcePackager: ) continue if name in namespace: - self._bind(name, namespace[name]) + self._bind(name, namespace[name], definition=definition) elif not hasattr(builtins, name): unresolved.append(name) if unresolved: @@ -2536,7 +2697,13 @@ class _SourcePackager: "name to different values" ) - def _bind(self, name: str, value: Any) -> None: + def _bind( + self, + name: str, + value: Any, + *, + definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None, + ) -> None: if _packaged_by_source(value): if value.__name__ != name: raise ValueError( @@ -2547,14 +2714,23 @@ class _SourcePackager: self._definitions.append(self._definition(value, entry=False)) self._claim(name, ("definition", id(value))) return - line = self._global_source(name, value) + line = self._global_source(name, value, definition=definition) self._claim(name, line) self._imports[name] = line - def _global_source(self, name: str, value: Any) -> str: + def _global_source( + self, + name: str, + value: Any, + *, + definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None, + ) -> str: """One module-level line that rebinds `name` to `value` in the artifact: an import for modules and importable classes/functions, a captured copy otherwise.""" + approved = _approved_global_namespace_binding(definition, name, value) + if approved is not None: + return approved if value is BlobReader: return f"from lance_blob import BlobReader as {name}" if isinstance(value, types.ModuleType): @@ -3440,20 +3616,25 @@ def function( values, such as instances of your own classes, inside the function or class body as well. - **Namespace restrictions.** The packaged source cannot import ``sys``, + **Namespace restrictions.** The packaged source may use three static + diagnostic operations: ``sys.stderr``, ``sys.version_info``, and + ``importlib.metadata.version``. Direct imports, ``from`` imports, and + aliases are treated the same way, whether the import appears inside the + function or class body or at module level. Any other import of ``sys``, ``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``, - including submodules such as ``ctypes.util`` and ``importlib.metadata``. - Referencing a module-level alias for one of these modules is also rejected. - References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, - ``compile``, or ``__import__`` are rejected as dynamic namespace access. - These restrictions are conservative: even ordinary uses such as - ``ctypes.util.find_library`` or ``sys.version`` are blocked because these - modules can reach names outside the reconstructed Function namespace. - Move such code into an importable helper module supplied with ``code=``, - ``pip=``, or ``conda=``, then import and call the helper from the Function. - Helpers imported normally keep their own module namespace; these checks do - not scan their bodies. A helper defined in ``__main__`` is packaged by source - and is subject to the same checks. + including submodules such as ``ctypes.util``, ``importlib.resources``, and + ``importlib.import_module``, is rejected. Referencing a module-level alias + for an unapproved module or operation is also rejected. References to + ``globals``, ``locals``, ``vars``, ``eval``, ``exec``, ``compile``, or + ``__import__`` are rejected as dynamic namespace access. These + restrictions are conservative: even ordinary uses such as + ``ctypes.util.find_library`` or ``sys.version`` remain blocked because + these modules can reach names outside the reconstructed Function + namespace. Move such code into an importable helper module supplied with + ``code=``, ``pip=``, or ``conda=``, then import and call the helper from + the Function. Helpers imported normally keep their own module namespace; + these checks do not scan their bodies. A helper defined in ``__main__`` is + packaged by source and is subject to the same checks. Changing any packaged source, including a module in ``code``, produces a new Function version; the environment built from ``pip`` or ``conda`` is diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index ae74cc8cd..874dd809f 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -727,7 +727,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): @pytest.mark.parametrize( "module_name", [ - "sys", "builtins", "importlib", "inspect", @@ -735,7 +734,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason(): "ctypes", "types", "ctypes.util", - "importlib.metadata", ], ) @pytest.mark.parametrize("import_style", ["import", "from", "global"]) @@ -772,6 +770,146 @@ def test_namespace_module_errors_explain_the_rule_and_remedy( assert "dynamic namespace access" not in message +@pytest.mark.parametrize("module_level", [False, True], ids=["body", "module"]) +@pytest.mark.parametrize( + ("import_statement", "expression"), + [ + ("import sys", "sys.stderr"), + ("import sys as diagnostic", "diagnostic.stderr"), + ("from sys import stderr", "stderr"), + ("from sys import stderr as error_stream", "error_stream"), + ("import sys", "sys.version_info"), + ("import sys as diagnostic", "diagnostic.version_info"), + ("from sys import version_info", "version_info"), + ("from sys import version_info as python_version", "python_version"), + ("import importlib.metadata", "importlib.metadata.version('pytest')"), + ("import importlib.metadata as diagnostic", "diagnostic.version('pytest')"), + ("from importlib import metadata", "metadata.version('pytest')"), + ( + "from importlib import metadata as diagnostic", + "diagnostic.version('pytest')", + ), + ("from importlib.metadata import version", "version('pytest')"), + ( + "from importlib.metadata import version as diagnostic", + "diagnostic('pytest')", + ), + ], +) +def test_diagnostic_namespace_operations_package_and_run( + helper_package, module_level, import_statement, expression +): + if module_level: + source = ( + f"{import_statement}\n\n" + "def probe(value: str) -> str:\n" + f" return str({expression}) + value\n" + ) + else: + source = ( + "def probe(value: str) -> str:\n" + f" {import_statement}\n" + f" return str({expression}) + value\n" + ) + module = helper_package("fx_diagnostic_operation", {"__init__.py": source}) + + packaged = artifact(function(module.probe)).decode() + namespace = {} + exec(compile(packaged, "user_function.py", "exec"), namespace) + assert namespace["probe"]("!").endswith("!") + + +@pytest.mark.parametrize( + ("body", "operation"), + [ + ("import sys\nreturn str(sys.modules)", "sys.modules"), + ("import sys as s\nreturn str(s.path)", "s.path"), + ("import sys\nreturn str(sys.version)", "sys.version"), + ("import sys\nreturn str(sys.stdout)", "sys.stdout"), + ("import sys\nreturn str(getattr(sys, 'stderr'))", "sys"), + ("import sys\nstream = sys\nreturn str(stream)", "sys"), + ("import sys\nsys = object()\nreturn str(sys)", "sys"), + ("from sys import path\nreturn str(path)", "sys.path"), + ( + "import importlib.metadata\n" + "return importlib.metadata.distribution('pytest').version", + "importlib.metadata.distribution", + ), + ( + "import importlib.metadata as m\nreturn m.distribution('pytest').version", + "m.distribution", + ), + ( + "from importlib.metadata import distribution\n" + "return distribution('pytest').version", + "importlib.metadata.distribution", + ), + ( + "from importlib.metadata import version\nreturn str(version.__globals__)", + "version.__globals__", + ), + ( + "import importlib\nreturn str(importlib.import_module('os'))", + "importlib", + ), + ( + "from importlib import import_module\nreturn str(import_module('os'))", + "importlib", + ), + ( + "import importlib.resources\nreturn str(importlib.resources.files('x'))", + "importlib.resources", + ), + ("import inspect\nreturn str(inspect.currentframe())", "inspect"), + ( + "from ctypes import util\nreturn str(util.find_library('c'))", + "ctypes", + ), + ("import gc\nreturn str(gc.get_objects())", "gc"), + ("import builtins\nreturn str(builtins)", "builtins"), + ("import types\nreturn str(types.SimpleNamespace())", "types"), + ], +) +def test_unsupported_namespace_operations_are_rejected(helper_package, body, operation): + source = "def blocked(value: str) -> str:\n" + textwrap.indent(body, " ") + module = helper_package( + "fx_unsupported_namespace_operation", {"__init__.py": source} + ) + + with pytest.raises(ValueError) as error: + function(module.blocked) + message = str(error.value) + assert repr(operation) in message + assert "supported diagnostic operations" in message + + +@pytest.mark.parametrize( + ("preamble", "body", "operation"), + [ + ( + "import sys as diagnostic", + "return str(diagnostic.modules)", + "diagnostic.modules", + ), + ( + "import importlib.metadata as diagnostic", + "return diagnostic.distribution('pytest').version", + "diagnostic.distribution", + ), + ("from sys import stderr", "return str(stderr.__class__)", "stderr.__class__"), + ], +) +def test_module_level_diagnostic_alias_rejects_unsupported_use( + helper_package, preamble, body, operation +): + source = f"{preamble}\n\ndef blocked(value: str) -> str:\n {body}\n" + module = helper_package("fx_diagnostic_alias", {"__init__.py": source}) + + with pytest.raises(ValueError) as error: + function(module.blocked) + assert repr(operation) in str(error.value) + + @pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") def test_udf_namespace_import_error_explains_the_helper_alternative(): with pytest.raises(ValueError, match="ctypes.util.*importable helper module"): From a98cffda4bc16e310bd8497bb138c58da651ab2d Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 18 Nov 2026 08:16:29 +0000 Subject: [PATCH 159/203] =?UTF-8?q?Bump=20version:=200.42.0-beta.19=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- 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 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 6efd2bf48..ba0d4ebaf 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.19" +current_version = "0.42.0-beta.20" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 923b7e94e..44405cdf0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "arrow-array", "arrow-buffer", @@ -6185,7 +6185,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index f6e7497d0..bf733dd23 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.42.0-beta.19 + 0.42.0-beta.20 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 5a49a1a60..e8b214d9f 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.19 + 0.42.0-beta.20 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 46d5fac54..06bfe4687 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.19 + 0.42.0-beta.20 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index d0d000e10..6de370ef1 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" 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 4f6851519..572858a82 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.42.0-beta.19", + "version": "0.42.0-beta.20", "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 a4027033a..18bd9e1c4 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.42.0-beta.19", + "version": "0.42.0-beta.20", "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 49a50f33f..79671f79e 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.42.0-beta.19", + "version": "0.42.0-beta.20", "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 8f9f3ec18..6048d5def 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.42.0-beta.19", + "version": "0.42.0-beta.20", "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 bc32a415f..7c6e7d4a4 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.42.0-beta.19", + "version": "0.42.0-beta.20", "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 7e7db948b..917f779fb 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.42.0-beta.19", + "version": "0.42.0-beta.20", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e1cd2879e..97d3aec62 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.42.0-beta.19", + "version": "0.42.0-beta.20", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index e040cb2b8..ae6debdd1 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.19", + "version": "0.42.0-beta.20", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 1b9c44290..8604daabf 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 97d2e732b..1d83c0cd4 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 8e0348a2b..11f1c9512 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.19" +version = "0.42.0-beta.20" edition = "2021" license.workspace = true repository.workspace = true From 9f58d8aab62eaa053289a5abb0a9f9deff4b62d4 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 18 Nov 2026 17:19:02 +0800 Subject: [PATCH 160/203] docs: add an ordinary Blob v2 photo tutorial (#5087) The quickstart links to a Blob example that assumes both tables already exist. Replace that gap with a from-empty photo tutorial: generate real PNG files with the standard library, ingest an ordinary Blob v2 table, filter metadata, save and compare exact image bytes, then create and verify a filtered destination through Enterprise SQL or an Embedded materialized copy. Keep Early access and distinguish Enterprise 1.12.0 row-ID fetches from deployment-dependent snapshot-bound reads. Cover source stability, range reads and Function readers for large media, ambiguous write recovery, and the absence of a SQL constructor for uploading client-side files. The executable Embedded workflow passed on Python SDK 0.42.0b17 using disposable local storage. Generated snippets, MDX compilation, combined-site `mint validate`, and `mint broken-links --check-anchors --check-redirects` passed. Enterprise connection/SQL examples were checked against the public API and existing 1.12 documentation but were not executed against an Enterprise deployment; this does not establish SQL copy behavior after source cleanup. No saved editions or publication state change. Fixes [OSS-3102](https://linear.app/lancedb/issue/OSS-3102/walk-users-from-image-files-to-a-filtered-blob-v2-table-copy). --- .../blob-v2/py/test_photo_tutorial.py | 149 ++++++++++++ docs/web/management/table.mdx | 226 ++++++++++++++---- docs/web/quickstart.mdx | 6 +- docs/web/snippets/photo_tutorial.mdx | 21 ++ 4 files changed, 356 insertions(+), 46 deletions(-) create mode 100644 docs/web-tests/blob-v2/py/test_photo_tutorial.py create mode 100644 docs/web/snippets/photo_tutorial.mdx diff --git a/docs/web-tests/blob-v2/py/test_photo_tutorial.py b/docs/web-tests/blob-v2/py/test_photo_tutorial.py new file mode 100644 index 000000000..0a33db8a1 --- /dev/null +++ b/docs/web-tests/blob-v2/py/test_photo_tutorial.py @@ -0,0 +1,149 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + + +def test_photo_tutorial(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + # --8<-- [start:photo_files] + import struct + import zlib + from pathlib import Path + + def solid_png(rgb): + def chunk(kind, data): + checksum = zlib.crc32(kind + data) & 0xFFFFFFFF + return ( + struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum) + ) + + header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0) + pixels = (b"\x00" + bytes(rgb) * 8) * 8 + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(pixels)) + + chunk(b"IEND", b"") + ) + + inputs = Path("photo-inputs") + inputs.mkdir() + for label, rgb in [("red", (255, 0, 0)), ("blue", (0, 0, 255))]: + (inputs / f"{label}.png").write_bytes(solid_png(rgb)) + # --8<-- [end:photo_files] + + # --8<-- [start:photo_connect_embedded] + import lancedb + + db = lancedb.connect("./photo-db") + # --8<-- [end:photo_connect_embedded] + + # --8<-- [start:photo_ingest] + import pyarrow as pa + + schema = pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("label", pa.string(), nullable=False), + lancedb.blob("image", nullable=False), + ], + metadata={"lance.blob.managed": "false"}, + ) + photos = db.create_table("photos", schema=schema) + photos.add( + [ + {"id": 1, "label": "red", "image": (inputs / "red.png").read_bytes()}, + {"id": 2, "label": "blue", "image": (inputs / "blue.png").read_bytes()}, + ] + ) + assert photos.count_rows() == 2 + # --8<-- [end:photo_ingest] + + # --8<-- [start:photo_fetch] + hits = ( + photos.search() + .where("label = 'red'") + .select(["id", "label"]) + .with_row_id(True) + .limit(10) + .to_list() + ) + assert [row["id"] for row in hits] == [1] + payloads = photos.fetch_blobs("image", [row["_rowid"] for row in hits]).to_pylist() + assert payloads == [(inputs / "red.png").read_bytes()] + saved = Path("selected-red.png") + saved.write_bytes(payloads[0]) + assert saved.read_bytes() == (inputs / "red.png").read_bytes() + # --8<-- [end:photo_fetch] + + # --8<-- [start:photo_bytes] + rows = ( + photos.search() + .where("label = 'red'") + .select(["id", "image"]) + .limit(10) + .to_list(blob_mode="bytes") + ) + assert rows == [{"id": 1, "image": (inputs / "red.png").read_bytes()}] + # --8<-- [end:photo_bytes] + + # --8<-- [start:photo_ranges] + with photos.fetch_blob_files("image", [hits[0]["_rowid"]])[0] as reader: + assert reader.read_range(0, 8) == b"\x89PNG\r\n\x1a\n" + # --8<-- [end:photo_ranges] + + # --8<-- [start:photo_copy_embedded] + selected = ( + photos.search() + .where("label = 'red'") + .select(["id", "label", "image"]) + .limit(10) + .to_arrow(blob_mode="bytes") + ) + db.create_table("photo_subset", data=selected, schema=schema) + # --8<-- [end:photo_copy_embedded] + + # --8<-- [start:photo_verify] + photo_subset = db.open_table("photo_subset") + assert photo_subset.count_rows() == 1 + copied = ( + photo_subset.search() + .select(["id", "label"]) + .with_row_id(True) + .limit(10) + .to_list() + ) + assert [(row["id"], row["label"]) for row in copied] == [(1, "red")] + copied_bytes = photo_subset.fetch_blobs( + "image", [row["_rowid"] for row in copied] + ).to_pylist() + assert copied_bytes == [(inputs / "red.png").read_bytes()] + # --8<-- [end:photo_verify] + + +def enterprise_connection(): + # --8<-- [start:photo_connect_enterprise] + import os + + import lancedb + + db = lancedb.connect( + os.environ["LANCEDB_URI"], + api_key=os.environ["LANCEDB_API_KEY"], + region=os.environ["LANCEDB_REGION"], + host_override=os.environ["LANCEDB_HOST_OVERRIDE"], + sql_host_override=os.environ["LANCEDB_SQL_HOST_OVERRIDE"], + ) + # --8<-- [end:photo_connect_enterprise] + return db + + +def copy_with_enterprise_sql(db): + # --8<-- [start:photo_copy_sql] + db.execute_query( + "CREATE TABLE photo_subset (id BIGINT, label VARCHAR, image BLOB)" + ).read_all() + db.execute_query( + "INSERT INTO photo_subset (id, label, image) " + "SELECT id, label, image FROM photos WHERE label = 'red'" + ).read_all() + # --8<-- [end:photo_copy_sql] diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index c24b08b4a..dba741c2b 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -141,6 +141,19 @@ import { PyQueryToPandasKwargs as QueryToPandasKwargs, } from '/snippets/blob_pylance.mdx'; +import { + PyPhotoFiles, + PyPhotoConnectEmbedded, + PyPhotoConnectEnterprise, + PyPhotoIngest, + PyPhotoFetch, + PyPhotoBytes, + PyPhotoRanges, + PyPhotoCopyEmbedded, + PyPhotoCopySql, + PyPhotoVerify, +} from '/snippets/photo_tutorial.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 searches over its columns.{/* Draft until branching reaches early access: restore "Branches let you make changes separately from the @@ -393,60 +406,183 @@ Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled are outside the GA support scope. */} -Suppose your Enterprise database has a `photos` table with an integer `id` and a -Blob v2 column named `image`. Set `LANCEDB_URI`, `LANCEDB_API_KEY`, and -`LANCEDB_HOST_OVERRIDE` to your database URI, API key, and HTTPS endpoint. -See [Connect to LanceDB Enterprise](/basics/catalog#enterprise). +#### From image files to a filtered table {#photo-tutorial} -An SDK query normally returns a descriptor with the blob's location and size. -Pass `blob_mode="bytes"` to get the actual image in the same query. Each result -contains Python `bytes`, or `None` for a null image. +Start in an empty working directory and an empty database. This Python tutorial +creates `photos` with `id`, `label`, and Blob v2 `image` columns, saves one +matching image, and copies that row into a fresh `photo_subset` table. It uses +ordinary tables, with Realtime Engine disabled. Avoid other writers while +running the examples. -```python -import os -import lancedb +Install a Python SDK that provides `lancedb.blob`. For preview builds, use the +[installation instructions](/quickstart#python-pre-release-builds). The examples +need `lancedb` and `pyarrow`; generating the images uses only Python's standard +library. -db = lancedb.connect( - os.environ["LANCEDB_URI"], - api_key=os.environ["LANCEDB_API_KEY"], - host_override=os.environ["LANCEDB_HOST_OVERRIDE"], -) -rows = ( - db.open_table("photos").search() - .where("id < 100") - .select(["id", "image"]) - .limit(10) - .to_list(blob_mode="bytes") -) -for row in rows: - image = row["image"] - print(row["id"], len(image) if image is not None else None) -``` +##### 1. Create two image files {#photo-files} -Use this mode with a Python SDK and Enterprise deployment that support -snapshot-bound blob reads. The bytes come from the same table version as the -filtered rows. Keep that version available until the read finishes. On -Enterprise 1.12.0, or when you already have row IDs, use `fetch_blobs()`. -Keep the source unchanged between selecting the IDs and fetching their bytes. -Inside a LanceDB Function, a parameter annotated with `lancedb.BlobReader` -lets the function seek and read the input on demand. -[Fetch blobs by row ID](#multimodal-read-blobs) · [Troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes) +Generate tiny red and blue PNG images with known pixel contents. Open these +files in an image viewer. To use your own photos later, replace the file paths +and the expected bytes in the checks. + + + + {PyPhotoFiles} + + + +##### 2. Choose a connection {#photo-connection} + +For LanceDB Embedded, create a local database: + + + + {PyPhotoConnectEmbedded} + + + +For LanceDB Enterprise, use an empty development database where you can create +ordinary tables. Get the API and Flight SQL endpoints from your administrator; +set these environment variables using the +[Enterprise connection instructions](/basics/catalog#enterprise) and +[SQL connection settings](/basics/sql#sql-is-remote). Choose this connection +instead of the Embedded connection to run the SQL copy later: + + + + {PyPhotoConnectEnterprise} + + + +##### 3. Define the schema and insert the images {#photo-ingest} + +The explicit schema makes `image` a Blob v2 field. The table metadata opts into +ordinary Blob storage. Table creation fails if `photos` already exists; use a +new database for another run. + + + + {PyPhotoIngest} + + + + +If table creation or ingestion loses its response, check whether `photos` +exists and inspect its IDs and image bytes before repeating the write. An +ambiguous result can mean the write committed. Repeating `add` can duplicate +rows. See [write recovery](/ingestion/insert#performance) and +[large upload recovery](/ingestion/insert#bulk-ingests-into-a-remote-table). + + +##### 4. Filter metadata, save an image, and check its contents {#photo-read} + +First select at most ten matching rows without loading their images. Fetch only +those rows' bytes, save the red image, and compare the complete saved file with +the original. This row-ID path works with Enterprise 1.12.0: + + + + {PyPhotoFetch} + + + +`id` is the application's photo ID; `_rowid` is the table's row identifier used +by `fetch_blobs`. Keep the source unchanged between the metadata query and the +fetch. Row IDs alone do not bind the fetch to the query's snapshot. Stable row +IDs across compaction do not protect against an overwrite or a same-name table +replacement. + +With a Python SDK and Enterprise deployment that support **snapshot-bound blob +reads**, request the bytes in the query instead: + + + + {PyPhotoBytes} + + + +The bytes then come from the same table version as the filtered rows. Keep that +version available until the read finishes. Enterprise 1.12.0 users should use +the row-ID example above; support for snapshot-bound reads depends on both the +SDK and the serving deployment. See +[troubleshoot Enterprise blob reads](/deployment/support#blob-query-bytes). +LanceDB Embedded also supports this query mode; use a reader checked out to a +fixed version if concurrent writers can overwrite the source. + +##### Choose a read method for larger media {#photo-read-method} + +| Task | Method | +| --- | --- | +| Save a small, bounded set of complete images | `fetch_blobs`, or query with `blob_mode="bytes"` on a supporting deployment | +| Read a header or part of a large video | `fetch_blob_files`, then `read_range` or `read_ranges` | +| Seek through a video in server-side processing | A LanceDB Function parameter annotated with `lancedb.BlobReader` | +| Copy rows inside Enterprise | SQL `INSERT INTO ... SELECT`, without downloading images to the client | + +A row limit bounds the number of images, not their total size. Avoid fetching +whole videos just to inspect their headers. Here is a range read against the +same red PNG; it verifies the eight-byte PNG signature: + + + + {PyPhotoRanges} + + + +For multiple slices, see [range reads](#multimodal-read-blobs). For a seekable +video reader inside a Function, see +[read a blob incrementally](/curation/create-function#incremental). #### Copy a subset of blob rows {#multimodal-copy-subset} -To copy images within the same Enterprise database, run the filter on the -server. This example appends matching rows to an existing `photo_subset` -table with the same `id` and blob `image` columns. +Continue with the same `photos`, selecting the same red image. Choose one copy +path below, then run the shared verification. Neither path overwrites an +existing `photo_subset`. -```sql -INSERT INTO photo_subset (id, image) -SELECT id, image FROM photos WHERE id < 100; -``` +##### Enterprise SQL {#photo-copy-sql} -In Enterprise 1.12.0, selecting a Blob v2 column directly in SQL returns the -payload as `large_binary`. Use `blob_descriptor(image)` when you want storage -metadata. For a copy, select `image` itself. -[SQL blob descriptors](/sql/dql/blob-descriptor) +On the Enterprise connection, create a fresh destination with a Blob column, +then copy matching rows on the server. `execute_query` submits one statement +per call; consume each result before continuing: + + + + {PyPhotoCopySql} + + + +Enterprise 1.12.0 supports this SQL copy. Selecting a Blob v2 column directly +in SQL returns the payload as `large_binary`. Select `image` itself for the +copy; use [`blob_descriptor(image)`](/sql/dql/blob-descriptor) to inspect storage +metadata instead. + +`lancedb.blob("image")` is a Python schema helper, not a SQL value constructor. +SQL has no `blob(local_path)` constructor to upload a client-side image file. +Ingest file bytes with the SDK as above, then use SQL to copy stored rows. +If the copy response is lost, inspect `photo_subset` before repeating the +`INSERT`; the same [write recovery rules](/ingestion/insert#performance) apply. + +##### LanceDB Embedded {#photo-copy-embedded} + +SQL requires Enterprise. With the Embedded connection, materialize this small +selection and give the destination the explicit Blob schema: + + + + {PyPhotoCopyEmbedded} + + + +##### Verify the destination {#photo-copy-verify} + +Reopen `photo_subset`, check its row count and application ID, and compare its +image bytes with the original local file. The destination has its own row IDs, +so query them again instead of reusing the source's `_rowid` values: + + + + {PyPhotoVerify} + + #### Blob storage layouts {#blob-storage-layouts} diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index 12c9f87ca..dda4d9acc 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -367,7 +367,11 @@ Store images, audio, or other binary data alongside vectors and metadata, in a c -See [Multimodal data types](/management/table#multimodal) for larger payloads and the Blob v2 column type, which avoids loading binary data on every scan. +For image files and larger payloads, follow the +[Blob photo tutorial](/management/table#photo-tutorial) to create an ordinary +Blob table, filter its metadata, save and check an image, and copy matching rows. +It includes an Embedded path and an Enterprise SQL path. Blob columns are in +Early access. ## 8\. Train on your data {#8-train} diff --git a/docs/web/snippets/photo_tutorial.mdx b/docs/web/snippets/photo_tutorial.mdx new file mode 100644 index 000000000..9c68d6c67 --- /dev/null +++ b/docs/web/snippets/photo_tutorial.mdx @@ -0,0 +1,21 @@ +{/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} + +export const PyPhotoBytes = "rows = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"image\"])\n .limit(10)\n .to_list(blob_mode=\"bytes\")\n)\nassert rows == [{\"id\": 1, \"image\": (inputs / \"red.png\").read_bytes()}]\n"; + +export const PyPhotoConnectEmbedded = "import lancedb\n\ndb = lancedb.connect(\"./photo-db\")\n"; + +export const PyPhotoConnectEnterprise = "import os\n\nimport lancedb\n\ndb = lancedb.connect(\n os.environ[\"LANCEDB_URI\"],\n api_key=os.environ[\"LANCEDB_API_KEY\"],\n region=os.environ[\"LANCEDB_REGION\"],\n host_override=os.environ[\"LANCEDB_HOST_OVERRIDE\"],\n sql_host_override=os.environ[\"LANCEDB_SQL_HOST_OVERRIDE\"],\n)\n"; + +export const PyPhotoCopyEmbedded = "selected = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"label\", \"image\"])\n .limit(10)\n .to_arrow(blob_mode=\"bytes\")\n)\ndb.create_table(\"photo_subset\", data=selected, schema=schema)\n"; + +export const PyPhotoCopySql = "db.execute_query(\n \"CREATE TABLE photo_subset (id BIGINT, label VARCHAR, image BLOB)\"\n).read_all()\ndb.execute_query(\n \"INSERT INTO photo_subset (id, label, image) \"\n \"SELECT id, label, image FROM photos WHERE label = 'red'\"\n).read_all()\n"; + +export const PyPhotoFetch = "hits = (\n photos.search()\n .where(\"label = 'red'\")\n .select([\"id\", \"label\"])\n .with_row_id(True)\n .limit(10)\n .to_list()\n)\nassert [row[\"id\"] for row in hits] == [1]\npayloads = photos.fetch_blobs(\"image\", [row[\"_rowid\"] for row in hits]).to_pylist()\nassert payloads == [(inputs / \"red.png\").read_bytes()]\nsaved = Path(\"selected-red.png\")\nsaved.write_bytes(payloads[0])\nassert saved.read_bytes() == (inputs / \"red.png\").read_bytes()\n"; + +export const PyPhotoFiles = "import struct\nimport zlib\nfrom pathlib import Path\n\ndef solid_png(rgb):\n def chunk(kind, data):\n checksum = zlib.crc32(kind + data) & 0xFFFFFFFF\n return (\n struct.pack(\">I\", len(data)) + kind + data + struct.pack(\">I\", checksum)\n )\n\n header = struct.pack(\">IIBBBBB\", 8, 8, 8, 2, 0, 0, 0)\n pixels = (b\"\\x00\" + bytes(rgb) * 8) * 8\n return (\n b\"\\x89PNG\\r\\n\\x1a\\n\"\n + chunk(b\"IHDR\", header)\n + chunk(b\"IDAT\", zlib.compress(pixels))\n + chunk(b\"IEND\", b\"\")\n )\n\ninputs = Path(\"photo-inputs\")\ninputs.mkdir()\nfor label, rgb in [(\"red\", (255, 0, 0)), (\"blue\", (0, 0, 255))]:\n (inputs / f\"{label}.png\").write_bytes(solid_png(rgb))\n"; + +export const PyPhotoIngest = "import pyarrow as pa\n\nschema = pa.schema(\n [\n pa.field(\"id\", pa.int64(), nullable=False),\n pa.field(\"label\", pa.string(), nullable=False),\n lancedb.blob(\"image\", nullable=False),\n ],\n metadata={\"lance.blob.managed\": \"false\"},\n)\nphotos = db.create_table(\"photos\", schema=schema)\nphotos.add(\n [\n {\"id\": 1, \"label\": \"red\", \"image\": (inputs / \"red.png\").read_bytes()},\n {\"id\": 2, \"label\": \"blue\", \"image\": (inputs / \"blue.png\").read_bytes()},\n ]\n)\nassert photos.count_rows() == 2\n"; + +export const PyPhotoRanges = "with photos.fetch_blob_files(\"image\", [hits[0][\"_rowid\"]])[0] as reader:\n assert reader.read_range(0, 8) == b\"\\x89PNG\\r\\n\\x1a\\n\"\n"; + +export const PyPhotoVerify = "photo_subset = db.open_table(\"photo_subset\")\nassert photo_subset.count_rows() == 1\ncopied = (\n photo_subset.search()\n .select([\"id\", \"label\"])\n .with_row_id(True)\n .limit(10)\n .to_list()\n)\nassert [(row[\"id\"], row[\"label\"]) for row in copied] == [(1, \"red\")]\ncopied_bytes = photo_subset.fetch_blobs(\n \"image\", [row[\"_rowid\"] for row in copied]\n).to_pylist()\nassert copied_bytes == [(inputs / \"red.png\").read_bytes()]\n"; From a6d7d02f71fe76654d4f403d814effb44175d9ba Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 18 Nov 2026 01:19:59 -0800 Subject: [PATCH 161/203] docs: add semantic sampling guide (#5085) Add a standalone Semantic Sampling guide immediately below Statistical Sampling in Data Curation, with links from the curation overview and SQL sampling reference. Explain per-partition row quotas, repeatability, filtering order, and index requirements. ```sql SELECT id, caption FROM documents TABLESAMPLE IVF (embedding, 100 ROWS) REPEATABLE (42); ``` --- docs/web/curation/index.mdx | 1 + docs/web/curation/semantic-sampling.mdx | 121 +++++++++++++++++++++ docs/web/curation/statistical-sampling.mdx | 2 + docs/web/docs.json | 1 + docs/web/sql/dql/sampling.mdx | 3 + 5 files changed, 128 insertions(+) create mode 100644 docs/web/curation/semantic-sampling.mdx diff --git a/docs/web/curation/index.mdx b/docs/web/curation/index.mdx index 59b993100..290eb19fe 100644 --- a/docs/web/curation/index.mdx +++ b/docs/web/curation/index.mdx @@ -24,6 +24,7 @@ records belong, and save the selected data or the rules used to produce it. | [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. | | [Statistical Sampling](/curation/statistical-sampling) | Which random fraction to inspect or use for an experiment. | +| [Semantic Sampling](/curation/semantic-sampling) | How to draw rows from every cluster in an existing IVF vector index. | | [Selective Sampling](/curation/selective-sampling) | How to re-fetch specific rows by ID, address or offset. | | [Join datasets](/curation/join) | How to attach labels, metadata or scores stored elsewhere. | | [Rank and deduplicate](/curation/windowing) | Which records to keep when several share an explicit key. | diff --git a/docs/web/curation/semantic-sampling.mdx b/docs/web/curation/semantic-sampling.mdx new file mode 100644 index 000000000..f51f68d6b --- /dev/null +++ b/docs/web/curation/semantic-sampling.mdx @@ -0,0 +1,121 @@ +--- +title: "Semantic Sampling" +sidebarTitle: "Semantic Sampling" +description: "Sample rows from every cluster in an existing IVF vector index with SQL TABLESAMPLE IVF." +icon: circle-nodes +keywords: ["semantic sampling", "sampling", "tablesample", "ivf", "clusters", "embeddings", "repeatable"] +availability: + embedded: unavailable + enterprise: available +--- + +Semantic sampling draws rows from every partition of an existing IVF vector +index. Each partition acts as a cluster of similar embeddings. Use it to +inspect examples across your embedding space, build a dataset with broader +topic coverage, or try an expensive operation on examples from each cluster. +The clusters reflect your embeddings and index; they do not guarantee +coverage of every label or topic. + +## Sample rows from every cluster {#sample} + +Connect with an [Enterprise SQL client](/basics/sql). The examples assume a +`documents` table with `id`, `caption`, and `embedding` columns. The +`embedding` column must have an up-to-date, single-segment +[IVF vector index](/indexing/vector-index) that includes every live row. +Wait for the index build to finish before sampling. + + +```sql SQL icon="database" +SELECT id, caption +FROM documents +TABLESAMPLE IVF (embedding, 100 ROWS) +REPEATABLE (42); +``` + + +This selects up to **100 rows from each IVF partition**, without replacement. +A partition with fewer than 100 rows contributes all its rows; empty +partitions contribute none. The result contains the table's existing columns, +so you can project the fields you need without returning `embedding`. + +The count is per partition, not a limit on the whole result. For example: + +| Rows in a partition | Rows selected with `100 ROWS` | +| --- | --- | +| 5 | 5 | +| 100 | 100 | +| 1,000 | 100 | + +With 1,024 populated partitions, the query returns at most 102,400 rows. +Choose the quota with the number of partitions and your output budget in mind. + +Equal quotas give sparse clusters more weight relative to their size. +This makes semantic sampling useful for cluster coverage, but the resulting +sample does not preserve the table's overall distribution. Use +[Statistical Sampling](/curation/statistical-sampling) for uniform row +sampling or account for the different sampling probabilities when estimating +whole-table statistics. + +To group records by partition or select a subset of whole partitions, use +[`ivf_partition()`](/sql/dql/ivf-partition) instead. Its `count` argument +selects the number of partitions; `TABLESAMPLE IVF` selects rows within +every partition. + +## Repeat a sample {#repeatable} + +`REPEATABLE (42)` fixes the seed. With the same table snapshot, index, and +seed, repeated queries select the same rows. Output order is unspecified. +Omit `REPEATABLE` to draw a new sample each time. + +Changes to the source data or rebuilding the index can change the selected +rows even with the same seed. Save a sample when you need a fixed dataset +for evaluation or comparison: + + +```sql SQL icon="database" +CREATE TABLE semantic_eval AS +SELECT id, caption, embedding +FROM documents +TABLESAMPLE IVF (embedding, 100 ROWS) +REPEATABLE (42); +``` + + +Create the output once with a fresh name and keep it unchanged. Record the +source version and sampling policy alongside the result. + +## Filter sampled rows {#filters} + +Sampling happens before `WHERE`, joins, aggregation, and an outer `LIMIT`. +For example, this draws up to 100 rows per partition and then removes rows +with missing captions: + + +```sql SQL icon="database" +SELECT id, caption +FROM documents +TABLESAMPLE IVF (embedding, 100 ROWS) +REPEATABLE (42) +WHERE caption IS NOT NULL; +``` + + +The result can contain fewer than 100 rows from a partition after filtering. +If you need a quota from an eligible subset, first save that subset as a +base table and build its IVF index before sampling it. + +## Requirements and limits {#requirements} + +| Requirement | Behavior | +| --- | --- | +| Source | Sample a base table directly. Views, derived relations, WAL-backed tables, and `CHANGES` relations are unsupported. | +| Vector column | Name the indexed vector column directly, rather than an expression. | +| Index | Exactly one eligible IVF index segment must cover every current fragment and assign every live row exactly once. Missing, ambiguous, or stale indexes are rejected. | +| New or unindexed rows | Rebuild the index so all live rows are covered by a single segment. Null vectors omitted by the index also prevent complete coverage. | +| Deleted rows | Tables with deletion vectors are rejected. Compact deleted rows and rebuild the IVF index before sampling. | +| Row count and seed | Use nonnegative integer literals. A count of zero returns no rows. This mode accepts row counts, not percentages. | + +Sampling examines the membership of every partition and fetches projected +data for the selected rows. A small quota limits the result size, but does +not limit index reads to that many entries. Large partitions can still +require substantial index reads and memory. diff --git a/docs/web/curation/statistical-sampling.mdx b/docs/web/curation/statistical-sampling.mdx index fc43bff12..2d37cefe1 100644 --- a/docs/web/curation/statistical-sampling.mdx +++ b/docs/web/curation/statistical-sampling.mdx @@ -16,6 +16,8 @@ statistics without reading every row. For a random subset through the Python SDK instead -- in Embedded or Enterprise -- see [Permutation](/training/permutation). To select specific, known rows rather than a random fraction, see [Selective Sampling](/curation/selective-sampling). +To draw rows from every cluster of an existing vector index, use +[Semantic Sampling](/curation/semantic-sampling). ## Example data {#example-data} diff --git a/docs/web/docs.json b/docs/web/docs.json index 4c800d65a..b561346cd 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -450,6 +450,7 @@ "curation/create-function", "curation/chunking", "curation/statistical-sampling", + "curation/semantic-sampling", "curation/selective-sampling", "curation/aggregate", "curation/join", diff --git a/docs/web/sql/dql/sampling.mdx b/docs/web/sql/dql/sampling.mdx index b6b24f8eb..c84caccc1 100644 --- a/docs/web/sql/dql/sampling.mdx +++ b/docs/web/sql/dql/sampling.mdx @@ -22,6 +22,9 @@ SELECT * FROM documents TABLESAMPLE (500 ROWS) -- 500 rows A bare number is a **percentage**. Add `ROWS` for a count instead. +To sample rows independently from every partition of an IVF vector index, +use [`TABLESAMPLE IVF`](/curation/semantic-sampling). + ## Rows or fragments {#methods} The standard calls these two methods of one clause. They are different From dd69a2c5350b6f097bfb9493b3926962ae0b5889 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 08:40:53 -0800 Subject: [PATCH 162/203] feat(cli): install release binaries with a shell script (#5082) Install the public CLI from GitHub Releases with `sh scripts/install.sh`. The script selects the macOS Apple Silicon or Linux ARM64/x86-64 archive, verifies its SHA-256 and reported version, and installs it under the user's home directory. Set `LANCEDB_VERSION` to pin a release, including a beta. The default resolves GitHub's latest stable tag, which must have CLI assets. If an Enterprise or other `lancedb` is already on PATH, the installer asks for a separate install directory. An existing destination (including a symlink) is always preserved. The installer workflow exercises that same release on all three native targets and checks checksum failures and existing executable handling. --- .github/workflows/cli-installer.yml | 32 ++++++++++ ci/tests/test_cli_installer.sh | 42 +++++++++++++ docs/web/tools/cli.mdx | 15 +++++ scripts/install.sh | 98 +++++++++++++++++++++++++++++ 4 files changed, 187 insertions(+) create mode 100644 .github/workflows/cli-installer.yml create mode 100644 ci/tests/test_cli_installer.sh create mode 100755 scripts/install.sh diff --git a/.github/workflows/cli-installer.yml b/.github/workflows/cli-installer.yml new file mode 100644 index 000000000..92dbfe9a7 --- /dev/null +++ b/.github/workflows/cli-installer.yml @@ -0,0 +1,32 @@ +name: CLI shell installer +on: + pull_request: + paths: + - 'scripts/install.sh' + - 'ci/tests/test_cli_installer.sh' + - '.github/workflows/cli-installer.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + install: + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, ubuntu-24.04-arm, macos-15] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - run: sh ci/tests/test_cli_installer.sh + - name: Install a pinned public release and run it + env: + LANCEDB_VERSION: v0.42.0-beta.19 + run: | + export LANCEDB_INSTALL_DIR="$RUNNER_TEMP/cli bin" + sh scripts/install.sh + test "$("$LANCEDB_INSTALL_DIR/lancedb" --version)" = "lancedb ${LANCEDB_VERSION#v}" + "$LANCEDB_INSTALL_DIR/lancedb" profile list diff --git a/ci/tests/test_cli_installer.sh b/ci/tests/test_cli_installer.sh new file mode 100644 index 000000000..5298530a9 --- /dev/null +++ b/ci/tests/test_cli_installer.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Run from repository root. The fake transport serves a deliberately corrupt archive. +set -eu +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +export HOME="$work/home" LANCEDB_VERSION=v0.42.0-beta.19 +unset LANCEDB_INSTALL_DIR +mkdir -p "$work/bin" "$HOME" +export PATH="$work/bin:$PATH" +cat > "$work/bin/curl" <<'MOCK' +#!/bin/sh +while [ "$1" != -o ]; do shift; done +case "$3" in + */SHA256SUMS) + for target in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu aarch64-apple-darwin; do + printf '%064d lancedb-%s-%s.tar.gz\n' 0 "$LANCEDB_VERSION" "$target" + done > "$2" ;; + *) printf 'corrupt archive' > "$2" ;; +esac +MOCK +chmod +x "$work/bin/curl" +reject() { + if sh scripts/install.sh > "$work/log" 2>&1; then + echo "Unexpected install success" >&2 + exit 1 + fi + grep -F "$1" "$work/log" +} + +printf 'existing admin CLI\n' > "$work/bin/lancedb" +chmod +x "$work/bin/lancedb" +reject 'on PATH' +test ! -e "$HOME/.local/bin/lancedb" +export LANCEDB_INSTALL_DIR="$work/separate bin" +mkdir -p "$LANCEDB_INSTALL_DIR" +ln -s "$work/bin/lancedb" "$LANCEDB_INSTALL_DIR/lancedb" +reject 'already exists' +test -L "$LANCEDB_INSTALL_DIR/lancedb" +rm "$LANCEDB_INSTALL_DIR/lancedb" +reject 'Checksum mismatch' +test -z "$(ls -A "$LANCEDB_INSTALL_DIR")" +test "$(cat "$work/bin/lancedb")" = 'existing admin CLI' diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index 0259bf9fb..a225287b9 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -18,6 +18,21 @@ statements supported by your deployment. ## Install +From a repository checkout, use the shell installer to select the archive for +your machine. For example, to install a specific published beta: + +```sh +LANCEDB_VERSION=v0.42.0-beta.19 sh scripts/install.sh +``` + +Omit `LANCEDB_VERSION` to select the latest stable GitHub release. The selected +release must include CLI archives. The installer verifies the archive checksum +and installs to `$HOME/.local/bin/lancedb`. If you already use an Enterprise CLI, +set `LANCEDB_INSTALL_DIR` to a separate absolute directory and invoke the public +client by its full path. To upgrade, move the existing executable first. + +### Manual download + Download a CLI archive and `SHA256SUMS` from the [LanceDB releases page](https://github.com/lancedb/lancedb/releases). The CLI shares the SDK release version, including beta versions. diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 000000000..5bd7130a5 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,98 @@ +#!/bin/sh +# Install the public LanceDB command-line client from GitHub Releases. +set -eu + +fail() { + printf 'lancedb installer: %s\n' "$*" >&2 + exit 1 +} + +download() { + curl -q --proto '=https' --proto-redir '=https' -fsSL "$@" +} + +main() { + [ "$#" -eq 0 ] || fail 'Set LANCEDB_VERSION and LANCEDB_INSTALL_DIR via the environment.' + releases=https://github.com/lancedb/lancedb/releases + platform=$(uname -s)-$(uname -m) + case "$platform" in + Darwin-arm64) target=aarch64-apple-darwin ;; + Linux-aarch64|Linux-arm64) target=aarch64-unknown-linux-gnu ;; + Linux-x86_64) target=x86_64-unknown-linux-gnu ;; + *) fail "No CLI archive for $platform. Supported: Apple Silicon macOS, Linux ARM64 and Linux x86-64." ;; + esac + + case "$target" in + *-linux-gnu) + libc=$(getconf GNU_LIBC_VERSION 2>/dev/null) || fail 'Linux requires glibc 2.28 or newer.' + printf '%s\n' "$libc" | awk -F '[ .]' '$1 == "glibc" && ($2 > 2 || ($2 == 2 && $3 >= 28)) { ok=1 } END { exit !ok }' || + fail 'Linux requires glibc 2.28 or newer.' + if [ "$target" = x86_64-unknown-linux-gnu ]; then + for feature in avx2 fma f16c; do + grep -qw "$feature" /proc/cpuinfo || fail "The Linux x86-64 binary requires CPU feature $feature." + done + fi ;; + *-apple-darwin) + os_version=$(sw_vers -productVersion) + [ "${os_version%%.*}" -ge 14 ] || fail 'Apple Silicon requires macOS 14 or newer.' ;; + esac + + dir=${LANCEDB_INSTALL_DIR:-"$HOME/.local/bin"} + case "$dir" in /*) ;; *) fail 'LANCEDB_INSTALL_DIR must be an absolute path.' ;; esac + dest=$dir/lancedb + if [ -e "$dest" ] || [ -L "$dest" ]; then + fail "$dest already exists. Move it first or choose a separate LANCEDB_INSTALL_DIR." + fi + if existing=$(command -v lancedb); then + if [ -z "${LANCEDB_INSTALL_DIR:-}" ]; then + fail "Found $existing on PATH. To install alongside it, set LANCEDB_INSTALL_DIR to a separate directory." + fi + fi + + tag=${LANCEDB_VERSION:-} + if [ -z "$tag" ]; then + latest=$(download --head --output /dev/null --write-out '%{url_effective}' "$releases/latest") + tag=${latest##*/} + fi + version=${tag#v} + # Match the stable and beta tag formats supported by ci/package_cli.py. + case "$version" in *[!0-9a-z.-]*|'') fail "Invalid release version: $tag" ;; esac + printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$' || + fail "Invalid release version: $tag" + + stem=lancedb-v$version-$target + archive=$stem.tar.gz + url=$releases/download/v$version + mkdir -p "$dir" + # Stage on the destination filesystem so the final hard link is atomic and cannot overwrite a file. + stage=$(mktemp -d "$dir/.lancedb-install.XXXXXXXX") + trap 'rm -rf "$stage"' EXIT + trap 'exit 1' HUP INT TERM + + download -o "$stage/SHA256SUMS" "$url/SHA256SUMS" || + fail "Could not fetch CLI checksums for v$version. Choose a release with CLI assets using LANCEDB_VERSION." + expected=$(awk -v name="$archive" '$2 == name { count++; hash=$1 } END { if (count != 1) exit 1; print hash }' "$stage/SHA256SUMS") || + fail "Expected exactly one checksum for $archive." + download -o "$stage/$archive" "$url/$archive" + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum < "$stage/$archive") + else + actual=$(shasum -a 256 < "$stage/$archive") + fi + [ "${actual%% *}" = "$expected" ] || fail "Checksum mismatch for $archive." + + tar -xzOf "$stage/$archive" "$stem/lancedb" > "$stage/lancedb" + chmod 755 "$stage/lancedb" + reported=$("$stage/lancedb" --version) || + fail "Cannot run $target on this machine. Check the CPU and OS requirements in the CLI install guide." + [ "$reported" = "lancedb $version" ] || fail "Unexpected CLI version: $reported" + ln "$stage/lancedb" "$dest" + printf 'Installed %s at %s\n' "$reported" "$dest" + case ":${PATH:-}:" in + *:"$dir":*) ;; + *) printf 'Add %s to PATH or invoke the full path above.\n' "$dir" ;; + esac +} + +# Keep the entry point last so a truncated download cannot start installation. +main "$@" From 96c25bd6b9516c1c15919a9541635c99b2b5be0e Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 09:02:45 -0800 Subject: [PATCH 163/203] feat(nodejs): add Enterprise table override APIs (#5077) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add TypeScript `getTableOverrides`, `updateTableOverrides`, and `resetTableOverrides` for LanceDB Enterprise tables, delegating to the shared Rust implementation used by Python. Document that updates perform GET → recursive local merge → full PUT. Unrelated fields are preserved from the read snapshot, but concurrent edits can be overwritten. CLI `set` and REST PUT retain replacement semantics. Fix an empty SDK update to return the current snapshot without a PUT. Live testing found that the previous implementation submitted an empty replacement and failed when no overrides were configured. The fix applies to Python, Rust, and TypeScript. Add mock HTTP/local coverage and an opt-in Enterprise integration suite for namespaces, branch isolation, REST replacement, validation failures, historical handles, and empty updates. --- docs/src/js/classes/Table.md | 74 ++++++ docs/web/maintenance/compaction.mdx | 53 +++++ nodejs/__test__/remote.test.ts | 213 ++++++++++++++++++ nodejs/__test__/table.test.ts | 46 ++++ .../table_overrides_integration.test.ts | 166 ++++++++++++++ nodejs/lancedb/table.ts | 64 ++++++ nodejs/src/table.rs | 31 +++ python/python/lancedb/remote/table.py | 6 +- python/python/lancedb/table.py | 36 ++- python/python/tests/test_remote_db.py | 17 ++ rust/lancedb/src/remote/table.rs | 28 +++ rust/lancedb/src/table.rs | 13 +- 12 files changed, 737 insertions(+), 10 deletions(-) create mode 100644 nodejs/__test__/table_overrides_integration.test.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 0a230ac94..966580451 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -901,6 +901,26 @@ Resolves to `undefined` only when the RTE write path is not enabled. *** +### getTableOverrides() + +```ts +getTableOverrides(): Promise> +``` + +Read the stored overrides for a remote Enterprise table. + +Overrides configure background behavior such as automatic compaction, +cleanup, and reindex execution. Keys use the server's snake_case names. +Returns an empty object when no overrides are set. Local tables are unsupported. +Custom table implementations inherit a default rejection unless they override +this method. + +#### Returns + +`Promise`<`Record`<`string`, `unknown`>> + +*** + ### indexStats() ```ts @@ -1379,6 +1399,22 @@ console.log(await job.status()); // "finished" *** +### resetTableOverrides() + +```ts +resetTableOverrides(): Promise> +``` + +Clear a remote Enterprise table's overrides and return an empty object. +Local tables and custom table implementations without override support reject +this operation. + +#### Returns + +`Promise`<`Record`<`string`, `unknown`>> + +*** + ### restore() ```ts @@ -1736,6 +1772,44 @@ resolves to the new table version. *** +### updateTableOverrides() + +```ts +updateTableOverrides(overrides): Promise> +``` + +Recursively merge overrides into a remote Enterprise table's stored overrides. + +Fetches the current overrides, merges nested objects locally, then sends the +complete replacement using REST PUT. Other values replace existing values; +unrelated fields from the read snapshot are preserved. This read-modify-write +is not atomic: concurrent edits can be overwritten, even to unrelated fields. +Coordinate writers when concurrent edits must be preserved. An empty update +only reads and returns the current overrides. + +Unlike this SDK method, CLI `set` and REST PUT replace the overrides object +without merging. Use [Table.resetTableOverrides](Table.md#resettableoverrides) to clear all overrides. +Local tables and custom table implementations without override support reject +this operation. + +#### Parameters + +* **overrides**: `Record`<`string`, `unknown`> + +#### Returns + +`Promise`<`Record`<`string`, `unknown`>> + +#### Example + +```ts +await table.updateTableOverrides({ + job_types: { compaction: { enabled: false } }, +}); +``` + +*** + ### vectorSearch() ```ts diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index d8638419e..ad3fe636d 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -282,6 +282,59 @@ need preserving; read the current object and retain unrelated fields when editing an existing policy. Use the same namespace and branch for policy reads, writes, and compaction submission. +The Python, TypeScript, and Rust SDKs can update selected fields while retaining +unrelated overrides from the current read snapshot. For an existing Enterprise +`table` handle: + + +```python Python +table.update_table_overrides( + job_types={ + "compaction": { + "target_rows_per_fragment": 100000, + "max_source_rows": 1000000, + } + } +) +``` +```typescript TypeScript +await table.updateTableOverrides({ + job_types: { + compaction: { + target_rows_per_fragment: 100000, + max_source_rows: 1000000, + }, + }, +}); +``` +```rust Rust +table + .update_table_overrides(serde_json::json!({ + "job_types": { + "compaction": { + "target_rows_per_fragment": 100000, + "max_source_rows": 1000000 + } + } + })) + .await?; +``` + + +Override keys use the server's `snake_case` names in every SDK. These examples +retain other compaction settings, such as `enabled`, and settings for other job +types from the read snapshot. An empty update only reads the current overrides; +use `reset_table_overrides()` / `resetTableOverrides()` to clear all overrides. + +SDK updates perform **GET → recursive merge in the client → full PUT**. This +read–modify–write is not atomic: concurrent edits can be overwritten, even to +unrelated fields. Coordinate override writers when concurrent edits must be +preserved. CLI `set` and REST PUT replace the object without merging. + +These methods require a compatible Enterprise deployment. For namespaced tables, +confirm that the deployment supports table-override reads and resets within +namespaces before relying on these APIs. + Each manual field resolves as **invocation option → table tuning → deployment/built-in default**. Automatic jobs resolve **table tuning → deployment/built-in default**. The fragment target has a shared deployment diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index c5f81391a..18bf0f1ce 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2929,3 +2929,216 @@ describe("job wait deadlines", () => { }, ); }); + +describe("table overrides", () => { + it.each([[], ["analytics", "features"]])( + "reads, recursively merges, and resets in namespace %j", + async (...namespacePath: string[]) => { + const requests: { method?: string; url: string; body?: unknown }[] = []; + const current = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { + enabled: true, + // biome-ignore lint/style/useNamingConvention: server wire format + target_rows_per_fragment: 1000, + }, + cleanup: { enabled: false }, + }, + custom: { keep: true, replace: [1, 2], clear: "value" }, + }; + const patch = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { compaction: { enabled: false } }, + custom: { replace: [3], clear: null, label: "測試" }, + }; + const merged = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { + enabled: false, + // biome-ignore lint/style/useNamingConvention: server wire format + target_rows_per_fragment: 1000, + }, + cleanup: { enabled: false }, + }, + custom: { keep: true, replace: [3], clear: null, label: "測試" }, + }; + await withMockDatabase( + (req, res) => { + const url = req.url ?? ""; + if (url.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + return; + } + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + const body = chunks.length + ? JSON.parse(Buffer.concat(chunks).toString()) + : undefined; + requests.push({ method: req.method, url, body }); + res + .writeHead(200) + .end( + JSON.stringify( + req.method === "GET" + ? current + : req.method === "PUT" + ? body.overrides + : {}, + ), + ); + }); + }, + async (db) => { + const table = await db.openTable("test", namespacePath); + await expect(table.getTableOverrides()).resolves.toEqual(current); + await expect(table.updateTableOverrides(patch)).resolves.toEqual( + merged, + ); + // The native conversion and merge must not mutate the caller's object. + expect(patch.job_types.compaction).toEqual({ enabled: false }); + expect(patch.custom.replace).toEqual([3]); + await expect(table.resetTableOverrides()).resolves.toEqual({}); + }, + ); + expect(requests.map((request) => request.method)).toEqual([ + "GET", + "GET", + "PUT", + "POST", + ]); + for (const request of requests) { + const url = new URL(request.url, "http://localhost"); + expect(url.pathname).toBe( + request.method === "POST" + ? "/admin/table/overrides/reset" + : "/admin/table/overrides", + ); + if (request.method === "PUT") { + expect(request.body).toEqual({ + db: "dev", + namespace: namespacePath, + table: "test", + overrides: merged, + }); + } else { + expect(url.searchParams.get("db")).toBe("dev"); + expect(url.searchParams.get("table")).toBe("test"); + expect(url.searchParams.getAll("namespace")).toEqual(namespacePath); + } + } + }, + ); + + it.each([{}, { custom: { keep: true } }])( + "only reads the snapshot %j for an empty update", + async (current) => { + const methods: string[] = []; + await withMockDatabase( + (req, res) => { + if (req.url?.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + return; + } + methods.push(req.method ?? ""); + res + .writeHead(req.method === "GET" ? 200 : 400) + .end(JSON.stringify(current)); + }, + async (db) => { + const table = await db.openTable("test"); + await expect(table.updateTableOverrides({})).resolves.toEqual( + current, + ); + }, + ); + expect(methods).toEqual(["GET"]); + }, + ); + + it.each([null, [], true, 1, "bad"])( + "rejects a non-object update %j before reading overrides", + async (value) => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + }, + async (db) => { + const table = await db.openTable("test"); + await expect( + table.updateTableOverrides( + value as unknown as Record, + ), + ).rejects.toThrow(/must be a JSON object/); + }, + ); + expect(requests).toEqual(["/v1/table/test/describe/"]); + }, + ); + + it.each([403, 404])( + "propagates GET failure %i without a PUT", + async (status) => { + const methods: string[] = []; + await withMockDatabase( + (req, res) => { + if (req.url?.includes("/describe/")) { + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + } else { + methods.push(req.method ?? ""); + res.writeHead(status).end("overrides unavailable"); + } + }, + async (db) => { + const table = await db.openTable("test"); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/overrides unavailable/); + }, + ); + expect(methods).toEqual(["GET"]); + }, + ); + + it("rejects writes on historical and closed handles before HTTP", async () => { + const requests: string[] = []; + await withMockDatabase( + (req, res) => { + requests.push(req.url ?? ""); + res + .writeHead(200) + .end(JSON.stringify({ version: 1, schema: { fields: [] } })); + }, + async (db) => { + const table = await db.openTable("test"); + await table.checkout(1); + requests.length = 0; + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/fixed at version 1/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /fixed at version 1/, + ); + table.close(); + await expect(table.getTableOverrides()).rejects.toThrow(/closed/); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/closed/); + await expect(table.resetTableOverrides()).rejects.toThrow(/closed/); + }, + ); + expect(requests).toEqual([]); + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 7a103d2c9..a93aadde7 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -5886,3 +5886,49 @@ describe("durable compaction validation", () => { ).rejects.toThrow("safe integer"); }); }); + +describe("Enterprise table overrides", () => { + it("keeps override methods optional for existing custom Table subclasses", async () => { + // Declare the old Table surface; only the new methods must be inherited. + // Keeping these override methods abstract must fail type checking here. + // biome-ignore lint/correctness/noUnusedVariables: declaration merging supplies the legacy members + interface LegacyTable + extends Omit< + Table, + "getTableOverrides" | "updateTableOverrides" | "resetTableOverrides" + > {} + class LegacyTable extends Table {} + + const table = new LegacyTable(); + await expect(table.getTableOverrides()).rejects.toThrow( + "getTableOverrides is not supported on this table type", + ); + await expect(table.updateTableOverrides({ custom: true })).rejects.toThrow( + "updateTableOverrides is not supported on this table type", + ); + await expect(table.resetTableOverrides()).rejects.toThrow( + "resetTableOverrides is not supported on this table type", + ); + }); + + it("rejects get, update, and reset on local tables", async () => { + const tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + const table = await db.createTable("items", [{ id: 1 }]); + try { + await expect(table.getTableOverrides()).rejects.toThrow( + /only on remote Enterprise tables/, + ); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/only on remote Enterprise tables/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /only on remote Enterprise tables/, + ); + } finally { + table.close(); + db.close(); + tmpDir.removeCallback(); + } + }); +}); diff --git a/nodejs/__test__/table_overrides_integration.test.ts b/nodejs/__test__/table_overrides_integration.test.ts new file mode 100644 index 000000000..ee6e0c493 --- /dev/null +++ b/nodejs/__test__/table_overrides_integration.test.ts @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { randomUUID } from "node:crypto"; +import { Connection, Table, connect } from "../lancedb"; + +// Run against an isolated Enterprise deployment: +// LANCEDB_TABLE_OVERRIDES_E2E=1 LANCEDB_URI=db://test \ +// LANCEDB_HOST_OVERRIDE=http://localhost:10024 LANCEDB_API_KEY=... \ +// pnpm test __test__/table_overrides_integration.test.ts --runInBand +const maybeDescribe = process.env.LANCEDB_TABLE_OVERRIDES_E2E + ? describe + : describe.skip; + +maybeDescribe("table overrides live integration", () => { + let db: Connection; + const namespace = [`overrides_${randomUUID().replaceAll("-", "_")}`]; + const nested = [...namespace, "nested"]; + const uri = process.env.LANCEDB_URI ?? "db://test"; + const host = process.env.LANCEDB_HOST_OVERRIDE; + const apiKey = process.env.LANCEDB_API_KEY; + + beforeAll(async () => { + if (!host || !apiKey) { + throw new Error( + "Set LANCEDB_HOST_OVERRIDE and LANCEDB_API_KEY for live tests", + ); + } + db = await connect(uri, { apiKey, hostOverride: host }); + await db.createNamespace(namespace); + await db.createNamespace(nested); + }); + + afterAll(async () => { + if (db) { + try { + await db.dropNamespace(nested); + await db.dropNamespace(namespace); + } finally { + db.close(); + } + } + }); + + async function withTable( + namespacePath: string[], + run: (table: Table, name: string) => Promise, + ) { + const name = `items_${randomUUID().replaceAll("-", "_")}`; + const table = await db.createTable(name, [{ id: 1 }], namespacePath); + try { + await run(table, name); + } finally { + table.close(); + await db.dropTable(name, namespacePath); + } + } + + it.each([ + { label: "root", path: [] }, + { label: "nested", path: nested }, + ])( + "merges, replaces via REST, and resets in $label namespace", + async ({ path }) => { + await withTable(path, async (table, name) => { + await expect(table.getTableOverrides()).resolves.toEqual({}); + await expect(table.updateTableOverrides({})).resolves.toEqual({}); + const initial = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { enabled: false }, + cleanup: { enabled: false }, + }, + custom: { keep: "測試", values: [1, 2], nullable: "old" }, + }; + await expect(table.updateTableOverrides(initial)).resolves.toEqual( + initial, + ); + const patch = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { compaction: { enabled: true } }, + custom: { values: [3], nullable: null }, + }; + const expected = { + // biome-ignore lint/style/useNamingConvention: server wire format + job_types: { + compaction: { enabled: true }, + cleanup: { enabled: false }, + }, + custom: { keep: "測試", values: [3], nullable: null }, + }; + await expect(table.updateTableOverrides(patch)).resolves.toEqual( + expected, + ); + await expect(table.getTableOverrides()).resolves.toEqual(expected); + await expect(table.updateTableOverrides({})).resolves.toEqual(expected); + + const replacement = { custom: { replacement: true } }; + const response = await fetch(`${host}/admin/table/overrides`, { + method: "PUT", + headers: { "x-api-key": apiKey!, "Content-Type": "application/json" }, + body: JSON.stringify({ + db: new URL(uri).hostname, + namespace: path, + table: name, + overrides: replacement, + }), + }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual(replacement); + await expect(table.getTableOverrides()).resolves.toEqual(replacement); + await expect(table.resetTableOverrides()).resolves.toEqual({}); + await expect(table.getTableOverrides()).resolves.toEqual({}); + await expect(table.countRows()).resolves.toBe(1); + }); + }, + ); + + it("isolates branch updates and resets from main", async () => { + await withTable(nested, async (table) => { + const initial = { custom: { main: true } }; + await table.updateTableOverrides(initial); + const branch = await (await table.branches()).create("experiment"); + try { + const expected = { custom: { main: true, branch: true } }; + await expect( + branch.updateTableOverrides({ custom: { branch: true } }), + ).resolves.toEqual(expected); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + await expect(branch.resetTableOverrides()).resolves.toEqual({}); + await expect(branch.getTableOverrides()).resolves.toEqual({}); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + } finally { + branch.close(); + } + }); + }); + + it("propagates server validation errors without changing stored overrides", async () => { + await withTable(nested, async (table) => { + const initial = { custom: { keep: true } }; + await table.updateTableOverrides(initial); + await expect( + table.updateTableOverrides({ + // biome-ignore lint/style/useNamingConvention: server wire format + auto_refresh_interval_seconds: -1, + }), + ).rejects.toThrow(); + await expect(table.getTableOverrides()).resolves.toEqual(initial); + }); + }); + + it("rejects writes at a fixed version", async () => { + await withTable(nested, async (table) => { + await table.checkout(1); + await expect( + table.updateTableOverrides({ custom: true }), + ).rejects.toThrow(/fixed at version/); + await expect(table.resetTableOverrides()).rejects.toThrow( + /fixed at version/, + ); + await table.checkoutLatest(); + await expect(table.getTableOverrides()).resolves.toEqual({}); + }); + }); +}); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 2fff63108..9f0760264 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1106,6 +1106,56 @@ export abstract class Table { * @returns {Promise} */ abstract getRTESpec(): Promise; + /** + * Read the stored overrides for a remote Enterprise table. + * + * Overrides configure background behavior such as automatic compaction, + * cleanup, and reindex execution. Keys use the server's snake_case names. + * Returns an empty object when no overrides are set. Local tables are unsupported. + * Custom table implementations inherit a default rejection unless they override + * this method. + */ + async getTableOverrides(): Promise> { + throw new Error("getTableOverrides is not supported on this table type"); + } + + /** + * Recursively merge overrides into a remote Enterprise table's stored overrides. + * + * Fetches the current overrides, merges nested objects locally, then sends the + * complete replacement using REST PUT. Other values replace existing values; + * unrelated fields from the read snapshot are preserved. This read-modify-write + * is not atomic: concurrent edits can be overwritten, even to unrelated fields. + * Coordinate writers when concurrent edits must be preserved. An empty update + * only reads and returns the current overrides. + * + * Unlike this SDK method, CLI `set` and REST PUT replace the overrides object + * without merging. Use {@link Table.resetTableOverrides} to clear all overrides. + * Local tables and custom table implementations without override support reject + * this operation. + * + * @example + * ```ts + * await table.updateTableOverrides({ + * job_types: { compaction: { enabled: false } }, + * }); + * ``` + */ + async updateTableOverrides( + // biome-ignore lint/correctness/noUnusedVariables: retain the public parameter name in generated docs + overrides: Record, + ): Promise> { + throw new Error("updateTableOverrides is not supported on this table type"); + } + + /** + * Clear a remote Enterprise table's overrides and return an empty object. + * Local tables and custom table implementations without override support reject + * this operation. + */ + async resetTableOverrides(): Promise> { + throw new Error("resetTableOverrides is not supported on this table type"); + } /** * Drain and close any cached RTE shard writers held for this table. * @@ -1916,6 +1966,20 @@ export class LocalTable extends Table { | undefined; } + async getTableOverrides(): Promise> { + return await this.inner.getTableOverrides(); + } + + async updateTableOverrides( + overrides: Record, + ): Promise> { + return await this.inner.updateTableOverrides(overrides); + } + + async resetTableOverrides(): Promise> { + return await this.inner.resetTableOverrides(); + } + async closeRTEWriters(): Promise { return await this.inner.closeRTEWriters(); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 3a9b8be72..617822171 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -821,6 +821,37 @@ impl Table { Ok(spec.map(RTEWriteSpec::from)) } + #[napi(catch_unwind, ts_return_type = "Promise>")] + pub async fn get_table_overrides(&self) -> napi::Result { + self.inner_ref()? + .get_table_overrides() + .await + .default_error() + } + + #[napi( + catch_unwind, + ts_args_type = "overrides: Record", + ts_return_type = "Promise>" + )] + pub async fn update_table_overrides( + &self, + overrides: serde_json::Value, + ) -> napi::Result { + self.inner_ref()? + .update_table_overrides(overrides) + .await + .default_error() + } + + #[napi(catch_unwind, ts_return_type = "Promise>")] + pub async fn reset_table_overrides(&self) -> napi::Result { + self.inner_ref()? + .reset_table_overrides() + .await + .default_error() + } + #[napi(catch_unwind, js_name = "closeRTEWriters")] pub async fn close_rte_writers(&self) -> napi::Result<()> { self.inner_ref()?.close_rte_writers().await.default_error() diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index ac936ebd9..2b7d3847d 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1380,7 +1380,11 @@ class RemoteTable(Table): return LOOP.run(self._table.get_table_overrides()) def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: - """Merge Enterprise table overrides into the current table overrides.""" + """Merge Enterprise table overrides using a non-atomic read-modify-write. + + See [the async method][lancedb.AsyncTable.update_table_overrides] + for merge behavior and concurrency limitations. + """ return LOOP.run(self._table.update_table_overrides(**overrides)) def reset_table_overrides(self) -> dict[str, Any]: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 8c3d30170..1dab667df 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2115,8 +2115,16 @@ class Table(ABC): def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: """Merge Enterprise table overrides into the current table overrides. - Only fields supplied in ``overrides`` are changed; unrelated existing - overrides are preserved by the remote service update flow. + Fetches the current overrides, recursively merges nested objects locally, + then sends the complete replacement using REST PUT. Other values replace + existing values; unrelated fields from the read snapshot are preserved. + This read-modify-write is not atomic: concurrent edits can be overwritten, + even to unrelated fields. Coordinate writers when concurrent edits must + be preserved. An empty update only reads and returns the current overrides. + + Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides + object without merging. Use ``reset_table_overrides()`` to clear all + overrides. Supported only on remote Enterprise tables. """ raise NotImplementedError @@ -6183,8 +6191,16 @@ class LanceTable(Table): def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: """Merge Enterprise table overrides into the current table overrides. - Only fields supplied in ``overrides`` are changed; unrelated overrides - from the current read snapshot are preserved. + Fetches the current overrides, recursively merges nested objects locally, + then sends the complete replacement using REST PUT. Other values replace + existing values; unrelated fields from the read snapshot are preserved. + This read-modify-write is not atomic: concurrent edits can be overwritten, + even to unrelated fields. Coordinate writers when concurrent edits must + be preserved. An empty update only reads and returns the current overrides. + + Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides + object without merging. Use ``reset_table_overrides()`` to clear all + overrides. Supported only on remote Enterprise tables. Examples -------- @@ -6962,8 +6978,16 @@ class AsyncTable: async def update_table_overrides(self, **overrides: Any) -> dict[str, Any]: """Merge Enterprise table overrides into the current table overrides. - Only fields supplied in ``overrides`` are changed; unrelated overrides - from the current read snapshot are preserved. + Fetches the current overrides, recursively merges nested objects locally, + then sends the complete replacement using REST PUT. Other values replace + existing values; unrelated fields from the read snapshot are preserved. + This read-modify-write is not atomic: concurrent edits can be overwritten, + even to unrelated fields. Coordinate writers when concurrent edits must + be preserved. An empty update only reads and returns the current overrides. + + Unlike this SDK method, CLI ``set`` and REST PUT replace the overrides + object without merging. Use ``reset_table_overrides()`` to clear all + overrides. Supported only on remote Enterprise tables. Examples -------- diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index eff207230..b74450553 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -4016,6 +4016,23 @@ def test_update_table_overrides_sync_remote_table_merges_existing_fields(): assert calls == ["GET", "PUT"] +@pytest.mark.parametrize("current", [{}, {"custom": {"keep": True}}]) +def test_empty_update_table_overrides_only_reads(current): + calls = [] + + def overrides_handler(request, parsed): + calls.append(request.command) + assert request.command == "GET" + assert parsed.path == "/admin/table/overrides" + assert_table_overrides_query(parsed) + send_json(request, current) + + with table_overrides_test_table(overrides_handler) as table: + assert table.update_table_overrides() == current + + assert calls == ["GET"] + + def test_reset_table_overrides_sync_remote_table(): def overrides_handler(request, parsed): assert request.command == "POST" diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2e116dd87..790f21961 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3984,6 +3984,9 @@ impl BaseTable for RemoteTable { }); } }; + if patch.is_empty() { + return Ok(serde_json::Value::Object(current)); + } Self::merge_table_overrides(&mut current, patch); let merged = serde_json::Value::Object(current); let body = self.table_overrides_set_body(merged); @@ -14158,6 +14161,31 @@ mod tests { assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2); } + #[tokio::test] + async fn test_update_table_overrides_empty_patch_only_reads() { + for current in [ + serde_json::json!({}), + serde_json::json!({"job_types": {"compaction": {"enabled": false}}}), + ] { + let snapshot = current.clone(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "GET"); + assert_eq!(request.url().path(), "/admin/table/overrides"); + http::Response::builder() + .status(200) + .body(snapshot.to_string()) + .unwrap() + }); + assert_eq!( + table + .update_table_overrides(serde_json::json!({})) + .await + .unwrap(), + current + ); + } + } + #[tokio::test] async fn test_reset_table_overrides() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index e7f8062e4..156474f23 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2736,9 +2736,16 @@ impl Table { /// Merge Enterprise table overrides into the current stored overrides. /// - /// This method uses patch semantics: fields present in `overrides` are - /// recursively merged into the existing table overrides and unrelated fields - /// are preserved. + /// Fetches the current overrides, recursively merges nested objects locally, + /// then sends the complete replacement using REST PUT. Other values replace + /// existing values; unrelated fields from the read snapshot are preserved. + /// This read-modify-write is not atomic: concurrent edits can be overwritten, + /// even to unrelated fields. Coordinate writers when concurrent edits must + /// be preserved. An empty update only reads and returns the current overrides. + /// + /// Unlike this SDK method, CLI `set` and REST PUT replace the overrides object + /// without merging. Use [`Self::reset_table_overrides`] to clear all overrides. + /// Supported only on remote Enterprise tables. pub async fn update_table_overrides( &self, overrides: TableOverrides, From 3907a492c02332093db716dfc91561819499b8fb Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 09:14:14 -0800 Subject: [PATCH 164/203] feat(sdk): add typed data prewarm previews (#5075) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LanceDB SDKs can submit data prewarm jobs, but callers have to issue SQL directly to inspect a plan before warming. The existing text response does not provide a typed pruning contract. This adds metadata-only preview helpers across Rust, Python sync/async, and TypeScript, using a compatible Enterprise server’s structured SQL response. This was accomplished with the following changes: - Add `explain_prewarm_data(PrewarmDataOptions)`, Python `explain_prewarm_data(...)`, and TypeScript `explainPrewarmData(options)`. - Expose `PrewarmDataPlan` and `PrewarmPruningSummary`, preserving zero versus unknown counts and future pruning-mode strings. - Reuse submission options, identifier/filter validation, namespace and branch context, and Azure source-account hint handling. - Validate the versioned JSON response without parsing display text, submitting a warming job, polling HTTP job APIs, or falling back to REST. - Add API documentation, Flight SQL transport tests, Python sync/async response tests, and an opt-in live-service integration test. ### Usage and behaviour ```python plan = table.explain_prewarm_data(["payload"], filter="quality > 0.7") print(plan.table_version, plan.pruning.selected_fragments) ``` The helper returns a plan directly. It requires table Select plus database/namespace Usage and a server supporting `EXPLAIN (FORMAT JSON) PREWARM`. It reads metadata without creating a warming job. Selected ranges are conservative physical candidates; unknown counts remain `None`/`null`. A later submission resolves and plans its own snapshot. Historical-version and Embedded table handles are unsupported. --- docs/src/js/classes/Table.md | 32 ++++ docs/src/js/globals.md | 2 + docs/src/js/interfaces/PrewarmDataOptions.md | 2 +- docs/src/js/interfaces/PrewarmDataPlan.md | 37 +++++ .../js/interfaces/PrewarmPruningSummary.md | 61 +++++++ docs/src/python/python.md | 4 + docs/web/enterprise/cache-prewarm.mdx | 71 +++++++++ nodejs/__test__/prewarm.test.ts | 33 ++++ nodejs/__test__/table.test.ts | 23 +++ nodejs/lancedb/index.ts | 6 +- nodejs/lancedb/prewarm.ts | 43 +++++ nodejs/lancedb/table.ts | 52 +++++- nodejs/src/table.rs | 17 ++ python/python/lancedb/_lancedb.pyi | 7 + python/python/lancedb/prewarm.py | 45 +++++- python/python/lancedb/remote/table.py | 20 ++- python/python/lancedb/table.py | 66 +++++++- python/python/tests/test_e2e_remote_db.py | 62 ++++++++ python/python/tests/test_remote_db.py | 126 ++++++++++++++- python/python/tests/test_table.py | 4 +- python/src/table.rs | 18 +++ rust/lancedb/src/remote/sql_test.rs | 96 ++++++++++- rust/lancedb/src/remote/table.rs | 38 +++++ rust/lancedb/src/remote/table/prewarm.rs | 150 ++++++++++++++++++ rust/lancedb/src/table.rs | 32 +++- rust/lancedb/src/table/prewarm.rs | 41 ++++- 26 files changed, 1070 insertions(+), 18 deletions(-) create mode 100644 docs/src/js/interfaces/PrewarmDataPlan.md create mode 100644 docs/src/js/interfaces/PrewarmPruningSummary.md create mode 100644 nodejs/__test__/prewarm.test.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 966580451..63b6cffa0 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -653,6 +653,38 @@ await table.enableRTE({ *** +### explainPrewarmData() + +```ts +explainPrewarmData(_options?): Promise +``` + +Preview prewarm with the same options as [prewarmDataAsync](Table.md#prewarmdataasync), without +submitting a warming job. Requires LanceDB Enterprise with structured SQL +previews, table Select and database/namespace Usage. Reads metadata and +returns the source version, readable plan, and conservative pruning summary. +A later submission plans its own snapshot. Historical and Embedded handles +are unsupported. Unknown measurements remain null. +Custom table implementations can override this method; its default rejects +with an unsupported-operation error. + +#### Parameters + +* **\_options?**: [`PrewarmDataOptions`](../interfaces/PrewarmDataOptions.md) + +#### Returns + +`Promise`<[`PrewarmDataPlan`](../interfaces/PrewarmDataPlan.md)> + +#### Example + +```ts +const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); +console.log(plan.pruning.selectedFragments); +``` + +*** + ### fetchBlobFiles() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 3893f9a7e..3c348faac 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -131,7 +131,9 @@ - [OptimizeOptions](interfaces/OptimizeOptions.md) - [OptimizeStats](interfaces/OptimizeStats.md) - [PrewarmDataOptions](interfaces/PrewarmDataOptions.md) +- [PrewarmDataPlan](interfaces/PrewarmDataPlan.md) - [PrewarmDataResult](interfaces/PrewarmDataResult.md) +- [PrewarmPruningSummary](interfaces/PrewarmPruningSummary.md) - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) - [RTEStats](interfaces/RTEStats.md) - [RTEWriteSpec](interfaces/RTEWriteSpec.md) diff --git a/docs/src/js/interfaces/PrewarmDataOptions.md b/docs/src/js/interfaces/PrewarmDataOptions.md index def1eb822..4815b84fb 100644 --- a/docs/src/js/interfaces/PrewarmDataOptions.md +++ b/docs/src/js/interfaces/PrewarmDataOptions.md @@ -6,7 +6,7 @@ # Interface: PrewarmDataOptions -Settings for submitting a durable remote data-cache prewarm job. +Settings for data-cache prewarm submissions and metadata previews. ## Properties diff --git a/docs/src/js/interfaces/PrewarmDataPlan.md b/docs/src/js/interfaces/PrewarmDataPlan.md new file mode 100644 index 000000000..c06a2ac0a --- /dev/null +++ b/docs/src/js/interfaces/PrewarmDataPlan.md @@ -0,0 +1,37 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmDataPlan + +# Interface: PrewarmDataPlan + +Metadata-only snapshot preview; no warming job is submitted. + +## Properties + +### plan + +```ts +plan: string; +``` + +Readable display text. Use pruning for structured facts. + +*** + +### pruning + +```ts +pruning: PrewarmPruningSummary; +``` + +*** + +### tableVersion + +```ts +tableVersion: number; +``` + +Snapshot used for this preview. A later submission plans its own snapshot. diff --git a/docs/src/js/interfaces/PrewarmPruningSummary.md b/docs/src/js/interfaces/PrewarmPruningSummary.md new file mode 100644 index 000000000..78d1ba00a --- /dev/null +++ b/docs/src/js/interfaces/PrewarmPruningSummary.md @@ -0,0 +1,61 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / PrewarmPruningSummary + +# Interface: PrewarmPruningSummary + +Conservative metadata proof, rather than exact matching rows. + +## Properties + +### fallbackReason + +```ts +fallbackReason: null | string; +``` + +*** + +### inputFragments + +```ts +inputFragments: number; +``` + +*** + +### mode + +```ts +mode: string; +``` + +Server-reported proof mode; future servers may add modes. + +*** + +### prunedFragments + +```ts +prunedFragments: number; +``` + +*** + +### selectedFragments + +```ts +selectedFragments: number; +``` + +*** + +### selectedRowRanges + +```ts +selectedRowRanges: null | number; +``` + +Candidate physical intervals, or null when unknown. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 04f315e1c..752bf540f 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -1520,3 +1520,7 @@ Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or ::: lancedb.compaction.CompactionResult ::: lancedb.prewarm.PrewarmDataResult + +::: lancedb.prewarm.PrewarmDataPlan + +::: lancedb.prewarm.PrewarmPruningSummary diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index c2a5347f1..56a091364 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -181,9 +181,80 @@ and pinned source version; preview creates no job: ```sql PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; EXPLAIN PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; +EXPLAIN (FORMAT JSON) PREWARM WITH (concurrency = 4) AS SELECT payload FROM events WHERE id >= 1000; DESCRIBE JOB '' FORMAT JSON; ``` +The typed SDK preview helpers return a `PrewarmDataPlan` with the source table +version, readable plan, and structured pruning summary. They require an Enterprise +deployment supporting `EXPLAIN (FORMAT JSON) PREWARM` and Flight SQL connectivity. +Preview requires table Select plus Usage on the database and namespace hierarchy; +it creates no warming job and does not use the job-monitoring APIs. + + + +```python +from lancedb.prewarm import PrewarmDataPlan + +plan: PrewarmDataPlan = table.explain_prewarm_data( + ["payload"], filter="id >= 1000", concurrency=4 +) +print(plan.table_version) +print(plan.pruning.mode) +print(plan.pruning.selected_fragments, plan.pruning.input_fragments) +print(plan.pruning.selected_row_ranges, plan.pruning.fallback_reason) +``` + +With an `AsyncTable`, use `await table.explain_prewarm_data(...)` with the same +arguments. It returns the same plan type. + + +```typescript +import type { PrewarmDataPlan } from "@lancedb/lancedb"; + +const plan: PrewarmDataPlan = await table.explainPrewarmData({ + columns: ["payload"], + filter: "id >= 1000", + concurrency: 4, +}); +console.log(plan.tableVersion); +console.log(plan.pruning.mode); +console.log(plan.pruning.selectedFragments, plan.pruning.inputFragments); +console.log(plan.pruning.selectedRowRanges, plan.pruning.fallbackReason); +``` + + +```rust +use lancedb::table::{PrewarmDataOptions, PrewarmDataPlan}; + +let plan: PrewarmDataPlan = table + .explain_prewarm_data( + PrewarmDataOptions::new() + .columns(["payload"]) + .filter("id >= 1000") + .concurrency(4), + ) + .await?; +println!( + "Snapshot {}: {} of {} fragments selected", + plan.table_version, plan.pruning.selected_fragments, plan.pruning.input_fragments +); +println!( + "Mode: {}, candidate ranges: {:?}, fallback: {:?}", + plan.pruning.mode, plan.pruning.selected_row_ranges, plan.pruning.fallback_reason +); +``` + + + +The `plan` string is for display; use `pruning` for structured facts. Selected +row ranges are conservative physical candidate intervals, not exact matching +rows. Unavailable range counts remain None/null; a reported zero means no +candidate ranges. The fallback reason describes why pruning was unavailable, +when reported. Pruning modes may expand in future server versions. A preview does not reserve its snapshot: a later submission +resolves and plans its own source version. Unsupported servers fail explicitly +without falling back to text parsing or REST. + The filter is a single SQL predicate used for conservative metadata pruning. Unknown or unavailable metadata keeps data eligible for warming. Omitted columns warm all fields; concurrency must be a positive integer. Historical diff --git a/nodejs/__test__/prewarm.test.ts b/nodejs/__test__/prewarm.test.ts new file mode 100644 index 000000000..ac6c23c22 --- /dev/null +++ b/nodejs/__test__/prewarm.test.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { decodePrewarmDataPlan } from "../lancedb/prewarm"; +import { Table } from "../lancedb/table"; + +test.each([null, 0, 2])( + "preview preserves unknown and zero range counts: %s", + (ranges) => { + const plan = decodePrewarmDataPlan( + JSON.parse(`{ + "table_version":42,"plan":"display text", + "pruning":{"mode":"future_mode","input_fragments":3,"selected_fragments":0, + "pruned_fragments":3,"selected_row_ranges":${ranges}} + }`), + ); + expect(plan.tableVersion).toBe(42); + expect(plan.pruning.mode).toBe("future_mode"); + expect(plan.pruning.selectedRowRanges).toBe(ranges); + expect(plan.pruning.fallbackReason).toBeNull(); + }, +); + +test("custom tables inherit an unsupported preview default", async () => { + // Only the inherited default is exercised; unrelated abstract operations + // do not need implementations in this fixture. + const table = Object.create(Table.prototype) as Table; + await expect( + table.explainPrewarmData({ columns: ["payload"], filter: "id > 0" }), + ).rejects.toThrow( + "data prewarm previews are not supported by this table implementation", + ); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index a93aadde7..04d80d5f9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4738,6 +4738,29 @@ describe.each(arrowVersions)( } }); + test("explainPrewarmData validates options and rejects Embedded tables", async () => { + const db = await connect(tmp.dirSync().name); + const table = await db.createTable("preview", [{ id: 1 }]); + await expect(table.explainPrewarmData()).rejects.toThrow( + "only supported on remote tables", + ); + await expect( + table.explainPrewarmData({ unsupported: true } as never), + ).rejects.toThrow("Unsupported data prewarm option"); + for (const concurrency of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 2 ** 32, + ]) { + await expect(table.explainPrewarmData({ concurrency })).rejects.toThrow( + "concurrency", + ); + } + }); + test("prewarmDataAsync validates options and rejects local tables", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("prewarm_job", [{ id: 1 }]); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 3f0aed61f..8a2607724 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -668,4 +668,8 @@ export { Listing, ListingOptions } from "./listing"; export type { CompactionResult } from "./compaction"; -export type { PrewarmDataResult } from "./prewarm"; +export type { + PrewarmDataPlan, + PrewarmDataResult, + PrewarmPruningSummary, +} from "./prewarm"; diff --git a/nodejs/lancedb/prewarm.ts b/nodejs/lancedb/prewarm.ts index 942e0a19f..3d40cd5c9 100644 --- a/nodejs/lancedb/prewarm.ts +++ b/nodejs/lancedb/prewarm.ts @@ -33,3 +33,46 @@ export function decodePrewarmDataResult(value: unknown): PrewarmDataResult { bytesRead: result.bytes_read ?? null, }; } + +/** Metadata-only snapshot preview; no warming job is submitted. */ +export interface PrewarmDataPlan { + /** Snapshot used for this preview. A later submission plans its own snapshot. */ + tableVersion: number; + /** Readable display text. Use pruning for structured facts. */ + plan: string; + pruning: PrewarmPruningSummary; +} + +/** Conservative metadata proof, rather than exact matching rows. */ +export interface PrewarmPruningSummary { + /** Server-reported proof mode; future servers may add modes. */ + mode: string; + inputFragments: number; + selectedFragments: number; + prunedFragments: number; + /** Candidate physical intervals, or null when unknown. */ + selectedRowRanges: number | null; + fallbackReason: string | null; +} + +/** @internal */ +export function decodePrewarmDataPlan(value: unknown): PrewarmDataPlan { + // Rust validates the versioned response before handing it to JavaScript. + const result = value as { + [key: string]: unknown; + pruning: Record; + }; + return { + tableVersion: result.table_version as number, + plan: result.plan as string, + pruning: { + mode: result.pruning.mode as string, + inputFragments: result.pruning.input_fragments as number, + selectedFragments: result.pruning.selected_fragments as number, + prunedFragments: result.pruning.pruned_fragments as number, + selectedRowRanges: + (result.pruning.selected_row_ranges as number | null) ?? null, + fallbackReason: (result.pruning.fallback_reason as string | null) ?? null, + }, + }; +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 9f0760264..3b3e7abe5 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -2,7 +2,12 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors import { CompactionResult, decodeCompactionResult } from "./compaction"; -import { PrewarmDataResult, decodePrewarmDataResult } from "./prewarm"; +import { + PrewarmDataPlan, + PrewarmDataResult, + decodePrewarmDataPlan, + decodePrewarmDataResult, +} from "./prewarm"; import { Table as ArrowTable, @@ -168,7 +173,7 @@ export interface UpdateOptions { where: string; } -/** Settings for submitting a durable remote data-cache prewarm job. */ +/** Settings for data-cache prewarm submissions and metadata previews. */ export interface PrewarmDataOptions { /** Lance field paths to warm; omitted or empty means every column. */ columns?: string[]; @@ -627,6 +632,28 @@ export abstract class Table { options?: PrewarmDataOptions, ): Promise>; + /** + * Preview prewarm with the same options as {@link prewarmDataAsync}, without + * submitting a warming job. Requires LanceDB Enterprise with structured SQL + * previews, table Select and database/namespace Usage. Reads metadata and + * returns the source version, readable plan, and conservative pruning summary. + * A later submission plans its own snapshot. Historical and Embedded handles + * are unsupported. Unknown measurements remain null. + * Custom table implementations can override this method; its default rejects + * with an unsupported-operation error. + * + * @example + * const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); + * console.log(plan.pruning.selectedFragments); + */ + async explainPrewarmData( + _options?: PrewarmDataOptions, + ): Promise { + throw new Error( + "data prewarm previews are not supported by this table implementation", + ); + } + /** * Waits for asynchronous indexing to complete on the table. * @@ -1641,17 +1668,20 @@ export class LocalTable extends Table { async prewarmDataAsync( options?: PrewarmDataOptions, ): Promise> { - for (const key of Object.keys(options ?? {})) { - if (!["columns", "filter", "concurrency"].includes(key)) { - throw new Error(`Unsupported data prewarm option: ${key}`); - } - } + validatePrewarmDataOptions(options); return new Job( await this.inner.prewarmDataAsync(options), decodePrewarmDataResult, ); } + async explainPrewarmData( + options?: PrewarmDataOptions, + ): Promise { + validatePrewarmDataOptions(options); + return decodePrewarmDataPlan(await this.inner.explainPrewarmData(options)); + } + async waitForIndex( indexNames: string[], timeoutSeconds: number, @@ -2368,3 +2398,11 @@ function validateCompactionOptions(options?: CompactionOptions): void { } } } + +function validatePrewarmDataOptions(options?: PrewarmDataOptions): void { + for (const key of Object.keys(options ?? {})) { + if (!["columns", "filter", "concurrency"].includes(key)) { + throw new Error(`Unsupported data prewarm option: ${key}`); + } + } +} diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 617822171..6a0a8cb60 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -341,6 +341,23 @@ impl Table { Ok(crate::job::Job::new_typed(job)) } + #[napi(catch_unwind)] + pub async fn explain_prewarm_data( + &self, + options: Option, + ) -> napi::Result { + let options = options + .map(PrewarmDataOptions::into_options) + .transpose()? + .unwrap_or_default(); + let plan = self + .inner_ref()? + .explain_prewarm_data(options) + .await + .default_error()?; + serde_json::to_value(plan).map_err(|error| napi::Error::from_reason(error.to_string())) + } + #[napi(catch_unwind)] pub async fn wait_for_index(&self, index_names: Vec, timeout_s: i64) -> Result<()> { let timeout = std::time::Duration::from_secs(timeout_s.try_into().unwrap()); diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index b4b97ff38..cdeebf6ef 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -645,6 +645,13 @@ class Table: async def restore(self, version: Optional[Union[int, str]] = None): ... async def prewarm_index(self, index_name: str) -> None: ... async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ... + async def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> str: ... async def prewarm_data_async( self, columns: Optional[List[str]] = None, diff --git a/python/python/lancedb/prewarm.py b/python/python/lancedb/prewarm.py index c21bd6cfd..441f40d6d 100644 --- a/python/python/lancedb/prewarm.py +++ b/python/python/lancedb/prewarm.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Results of remote data-cache prewarm jobs.""" +"""Typed metadata previews and results of data-cache prewarm jobs.""" from dataclasses import dataclass, fields import json @@ -30,3 +30,46 @@ class PrewarmDataResult: value = json.loads(raw) names = {field.name for field in fields(cls)} return cls(**{key: item for key, item in value.items() if key in names}) + + +@dataclass(frozen=True) +class PrewarmPruningSummary: + """Conservative metadata pruning; selected ranges are not exact row matches. + + ``mode`` is a server-reported string, including future pruning modes. + Unknown interval counts and fallback reasons remain None. + """ + + mode: str + input_fragments: int + selected_fragments: int + pruned_fragments: int + selected_row_ranges: Optional[int] = None + fallback_reason: Optional[str] = None + + +@dataclass(frozen=True) +class PrewarmDataPlan: + """Metadata-only preview for a snapshot, without a warming job. + + A later submission chooses its own snapshot and can produce a different + plan. ``plan`` is readable display text; use ``pruning`` for structured facts. + """ + + table_version: int + plan: str + pruning: PrewarmPruningSummary + + @classmethod + def from_json(cls, raw: str) -> "PrewarmDataPlan": + # The native SDK validates the wire format before returning this value. + value = json.loads(raw) + summary = value["pruning"] + names = {field.name for field in fields(PrewarmPruningSummary)} + return cls( + table_version=value["table_version"], + plan=value["plan"], + pruning=PrewarmPruningSummary( + **{key: item for key, item in summary.items() if key in names} + ), + ) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 2b7d3847d..a5d08bd72 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -48,7 +48,7 @@ from lancedb.index import ( Bitmap, LabelList, ) -from lancedb.prewarm import PrewarmDataResult +from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult from lancedb.job import Job from lancedb.functions import ( FunctionProvenance, @@ -1486,6 +1486,24 @@ class RemoteTable(Table): self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) ) + def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview prewarm without submitting a warming job. + + See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data] + for options, permissions, snapshot semantics, and limitations. + """ + return LOOP.run( + self._table.explain_prewarm_data( + columns, filter=filter, concurrency=concurrency + ) + ) + def prewarm_data_async( self, columns: Optional[List[str]] = None, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 1dab667df..d9c20e287 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -48,7 +48,7 @@ from ._blob import ( from .types import BlobMode from lancedb.arrow import peek_reader from lancedb.background_loop import LOOP, embedding_executor -from lancedb.prewarm import PrewarmDataResult +from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult from lancedb.job import AsyncJob, Job, _typed_job from lancedb.compaction import CompactionResult from .dependencies import ( @@ -2039,6 +2039,34 @@ class Table(ABC): """ self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview data prewarm without creating a warming job. + + Accepts the same columns, filter, and concurrency as ``prewarm_data_async`` + and uses the table handle's namespace and branch. Requires LanceDB + Enterprise with structured SQL previews, table Select, and database/namespace + Usage. Historical-version and Embedded handles are unsupported. + + Returns the source version, readable plan, and conservative pruning summary. + Unknown metrics remain None; selected ranges are not exact matching rows. + The preview reads metadata. A later submission plans its own snapshot. + + Examples + -------- + >>> plan = table.explain_prewarm_data( # doctest: +SKIP + ... ["video"], filter="quality > 0.7") + >>> print(plan.pruning.selected_fragments) # doctest: +SKIP + """ + raise NotImplementedError( + "data prewarm previews are only supported on remote tables" + ) + def prewarm_data_async( self, columns: Optional[List[str]] = None, @@ -4984,6 +5012,24 @@ class LanceTable(Table): self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) ) + def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview prewarm without submitting a warming job. + + See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data] + for options, permissions, snapshot semantics, and limitations. + """ + return LOOP.run( + self._table.explain_prewarm_data( + columns, filter=filter, concurrency=concurrency + ) + ) + def prewarm_data_async( self, columns: Optional[List[str]] = None, @@ -7519,6 +7565,24 @@ class AsyncTable: """ await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + async def explain_prewarm_data( + self, + columns: Optional[List[str]] = None, + *, + filter: Optional[str] = None, + concurrency: Optional[int] = None, + ) -> PrewarmDataPlan: + """Preview prewarm without submitting a warming job. + + See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data] + for options, permissions, snapshot semantics, and limitations. + """ + return PrewarmDataPlan.from_json( + await self._inner.explain_prewarm_data( + columns, filter=filter, concurrency=concurrency + ) + ) + async def prewarm_data_async( self, columns: Optional[List[str]] = None, diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index f09581bff..9ef746ce1 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -308,3 +308,65 @@ def test_against_local_server(): table = conn.open_table("sift1m_ivf1024_pq16") df = table.search(np.random.rand(128)).to_pandas() assert len(df) == 10 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +async def test_prewarm_preview_against_server( + maintenance_connection_options, asynchronous +): + """Preview is typed, source-versioned, and creates no maintenance jobs.""" + from lancedb.prewarm import PrewarmDataPlan + + connection = ( + await lancedb.connect_async(**maintenance_connection_options) + if asynchronous + else lancedb.connect(**maintenance_connection_options) + ) + + async def call(method, *args, **kwargs): + result = method(*args, **kwargs) + return await result if asynchronous else result + + async def jobs(): + reader = await call(connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"') + result = await call(reader.read_all) + if asynchronous: + return [row for batch in result for row in batch.to_pylist()] + return result.to_pylist() + + name = f"preview_{uuid4().hex}" + created = False + try: + table = await call(connection.create_table, name, [{"id": 1, "payload": "one"}]) + created = True + version = await table.version() if asynchronous else table.version + before = await jobs() + for predicate, mode, selected in [ + (None, "unfiltered", 1), + ("TRUE", "full_warm_fallback", 1), + ("FALSE", "constant", 0), + ("id > 10", "full_warm_fallback", 1), + ]: + preview = await call( + table.explain_prewarm_data, ["payload"], filter=predicate, concurrency=2 + ) + assert isinstance(preview, PrewarmDataPlan) + assert preview.table_version == version + assert preview.pruning.mode == mode + assert preview.pruning.input_fragments == 1 + assert preview.pruning.selected_fragments == selected + if mode == "full_warm_fallback": + assert preview.pruning.fallback_reason + assert await jobs() == before + assert (await table.version() if asynchronous else table.version) == version + # A preview does not reserve the source snapshot for a later request. + await call(table.add, [{"id": 2, "payload": "two"}]) + newer = await call(table.explain_prewarm_data) + assert newer.table_version > version + assert newer.pruning.input_fragments == 2 + assert await jobs() == before + finally: + if created: + await call(connection.drop_table, name) + connection.close() diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b74450553..381847954 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -8214,7 +8214,9 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod {"concurrency": 1.5}, ], ) -@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +@pytest.mark.parametrize( + "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"] +) def test_remote_data_prewarm_validates_before_submission(options, method): flight = pytest.importorskip("pyarrow.flight") @@ -8441,3 +8443,125 @@ def test_remote_compaction_rejects_boolean_budgets_without_submitting( with pytest.raises(ValueError, match="must be an integer, not a bool"): getattr(table, method)(compaction_options={option: value}) assert server.calls == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "mode,selected,ranges,reason", + [ + ("unfiltered", 3, None, None), + ("constant", 0, 0, None), + ("zonemap_ranges", 1, 2, None), + ("full_warm_fallback", 3, None, "no metadata proof"), + ("future_mode", 2, None, None), + ], +) +async def test_remote_data_prewarm_preview( + asynchronous, mode, selected, ranges, reason +): + from lancedb.prewarm import PrewarmDataPlan, PrewarmPruningSummary + + flight = pytest.importorskip("pyarrow.flight") + + class PreviewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + payload = { + "format_version": 1, + "table_version": 42, + "plan": "metadata preview", + "pruning": { + "mode": mode, + "input_fragments": 3, + "selected_fragments": selected, + "pruned_fragments": 3 - selected, + "selected_row_ranges": ranges, + "fallback_reason": reason, + }, + } + return flight.RecordBatchStream( + pa.table({"plan_type": ["logical_plan"], "plan": [json.dumps(payload)]}) + ) + + server = PreviewServer() + with _mock_remote_sql_connection(server) as kwargs: + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + plan = await table.explain_prewarm_data( + ["attrs.score"], filter="id > 0", concurrency=4 + ) + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + plan = table.explain_prewarm_data( + ["attrs.score"], filter="id > 0", concurrency=4 + ) + assert isinstance(plan, PrewarmDataPlan) + assert isinstance(plan.pruning, PrewarmPruningSummary) + assert plan.table_version == 42 + assert plan.pruning.mode == mode + assert plan.pruning.selected_fragments == selected + assert plan.pruning.selected_row_ranges == ranges + assert plan.pruning.fallback_reason == reason + assert len(server.tickets) == 1 + assert b"EXPLAIN (FORMAT JSON) PREWARM" in server.tickets[0] + assert b'"attrs"."score"' in server.tickets[0] + assert b"concurrency = 4" in server.tickets[0] + assert b"id > 0" in server.tickets[0] + + +@pytest.mark.parametrize( + "payload", + [ + "legacy display text", + '{"format_version":2,"table_version":42,"plan":"future","pruning":{}}', + '{"format_version":1,"table_version":42,"plan":"missing pruning"}', + ], +) +def test_remote_prewarm_preview_rejects_incompatible_payload_without_retry(payload): + flight = pytest.importorskip("pyarrow.flight") + + class PreviewServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + return flight.RecordBatchStream(pa.table({"plan": [payload]})) + + server = PreviewServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(Exception, match="valid structured preview"): + table.explain_prewarm_data() + assert len(server.tickets) == 1 + + +def test_remote_prewarm_preview_reports_old_server_format_support(): + flight = pytest.importorskip("pyarrow.flight") + + class OldServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.tickets = [] + + def do_get(self, context, ticket): + self.tickets.append(ticket.ticket) + raise flight.FlightInternalError( + "Invalid explain format. Expected 'indent', 'tree', 'pgjson' " + "or 'graphviz'. Got 'JSON'" + ) + + server = OldServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises( + NotImplementedError, match=r"EXPLAIN \(FORMAT JSON\) PREWARM" + ): + table.explain_prewarm_data() + assert len(server.tickets) == 1 diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index ebc3c3006..90ae62d1b 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6418,7 +6418,9 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db): @pytest.mark.asyncio @pytest.mark.parametrize("asynchronous", [False, True]) -@pytest.mark.parametrize("method", ["prewarm_data", "prewarm_data_async"]) +@pytest.mark.parametrize( + "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"] +) async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method): if asynchronous: db = await lancedb.connect_async(tmp_path) diff --git a/python/src/table.rs b/python/src/table.rs index e421c939d..a47d82d98 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1913,6 +1913,24 @@ impl Table { }) } + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + pub fn explain_prewarm_data<'py>( + self_: PyRef<'py, Self>, + columns: Option>, + filter: Option, + concurrency: Option<&Bound<'py, PyAny>>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let mut options = + lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); + options.filter = filter; + options.concurrency = positive_u32_integer(concurrency, "concurrency")?; + future_into_py(self_.py(), async move { + let plan = inner.explain_prewarm_data(options).await.infer_error()?; + serde_json::to_string(&plan).map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) + } + pub fn list_indices(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index a80e26ad9..a8f39fc2e 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -518,7 +518,8 @@ impl FlightService for TestSqlService { { return Err(error.clone()); } - if command.query.starts_with("PREWARM") + if (command.query.starts_with("PREWARM") + || command.query.starts_with("EXPLAIN (FORMAT JSON) PREWARM")) && let Some(error) = &self.prewarm_error { return Err(error.clone()); @@ -4671,7 +4672,16 @@ async fn remote_prewarm_errors_preserve_diagnostics_and_never_fall_back() { unsupported, "{error}" ); - assert_eq!(statements.lock().unwrap().len(), 1); + let preview_error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert_eq!( + matches!(preview_error, Error::NotSupported { .. }), + unsupported, + "{preview_error}" + ); + assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } @@ -4782,6 +4792,12 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() { let error = table.prewarm_data(None).await.unwrap_err(); assert!(matches!(error, Error::NotSupported { .. })); assert!(error.to_string().contains("historical version 7")); + let error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("historical version 7")); assert!(statements.lock().unwrap().is_empty()); shutdown.send(()).unwrap(); } @@ -4851,3 +4867,79 @@ async fn remote_compaction_tracks_registry_job_and_real_result() { ); shutdown.send(()).unwrap(); } + +#[tokio::test] +async fn remote_prewarm_preview_uses_sql_without_any_http_jobs() { + use crate::table::PrewarmDataOptions; + for azure in [false, true] { + let preview = serde_json::json!({ + "format_version":1,"table_version":42,"plan":"metadata preview", + "pruning":{"mode":"zonemap_ranges","input_fragments":4, + "selected_fragments":1,"pruned_fragments":3,"selected_row_ranges":2} + }); + let service = TestSqlService { + adaptive: true, + result: RecordBatch::try_from_iter([ + ( + "plan_type", + Arc::new(StringArray::from(vec!["logical_plan"])) as ArrayRef, + ), + ( + "plan", + Arc::new(StringArray::from(vec![preview.to_string()])) as ArrayRef, + ), + ]) + .unwrap(), + prewarm_azure_supported: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let mut config = ClientConfig::default(); + if azure { + config.extra_headers.insert( + "x-azure-storage-account-name".into(), + "sourceaccount".into(), + ); + } + let (sql, shutdown) = start_sql_service(service, config).await; + let client = client_with_handler(|_| -> http::Response { + panic!("preview must not use HTTP job APIs or REST fallback") + }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "clips".into(), + vec!["team".into()], + "team$clips".into(), + Default::default(), + Some(sql), + ) + .with_branch(Some("experiment".into())); + let plan = table + .explain_prewarm_data( + PrewarmDataOptions::new() + .columns(["attrs.score"]) + .filter("id > 0") + .concurrency(4), + ) + .await + .unwrap(); + assert_eq!(plan.table_version, 42); + assert_eq!(plan.pruning.selected_row_ranges, Some(2)); + assert_eq!( + *statements.lock().unwrap(), + [ + "EXPLAIN (FORMAT JSON) PREWARM WITH (branch = 'experiment', concurrency = 4) AS SELECT \"attrs\".\"score\" FROM \"clips\" WHERE id > 0" + ] + ); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.namespace_path == "team" && h.database == "analytics") + ); + shutdown.send(()).unwrap(); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 790f21961..649edd133 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4806,6 +4806,44 @@ impl BaseTable for RemoteTable { )))) } + async fn explain_prewarm_data( + &self, + options: crate::table::PrewarmDataOptions, + ) -> Result { + if let Some(version) = *self.version.read().await { + return Err(Error::NotSupported { + message: format!( + "SQL PREWARM does not support historical version {version}; use checkout_latest() to preview the current branch" + ), + }); + } + let statement = format!( + "EXPLAIN (FORMAT JSON) {}", + prewarm::statement(&self.name, self.branch.as_deref(), &options)? + ); + let client = self.sql_client.as_ref().ok_or_else(|| Error::NotSupported { + message: "data prewarm previews require a Flight SQL endpoint supporting EXPLAIN (FORMAT JSON) PREWARM".into(), + })?; + let query = client + .execute_prewarm(crate::database::ExecuteQueryRequest { + query: statement, + default_namespace_path: self.namespace.clone(), + parameters: None, + }) + .await + .map_err(prewarm::map_explain_error)?; + let mut reader = query.reader().await.map_err(prewarm::map_explain_error)?; + let mut batches = Vec::new(); + while let Some(batch) = reader + .try_next() + .await + .map_err(prewarm::map_explain_error)? + { + batches.push(batch); + } + prewarm::plan(&batches) + } + async fn table_definition(&self) -> Result { let schema = self.schema().await?; TableDefinition::try_from_rich_schema(schema) diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs index 8388b6350..d87465acf 100644 --- a/rust/lancedb/src/remote/table/prewarm.rs +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -103,6 +103,77 @@ pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> { Ok((id.value(0).into(), version.value(0))) } +/// Decode the versioned JSON payload without depending on the display text. +pub(super) fn plan(batches: &[RecordBatch]) -> Result { + let invalid = || { + Error::Runtime { + message: "EXPLAIN PREWARM did not return a valid structured preview; a server supporting EXPLAIN (FORMAT JSON) PREWARM is required".into(), + } + }; + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(invalid()); + } + let batch = batches + .iter() + .find(|batch| batch.num_rows() == 1) + .ok_or_else(invalid)?; + let payload = batch + .column_by_name("plan") + .and_then(|array| array.as_any().downcast_ref::()) + .ok_or_else(invalid)?; + if payload.is_null(0) { + return Err(invalid()); + } + #[derive(serde::Deserialize)] + struct Preview { + format_version: u32, + #[serde(flatten)] + plan: crate::table::PrewarmDataPlan, + } + let preview: Preview = serde_json::from_str(payload.value(0)).map_err(|_| invalid())?; + if preview.format_version != 1 { + return Err(invalid()); + } + Ok(preview.plan) +} + +pub(super) fn map_explain_error(error: Error) -> Error { + fn unsupported_format(error: &Error) -> bool { + match error { + Error::Sql { + message, grpc_code, .. + } => { + let diagnostic = message.to_ascii_lowercase(); + // Older servers hand this EXPLAIN to DataFusion, which rejects + // JSON as a configuration error (sometimes gRPC Internal). + (*grpc_code == tonic::Code::Internal as i32 + || *grpc_code == tonic::Code::InvalidArgument as i32) + && diagnostic.contains("invalid explain format.") + && diagnostic.contains("got 'json'") + } + Error::JobFailed { failure, .. } => { + failure.source.as_deref().is_some_and(unsupported_format) + } + _ => false, + } + } + let error = if unsupported_format(&error) { + Error::NotSupported { + message: error.to_string(), + } + } else { + map_error(error) + }; + match error { + Error::NotSupported { message } => Error::NotSupported { + message: format!( + "Data prewarm previews require a server supporting EXPLAIN (FORMAT JSON) PREWARM; upgrade the server. Preview will not fall back to text or REST. Server diagnostic: {message}" + ), + }, + other => other, + } +} + pub(super) fn map_error(error: Error) -> Error { fn unsupported(error: &Error) -> Option<&Error> { match error { @@ -143,6 +214,85 @@ mod tests { use arrow_schema::{DataType, Field, Schema}; use std::sync::Arc; + #[test] + fn preview_maps_old_explain_format_errors_without_masking_auth_or_filters() { + for (code, message, unsupported) in [ + ( + tonic::Code::Internal, + "Invalid or Unsupported Configuration: Invalid explain format. Expected 'indent', 'tree', 'pgjson' or 'graphviz'. Got 'JSON'", + true, + ), + ( + tonic::Code::InvalidArgument, + "Invalid explain format. Got 'JSON'", + true, + ), + ( + tonic::Code::PermissionDenied, + "Invalid explain format. Got 'JSON'", + false, + ), + ( + tonic::Code::InvalidArgument, + "invalid filter expression", + false, + ), + ] { + let error = map_explain_error(Error::Sql { + message: message.into(), + request_id: "preview-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + }); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error}" + ); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("preview-request")); + if unsupported { + assert!(error.to_string().contains("EXPLAIN (FORMAT JSON) PREWARM")); + } + } + } + + #[test] + fn preview_requires_one_versioned_typed_payload() { + let valid = serde_json::json!({ + "format_version": 1, "table_version": 42, "plan": "display only", + "pruning": {"mode":"future_mode", "input_fragments":3, + "selected_fragments":0, "pruned_fragments":3, "selected_row_ranges":0}, + "future_field": true, + }); + let batch = |value: &serde_json::Value| { + RecordBatch::try_from_iter([( + "plan", + Arc::new(StringArray::from(vec![value.to_string()])) as arrow_array::ArrayRef, + )]) + .unwrap() + }; + let result = plan(&[batch(&valid)]).unwrap(); + assert_eq!(result.table_version, 42); + assert_eq!(result.pruning.mode, "future_mode"); + assert_eq!(result.pruning.selected_row_ranges, Some(0)); + assert_eq!(result.pruning.fallback_reason, None); + for mutation in ["version", "missing", "negative", "text"] { + let mut value = valid.clone(); + match mutation { + "version" => value["format_version"] = 2.into(), + "missing" => { + value.as_object_mut().unwrap().remove("pruning"); + } + "negative" => value["pruning"]["selected_fragments"] = (-1).into(), + _ => value = "legacy display text".into(), + } + assert!(plan(&[batch(&value)]).is_err(), "{mutation}"); + } + assert!(plan(&[]).is_err()); + assert!(plan(&[batch(&valid), batch(&valid)]).is_err()); + } + #[test] fn quotes_paths_branch_and_filter_without_changing_options() { let options = PrewarmDataOptions::new() diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 156474f23..775261bb5 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -88,7 +88,7 @@ pub mod merge; pub mod optimize; pub use optimize::CompactionResult; mod prewarm; -pub use prewarm::{PrewarmDataOptions, PrewarmDataResult}; +pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary}; pub(crate) mod primary_key; pub mod query; pub mod refresh; @@ -701,6 +701,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "data prewarm jobs are only supported on remote tables".into(), }) } + /// Preview data-cache prewarm without submitting a warming job. + async fn explain_prewarm_data(&self, _options: PrewarmDataOptions) -> Result { + Err(Error::NotSupported { + message: "data prewarm previews are only supported on remote tables".into(), + }) + } + /// Get statistics about the index. async fn index_stats(&self, index_name: &str) -> Result>; /// Merge insert new records into the table. @@ -3199,6 +3206,29 @@ impl Table { self.inner.prewarm_data_async(options).await } + /// Preview data-cache prewarm using the same options as [`Self::prewarm_data_async`]. + /// + /// Requires LanceDB Enterprise with structured SQL PREWARM previews and + /// SELECT permission plus database/namespace usage. Reads metadata without + /// submitting a warming job. A later submission plans its own snapshot. + /// Historical-version and Embedded handles are unsupported. + /// + /// ```no_run + /// # async fn preview(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::PrewarmDataOptions; + /// let plan = table.explain_prewarm_data(PrewarmDataOptions::new() + /// .columns(["video"]).filter("quality > 0.7")).await?; + /// println!("version={}, selected={}", plan.table_version, plan.pruning.selected_fragments); + /// # Ok(()) + /// # } + /// ``` + pub async fn explain_prewarm_data( + &self, + options: PrewarmDataOptions, + ) -> Result { + self.inner.explain_prewarm_data(options).await + } + /// Poll until the columns are fully indexed. Will return Error::Timeout if the columns /// are not fully indexed within the timeout. pub async fn wait_for_index( diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs index 1d0f8c002..badb5a8ad 100644 --- a/rust/lancedb/src/table/prewarm.rs +++ b/rust/lancedb/src/table/prewarm.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Options for submitting a durable data-cache prewarm job. +//! Options, previews, and results for data-cache prewarm. /// Data prewarm settings for [`super::Table::prewarm_data_async`]. /// @@ -44,6 +44,40 @@ impl PrewarmDataOptions { } } +/// Metadata-only preview of a data-cache prewarm on one table snapshot. +/// +/// No warming job is submitted. A later submission chooses its own snapshot and +/// may produce a different plan if the table or index metadata has changed. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmDataPlan { + /// Source snapshot used to produce this preview. + pub table_version: u64, + /// Human-readable plan, intended for display rather than parsing. + pub plan: String, + /// Conservative metadata pruning, not exact row-filter matches. + pub pruning: PrewarmPruningSummary, +} + +/// Conservative pruning facts for a PREWARM preview. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] +pub struct PrewarmPruningSummary { + /// Proof mode, such as `unfiltered`, `constant`, `zonemap_ranges`, or + /// `full_warm_fallback`. Future servers may return additional modes. + pub mode: String, + /// Fragments in the source snapshot. + pub input_fragments: u64, + /// Fragments selected for warming. + pub selected_fragments: u64, + /// Fragments excluded by metadata proof. + pub pruned_fragments: u64, + /// Candidate physical intervals, when known; not an exact matching-row count. + pub selected_row_ranges: Option, + /// Why metadata could not prune, when reported. + pub fallback_reason: Option, +} + /// Reported outcome of a remote data-prewarm job. Counts describe executor work; /// absent measurements remain unknown rather than being inferred as zero. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -108,6 +142,11 @@ mod tests { .prewarm_data_async(PrewarmDataOptions::new().filter("id > 0")) .await .unwrap_err(); + let preview_error = table + .explain_prewarm_data(Default::default()) + .await + .unwrap_err(); + assert!(matches!(preview_error, crate::Error::NotSupported { .. })); assert!(matches!(error, crate::Error::NotSupported { .. })); assert!( error From 23f9d5a74146cf2e8a1e402cdcaf71e09631b2a2 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 11:07:32 -0800 Subject: [PATCH 165/203] feat(sdk): support bound parameters in data prewarm (#5076) Data prewarm methods accept filter expressions but cannot bind their values, which forces applications to build literal SQL themselves. This adds optional positional and named parameters to data-prewarm submission and typed previews across Rust, Python, and TypeScript. Values use the existing typed Arrow SQL transport and remain separate from the filter text. Existing calls and job-handle behavior are preserved; parameterized filters require a compatible LanceDB Enterprise server. This was accomplished with the following changes: - Add `PrewarmDataOptions::parameters(RecordBatch)` and forward the batch through SQL submission and `EXPLAIN PREWARM` requests. - Reuse Python's `QueryParameters` conversion for synchronous/asynchronous, legacy/job-returning, and typed preview methods. - Add TypeScript positional-array, named-object, and explicit Arrow parameter inputs, with safe scalar encoding and native IPC forwarding. - Keep parameter values out of Rust option debug output and reject invalid input before submission where possible. - Add transport and codec regression tests, including injection-shaped strings, typed Arrow values, legacy method forwarding, and typed preview bindings. - Document bound filters in the cache-prewarm guide with Python, TypeScript, and Rust examples; update generic SQL parameter documentation. ### Usage and behaviour ```python job = table.prewarm_data_async( ["payload"], filter="id >= $minimum", parameters={"minimum": 1000} ) job.wait() ``` ```typescript const job = await table.prewarmDataAsync({ columns: ["payload"], filter: "id >= $1", parameters: [1000], }); await job.wait(); ``` Python accepts a sequence, mapping, or one-row Arrow batch/table. TypeScript accepts scalar arrays/objects or one-row Arrow input; safe integers and bigint use Int64, fractional numbers use Float64. Rust accepts a one-row Arrow batch. Parameters bind filter values, while table identity, branch, and concurrency keep their existing interfaces. Submission-only methods also forward bindings and retain their existing return behavior. Typed preview helpers accept the same parameters without creating a job. ### Testing Python prewarm Flight transport tests pass (65 cases), Embedded compatibility tests pass (6 cases), and focused Node parameter/prewarm tests pass (45 cases, including ten codec and native-boundary cases). Earlier matching-server verification passed 57 Python/SQL scenarios, 14 Node scenarios, and Rust SDK checks, covering selective and empty plans, typed values, authorization, pinned branches, legacy methods, and injection-shaped strings. A bound job also survives a full runtime restart. The guide submission examples were also verified in Python, TypeScript, and Rust; the TypeScript example type-checks. Live-server checks used filesystem storage. --- docs/src/js/classes/Table.md | 7 +- docs/src/js/globals.md | 2 + docs/src/js/interfaces/PrewarmDataOptions.md | 10 ++ .../js/type-aliases/QueryParameterValue.md | 20 ++++ docs/src/js/type-aliases/QueryParameters.md | 16 +++ docs/web/enterprise/cache-prewarm.mdx | 69 ++++++++--- nodejs/__test__/sql_parameters.test.ts | 111 ++++++++++++++++++ nodejs/__test__/table.test.ts | 6 +- nodejs/lancedb/index.ts | 2 + nodejs/lancedb/sql.ts | 104 ++++++++++++++++ nodejs/lancedb/table.ts | 37 ++++-- nodejs/src/table.rs | 16 +++ python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/db.py | 7 +- python/python/lancedb/remote/table.py | 18 ++- python/python/lancedb/table.py | 61 ++++++++-- python/python/tests/test_remote_db.py | 84 +++++++++++++ python/src/table.rs | 8 +- rust/lancedb/src/connection.rs | 5 +- rust/lancedb/src/remote/table.rs | 4 +- rust/lancedb/src/remote/table/prewarm.rs | 33 ++++++ rust/lancedb/src/table/prewarm.rs | 41 ++++++- 22 files changed, 613 insertions(+), 50 deletions(-) create mode 100644 docs/src/js/type-aliases/QueryParameterValue.md create mode 100644 docs/src/js/type-aliases/QueryParameters.md create mode 100644 nodejs/__test__/sql_parameters.test.ts create mode 100644 nodejs/lancedb/sql.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 63b6cffa0..72f68c40f 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -679,7 +679,9 @@ with an unsupported-operation error. #### Example ```ts -const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); +const plan = await table.explainPrewarmData({ + columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7}, +}); console.log(plan.pruning.selectedFragments); ``` @@ -1221,7 +1223,8 @@ the job. After `job.refresh()`, `job.spec.table_version` is the pinned version. ```ts const job = await table.prewarmDataAsync({ - columns: ["video"], filter: "quality > 0.7", concurrency: 4, + columns: ["video"], filter: "quality > $minimum", + parameters: { minimum: 0.7 }, concurrency: 4, }); await job.wait(); ``` diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 3c348faac..0a0742389 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -191,6 +191,8 @@ - [JobProgressCallback](type-aliases/JobProgressCallback.md) - [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md) - [MultiVector](type-aliases/MultiVector.md) +- [QueryParameterValue](type-aliases/QueryParameterValue.md) +- [QueryParameters](type-aliases/QueryParameters.md) - [RecordBatchLike](type-aliases/RecordBatchLike.md) - [SchemaLike](type-aliases/SchemaLike.md) - [TableLike](type-aliases/TableLike.md) diff --git a/docs/src/js/interfaces/PrewarmDataOptions.md b/docs/src/js/interfaces/PrewarmDataOptions.md index 4815b84fb..fae916320 100644 --- a/docs/src/js/interfaces/PrewarmDataOptions.md +++ b/docs/src/js/interfaces/PrewarmDataOptions.md @@ -37,3 +37,13 @@ optional filter: string; ``` A single SQL predicate for conservative metadata pruning. + +*** + +### parameters? + +```ts +optional parameters: QueryParameters; +``` + +Typed positional or named filter values, sent separately from SQL. diff --git a/docs/src/js/type-aliases/QueryParameterValue.md b/docs/src/js/type-aliases/QueryParameterValue.md new file mode 100644 index 000000000..a8f275052 --- /dev/null +++ b/docs/src/js/type-aliases/QueryParameterValue.md @@ -0,0 +1,20 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / QueryParameterValue + +# Type Alias: QueryParameterValue + +```ts +type QueryParameterValue: + | string + | number + | bigint + | boolean + | Date + | Uint8Array + | null; +``` + +Scalar SQL values. Use a one-row Arrow table for explicit Arrow types. diff --git a/docs/src/js/type-aliases/QueryParameters.md b/docs/src/js/type-aliases/QueryParameters.md new file mode 100644 index 000000000..dfce3ed30 --- /dev/null +++ b/docs/src/js/type-aliases/QueryParameters.md @@ -0,0 +1,16 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / QueryParameters + +# Type Alias: QueryParameters + +```ts +type QueryParameters: readonly QueryParameterValue[] | Readonly> | TableLike | RecordBatchLike; +``` + +Values for `$1`/`$name` placeholders, sent separately from SQL text. +Arrays bind by position; objects bind by name. Arrow columns bind both ways. +Safe integers and bigint use Int64; fractional numbers use Float64. +Arrow input preserves explicit types. diff --git a/docs/web/enterprise/cache-prewarm.mdx b/docs/web/enterprise/cache-prewarm.mdx index 56a091364..007cff0ab 100644 --- a/docs/web/enterprise/cache-prewarm.mdx +++ b/docs/web/enterprise/cache-prewarm.mdx @@ -14,7 +14,7 @@ the [tiered index cache](/enterprise/tiered-index-cache), and [on-demand data prewarm](#on-demand-data-prewarm) fills the [data page cache](/enterprise/data-page-cache) through a durable job. -For startup index prewarm, you configure which tables to warm. Each plan +For startup index prewarm, you configure which tables to warm. Each executor loads those tables' indexes before it joins the fleet. The executor does not accept queries until startup prewarming finishes. @@ -32,7 +32,7 @@ an idempotent hint that loads a built index into memory ahead of a query. }}}%% flowchart LR List[("Configured list
of tables to prewarm")] - Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + Start["Executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] List -.-> Warm Warm --> Ready["Ready — joins the fleet,
starts serving queries"] classDef default fill:#1e1b19,stroke:#4c443f,stroke-width:1px,color:#f4ebe8 @@ -52,7 +52,7 @@ flowchart LR }}}%% flowchart LR List[("Configured list
of tables to prewarm")] - Start["Plan executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] + Start["Executor starts
(not ready — no queries served)"] --> Warm["Loads the configured
tables' indexes into cache"] List -.-> Warm Warm --> Ready["Ready — joins the fleet,
starts serving queries"] classDef default fill:#ffffff,stroke:#ad9e95,stroke-width:1px,color:#221d19 @@ -91,7 +91,8 @@ The table handle determines the database, namespace, and branch in every SDK. from datetime import timedelta job = table.prewarm_data_async( - ["video"], filter="quality > 0.7", concurrency=4 + ["video"], filter="quality > $minimum", + parameters={"minimum": 0.7}, concurrency=4 ) print(job.id) result = job.wait(timeout=timedelta(minutes=10), progress=print) @@ -105,7 +106,8 @@ db.open_job(job.id).wait() ```typescript const job = await table.prewarmDataAsync({ columns: ["video"], - filter: "quality > 0.7", + filter: "quality > $1", + parameters: [0.7], concurrency: 4, }); console.log(job.id); @@ -121,14 +123,20 @@ if (job.id !== null) { ```rust use std::time::Duration; +use std::sync::Arc; +use arrow_array::{ArrayRef, Float64Array, RecordBatch}; use lancedb::job::JobWaitOptions; use lancedb::table::{PrewarmDataOptions, PrewarmDataResult}; +let parameters = RecordBatch::try_from_iter([ + ("minimum", Arc::new(Float64Array::from(vec![0.7])) as ArrayRef), +])?; let job = table .prewarm_data_async( PrewarmDataOptions::new() .columns(["video"]) - .filter("quality > 0.7") + .filter("quality > $minimum") + .parameters(parameters) .concurrency(4), ) .await?; @@ -150,8 +158,22 @@ The method returns when the job is accepted. Waiting finishes when warming reaches a terminal state; a timeout does not cancel the job. Use `job.refresh()` and `job.spec["table_version"]` to inspect the captured source version. In Python's asynchronous API, await submission and `job.wait()`. -Node exposes `table.prewarmDataAsync({ columns, filter, concurrency })` with -the same lifecycle. +The TypeScript SDK exposes +`table.prewarmDataAsync({ columns, filter, parameters, concurrency })` with the +same lifecycle. + +Pass `parameters` alongside a filter to bind positional `$1`/`$2` or named +`$name` values. Python accepts a sequence, mapping, or one-row Arrow batch/table; +TypeScript accepts a scalar array, named object, or one-row Arrow batch/table. +Rust accepts a one-row Arrow `RecordBatch`. Values travel separately from SQL +text, and table/column identifiers, branch, and concurrency retain their existing +interfaces. Existing literal filters continue to work without parameters. + +Bound filters require an Enterprise server that supports parameterized PREWARM. +The server accepts up to 1,024 scalar parameters and 64 KiB of encoded Arrow IPC. +Missing, unused, malformed, oversized, and unsupported bindings fail before job +creation. TypeScript encodes safe integer numbers and bigint as Int64 and +fractional numbers as Float64; use Arrow input when an explicit type is needed. Waiting returns a typed `PrewarmDataResult`: the pinned source version, selected fragment count, targeted/completed executor counts, and partial @@ -197,7 +219,7 @@ it creates no warming job and does not use the job-monitoring APIs. from lancedb.prewarm import PrewarmDataPlan plan: PrewarmDataPlan = table.explain_prewarm_data( - ["payload"], filter="id >= 1000", concurrency=4 + ["payload"], filter="id >= $minimum", parameters={"minimum": 1000}, concurrency=4 ) print(plan.table_version) print(plan.pruning.mode) @@ -214,7 +236,8 @@ import type { PrewarmDataPlan } from "@lancedb/lancedb"; const plan: PrewarmDataPlan = await table.explainPrewarmData({ columns: ["payload"], - filter: "id >= 1000", + filter: "id >= $minimum", + parameters: { minimum: 1000 }, concurrency: 4, }); console.log(plan.tableVersion); @@ -225,13 +248,19 @@ console.log(plan.pruning.selectedRowRanges, plan.pruning.fallbackReason); ```rust +use std::sync::Arc; +use arrow_array::{ArrayRef, Int64Array, RecordBatch}; use lancedb::table::{PrewarmDataOptions, PrewarmDataPlan}; +let parameters = RecordBatch::try_from_iter([ + ("minimum", Arc::new(Int64Array::from(vec![1000])) as ArrayRef), +])?; let plan: PrewarmDataPlan = table .explain_prewarm_data( PrewarmDataOptions::new() .columns(["payload"]) - .filter("id >= 1000") + .filter("id >= $minimum") + .parameters(parameters) .concurrency(4), ) .await?; @@ -255,15 +284,25 @@ when reported. Pruning modes may expand in future server versions. A preview doe resolves and plans its own source version. Unsupported servers fail explicitly without falling back to text parsing or REST. +Python's SQL interface also accepts bindings for a preview without submitting a +warming job: + +```python +plan = db.execute_query( + "EXPLAIN PREWARM AS SELECT video FROM clips WHERE quality > $minimum", + parameters={"minimum": 0.7}, +).read_all() +``` + The filter is a single SQL predicate used for conservative metadata pruning. Unknown or unavailable metadata keeps data eligible for warming. Omitted columns warm all fields; concurrency must be a positive integer. Historical version checkouts are unsupported: use the latest version of the selected branch. The server never needs to scan rows merely to evaluate the predicate. -`prewarm_data(columns, filter=..., concurrency=...)` and -`prewarmData({ columns, filter, concurrency })` accept the same options as the -job-returning methods but return after acceptance without retaining the handle. +`prewarm_data(columns, filter=..., parameters=..., concurrency=...)` and +`prewarmData({ columns, filter, parameters, concurrency })` accept the same +options as the job-returning methods but return after acceptance without retaining the handle. The existing TypeScript `prewarmData(columns)` array form remains supported. These methods require SQL PREWARM support and Flight SQL connectivity. Unsupported servers fail without a REST fallback or silently @@ -280,6 +319,6 @@ already-cached data is safe. Index prewarm keeps its existing behavior. The deserialized-index cache populated by startup index prewarm.
- Where plan executors and query nodes sit in the serving fleet. + Where executors and query nodes sit in the serving fleet.
diff --git a/nodejs/__test__/sql_parameters.test.ts b/nodejs/__test__/sql_parameters.test.ts new file mode 100644 index 000000000..2e8c979df --- /dev/null +++ b/nodejs/__test__/sql_parameters.test.ts @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Int32, Table, tableFromIPC, vectorFromArray } from "../lancedb/arrow"; +import { toParameterBuffer } from "../lancedb/sql"; +import { LocalTable } from "../lancedb/table"; + +describe("SQL parameter encoding", () => { + test.each([false, true])( + "prewarm submission and preview forward typed bindings (named: %s)", + async (named) => { + const attack = "training' OR TRUE; DROP TABLE items; --"; + const parameters = named ? { minimum: 42n, tag: attack } : [42n, attack]; + const filter = named + ? "id >= $minimum AND tag = $tag" + : "id >= $1 AND tag = $2"; + const submission = jest.fn().mockResolvedValue({}); + const preview = jest.fn().mockResolvedValue( + JSON.parse(`{ + "table_version": 42, + "plan": "metadata preview", + "pruning": { + "mode": "zonemap_ranges", + "input_fragments": 3, + "selected_fragments": 1, + "pruned_fragments": 2, + "selected_row_ranges": 2 + } + }`), + ); + const table = new LocalTable({ + prewarmDataAsync: submission, + explainPrewarmData: preview, + } as never); + await table.prewarmDataAsync({ filter, parameters }); + const plan = await table.explainPrewarmData({ filter, parameters }); + expect(plan.tableVersion).toBe(42); + expect(plan.pruning.selectedFragments).toBe(1); + for (const call of [submission, preview]) { + expect(call).toHaveBeenCalledTimes(1); + const options = call.mock.calls[0][0]; + expect(options.filter).toBe(filter); + expect(options.filter).not.toContain(attack); + expect(Buffer.isBuffer(options.parameters)).toBe(true); + const batch = tableFromIPC(options.parameters); + expect(batch.schema.fields.map((field) => field.name)).toEqual( + named ? ["minimum", "tag"] : ["1", "2"], + ); + expect(batch.getChildAt(0)?.get(0)).toBe(42n); + expect(batch.getChildAt(1)?.get(0)).toBe(attack); + } + }, + ); + + test("positional and named bindings preserve values without SQL interpolation", async () => { + const attack = "training' OR TRUE; DROP TABLE items; --"; + const date = new Date("2026-01-02T00:00:00Z"); + const batch = tableFromIPC( + await toParameterBuffer([ + 42n, + attack, + null, + true, + date, + 0.7, + new Uint8Array([1, 2]), + ]), + ); + expect(batch.schema.fields.map((field) => field.name)).toEqual([ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + ]); + expect(batch.getChildAt(0)?.get(0)).toBe(42n); + expect(batch.getChildAt(1)?.get(0)).toBe(attack); + expect(batch.getChildAt(2)?.get(0)).toBeNull(); + expect(batch.getChildAt(4)?.get(0)).toBe(date.getTime()); + const named = tableFromIPC( + await toParameterBuffer({ minimum: 42n, tag: attack }), + ); + expect(named.schema.fields.map((field) => field.name)).toEqual([ + "minimum", + "tag", + ]); + expect(named.getChild("tag")?.get(0)).toBe(attack); + }); + + test("explicit Arrow input preserves its types", async () => { + const input = new Table({ minimum: vectorFromArray([42], new Int32()) }); + for (const parameters of [input, input.batches[0]]) { + const decoded = tableFromIPC(await toParameterBuffer(parameters)); + expect(decoded.schema.fields[0].type.toString()).toBe("Int32"); + expect(decoded.getChildAt(0)?.get(0)).toBe(42); + } + }); + + test.each([ + [], + { value: undefined }, + { value: 2 ** 53 }, + { value: 1n << 63n }, + { value: {} }, + { value: new Date("invalid") }, + ])("invalid parameters fail before submission: %p", async (parameters) => { + await expect(toParameterBuffer(parameters as never)).rejects.toThrow(); + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 04d80d5f9..bfe69e931 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4744,6 +4744,9 @@ describe.each(arrowVersions)( await expect(table.explainPrewarmData()).rejects.toThrow( "only supported on remote tables", ); + await expect( + table.explainPrewarmData({ filter: "id > $1", parameters: [1] }), + ).rejects.toThrow("only supported on remote tables"); await expect( table.explainPrewarmData({ unsupported: true } as never), ).rejects.toThrow("Unsupported data prewarm option"); @@ -4770,8 +4773,9 @@ describe.each(arrowVersions)( await expect( table.prewarmDataAsync({ columns: ["id"], - filter: "id > 0", + filter: "id > $1", concurrency: 2, + parameters: [1], }), ).rejects.toThrow("only supported on remote tables"); await expect( diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 8a2607724..b99d856cc 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -673,3 +673,5 @@ export type { PrewarmDataResult, PrewarmPruningSummary, } from "./prewarm"; + +export type { QueryParameters, QueryParameterValue } from "./sql"; diff --git a/nodejs/lancedb/sql.ts b/nodejs/lancedb/sql.ts new file mode 100644 index 000000000..e7cb4de6f --- /dev/null +++ b/nodejs/lancedb/sql.ts @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + Binary, + Bool, + type DataType, + Float64, + Int64, + Null, + RecordBatchFileWriter, + type RecordBatchLike, + Table, + type TableLike, + TimestampMillisecond, + Utf8, + vectorFromArray, +} from "./arrow"; +import { sanitizeTable } from "./sanitize"; + +/** Scalar SQL values. Use a one-row Arrow table for explicit Arrow types. */ +export type QueryParameterValue = + | string + | number + | bigint + | boolean + | Date + | Uint8Array + | null; + +/** Values for `$1`/`$name` placeholders, sent separately from SQL text. + * Arrays bind by position; objects bind by name. Arrow columns bind both ways. + * Safe integers and bigint use Int64; fractional numbers use Float64. + * Arrow input preserves explicit types. + */ +export type QueryParameters = + | readonly QueryParameterValue[] + | Readonly> + | TableLike + | RecordBatchLike; + +/** @internal */ +export async function toParameterBuffer( + parameters: QueryParameters, +): Promise { + let table: Table; + if ( + "schema" in parameters && + parameters.schema !== null && + typeof parameters.schema === "object" && + "fields" in parameters.schema + ) { + const arrow = parameters as TableLike | RecordBatchLike; + table = sanitizeTable( + "batches" in arrow ? arrow : { schema: arrow.schema, batches: [arrow] }, + ); + } else { + const entries = Array.isArray(parameters) + ? parameters.map((value, index) => [String(index + 1), value] as const) + : Object.entries(parameters); + const columns = Object.fromEntries( + entries.map(([name, input]) => { + let value = input; + let type: DataType; + if (value === null) type = new Null(); + else if (typeof value === "string") type = new Utf8(); + else if (typeof value === "boolean") type = new Bool(); + else if (typeof value === "number") { + if ( + !Number.isFinite(value) || + (Number.isInteger(value) && !Number.isSafeInteger(value)) + ) { + throw new Error( + "Numeric parameters must be finite and integers must be safe; use bigint for Int64", + ); + } + type = Number.isInteger(value) ? new Int64() : new Float64(); + if (Number.isInteger(value)) value = BigInt(value); + } else if (typeof value === "bigint") { + if (value < -(1n << 63n) || value >= 1n << 63n) { + throw new Error("bigint parameters must fit Int64"); + } + type = new Int64(); + } else if (value instanceof Date && Number.isFinite(value.getTime())) { + type = new TimestampMillisecond(); + } else if (value instanceof Uint8Array) type = new Binary(); + else + throw new Error( + "Query parameters must be scalar values or a one-row Arrow table", + ); + return [name, vectorFromArray([value], type)]; + }), + ); + table = new Table(columns); + } + if (table.numRows !== 1) { + throw new Error( + `Query parameters must contain exactly one row, got ${table.numRows}`, + ); + } + return Buffer.from( + await RecordBatchFileWriter.writeAll(table).toUint8Array(), + ); +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 3b3e7abe5..eecb83fb6 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -71,6 +71,7 @@ import { instanceOfFullTextQuery, } from "./query"; import { sanitizeType } from "./sanitize"; +import { QueryParameters, toParameterBuffer } from "./sql"; import { IntoSql, toSQL } from "./util"; export { IndexConfig } from "./native"; export { @@ -179,6 +180,8 @@ export interface PrewarmDataOptions { columns?: string[]; /** A single SQL predicate for conservative metadata pruning. */ filter?: string; + /** Typed positional or named filter values, sent separately from SQL. */ + parameters?: QueryParameters; /** Positive per-executor concurrency, at most 4294967295. */ concurrency?: number; } @@ -624,7 +627,8 @@ export abstract class Table { * * @example * const job = await table.prewarmDataAsync({ - * columns: ["video"], filter: "quality > 0.7", concurrency: 4, + * columns: ["video"], filter: "quality > $minimum", + * parameters: { minimum: 0.7 }, concurrency: 4, * }); * await job.wait(); */ @@ -643,7 +647,9 @@ export abstract class Table { * with an unsupported-operation error. * * @example - * const plan = await table.explainPrewarmData({columns: ["video"], filter: "quality > 0.7"}); + * const plan = await table.explainPrewarmData({ + * columns: ["video"], filter: "quality > $minimum", parameters: {minimum: 0.7}, + * }); * console.log(plan.pruning.selectedFragments); */ async explainPrewarmData( @@ -1668,9 +1674,10 @@ export class LocalTable extends Table { async prewarmDataAsync( options?: PrewarmDataOptions, ): Promise> { - validatePrewarmDataOptions(options); return new Job( - await this.inner.prewarmDataAsync(options), + await this.inner.prewarmDataAsync( + await toNativePrewarmDataOptions(options), + ), decodePrewarmDataResult, ); } @@ -1678,8 +1685,11 @@ export class LocalTable extends Table { async explainPrewarmData( options?: PrewarmDataOptions, ): Promise { - validatePrewarmDataOptions(options); - return decodePrewarmDataPlan(await this.inner.explainPrewarmData(options)); + return decodePrewarmDataPlan( + await this.inner.explainPrewarmData( + await toNativePrewarmDataOptions(options), + ), + ); } async waitForIndex( @@ -2399,9 +2409,22 @@ function validateCompactionOptions(options?: CompactionOptions): void { } } +async function toNativePrewarmDataOptions(options?: PrewarmDataOptions) { + validatePrewarmDataOptions(options); + return options === undefined + ? undefined + : { + ...options, + parameters: + options.parameters === undefined + ? undefined + : await toParameterBuffer(options.parameters), + }; +} + function validatePrewarmDataOptions(options?: PrewarmDataOptions): void { for (const key of Object.keys(options ?? {})) { - if (!["columns", "filter", "concurrency"].includes(key)) { + if (!["columns", "filter", "concurrency", "parameters"].includes(key)) { throw new Error(`Unsupported data prewarm option: ${key}`); } } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 6a0a8cb60..1a4c3e91c 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -33,6 +33,7 @@ pub struct PrewarmDataOptions { pub columns: Option>, pub filter: Option, pub concurrency: Option, + pub parameters: Option, } impl PrewarmDataOptions { @@ -40,6 +41,21 @@ impl PrewarmDataOptions { let mut options = lancedb::table::PrewarmDataOptions::new().columns(self.columns.unwrap_or_default()); options.filter = self.filter; + if let Some(parameters) = self.parameters { + let mut batches = ipc_file_to_batches(parameters.to_vec()) + .and_then(|reader| { + reader + .collect::, _>>() + .map_err(Into::into) + }) + .map_err(|error| napi::Error::from_reason(error.to_string()))?; + if batches.len() != 1 || batches[0].num_rows() != 1 { + return Err(napi::Error::from_reason( + "prewarm parameters must contain one row in one batch", + )); + } + options.parameters = Some(batches.remove(0)); + } if let Some(value) = self.concurrency { if !value.is_finite() || value.fract() != 0.0 || value < 1.0 || value > u32::MAX as f64 { diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index cdeebf6ef..98936e0a2 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -651,6 +651,7 @@ class Table: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[pa.RecordBatch] = None, ) -> str: ... async def prewarm_data_async( self, @@ -658,6 +659,7 @@ class Table: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[pa.RecordBatch] = None, ) -> Job: ... async def list_indices(self) -> list[IndexConfig]: ... async def tokenize( diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 8c9901aff..86001ef10 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1738,8 +1738,11 @@ 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. With or - without parameters, the server chooses whether to stream rows on the + Parameters are supported in queries and, on compatible Enterprise servers, + scalar filter values in ``PREWARM`` and ``EXPLAIN PREWARM``. Support for + other statement types depends on the server. + + 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 diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index a5d08bd72..f984b47fb 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -24,6 +24,7 @@ from typing import ( import warnings from lancedb import __version__ +from lancedb.sql import QueryParameters from lancedb._blob import BlobFile from lancedb._lancedb import ( @@ -1452,6 +1453,7 @@ class RemoteTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """Prewarm data for the table. @@ -1474,6 +1476,9 @@ class RemoteTable(Table): The columns to prewarm. If None, all columns are prewarmed. filter: str, optional A single SQL predicate for conservative metadata pruning. + parameters: sequence, mapping, or one-row Arrow batch/table, optional + Scalar values for ``$1``/``$name`` placeholders in ``filter``. + Values are sent separately from SQL; requires server support. concurrency: int, optional Positive per-executor warming concurrency; omitted uses the server default. @@ -1483,7 +1488,9 @@ class RemoteTable(Table): ... ["payload"], filter="quality > 0.7", concurrency=4) """ return LOOP.run( - self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + self._table.prewarm_data( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) ) def explain_prewarm_data( @@ -1492,6 +1499,7 @@ class RemoteTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview prewarm without submitting a warming job. @@ -1500,7 +1508,7 @@ class RemoteTable(Table): """ return LOOP.run( self._table.explain_prewarm_data( - columns, filter=filter, concurrency=concurrency + columns, filter=filter, concurrency=concurrency, parameters=parameters ) ) @@ -1510,11 +1518,15 @@ class RemoteTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> Job[PrewarmDataResult]: return Job( LOOP.run( self._table.prewarm_data_async( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=parameters, ) ) ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index d9c20e287..dfb1d1cde 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -47,6 +47,7 @@ from ._blob import ( ) from .types import BlobMode from lancedb.arrow import peek_reader +from lancedb.sql import QueryParameters, to_parameter_batch from lancedb.background_loop import LOOP, embedding_executor from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult from lancedb.job import AsyncJob, Job, _typed_job @@ -2019,6 +2020,7 @@ class Table(ABC): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """Submit remote data prewarm and return after acceptance. @@ -2037,7 +2039,9 @@ class Table(ABC): >>> table.prewarm_data( # doctest: +SKIP ... ["payload"], filter="quality > 0.7", concurrency=4) """ - self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + self.prewarm_data_async( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) def explain_prewarm_data( self, @@ -2045,13 +2049,15 @@ class Table(ABC): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview data prewarm without creating a warming job. - Accepts the same columns, filter, and concurrency as ``prewarm_data_async`` - and uses the table handle's namespace and branch. Requires LanceDB - Enterprise with structured SQL previews, table Select, and database/namespace - Usage. Historical-version and Embedded handles are unsupported. + Accepts the same columns, filter, parameters, and concurrency as + ``prewarm_data_async`` and uses the table handle's namespace and branch. + Requires LanceDB Enterprise with structured SQL previews, table Select, + and database/namespace Usage. Historical-version and Embedded handles + are unsupported. Returns the source version, readable plan, and conservative pruning summary. Unknown metrics remain None; selected ranges are not exact matching rows. @@ -2060,7 +2066,7 @@ class Table(ABC): Examples -------- >>> plan = table.explain_prewarm_data( # doctest: +SKIP - ... ["video"], filter="quality > 0.7") + ... ["video"], filter="quality > $minimum", parameters={"minimum": 0.7}) >>> print(plan.pruning.selected_fragments) # doctest: +SKIP """ raise NotImplementedError( @@ -2073,6 +2079,7 @@ class Table(ABC): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> Job[PrewarmDataResult]: """Submit a remote data-cache prewarm and return its durable job. @@ -2080,6 +2087,8 @@ class Table(ABC): The table handle supplies the branch and namespace. ``columns`` uses Lance field paths; an omitted/empty list warms all columns. ``filter`` is one SQL predicate for conservative metadata pruning, not a row scan. + ``parameters`` binds ``$1``/``$name`` values using a sequence, mapping, + or one-row Arrow batch/table. Values are sent separately from SQL. ``concurrency`` is a positive per-executor integer. Historical-version handles are unsupported; call ``checkout_latest()`` first. @@ -2097,7 +2106,8 @@ class Table(ABC): Examples -------- >>> job = table.prewarm_data_async( # doctest: +SKIP - ... ["video"], filter="quality > 0.7", concurrency=4) + ... ["video"], filter="quality > $min", parameters={"min": 0.7}, + ... concurrency=4) >>> job.wait() # doctest: +SKIP """ raise NotImplementedError( @@ -4977,6 +4987,7 @@ class LanceTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """ Prewarm data for the table. @@ -5000,6 +5011,9 @@ class LanceTable(Table): The columns to prewarm. If None, all columns are prewarmed. filter: str, optional A single SQL predicate for conservative metadata pruning. + parameters: sequence, mapping, or one-row Arrow batch/table, optional + Scalar values for ``$1``/``$name`` placeholders in ``filter``. + Values are sent separately from SQL; requires server support. concurrency: int, optional Positive per-executor warming concurrency; omitted uses the server default. @@ -5009,7 +5023,9 @@ class LanceTable(Table): ... ["payload"], filter="quality > 0.7", concurrency=4) """ return LOOP.run( - self._table.prewarm_data(columns, filter=filter, concurrency=concurrency) + self._table.prewarm_data( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) ) def explain_prewarm_data( @@ -5018,6 +5034,7 @@ class LanceTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview prewarm without submitting a warming job. @@ -5026,7 +5043,7 @@ class LanceTable(Table): """ return LOOP.run( self._table.explain_prewarm_data( - columns, filter=filter, concurrency=concurrency + columns, filter=filter, concurrency=concurrency, parameters=parameters ) ) @@ -5036,11 +5053,15 @@ class LanceTable(Table): *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> Job[PrewarmDataResult]: return Job( LOOP.run( self._table.prewarm_data_async( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=parameters, ) ) ) @@ -7532,6 +7553,7 @@ class AsyncTable: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> None: """ Prewarm data for the table. @@ -7555,6 +7577,9 @@ class AsyncTable: The columns to prewarm. If None, all columns are prewarmed. filter: str, optional A single SQL predicate for conservative metadata pruning. + parameters: sequence, mapping, or one-row Arrow batch/table, optional + Scalar values for ``$1``/``$name`` placeholders in ``filter``. + Values are sent separately from SQL; requires server support. concurrency: int, optional Positive per-executor warming concurrency; omitted uses the server default. @@ -7563,7 +7588,9 @@ class AsyncTable: >>> await table.prewarm_data( # doctest: +SKIP ... ["payload"], filter="quality > 0.7", concurrency=4) """ - await self.prewarm_data_async(columns, filter=filter, concurrency=concurrency) + await self.prewarm_data_async( + columns, filter=filter, concurrency=concurrency, parameters=parameters + ) async def explain_prewarm_data( self, @@ -7571,6 +7598,7 @@ class AsyncTable: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> PrewarmDataPlan: """Preview prewarm without submitting a warming job. @@ -7579,7 +7607,10 @@ class AsyncTable: """ return PrewarmDataPlan.from_json( await self._inner.explain_prewarm_data( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=to_parameter_batch(parameters), ) ) @@ -7589,6 +7620,7 @@ class AsyncTable: *, filter: Optional[str] = None, concurrency: Optional[int] = None, + parameters: Optional[QueryParameters] = None, ) -> AsyncJob[PrewarmDataResult]: """Submit data prewarm and return a durable handle after acceptance. @@ -7604,7 +7636,10 @@ class AsyncTable: """ return _typed_job( await self._inner.prewarm_data_async( - columns, filter=filter, concurrency=concurrency + columns, + filter=filter, + concurrency=concurrency, + parameters=to_parameter_batch(parameters), ), PrewarmDataResult.from_json, ) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 381847954..bb649aaa2 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -8212,6 +8212,8 @@ async def test_remote_data_prewarm_sql_receipt_and_durable_job(asynchronous, mod {"concurrency": 2**32}, {"concurrency": True}, {"concurrency": 1.5}, + {"parameters": [1]}, + {"filter": "id > $1", "parameters": pa.table({"1": [1, 2]})}, ], ) @pytest.mark.parametrize( @@ -8236,6 +8238,88 @@ def test_remote_data_prewarm_validates_before_submission(options, method): assert not server.tickets +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"] +) +@pytest.mark.parametrize("named", [False, True]) +async def test_prewarm_bound_parameters_reach_flight(asynchronous, method, named): + flight = pytest.importorskip("pyarrow.flight") + attack = "training' OR TRUE; DROP TABLE items; --" + + class ParameterServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = [] + + def do_exchange(self, context, descriptor, reader, writer): + self.calls.append((descriptor.command, reader.read_all())) + if method == "explain_prewarm_data": + result = pa.table( + { + "plan_type": ["logical_plan"], + "plan": [ + json.dumps( + { + "format_version": 1, + "table_version": 42, + "plan": "metadata preview", + "pruning": { + "mode": "zonemap_ranges", + "input_fragments": 3, + "selected_fragments": 1, + "pruned_fragments": 2, + "selected_row_ranges": 2, + }, + } + ) + ], + } + ) + else: + result = pa.table( + { + "job_id": ["bound-job"], + "table_version": pa.array([42], pa.uint64()), + } + ) + writer.begin(result.schema) + writer.write_table(result) + writer.close() + + server = ParameterServer() + with _mock_remote_sql_connection(server, _create_table_handler) as kwargs: + parameters = {"min": 8, "tag": attack} if named else [8, attack] + predicate = "id >= $min AND tag = $tag" if named else "id >= $1 AND tag = $2" + if asynchronous: + db = await lancedb.connect_async(**kwargs) + table = await db.create_table("test", [{"id": 1}]) + result = await getattr(table, method)( + ["payload"], filter=predicate, parameters=parameters + ) + else: + db = lancedb.connect(**kwargs) + table = db.create_table("test", [{"id": 1}]) + result = getattr(table, method)( + ["payload"], filter=predicate, parameters=parameters + ) + if method == "prewarm_data": + assert result is None + elif method == "explain_prewarm_data": + assert result.table_version == 42 + assert result.pruning.selected_fragments == 1 + else: + assert result.id == "bound-job" + ((command, received),) = server.calls + assert b"PREWARM" in command and predicate.encode() in command + if method == "explain_prewarm_data": + assert b"EXPLAIN (FORMAT JSON) PREWARM" in command + assert attack.encode() not in command + assert received.column(0).to_pylist() == [8] + assert received.column(1).to_pylist() == [attack] + + def test_remote_data_prewarm_malformed_receipt_is_not_retried(): flight = pytest.importorskip("pyarrow.flight") diff --git a/python/src/table.rs b/python/src/table.rs index a47d82d98..c24b10405 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1895,17 +1895,19 @@ impl Table { }) } - #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))] pub fn prewarm_data_async<'py>( self_: PyRef<'py, Self>, columns: Option>, filter: Option, concurrency: Option<&Bound<'py, PyAny>>, + parameters: Option>, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let mut options = lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); options.filter = filter; + options.parameters = parameters.map(|parameters| parameters.0); options.concurrency = positive_u32_integer(concurrency, "concurrency")?; future_into_py(self_.py(), async move { let job = inner.prewarm_data_async(options).await.infer_error()?; @@ -1913,17 +1915,19 @@ impl Table { }) } - #[pyo3(signature = (columns=None, *, filter=None, concurrency=None))] + #[pyo3(signature = (columns=None, *, filter=None, concurrency=None, parameters=None))] pub fn explain_prewarm_data<'py>( self_: PyRef<'py, Self>, columns: Option>, filter: Option, concurrency: Option<&Bound<'py, PyAny>>, + parameters: Option>, ) -> PyResult> { let inner = self_.inner_ref()?.clone(); let mut options = lancedb::table::PrewarmDataOptions::new().columns(columns.unwrap_or_default()); options.filter = filter; + options.parameters = parameters.map(|parameters| parameters.0); options.concurrency = positive_u32_integer(concurrency, "concurrency")?; future_into_py(self_.py(), async move { let plan = inner.explain_prewarm_data(options).await.infer_error()?; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 29f70d164..bbefc3ca8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -381,7 +381,10 @@ impl ExecuteQueryAsyncBuilder { /// /// Every placeholder needs a value and every parameter must be used by a /// placeholder. Parameters are supported in queries (`SELECT`, and - /// `EXPLAIN` of one), not in DDL or DML, nor in table-function arguments. + /// `EXPLAIN` of one) and, on compatible Enterprise servers, filter values in + /// `PREWARM` and `EXPLAIN PREWARM`. Prewarm bindings must be scalars. + /// Support for other statements depends on the server; table-function + /// arguments do not accept parameters. /// Do not follow a named placeholder directly with `$`: `$a$` starts a /// dollar-quoted string. /// diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 649edd133..54b7ea7b2 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4789,7 +4789,7 @@ impl BaseTable for RemoteTable { .execute_prewarm(crate::database::ExecuteQueryRequest { query: statement, default_namespace_path: self.namespace.clone(), - parameters: None, + parameters: options.parameters, }) .await .map_err(prewarm::map_error)?; @@ -4828,7 +4828,7 @@ impl BaseTable for RemoteTable { .execute_prewarm(crate::database::ExecuteQueryRequest { query: statement, default_namespace_path: self.namespace.clone(), - parameters: None, + parameters: options.parameters, }) .await .map_err(prewarm::map_explain_error)?; diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs index d87465acf..4b6b2236f 100644 --- a/rust/lancedb/src/remote/table/prewarm.rs +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -20,6 +20,14 @@ pub(super) fn statement( if options.concurrency == Some(0) { return Err(invalid("prewarm concurrency must be greater than 0")); } + if let Some(parameters) = &options.parameters { + if options.filter.is_none() { + return Err(invalid("prewarm parameters require a filter")); + } + if parameters.num_rows() != 1 { + return Err(invalid("prewarm parameters must contain exactly one row")); + } + } if let Some(filter) = &options.filter { if filter.trim().is_empty() { return Err(invalid("prewarm filter must not be empty")); @@ -293,6 +301,31 @@ mod tests { assert!(plan(&[batch(&valid), batch(&valid)]).is_err()); } + #[test] + fn bound_values_are_never_rendered_into_sql() { + let value = "training' OR TRUE; DROP TABLE clips; --"; + let parameters = RecordBatch::try_from_iter(vec![( + "tag", + Arc::new(StringArray::from(vec![value])) as arrow_array::ArrayRef, + )]) + .unwrap(); + let options = PrewarmDataOptions::new() + .filter("tag = $tag") + .parameters(parameters); + let sql = statement("clips", Some("experiment"), &options).unwrap(); + assert!(sql.ends_with("WHERE tag = $tag")); + assert!(!sql.contains(value)); + assert!(!format!("{options:?}").contains(value)); + assert!( + statement( + "clips", + None, + &PrewarmDataOptions::new().parameters(options.parameters.unwrap()) + ) + .is_err() + ); + } + #[test] fn quotes_paths_branch_and_filter_without_changing_options() { let options = PrewarmDataOptions::new() diff --git a/rust/lancedb/src/table/prewarm.rs b/rust/lancedb/src/table/prewarm.rs index badb5a8ad..bc1128c54 100644 --- a/rust/lancedb/src/table/prewarm.rs +++ b/rust/lancedb/src/table/prewarm.rs @@ -3,22 +3,40 @@ //! Options, previews, and results for data-cache prewarm. -/// Data prewarm settings for [`super::Table::prewarm_data_async`]. +/// Data prewarm settings for [`super::Table::prewarm_data_async`] and +/// [`super::Table::explain_prewarm_data`]. /// /// The table handle supplies the database, namespace, and branch. Omitted /// columns warm all fields. The filter selects conservative metadata ranges; /// it does not execute a row-filter scan or change the source data. -#[derive(Debug, Clone, Default)] +#[derive(Clone, Default)] #[non_exhaustive] pub struct PrewarmDataOptions { /// Lance field paths, including nested paths such as `attrs.score`. pub columns: Vec, /// An optional SQL predicate for metadata pruning. pub filter: Option, + /// One row of typed filter values. Column i binds `$` and a + /// nonnumeric column name also binds `$name`. Requires server support. + pub parameters: Option, /// Positive per-executor warming concurrency. Omit for the server default. pub concurrency: Option, } +impl std::fmt::Debug for PrewarmDataOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PrewarmDataOptions") + .field("columns", &self.columns) + .field("filter", &self.filter) + .field("concurrency", &self.concurrency) + .field( + "parameter_count", + &self.parameters.as_ref().map(|batch| batch.num_columns()), + ) + .finish() + } +} + impl PrewarmDataOptions { /// Use server defaults and warm every column. pub fn new() -> Self { @@ -37,6 +55,25 @@ impl PrewarmDataOptions { self } + /// Bind scalar filter values without interpolating them into SQL text. + /// + /// ``` + /// # use lancedb::table::PrewarmDataOptions; + /// # use arrow_array::{ArrayRef, Int64Array, RecordBatch}; + /// # use std::sync::Arc; + /// let values = RecordBatch::try_from_iter(vec![( + /// "minimum", Arc::new(Int64Array::from(vec![100])) as ArrayRef, + /// )]).unwrap(); + /// let options = PrewarmDataOptions::new() + /// .columns(["payload"]) + /// .filter("id >= $minimum") + /// .parameters(values); + /// ``` + pub fn parameters(mut self, parameters: arrow_array::RecordBatch) -> Self { + self.parameters = Some(parameters); + self + } + /// Set positive per-executor warming concurrency. pub fn concurrency(mut self, concurrency: u32) -> Self { self.concurrency = Some(concurrency); From 72b46439bf0a4b8708a0e37af26a66cb909dfa37 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Wed, 18 Nov 2026 15:38:02 -0800 Subject: [PATCH 166/203] ci: publish and verify the CLI shell installer (#5090) #5082 added the CLI installer, but users still needed a repository checkout to run the script. This PR publishes it at `https://downloads.lancedb.com/cli/install.sh` whenever `scripts/install.sh` changes on `main`. The installer continues to fetch binaries and checksums from GitHub Releases. This was accomplished with the following changes: - Serialize publishes and check out current `main` so retrying an old run picks up the current script. - Use GitHub OIDC to upload the installer to S3, invalidate its CloudFront path, and compare the public download byte for byte with the checked-out script. - Allow a manual run on `main` for the first publish and retries. The first run requires the `CLI_INSTALLER_AWS_ROLE_ARN` and `CLI_INSTALLER_DISTRIBUTION_ID` repository variables. ### Testing The installer failure-case tests passed. With simulated AWS and HTTP responses, the publish step accepted matching bytes, rejected a stale download, and stopped before upload when the distribution ID was missing. --- .github/workflows/publish-cli-installer.yml | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .github/workflows/publish-cli-installer.yml diff --git a/.github/workflows/publish-cli-installer.yml b/.github/workflows/publish-cli-installer.yml new file mode 100644 index 000000000..6b73e2fc1 --- /dev/null +++ b/.github/workflows/publish-cli-installer.yml @@ -0,0 +1,48 @@ +name: Publish CLI installer + +on: + push: + branches: [main] + paths: + - scripts/install.sh + workflow_dispatch: + +permissions: + contents: read + id-token: write + +jobs: + publish: + if: github.repository == 'lancedb/lancedb' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + concurrency: + group: publish-cli-installer + cancel-in-progress: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Queued jobs and retries publish the installer currently on main. + ref: refs/heads/main + persist-credentials: false + + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 + with: + aws-region: us-west-2 + role-to-assume: ${{ vars.CLI_INSTALLER_AWS_ROLE_ARN }} + + - name: Publish and verify the installer + shell: bash + env: + DISTRIBUTION_ID: ${{ vars.CLI_INSTALLER_DISTRIBUTION_ID }} + run: | + : "${DISTRIBUTION_ID:?Set CLI_INSTALLER_DISTRIBUTION_ID before publishing}" + key=cli/install.sh + aws s3api put-object --bucket lancedb-downloads --key "$key" \ + --body scripts/install.sh --content-type 'text/plain; charset=utf-8' \ + --cache-control 'public, max-age=0, must-revalidate' > /dev/null + invalidation=$(aws cloudfront create-invalidation --distribution-id "$DISTRIBUTION_ID" \ + --paths "/$key" --query Invalidation.Id --output text) + aws cloudfront wait invalidation-completed --distribution-id "$DISTRIBUTION_ID" --id "$invalidation" + curl --fail --silent --show-error --retry 3 "https://downloads.lancedb.com/$key" \ + --output "$RUNNER_TEMP/published-installer.sh" + cmp scripts/install.sh "$RUNNER_TEMP/published-installer.sh" From 2dd1a6ad25ecf32a177bd02c1aa5971c73a420fc Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Wed, 18 Nov 2026 16:02:06 -0800 Subject: [PATCH 167/203] docs: add sidebar icons for Function failures and catalog pagination (#5092) ## Summary Add a warning triangle for Function Failures and a numbered list for Catalog listing pagination in the documentation sidebar. Each page gets one `icon` field in its metadata. ## Verification Assembled the documentation locally and confirmed both icon fields on the generated sidebar pages. --- docs/web/management/function-failures.mdx | 1 + docs/web/sql/pagination.mdx | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 131204382..226d8b573 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -2,6 +2,7 @@ title: "Handle Function failures" sidebarTitle: "Function Failures" description: "Keep usable outputs, inspect row errors, retry by stable identity and isolate inputs that need attention." +icon: triangle-exclamation tag: "Early access" availability: embedded: unavailable diff --git a/docs/web/sql/pagination.mdx b/docs/web/sql/pagination.mdx index d6649ebfe..d14a364fc 100644 --- a/docs/web/sql/pagination.mdx +++ b/docs/web/sql/pagination.mdx @@ -1,6 +1,7 @@ --- title: "Catalog listing pagination" description: "Use one continuation-token syntax for SQL catalog listings." +icon: list-ol --- Catalog `SHOW` statements share one pagination suffix: From 4b428101ddb19636421421e5e3106f5e808d6a5f Mon Sep 17 00:00:00 2001 From: Sarwar Bhuiyan Date: Wed, 18 Nov 2026 19:43:12 -0500 Subject: [PATCH 168/203] feat: expose the RTREE index in the Python and TypeScript SDKs (#4942) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #4554. Supersedes #4555. This exposes Lance's R-tree index in the Python and TypeScript SDKs. Python gets a `lancedb.index.RTree` config with an optional `page_size`, accepted by `create_index(config=...)` on local, async and remote tables. TypeScript gets `Index.rtree({ pageSize })` and `RTreeOptions`. Both map to the Rust crate's existing `Index::RTree`, so remote tables send `index_type: "RTREE"`. The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` filters between a GeoArrow column and a constant geometry, in either argument order, including as a prefilter on vector search. The scalar index docs page gets an R-tree section. `geo` is now a default feature of the Python and Node packages. Without it, a local table can neither build the index nor evaluate `ST_*` filters, and because wheels and npm packages are prebuilt, an opt-in Cargo feature would not reach users. pylance already ships with `geo` on. It adds pure-Rust crates under licenses that `deny.toml` already allows. `Cargo.lock` doesn't change, and the third-party license notices are regenerated. The cost is size: the macOS arm64 release wheel grows from 69.4 MB to 71.7 MB (+2.4 MB, +3.4%). The tests pin the constant-first predicate bug that held up #4555, which lance-format/lance#10080 fixed, in queries, `delete()` and `update()`, with and without the index. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- RUST_THIRD_PARTY_LICENSES.html | 8133 ++++++++++++++++++++---- docs/src/js/classes/Index.md | 48 + docs/src/js/globals.md | 1 + docs/src/js/interfaces/RTreeOptions.md | 21 + docs/web-tests/py/test_indexing.py | 77 + docs/web/indexing/scalar-index.mdx | 142 +- docs/web/snippets/indexing.mdx | 10 + nodejs/Cargo.toml | 2 +- nodejs/RUST_THIRD_PARTY_LICENSES.html | 7683 ++++++++++++++++++---- nodejs/__test__/remote.test.ts | 81 + nodejs/__test__/table.test.ts | 98 + nodejs/lancedb/index.ts | 1 + nodejs/lancedb/indices.ts | 59 + nodejs/src/index.rs | 15 +- python/Cargo.toml | 2 +- python/RUST_THIRD_PARTY_LICENSES.html | 7610 +++++++++++++++++++--- python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/index.py | 40 + python/python/lancedb/query.py | 8 +- python/python/lancedb/remote/table.py | 2 +- python/python/lancedb/table.py | 14 +- python/python/lancedb/types.py | 1 + python/python/tests/test_index.py | 386 ++ python/python/tests/test_remote_db.py | 49 + python/src/index.rs | 19 +- 25 files changed, 21398 insertions(+), 3107 deletions(-) create mode 100644 docs/src/js/interfaces/RTreeOptions.md diff --git a/RUST_THIRD_PARTY_LICENSES.html b/RUST_THIRD_PARTY_LICENSES.html index 2016fedcd..a1c82cfcb 100644 --- a/RUST_THIRD_PARTY_LICENSES.html +++ b/RUST_THIRD_PARTY_LICENSES.html @@ -44,19 +44,19 @@

Overview of licenses:

All license text:

@@ -65,230 +65,20 @@

BSD Zero Clause License

Used by:

-
Copyright (C) 2020 by museun <museun@outlook.com>
+                
Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
 
-Permission to use, copy, modify, and/or distribute this software for any purpose
-with or without fee is hereby granted.
+Permission to use, copy, modify, and/or distribute this software for
+any purpose with or without fee is hereby granted.
 
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-THIS SOFTWARE.
-
- -
  • -

    Apache License 2.0

    -

    Used by:

    - -
    -                                 Apache License
    -                           Version 2.0, January 2004
    -                        http://www.apache.org/licenses/
    -
    -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    -
    -   1. Definitions.
    -
    -      "License" shall mean the terms and conditions for use, reproduction,
    -      and distribution as defined by Sections 1 through 9 of this document.
    -
    -      "Licensor" shall mean the copyright owner or entity authorized by
    -      the copyright owner that is granting the License.
    -
    -      "Legal Entity" shall mean the union of the acting entity and all
    -      other entities that control, are controlled by, or are under common
    -      control with that entity. For the purposes of this definition,
    -      "control" means (i) the power, direct or indirect, to cause the
    -      direction or management of such entity, whether by contract or
    -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    -      outstanding shares, or (iii) beneficial ownership of such entity.
    -
    -      "You" (or "Your") shall mean an individual or Legal Entity
    -      exercising permissions granted by this License.
    -
    -      "Source" form shall mean the preferred form for making modifications,
    -      including but not limited to software source code, documentation
    -      source, and configuration files.
    -
    -      "Object" form shall mean any form resulting from mechanical
    -      transformation or translation of a Source form, including but
    -      not limited to compiled object code, generated documentation,
    -      and conversions to other media types.
    -
    -      "Work" shall mean the work of authorship, whether in Source or
    -      Object form, made available under the License, as indicated by a
    -      copyright notice that is included in or attached to the work
    -      (an example is provided in the Appendix below).
    -
    -      "Derivative Works" shall mean any work, whether in Source or Object
    -      form, that is based on (or derived from) the Work and for which the
    -      editorial revisions, annotations, elaborations, or other modifications
    -      represent, as a whole, an original work of authorship. For the purposes
    -      of this License, Derivative Works shall not include works that remain
    -      separable from, or merely link (or bind by name) to the interfaces of,
    -      the Work and Derivative Works thereof.
    -
    -      "Contribution" shall mean any work of authorship, including
    -      the original version of the Work and any modifications or additions
    -      to that Work or Derivative Works thereof, that is intentionally
    -      submitted to Licensor for inclusion in the Work by the copyright owner
    -      or by an individual or Legal Entity authorized to submit on behalf of
    -      the copyright owner. For the purposes of this definition, "submitted"
    -      means any form of electronic, verbal, or written communication sent
    -      to the Licensor or its representatives, including but not limited to
    -      communication on electronic mailing lists, source code control systems,
    -      and issue tracking systems that are managed by, or on behalf of, the
    -      Licensor for the purpose of discussing and improving the Work, but
    -      excluding communication that is conspicuously marked or otherwise
    -      designated in writing by the copyright owner as "Not a Contribution."
    -
    -      "Contributor" shall mean Licensor and any individual or Legal Entity
    -      on behalf of whom a Contribution has been received by Licensor and
    -      subsequently incorporated within the Work.
    -
    -   2. Grant of Copyright License. Subject to the terms and conditions of
    -      this License, each Contributor hereby grants to You a perpetual,
    -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    -      copyright license to reproduce, prepare Derivative Works of,
    -      publicly display, publicly perform, sublicense, and distribute the
    -      Work and such Derivative Works in Source or Object form.
    -
    -   3. Grant of Patent License. Subject to the terms and conditions of
    -      this License, each Contributor hereby grants to You a perpetual,
    -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    -      (except as stated in this section) patent license to make, have made,
    -      use, offer to sell, sell, import, and otherwise transfer the Work,
    -      where such license applies only to those patent claims licensable
    -      by such Contributor that are necessarily infringed by their
    -      Contribution(s) alone or by combination of their Contribution(s)
    -      with the Work to which such Contribution(s) was submitted. If You
    -      institute patent litigation against any entity (including a
    -      cross-claim or counterclaim in a lawsuit) alleging that the Work
    -      or a Contribution incorporated within the Work constitutes direct
    -      or contributory patent infringement, then any patent licenses
    -      granted to You under this License for that Work shall terminate
    -      as of the date such litigation is filed.
    -
    -   4. Redistribution. You may reproduce and distribute copies of the
    -      Work or Derivative Works thereof in any medium, with or without
    -      modifications, and in Source or Object form, provided that You
    -      meet the following conditions:
    -
    -      (a) You must give any other recipients of the Work or
    -          Derivative Works a copy of this License; and
    -
    -      (b) You must cause any modified files to carry prominent notices
    -          stating that You changed the files; and
    -
    -      (c) You must retain, in the Source form of any Derivative Works
    -          that You distribute, all copyright, patent, trademark, and
    -          attribution notices from the Source form of the Work,
    -          excluding those notices that do not pertain to any part of
    -          the Derivative Works; and
    -
    -      (d) If the Work includes a "NOTICE" text file as part of its
    -          distribution, then any Derivative Works that You distribute must
    -          include a readable copy of the attribution notices contained
    -          within such NOTICE file, excluding those notices that do not
    -          pertain to any part of the Derivative Works, in at least one
    -          of the following places: within a NOTICE text file distributed
    -          as part of the Derivative Works; within the Source form or
    -          documentation, if provided along with the Derivative Works; or,
    -          within a display generated by the Derivative Works, if and
    -          wherever such third-party notices normally appear. The contents
    -          of the NOTICE file are for informational purposes only and
    -          do not modify the License. You may add Your own attribution
    -          notices within Derivative Works that You distribute, alongside
    -          or as an addendum to the NOTICE text from the Work, provided
    -          that such additional attribution notices cannot be construed
    -          as modifying the License.
    -
    -      You may add Your own copyright statement to Your modifications and
    -      may provide additional or different license terms and conditions
    -      for use, reproduction, or distribution of Your modifications, or
    -      for any such Derivative Works as a whole, provided Your use,
    -      reproduction, and distribution of the Work otherwise complies with
    -      the conditions stated in this License.
    -
    -   5. Submission of Contributions. Unless You explicitly state otherwise,
    -      any Contribution intentionally submitted for inclusion in the Work
    -      by You to the Licensor shall be under the terms and conditions of
    -      this License, without any additional terms or conditions.
    -      Notwithstanding the above, nothing herein shall supersede or modify
    -      the terms of any separate license agreement you may have executed
    -      with Licensor regarding such Contributions.
    -
    -   6. Trademarks. This License does not grant permission to use the trade
    -      names, trademarks, service marks, or product names of the Licensor,
    -      except as required for reasonable and customary use in describing the
    -      origin of the Work and reproducing the content of the NOTICE file.
    -
    -   7. Disclaimer of Warranty. Unless required by applicable law or
    -      agreed to in writing, Licensor provides the Work (and each
    -      Contributor provides its Contributions) on an "AS IS" BASIS,
    -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    -      implied, including, without limitation, any warranties or conditions
    -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    -      PARTICULAR PURPOSE. You are solely responsible for determining the
    -      appropriateness of using or redistributing the Work and assume any
    -      risks associated with Your exercise of permissions under this License.
    -
    -   8. Limitation of Liability. In no event and under no legal theory,
    -      whether in tort (including negligence), contract, or otherwise,
    -      unless required by applicable law (such as deliberate and grossly
    -      negligent acts) or agreed to in writing, shall any Contributor be
    -      liable to You for damages, including any direct, indirect, special,
    -      incidental, or consequential damages of any character arising as a
    -      result of this License or out of the use or inability to use the
    -      Work (including but not limited to damages for loss of goodwill,
    -      work stoppage, computer failure or malfunction, or any and all
    -      other commercial damages or losses), even if such Contributor
    -      has been advised of the possibility of such damages.
    -
    -   9. Accepting Warranty or Additional Liability. While redistributing
    -      the Work or Derivative Works thereof, You may choose to offer,
    -      and charge a fee for, acceptance of support, warranty, indemnity,
    -      or other liability obligations and/or rights consistent with this
    -      License. However, in accepting such obligations, You may act only
    -      on Your own behalf and on Your sole responsibility, not on behalf
    -      of any other Contributor, and only if You agree to indemnify,
    -      defend, and hold each Contributor harmless for any liability
    -      incurred by, or claims asserted against, such Contributor by reason
    -      of your accepting any such warranty or additional liability.
    -
    -   END OF TERMS AND CONDITIONS
    -
    -   APPENDIX: How to apply the Apache License to your work.
    -
    -      To apply the Apache License to your work, attach the following
    -      boilerplate notice, with the fields enclosed by brackets "[]"
    -      replaced with your own identifying information. (Don't include
    -      the brackets!)  The text should be enclosed in the appropriate
    -      comment syntax for the file format. We also recommend that a
    -      file or class name and description of purpose be included on the
    -      same "printed page" as the copyright notice for easier
    -      identification within third-party archives.
    -
    -   Copyright 2023 Jacob Pratt
    -
    -   Licensed under the Apache License, Version 2.0 (the "License");
    -   you may not use this file except in compliance with the License.
    -   You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
    +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
    +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     
  • @@ -505,7 +295,7 @@ THIS SOFTWARE.

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -715,7 +505,8 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -924,24 +715,19 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

    @@ -1152,7 +938,8 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -1364,7 +1151,15 @@ THIS SOFTWARE.
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -1592,34 +1387,316 @@ Software.
                     

    Apache License 2.0

    Used by:

    +
    +                                 Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +Licenses for support code
    +-------------------------
    +
    +Parts of the TLS test suite are under the Go license. This code is not included
    +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
    +distributing code linked against BoringSSL does not trigger this license:
    +
    +Copyright (c) 2009 The Go Authors. All rights reserved.
    +
    +Redistribution and use in source and binary forms, with or without
    +modification, are permitted provided that the following conditions are
    +met:
    +
    +   * Redistributions of source code must retain the above copyright
    +notice, this list of conditions and the following disclaimer.
    +   * Redistributions in binary form must reproduce the above
    +copyright notice, this list of conditions and the following disclaimer
    +in the documentation and/or other materials provided with the
    +distribution.
    +   * Neither the name of Google Inc. nor the names of its
    +contributors may be used to endorse or promote products derived from
    +this software without specific prior written permission.
    +
    +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    +
    +
    +BoringSSL uses the Chromium test infrastructure to run a continuous build,
    +trybots etc. The scripts which manage this, and the script for generating build
    +metadata, are under the Chromium license. Distributing code linked against
    +BoringSSL does not trigger this license.
    +
    +Copyright 2015 The Chromium Authors. All rights reserved.
    +
    +Redistribution and use in source and binary forms, with or without
    +modification, are permitted provided that the following conditions are
    +met:
    +
    +   * Redistributions of source code must retain the above copyright
    +notice, this list of conditions and the following disclaimer.
    +   * Redistributions in binary form must reproduce the above
    +copyright notice, this list of conditions and the following disclaimer
    +in the documentation and/or other materials provided with the
    +distribution.
    +   * Neither the name of Google Inc. nor the names of its
    +contributors may be used to endorse or promote products derived from
    +this software without specific prior written permission.
    +
    +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                      Apache License
    @@ -1833,6 +1910,238 @@ This project includes code from Apache Aurora.
     Copyright: 2016 The Apache Software Foundation.
     Home page: https://aurora.apache.org/
     License: http://www.apache.org/licenses/LICENSE-2.0
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
    +                                 Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +--------------------------------------------------------------------------------
    +
    +arrow-array/src/delta.rs: MIT
    +
    +This file is derived from the chronoutil crate. The full MIT license
    +text is in arrow-array/LICENSE-MIT.
     
  • @@ -1840,9 +2149,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

    Used by:

                                      Apache License
    @@ -2052,7 +2359,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                      Apache License
    @@ -2252,7 +2559,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Used by:

                                      Apache License
    @@ -2462,41 +2768,39 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -2705,7 +3009,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -2914,7 +3218,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3104,7 +3409,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
           same "printed page" as the copyright notice for easier
           identification within third-party archives.
     
    -   Copyright 2020 - 2025 Tatsuya Kawano
    +   Copyright 2019 TiKV Project Authors.
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 - 2026 Tatsuya Kawano
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 Sébastien Crozet
     
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
    @@ -3124,7 +3847,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3332,8 +4054,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3752,7 +4474,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -3961,9 +4683,21 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -4172,7 +4906,456 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +------------------------------------------------------------------------------------
    +This product bundles third-party components under other open source licenses.
    +This section summarizes those components and their licenses. See the referenced
    +license files for text of these licenses.
    +
    +
    +Creative Commons Zero v1.0 Universal
    +------------------------------------
    +
    +bindings/dotnet/.gitignore
    +
    +The above file is derived from VisualStudio.gitignore in
    +https://github.com/github/gitignore. Its license text is in
    +bindings/dotnet/LICENSE-CC0-1.0.txt.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright [yyyy] [name of copyright owner]
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +   
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                     Apache License
                                Version 2.0, January 2004
    @@ -4381,6 +5564,219 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "{}"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright Individual contributors
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                     Apache License
    @@ -4590,22 +5986,38 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                     Apache License
                                Version 2.0, January 2004
    @@ -4815,12 +6227,419 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

    +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   Copyright 2019 Yoshua Wuyts
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                     Apache License
    +                           Version 2.0, January 2004
    +                        http://www.apache.org/licenses/
    +
    +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +   1. Definitions.
    +
    +      "License" shall mean the terms and conditions for use, reproduction,
    +      and distribution as defined by Sections 1 through 9 of this document.
    +
    +      "Licensor" shall mean the copyright owner or entity authorized by
    +      the copyright owner that is granting the License.
    +
    +      "Legal Entity" shall mean the union of the acting entity and all
    +      other entities that control, are controlled by, or are under common
    +      control with that entity. For the purposes of this definition,
    +      "control" means (i) the power, direct or indirect, to cause the
    +      direction or management of such entity, whether by contract or
    +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +      outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +      "You" (or "Your") shall mean an individual or Legal Entity
    +      exercising permissions granted by this License.
    +
    +      "Source" form shall mean the preferred form for making modifications,
    +      including but not limited to software source code, documentation
    +      source, and configuration files.
    +
    +      "Object" form shall mean any form resulting from mechanical
    +      transformation or translation of a Source form, including but
    +      not limited to compiled object code, generated documentation,
    +      and conversions to other media types.
    +
    +      "Work" shall mean the work of authorship, whether in Source or
    +      Object form, made available under the License, as indicated by a
    +      copyright notice that is included in or attached to the work
    +      (an example is provided in the Appendix below).
    +
    +      "Derivative Works" shall mean any work, whether in Source or Object
    +      form, that is based on (or derived from) the Work and for which the
    +      editorial revisions, annotations, elaborations, or other modifications
    +      represent, as a whole, an original work of authorship. For the purposes
    +      of this License, Derivative Works shall not include works that remain
    +      separable from, or merely link (or bind by name) to the interfaces of,
    +      the Work and Derivative Works thereof.
    +
    +      "Contribution" shall mean any work of authorship, including
    +      the original version of the Work and any modifications or additions
    +      to that Work or Derivative Works thereof, that is intentionally
    +      submitted to Licensor for inclusion in the Work by the copyright owner
    +      or by an individual or Legal Entity authorized to submit on behalf of
    +      the copyright owner. For the purposes of this definition, "submitted"
    +      means any form of electronic, verbal, or written communication sent
    +      to the Licensor or its representatives, including but not limited to
    +      communication on electronic mailing lists, source code control systems,
    +      and issue tracking systems that are managed by, or on behalf of, the
    +      Licensor for the purpose of discussing and improving the Work, but
    +      excluding communication that is conspicuously marked or otherwise
    +      designated in writing by the copyright owner as "Not a Contribution."
    +
    +      "Contributor" shall mean Licensor and any individual or Legal Entity
    +      on behalf of whom a Contribution has been received by Licensor and
    +      subsequently incorporated within the Work.
    +
    +   2. Grant of Copyright License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      copyright license to reproduce, prepare Derivative Works of,
    +      publicly display, publicly perform, sublicense, and distribute the
    +      Work and such Derivative Works in Source or Object form.
    +
    +   3. Grant of Patent License. Subject to the terms and conditions of
    +      this License, each Contributor hereby grants to You a perpetual,
    +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +      (except as stated in this section) patent license to make, have made,
    +      use, offer to sell, sell, import, and otherwise transfer the Work,
    +      where such license applies only to those patent claims licensable
    +      by such Contributor that are necessarily infringed by their
    +      Contribution(s) alone or by combination of their Contribution(s)
    +      with the Work to which such Contribution(s) was submitted. If You
    +      institute patent litigation against any entity (including a
    +      cross-claim or counterclaim in a lawsuit) alleging that the Work
    +      or a Contribution incorporated within the Work constitutes direct
    +      or contributory patent infringement, then any patent licenses
    +      granted to You under this License for that Work shall terminate
    +      as of the date such litigation is filed.
    +
    +   4. Redistribution. You may reproduce and distribute copies of the
    +      Work or Derivative Works thereof in any medium, with or without
    +      modifications, and in Source or Object form, provided that You
    +      meet the following conditions:
    +
    +      (a) You must give any other recipients of the Work or
    +          Derivative Works a copy of this License; and
    +
    +      (b) You must cause any modified files to carry prominent notices
    +          stating that You changed the files; and
    +
    +      (c) You must retain, in the Source form of any Derivative Works
    +          that You distribute, all copyright, patent, trademark, and
    +          attribution notices from the Source form of the Work,
    +          excluding those notices that do not pertain to any part of
    +          the Derivative Works; and
    +
    +      (d) If the Work includes a "NOTICE" text file as part of its
    +          distribution, then any Derivative Works that You distribute must
    +          include a readable copy of the attribution notices contained
    +          within such NOTICE file, excluding those notices that do not
    +          pertain to any part of the Derivative Works, in at least one
    +          of the following places: within a NOTICE text file distributed
    +          as part of the Derivative Works; within the Source form or
    +          documentation, if provided along with the Derivative Works; or,
    +          within a display generated by the Derivative Works, if and
    +          wherever such third-party notices normally appear. The contents
    +          of the NOTICE file are for informational purposes only and
    +          do not modify the License. You may add Your own attribution
    +          notices within Derivative Works that You distribute, alongside
    +          or as an addendum to the NOTICE text from the Work, provided
    +          that such additional attribution notices cannot be construed
    +          as modifying the License.
    +
    +      You may add Your own copyright statement to Your modifications and
    +      may provide additional or different license terms and conditions
    +      for use, reproduction, or distribution of Your modifications, or
    +      for any such Derivative Works as a whole, provided Your use,
    +      reproduction, and distribution of the Work otherwise complies with
    +      the conditions stated in this License.
    +
    +   5. Submission of Contributions. Unless You explicitly state otherwise,
    +      any Contribution intentionally submitted for inclusion in the Work
    +      by You to the Licensor shall be under the terms and conditions of
    +      this License, without any additional terms or conditions.
    +      Notwithstanding the above, nothing herein shall supersede or modify
    +      the terms of any separate license agreement you may have executed
    +      with Licensor regarding such Contributions.
    +
    +   6. Trademarks. This License does not grant permission to use the trade
    +      names, trademarks, service marks, or product names of the Licensor,
    +      except as required for reasonable and customary use in describing the
    +      origin of the Work and reproducing the content of the NOTICE file.
    +
    +   7. Disclaimer of Warranty. Unless required by applicable law or
    +      agreed to in writing, Licensor provides the Work (and each
    +      Contributor provides its Contributions) on an "AS IS" BASIS,
    +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +      implied, including, without limitation, any warranties or conditions
    +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +      PARTICULAR PURPOSE. You are solely responsible for determining the
    +      appropriateness of using or redistributing the Work and assume any
    +      risks associated with Your exercise of permissions under this License.
    +
    +   8. Limitation of Liability. In no event and under no legal theory,
    +      whether in tort (including negligence), contract, or otherwise,
    +      unless required by applicable law (such as deliberate and grossly
    +      negligent acts) or agreed to in writing, shall any Contributor be
    +      liable to You for damages, including any direct, indirect, special,
    +      incidental, or consequential damages of any character arising as a
    +      result of this License or out of the use or inability to use the
    +      Work (including but not limited to damages for loss of goodwill,
    +      work stoppage, computer failure or malfunction, or any and all
    +      other commercial damages or losses), even if such Contributor
    +      has been advised of the possibility of such damages.
    +
    +   9. Accepting Warranty or Additional Liability. While redistributing
    +      the Work or Derivative Works thereof, You may choose to offer,
    +      and charge a fee for, acceptance of support, warranty, indemnity,
    +      or other liability obligations and/or rights consistent with this
    +      License. However, in accepting such obligations, You may act only
    +      on Your own behalf and on Your sole responsibility, not on behalf
    +      of any other Contributor, and only if You agree to indemnify,
    +      defend, and hold each Contributor harmless for any liability
    +      incurred by, or claims asserted against, such Contributor by reason
    +      of your accepting any such warranty or additional liability.
    +
    +   END OF TERMS AND CONDITIONS
    +
    +   APPENDIX: How to apply the Apache License to your work.
    +
    +      To apply the Apache License to your work, attach the following
    +      boilerplate notice, with the fields enclosed by brackets "[]"
    +      replaced with your own identifying information. (Don't include
    +      the brackets!)  The text should be enclosed in the appropriate
    +      comment syntax for the file format. We also recommend that a
    +      file or class name and description of purpose be included on the
    +      same "printed page" as the copyright notice for easier
    +      identification within third-party archives.
    +
    +   Copyright 2020 Sébastien Crozet
    +
    +   Licensed under the Apache License, Version 2.0 (the "License");
    +   you may not use this file except in compliance with the License.
    +   You may obtain a copy of the License at
    +
    +       http://www.apache.org/licenses/LICENSE-2.0
    +
    +   Unless required by applicable law or agreed to in writing, software
    +   distributed under the License is distributed on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +   See the License for the specific language governing permissions and
    +   limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                    Apache License
                                Version 2.0, January 2004
    @@ -5030,7 +6849,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                     

    Apache License 2.0

    Used by:

                                   Apache License
                                Version 2.0, January 2004
    @@ -5448,15 +7267,15 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -5666,7 +7485,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -5874,7 +7693,8 @@ limitations under the License.

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6083,8 +7903,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6293,7 +8112,6 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
    @@ -6503,7 +8321,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -6693,7 +8511,7 @@ APPENDIX: How to apply the Apache License to your work.
        same "printed page" as the copyright notice for easier
        identification within third-party archives.
     
    -Copyright 2018 The pin-utils authors
    +Copyright 2018 Brian Myers
     
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
    @@ -6712,8 +8530,8 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7120,6 +8938,215 @@ You may obtain a copy of the License at
     
        http://www.apache.org/licenses/LICENSE-2.0
     
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    + +
                                  Apache License
    +                        Version 2.0, January 2004
    +                     http://www.apache.org/licenses/
    +
    +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +1. Definitions.
    +
    +   "License" shall mean the terms and conditions for use, reproduction,
    +   and distribution as defined by Sections 1 through 9 of this document.
    +
    +   "Licensor" shall mean the copyright owner or entity authorized by
    +   the copyright owner that is granting the License.
    +
    +   "Legal Entity" shall mean the union of the acting entity and all
    +   other entities that control, are controlled by, or are under common
    +   control with that entity. For the purposes of this definition,
    +   "control" means (i) the power, direct or indirect, to cause the
    +   direction or management of such entity, whether by contract or
    +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +   outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +   "You" (or "Your") shall mean an individual or Legal Entity
    +   exercising permissions granted by this License.
    +
    +   "Source" form shall mean the preferred form for making modifications,
    +   including but not limited to software source code, documentation
    +   source, and configuration files.
    +
    +   "Object" form shall mean any form resulting from mechanical
    +   transformation or translation of a Source form, including but
    +   not limited to compiled object code, generated documentation,
    +   and conversions to other media types.
    +
    +   "Work" shall mean the work of authorship, whether in Source or
    +   Object form, made available under the License, as indicated by a
    +   copyright notice that is included in or attached to the work
    +   (an example is provided in the Appendix below).
    +
    +   "Derivative Works" shall mean any work, whether in Source or Object
    +   form, that is based on (or derived from) the Work and for which the
    +   editorial revisions, annotations, elaborations, or other modifications
    +   represent, as a whole, an original work of authorship. For the purposes
    +   of this License, Derivative Works shall not include works that remain
    +   separable from, or merely link (or bind by name) to the interfaces of,
    +   the Work and Derivative Works thereof.
    +
    +   "Contribution" shall mean any work of authorship, including
    +   the original version of the Work and any modifications or additions
    +   to that Work or Derivative Works thereof, that is intentionally
    +   submitted to Licensor for inclusion in the Work by the copyright owner
    +   or by an individual or Legal Entity authorized to submit on behalf of
    +   the copyright owner. For the purposes of this definition, "submitted"
    +   means any form of electronic, verbal, or written communication sent
    +   to the Licensor or its representatives, including but not limited to
    +   communication on electronic mailing lists, source code control systems,
    +   and issue tracking systems that are managed by, or on behalf of, the
    +   Licensor for the purpose of discussing and improving the Work, but
    +   excluding communication that is conspicuously marked or otherwise
    +   designated in writing by the copyright owner as "Not a Contribution."
    +
    +   "Contributor" shall mean Licensor and any individual or Legal Entity
    +   on behalf of whom a Contribution has been received by Licensor and
    +   subsequently incorporated within the Work.
    +
    +2. Grant of Copyright License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   copyright license to reproduce, prepare Derivative Works of,
    +   publicly display, publicly perform, sublicense, and distribute the
    +   Work and such Derivative Works in Source or Object form.
    +
    +3. Grant of Patent License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   (except as stated in this section) patent license to make, have made,
    +   use, offer to sell, sell, import, and otherwise transfer the Work,
    +   where such license applies only to those patent claims licensable
    +   by such Contributor that are necessarily infringed by their
    +   Contribution(s) alone or by combination of their Contribution(s)
    +   with the Work to which such Contribution(s) was submitted. If You
    +   institute patent litigation against any entity (including a
    +   cross-claim or counterclaim in a lawsuit) alleging that the Work
    +   or a Contribution incorporated within the Work constitutes direct
    +   or contributory patent infringement, then any patent licenses
    +   granted to You under this License for that Work shall terminate
    +   as of the date such litigation is filed.
    +
    +4. Redistribution. You may reproduce and distribute copies of the
    +   Work or Derivative Works thereof in any medium, with or without
    +   modifications, and in Source or Object form, provided that You
    +   meet the following conditions:
    +
    +   (a) You must give any other recipients of the Work or
    +       Derivative Works a copy of this License; and
    +
    +   (b) You must cause any modified files to carry prominent notices
    +       stating that You changed the files; and
    +
    +   (c) You must retain, in the Source form of any Derivative Works
    +       that You distribute, all copyright, patent, trademark, and
    +       attribution notices from the Source form of the Work,
    +       excluding those notices that do not pertain to any part of
    +       the Derivative Works; and
    +
    +   (d) If the Work includes a "NOTICE" text file as part of its
    +       distribution, then any Derivative Works that You distribute must
    +       include a readable copy of the attribution notices contained
    +       within such NOTICE file, excluding those notices that do not
    +       pertain to any part of the Derivative Works, in at least one
    +       of the following places: within a NOTICE text file distributed
    +       as part of the Derivative Works; within the Source form or
    +       documentation, if provided along with the Derivative Works; or,
    +       within a display generated by the Derivative Works, if and
    +       wherever such third-party notices normally appear. The contents
    +       of the NOTICE file are for informational purposes only and
    +       do not modify the License. You may add Your own attribution
    +       notices within Derivative Works that You distribute, alongside
    +       or as an addendum to the NOTICE text from the Work, provided
    +       that such additional attribution notices cannot be construed
    +       as modifying the License.
    +
    +   You may add Your own copyright statement to Your modifications and
    +   may provide additional or different license terms and conditions
    +   for use, reproduction, or distribution of Your modifications, or
    +   for any such Derivative Works as a whole, provided Your use,
    +   reproduction, and distribution of the Work otherwise complies with
    +   the conditions stated in this License.
    +
    +5. Submission of Contributions. Unless You explicitly state otherwise,
    +   any Contribution intentionally submitted for inclusion in the Work
    +   by You to the Licensor shall be under the terms and conditions of
    +   this License, without any additional terms or conditions.
    +   Notwithstanding the above, nothing herein shall supersede or modify
    +   the terms of any separate license agreement you may have executed
    +   with Licensor regarding such Contributions.
    +
    +6. Trademarks. This License does not grant permission to use the trade
    +   names, trademarks, service marks, or product names of the Licensor,
    +   except as required for reasonable and customary use in describing the
    +   origin of the Work and reproducing the content of the NOTICE file.
    +
    +7. Disclaimer of Warranty. Unless required by applicable law or
    +   agreed to in writing, Licensor provides the Work (and each
    +   Contributor provides its Contributions) on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +   implied, including, without limitation, any warranties or conditions
    +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +   PARTICULAR PURPOSE. You are solely responsible for determining the
    +   appropriateness of using or redistributing the Work and assume any
    +   risks associated with Your exercise of permissions under this License.
    +
    +8. Limitation of Liability. In no event and under no legal theory,
    +   whether in tort (including negligence), contract, or otherwise,
    +   unless required by applicable law (such as deliberate and grossly
    +   negligent acts) or agreed to in writing, shall any Contributor be
    +   liable to You for damages, including any direct, indirect, special,
    +   incidental, or consequential damages of any character arising as a
    +   result of this License or out of the use or inability to use the
    +   Work (including but not limited to damages for loss of goodwill,
    +   work stoppage, computer failure or malfunction, or any and all
    +   other commercial damages or losses), even if such Contributor
    +   has been advised of the possibility of such damages.
    +
    +9. Accepting Warranty or Additional Liability. While redistributing
    +   the Work or Derivative Works thereof, You may choose to offer,
    +   and charge a fee for, acceptance of support, warranty, indemnity,
    +   or other liability obligations and/or rights consistent with this
    +   License. However, in accepting such obligations, You may act only
    +   on Your own behalf and on Your sole responsibility, not on behalf
    +   of any other Contributor, and only if You agree to indemnify,
    +   defend, and hold each Contributor harmless for any liability
    +   incurred by, or claims asserted against, such Contributor by reason
    +   of your accepting any such warranty or additional liability.
    +
    +END OF TERMS AND CONDITIONS
    +
    +APPENDIX: How to apply the Apache License to your work.
    +
    +   To apply the Apache License to your work, attach the following
    +   boilerplate notice, with the fields enclosed by brackets "[]"
    +   replaced with your own identifying information. (Don't include
    +   the brackets!)  The text should be enclosed in the appropriate
    +   comment syntax for the file format. We also recommend that a
    +   file or class name and description of purpose be included on the
    +   same "printed page" as the copyright notice for easier
    +   identification within third-party archives.
    +
    +Copyright 2019 quininer kel
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +	http://www.apache.org/licenses/LICENSE-2.0
    +
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    @@ -7132,7 +9159,9 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7342,7 +9371,7 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7760,7 +9789,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -7969,7 +9998,7 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -8180,7 +10209,216 @@ limitations under the License.
                     

    Apache License 2.0

    Used by:

    +
                                  Apache License
    +                        Version 2.0, January 2004
    +                     http://www.apache.org/licenses/
    +
    +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    +
    +1. Definitions.
    +
    +   "License" shall mean the terms and conditions for use, reproduction,
    +   and distribution as defined by Sections 1 through 9 of this document.
    +
    +   "Licensor" shall mean the copyright owner or entity authorized by
    +   the copyright owner that is granting the License.
    +
    +   "Legal Entity" shall mean the union of the acting entity and all
    +   other entities that control, are controlled by, or are under common
    +   control with that entity. For the purposes of this definition,
    +   "control" means (i) the power, direct or indirect, to cause the
    +   direction or management of such entity, whether by contract or
    +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
    +   outstanding shares, or (iii) beneficial ownership of such entity.
    +
    +   "You" (or "Your") shall mean an individual or Legal Entity
    +   exercising permissions granted by this License.
    +
    +   "Source" form shall mean the preferred form for making modifications,
    +   including but not limited to software source code, documentation
    +   source, and configuration files.
    +
    +   "Object" form shall mean any form resulting from mechanical
    +   transformation or translation of a Source form, including but
    +   not limited to compiled object code, generated documentation,
    +   and conversions to other media types.
    +
    +   "Work" shall mean the work of authorship, whether in Source or
    +   Object form, made available under the License, as indicated by a
    +   copyright notice that is included in or attached to the work
    +   (an example is provided in the Appendix below).
    +
    +   "Derivative Works" shall mean any work, whether in Source or Object
    +   form, that is based on (or derived from) the Work and for which the
    +   editorial revisions, annotations, elaborations, or other modifications
    +   represent, as a whole, an original work of authorship. For the purposes
    +   of this License, Derivative Works shall not include works that remain
    +   separable from, or merely link (or bind by name) to the interfaces of,
    +   the Work and Derivative Works thereof.
    +
    +   "Contribution" shall mean any work of authorship, including
    +   the original version of the Work and any modifications or additions
    +   to that Work or Derivative Works thereof, that is intentionally
    +   submitted to Licensor for inclusion in the Work by the copyright owner
    +   or by an individual or Legal Entity authorized to submit on behalf of
    +   the copyright owner. For the purposes of this definition, "submitted"
    +   means any form of electronic, verbal, or written communication sent
    +   to the Licensor or its representatives, including but not limited to
    +   communication on electronic mailing lists, source code control systems,
    +   and issue tracking systems that are managed by, or on behalf of, the
    +   Licensor for the purpose of discussing and improving the Work, but
    +   excluding communication that is conspicuously marked or otherwise
    +   designated in writing by the copyright owner as "Not a Contribution."
    +
    +   "Contributor" shall mean Licensor and any individual or Legal Entity
    +   on behalf of whom a Contribution has been received by Licensor and
    +   subsequently incorporated within the Work.
    +
    +2. Grant of Copyright License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   copyright license to reproduce, prepare Derivative Works of,
    +   publicly display, publicly perform, sublicense, and distribute the
    +   Work and such Derivative Works in Source or Object form.
    +
    +3. Grant of Patent License. Subject to the terms and conditions of
    +   this License, each Contributor hereby grants to You a perpetual,
    +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    +   (except as stated in this section) patent license to make, have made,
    +   use, offer to sell, sell, import, and otherwise transfer the Work,
    +   where such license applies only to those patent claims licensable
    +   by such Contributor that are necessarily infringed by their
    +   Contribution(s) alone or by combination of their Contribution(s)
    +   with the Work to which such Contribution(s) was submitted. If You
    +   institute patent litigation against any entity (including a
    +   cross-claim or counterclaim in a lawsuit) alleging that the Work
    +   or a Contribution incorporated within the Work constitutes direct
    +   or contributory patent infringement, then any patent licenses
    +   granted to You under this License for that Work shall terminate
    +   as of the date such litigation is filed.
    +
    +4. Redistribution. You may reproduce and distribute copies of the
    +   Work or Derivative Works thereof in any medium, with or without
    +   modifications, and in Source or Object form, provided that You
    +   meet the following conditions:
    +
    +   (a) You must give any other recipients of the Work or
    +       Derivative Works a copy of this License; and
    +
    +   (b) You must cause any modified files to carry prominent notices
    +       stating that You changed the files; and
    +
    +   (c) You must retain, in the Source form of any Derivative Works
    +       that You distribute, all copyright, patent, trademark, and
    +       attribution notices from the Source form of the Work,
    +       excluding those notices that do not pertain to any part of
    +       the Derivative Works; and
    +
    +   (d) If the Work includes a "NOTICE" text file as part of its
    +       distribution, then any Derivative Works that You distribute must
    +       include a readable copy of the attribution notices contained
    +       within such NOTICE file, excluding those notices that do not
    +       pertain to any part of the Derivative Works, in at least one
    +       of the following places: within a NOTICE text file distributed
    +       as part of the Derivative Works; within the Source form or
    +       documentation, if provided along with the Derivative Works; or,
    +       within a display generated by the Derivative Works, if and
    +       wherever such third-party notices normally appear. The contents
    +       of the NOTICE file are for informational purposes only and
    +       do not modify the License. You may add Your own attribution
    +       notices within Derivative Works that You distribute, alongside
    +       or as an addendum to the NOTICE text from the Work, provided
    +       that such additional attribution notices cannot be construed
    +       as modifying the License.
    +
    +   You may add Your own copyright statement to Your modifications and
    +   may provide additional or different license terms and conditions
    +   for use, reproduction, or distribution of Your modifications, or
    +   for any such Derivative Works as a whole, provided Your use,
    +   reproduction, and distribution of the Work otherwise complies with
    +   the conditions stated in this License.
    +
    +5. Submission of Contributions. Unless You explicitly state otherwise,
    +   any Contribution intentionally submitted for inclusion in the Work
    +   by You to the Licensor shall be under the terms and conditions of
    +   this License, without any additional terms or conditions.
    +   Notwithstanding the above, nothing herein shall supersede or modify
    +   the terms of any separate license agreement you may have executed
    +   with Licensor regarding such Contributions.
    +
    +6. Trademarks. This License does not grant permission to use the trade
    +   names, trademarks, service marks, or product names of the Licensor,
    +   except as required for reasonable and customary use in describing the
    +   origin of the Work and reproducing the content of the NOTICE file.
    +
    +7. Disclaimer of Warranty. Unless required by applicable law or
    +   agreed to in writing, Licensor provides the Work (and each
    +   Contributor provides its Contributions) on an "AS IS" BASIS,
    +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    +   implied, including, without limitation, any warranties or conditions
    +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    +   PARTICULAR PURPOSE. You are solely responsible for determining the
    +   appropriateness of using or redistributing the Work and assume any
    +   risks associated with Your exercise of permissions under this License.
    +
    +8. Limitation of Liability. In no event and under no legal theory,
    +   whether in tort (including negligence), contract, or otherwise,
    +   unless required by applicable law (such as deliberate and grossly
    +   negligent acts) or agreed to in writing, shall any Contributor be
    +   liable to You for damages, including any direct, indirect, special,
    +   incidental, or consequential damages of any character arising as a
    +   result of this License or out of the use or inability to use the
    +   Work (including but not limited to damages for loss of goodwill,
    +   work stoppage, computer failure or malfunction, or any and all
    +   other commercial damages or losses), even if such Contributor
    +   has been advised of the possibility of such damages.
    +
    +9. Accepting Warranty or Additional Liability. While redistributing
    +   the Work or Derivative Works thereof, You may choose to offer,
    +   and charge a fee for, acceptance of support, warranty, indemnity,
    +   or other liability obligations and/or rights consistent with this
    +   License. However, in accepting such obligations, You may act only
    +   on Your own behalf and on Your sole responsibility, not on behalf
    +   of any other Contributor, and only if You agree to indemnify,
    +   defend, and hold each Contributor harmless for any liability
    +   incurred by, or claims asserted against, such Contributor by reason
    +   of your accepting any such warranty or additional liability.
    +
    +END OF TERMS AND CONDITIONS
    +
    +APPENDIX: How to apply the Apache License to your work.
    +
    +   To apply the Apache License to your work, attach the following
    +   boilerplate notice, with the fields enclosed by brackets "[]"
    +   replaced with your own identifying information. (Don't include
    +   the brackets!)  The text should be enclosed in the appropriate
    +   comment syntax for the file format. We also recommend that a
    +   file or class name and description of purpose be included on the
    +   same "printed page" as the copyright notice for easier
    +   identification within third-party archives.
    +
    +Copyright 2024 Liam Gray <gmail@liamg.me>
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +	http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +
    +
  • +
  • +

    Apache License 2.0

    +

    Used by:

    +
                                  Apache License
                             Version 2.0, January 2004
    @@ -8390,7 +10628,8 @@ limitations under the License.
                     

    Used by:

                                  Apache License
                             Version 2.0, January 2004
    @@ -8598,156 +10837,175 @@ limitations under the License.

    Apache License 2.0

    Used by:

      +
    • addr2line 0.25.1
    • ahash 0.8.12
    • -
    • arc-swap 1.7.1
    • -
    • arrayvec 0.7.6
    • +
    • arc-swap 1.9.3
    • +
    • arrayvec 0.7.8
    • async-channel 2.5.0
    • -
    • async-compression 0.4.19
    • -
    • async-lock 3.4.1
    • +
    • async-compression 0.4.42
    • +
    • async-lock 3.4.2
    • atomic-waker 1.1.2
    • autocfg 1.5.0
    • -
    • base64 0.21.7
    • +
    • backtrace 0.3.76
    • base64 0.22.1
    • -
    • bitflags 2.9.4
    • -
    • bumpalo 3.19.0
    • +
    • base64 0.23.1
    • +
    • bitflags 1.3.2
    • +
    • bitflags 2.11.1
    • +
    • bstr 1.12.1
    • +
    • bumpalo 3.20.2
    • bytes-utils 0.1.4
    • -
    • cc 1.2.40
    • -
    • cexpr 0.6.0
    • -
    • cfg-if 1.0.3
    • -
    • cmake 0.1.54
    • +
    • cast 0.3.0
    • +
    • cc 1.2.62
    • +
    • cfg-if 0.1.10
    • +
    • cfg-if 1.0.4
    • +
    • cmake 0.1.58
    • +
    • compression-codecs 0.4.38
    • +
    • compression-core 0.4.32
    • concurrent-queue 2.5.0
    • const-random-macro 0.1.16
    • const-random 0.1.18
    • core-foundation-sys 0.8.7
    • core-foundation 0.10.1
    • core-foundation 0.9.4
    • +
    • cpp_demangle 0.4.5
    • +
    • criterion-plot 0.8.2
    • +
    • criterion 0.8.2
    • crossbeam-channel 0.5.15
    • crossbeam-deque 0.8.6
    • -
    • crossbeam-epoch 0.9.18
    • +
    • crossbeam-epoch 0.9.20
    • crossbeam-queue 0.3.12
    • +
    • crossbeam-skiplist 0.1.3
    • crossbeam-utils 0.8.21
    • +
    • debugid 0.8.0
    • displaydoc 0.2.5
    • either 1.15.0
    • +
    • encoding_rs_io 0.1.7
    • equivalent 1.0.2
    • errno 0.3.14
    • event-listener-strategy 0.5.4
    • -
    • event-listener 5.4.1
    • -
    • fastrand 2.3.0
    • -
    • find-msvc-tools 0.1.3
    • +
    • event-listener 5.4.2
    • +
    • fastrand 2.4.1
    • +
    • find-msvc-tools 0.1.9
    • +
    • findshlibs 0.10.2
    • fixedbitset 0.5.7
    • +
    • flate2 1.1.9
    • fnv 1.0.7
    • form_urlencoded 1.2.2
    • -
    • fs4 0.8.4
    • +
    • foyer-intrusive-collections 0.10.0-dev
    • +
    • fs4 0.13.1
    • futures-timer 3.0.3
    • -
    • geohash 0.13.1
    • +
    • geohash 0.13.2
    • +
    • gimli 0.32.3
    • glob 0.3.3
    • -
    • group 0.12.1
    • +
    • group 0.14.0
    • hash32 0.3.1
    • hashbrown 0.14.5
    • hashbrown 0.15.5
    • -
    • hashbrown 0.16.0
    • +
    • hashbrown 0.16.1
    • +
    • hashbrown 0.17.1
    • heapless 0.8.0
    • heck 0.5.0
    • hermit-abi 0.5.2
    • httparse 1.10.1
    • -
    • hyper-rustls 0.24.2
    • -
    • hyper-rustls 0.27.7
    • +
    • hyper-rustls 0.27.9
    • +
    • hyper-timeout 0.5.2
    • +
    • hyper-tls 0.6.0
    • idna 1.1.0
    • -
    • idna_adapter 1.2.1
    • -
    • indexmap 2.12.0
    • -
    • itertools 0.11.0
    • -
    • itertools 0.12.1
    • +
    • idna_adapter 1.2.2
    • +
    • indexmap 2.14.0
    • itertools 0.13.0
    • itertools 0.14.0
    • +
    • itertools 0.15.0
    • jobserver 0.1.34
    • -
    • js-sys 0.3.81
    • +
    • js-sys 0.3.107
    • lazy_static 1.5.0
    • -
    • lazycell 1.3.0
    • -
    • linux-raw-sys 0.11.0
    • +
    • linux-raw-sys 0.12.1
    • linux-raw-sys 0.4.15
    • lock_api 0.4.14
    • -
    • log 0.4.28
    • +
    • log 0.4.34
    • lzma-sys 0.1.20
    • matrixmultiply 0.3.10
    • mime 0.3.17
    • -
    • multimap 0.10.1
    • ndarray 0.16.1
    • -
    • num-bigint-dig 0.8.4
    • +
    • num-bigint-dig 0.8.6
    • num-bigint 0.4.6
    • +
    • num-bigint 0.5.1
    • num-complex 0.4.6
    • num-integer 0.1.46
    • num-iter 0.1.45
    • +
    • num-rational 0.4.2
    • num-traits 0.2.19
    • num_cpus 1.17.0
    • -
    • once_cell 1.21.3
    • -
    • openssl-probe 0.1.6
    • +
    • oauth2 5.0.0
    • +
    • object 0.37.3
    • +
    • once_cell 1.21.4
    • +
    • openssl-probe 0.2.1
    • parking 2.2.1
    • parking_lot 0.12.5
    • parking_lot_core 0.9.12
    • percent-encoding 2.3.2
    • petgraph 0.8.3
    • -
    • pkg-config 0.3.32
    • -
    • prost-build 0.14.3
    • -
    • prost-derive 0.14.3
    • +
    • pkg-config 0.3.33
    • +
    • prost-derive 0.14.4
    • prost-types 0.14.3
    • -
    • prost 0.14.3
    • +
    • prost 0.14.4
    • +
    • rand_xoshiro 0.6.0
    • rawpointer 0.2.1
    • rayon-core 1.13.0
    • -
    • rayon 1.11.0
    • -
    • regex-automata 0.4.13
    • -
    • regex-lite 0.1.7
    • -
    • regex-syntax 0.8.6
    • -
    • regex 1.12.2
    • +
    • rayon 1.12.0
    • +
    • regex-automata 0.4.16
    • +
    • regex-lite 0.1.9
    • +
    • regex-syntax 0.8.11
    • +
    • regex 1.13.1
    • ring 0.17.14
    • +
    • roaring 0.11.5
    • robust 1.2.0
    • -
    • rustc-hash 1.1.0
    • +
    • rustc-demangle 0.1.27
    • rustc_version 0.4.1
    • rustix 0.38.44
    • -
    • rustix 1.1.2
    • -
    • rustls-native-certs 0.6.3
    • -
    • rustls-native-certs 0.8.1
    • -
    • rustls-pemfile 1.0.4
    • -
    • rustls-pemfile 2.2.0
    • -
    • rustls 0.21.12
    • -
    • rustls 0.23.31
    • +
    • rustix 1.1.4
    • +
    • rustls-native-certs 0.8.3
    • +
    • rustls 0.23.46
    • scoped-tls 1.0.1
    • scopeguard 1.2.0
    • -
    • sct 0.7.1
    • -
    • security-framework-sys 2.15.0
    • -
    • security-framework 2.11.1
    • -
    • security-framework 3.5.1
    • -
    • serde_with 3.15.0
    • -
    • serde_with_macros 3.15.0
    • -
    • shellexpand 3.1.1
    • -
    • signal-hook-registry 1.4.6
    • -
    • smallvec 1.15.1
    • -
    • socket2 0.5.10
    • -
    • socket2 0.6.0
    • -
    • sqlparser 0.59.0
    • -
    • sqlparser_derive 0.3.0
    • -
    • stable_deref_trait 1.2.0
    • -
    • syn 1.0.109
    • +
    • security-framework-sys 2.17.0
    • +
    • security-framework 3.7.0
    • +
    • serde_with 3.24.0
    • +
    • serde_with_macros 3.24.0
    • +
    • shellexpand 3.1.2
    • +
    • signal-hook-registry 1.4.8
    • +
    • simd_cesu8 1.1.1
    • +
    • smallvec 1.16.5
    • +
    • socket2 0.6.3
    • +
    • sqlparser 0.62.0
    • +
    • sqlparser_derive 0.5.0
    • +
    • stable_deref_trait 1.2.1
    • +
    • str_stack 0.1.1
    • +
    • symlink 0.1.0
    • system-configuration-sys 0.6.0
    • -
    • system-configuration 0.6.1
    • -
    • tempfile 3.23.0
    • +
    • system-configuration 0.7.0
    • +
    • tempfile 3.27.0
    • thread-tree 0.3.3
    • -
    • thread_local 1.1.9
    • -
    • unicase 2.8.1
    • -
    • unicode-segmentation 1.12.0
    • -
    • unicode-width 0.2.2
    • -
    • url 2.5.7
    • -
    • uuid 1.18.1
    • +
    • thread_local 1.1.10
    • +
    • tinytemplate 1.2.1
    • +
    • unicase 2.9.0
    • +
    • unicode-normalization 0.1.25
    • +
    • unicode-segmentation 1.13.2
    • +
    • unicode-width 0.1.14
    • +
    • unicode-width 0.2.3
    • +
    • url 2.5.8
    • +
    • uuid 1.29.0
    • version_check 0.9.5
    • wasi 0.11.1+wasi-snapshot-preview1
    • wasi 0.14.7+wasi-0.2.4
    • -
    • wasm-bindgen-backend 0.2.104
    • -
    • wasm-bindgen-futures 0.4.54
    • -
    • wasm-bindgen-macro-support 0.2.104
    • -
    • wasm-bindgen-macro 0.2.104
    • -
    • wasm-bindgen-shared 0.2.104
    • -
    • wasm-bindgen 0.2.104
    • -
    • web-sys 0.3.81
    • -
    • wit-bindgen 0.46.0
    • +
    • wasip2 1.0.3+wasi-0.2.9
    • +
    • wasm-bindgen-futures 0.4.80
    • +
    • wasm-bindgen-macro-support 0.2.130
    • +
    • wasm-bindgen-macro 0.2.130
    • +
    • wasm-bindgen-shared 0.2.130
    • +
    • wasm-bindgen 0.2.130
    • +
    • web-sys 0.3.107
    • +
    • wit-bindgen 0.57.1
    • wkb 0.9.2
    • wkt 0.14.0
    • xmlparser 0.13.6
    • @@ -8959,7 +11217,7 @@ limitations under the License.

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9169,14 +11427,14 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9386,41 +11644,56 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -9629,10 +11902,209 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +Copyright (c) 2015-2022 Amod Malviya
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      + +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                    Apache License
                               Version 2.0, January 2004
      @@ -9827,11 +12299,13 @@ APPENDIX: How to apply the Apache License to your work.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -10040,8 +12514,8 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -10250,7 +12724,427 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright [yyyy] [name of copyright owner]
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright [yyyy] [name of copyright owner]
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
         Copyright (c) 2017-present PyO3 Project and Contributors.  https://github.com/PyO3
       
      @@ -10447,7 +13341,9 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
                                  Version 2.0, January 2004
      @@ -10656,7 +13552,9 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
       Version 2.0, January 2004
      @@ -10935,137 +13833,190 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Apache License
       Version 2.0, January 2004
      @@ -11382,10 +14333,10 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      Rust-chrono is dual-licensed under The MIT License [1] and
      -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
      +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
       contributors.
       
       Nota Bene: This is same as the Rust Project's own license.
      @@ -11624,6 +14575,40 @@ See the License for the specific language governing permissions and
       limitations under the License.
       ~~~~
       
      +
      +
    • +
    • +

      BSD 2-Clause "Simplified" License

      +

      Used by:

      + +
      Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +1. Redistributions of source code must retain the above copyright
      +   notice, this list of conditions and the following disclaimer.
      +
      +2. Redistributions in binary form must reproduce the above copyright
      +   notice, this list of conditions and the following disclaimer in the
      +   documentation and/or other materials provided with the
      +   distribution.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    • @@ -11658,6 +14643,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
    • + +
    • +

      BSD 2-Clause "Simplified" License

      +

      Used by:

      + +
      Copyright (c) 2017-2020
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are met:
      +
      +1. Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +2. Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
      +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      + +
      // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
      +//
      +// Redistribution and use in source and binary forms, with or without
      +// modification, are permitted provided that the following conditions are met:
      +//
      +// 1. Redistributions of source code must retain the above copyright notice, this
      +//    list of conditions and the following disclaimer.
      +//
      +// 2. Redistributions in binary form must reproduce the above copyright notice,
      +//    this list of conditions and the following disclaimer in the documentation
      +//    and/or other materials provided with the distribution.
      +//
      +// 3. Neither the name of the copyright holder nor the names of its
      +//    contributors may be used to endorse or promote products derived from
      +//    this software without specific prior written permission.
      +//
      +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
      +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
      +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
      +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
      +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
      +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +/// The PUA code points special-cased in the GB18030 encoder.
      +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
      +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
      +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
      +];
      +
      +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
      +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
      +    [0xA6, 0xD9],
      +    [0xA6, 0xDA],
      +    [0xA6, 0xDB],
      +    [0xA6, 0xDC],
      +    [0xA6, 0xDD],
      +    [0xA6, 0xDE],
      +    [0xA6, 0xDF],
      +    [0xA6, 0xEC],
      +    [0xA6, 0xED],
      +    [0xA6, 0xF3],
      +    [0xFE, 0x59],
      +    [0xFE, 0x61],
      +    [0xFE, 0x66],
      +    [0xFE, 0x67],
      +    [0xFE, 0x6D],
      +    [0xFE, 0x7E],
      +    [0xFE, 0x90],
      +    [0xFE, 0xA0],
      +];
       
    • @@ -11665,6 +14743,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

      Used by:

      BSD 3-Clause License
       
      @@ -11701,26 +14780,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      BSD 3-Clause License
       
      -Copyright (c) 2013, Jyun-Yan You
      -All rights reserved.
      +Copyright (c) 2026, Alexandre Bury
       
       Redistribution and use in source and binary forms, with or without
       modification, are permitted provided that the following conditions are met:
       
      -* Redistributions of source code must retain the above copyright notice, this
      -  list of conditions and the following disclaimer.
      +1. Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
       
      -* Redistributions in binary form must reproduce the above copyright notice,
      -  this list of conditions and the following disclaimer in the documentation
      -  and/or other materials provided with the distribution.
      +2. Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
       
      -* Neither the name of the copyright holder nor the names of its
      -  contributors may be used to endorse or promote products derived from
      -  this software without specific prior written permission.
      +3. Neither the name of the copyright holder nor the names of its
      +   contributors may be used to endorse or promote products derived from
      +   this software without specific prior written permission.
       
       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
       AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      @@ -11738,10 +14818,50 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      +
      BSD License
      +
      +For Zstandard software
      +
      +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without modification,
      +are permitted provided that the following conditions are met:
      +
      + * Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +
      + * Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      + * Neither the name Facebook, nor Meta, nor the names of its contributors may
      +   be used to endorse or promote products derived from this software without
      +   specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      +
      Copyright (c) 2001, Dr Martin Porter
       Copyright (c) 2004,2005, Richard Boulton
      +Copyright (c) 2013, Yoshiki Shibukawa
      +Copyright (c) 2006-2025, Olly Betts
       All rights reserved.
       
       Redistribution and use in source and binary forms, with or without
      @@ -11766,16 +14886,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
       LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
       ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
    • BSD 3-Clause "New" or "Revised" License

      Used by:

      Copyright (c) 2016 Dropbox, Inc.
       All rights reserved.
      @@ -11832,8 +14952,53 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                       

      BSD 3-Clause "New" or "Revised" License

      Used by:

      +
      Copyright (c) 2026, frostem contributors
      +Copyright (c) 2001, Dr Martin Porter
      +Copyright (c) 2004,2005, Richard Boulton
      +Copyright (c) 2013, Yoshiki Shibukawa
      +Copyright (c) 2006-2025, Olly Betts
      +All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions
      +are met:
      +
      +  1. Redistributions of source code must retain the above copyright notice,
      +     this list of conditions and the following disclaimer.
      +  2. Redistributions in binary form must reproduce the above copyright notice,
      +     this list of conditions and the following disclaimer in the documentation
      +     and/or other materials provided with the distribution.
      +  3. Neither the name of the Snowball project nor the names of its contributors
      +     may be used to endorse or promote products derived from this software
      +     without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      +
      Copyright (c) <year> <owner>. 
       
      @@ -11880,13 +15045,54 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
       CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
       OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
       OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      BSD 3-Clause "New" or "Revised" License

      +

      Used by:

      + +
      The auto-generated bindings are under the 3-clause BSD license:
      +
      +BSD License
      +
      +For Zstandard software
      +
      +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without modification,
      +are permitted provided that the following conditions are met:
      +
      + * Redistributions of source code must retain the above copyright notice, this
      +   list of conditions and the following disclaimer.
      +
      + * Redistributions in binary form must reproduce the above copyright notice,
      +   this list of conditions and the following disclaimer in the documentation
      +   and/or other materials provided with the distribution.
      +
      + * Neither the name Facebook, nor Meta, nor the names of its contributors may
      +   be used to endorse or promote products derived from this software without
      +   specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
      +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
      +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    • Boost Software License 1.0

      Used by:

      Boost Software License - Version 1.0 - August 17th, 2003
       
      @@ -11911,6 +15117,21 @@ SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
       FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
       ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
       DEALINGS IN THE SOFTWARE.
      +
      +
    • +
    • +

      Boost Software License 1.0

      +

      Used by:

      + +
      Boost Software License - Version 1.0 - August 17th, 2003
      +
      +Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following:
      +
      +The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor.
      +
      +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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       
    • @@ -12040,13 +15261,405 @@ express Statement of Purpose. d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. +
    • + +
    • +

      Common Development and Distribution License 1.0

      +

      Used by:

      + +
      Unless otherwise noted, all files in this distribution are released
      +under the Common Development and Distribution License (CDDL).
      +Exceptions are noted within the associated source files.
      +
      +--------------------------------------------------------------------
      +
      +
      +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
      +
      +1. Definitions.
      +
      +    1.1. "Contributor" means each individual or entity that creates
      +         or contributes to the creation of Modifications.
      +
      +    1.2. "Contributor Version" means the combination of the Original
      +         Software, prior Modifications used by a Contributor (if any),
      +         and the Modifications made by that particular Contributor.
      +
      +    1.3. "Covered Software" means (a) the Original Software, or (b)
      +         Modifications, or (c) the combination of files containing
      +         Original Software with files containing Modifications, in
      +         each case including portions thereof.
      +
      +    1.4. "Executable" means the Covered Software in any form other
      +         than Source Code.
      +
      +    1.5. "Initial Developer" means the individual or entity that first
      +         makes Original Software available under this License.
      +
      +    1.6. "Larger Work" means a work which combines Covered Software or
      +         portions thereof with code not governed by the terms of this
      +         License.
      +
      +    1.7. "License" means this document.
      +
      +    1.8. "Licensable" means having the right to grant, to the maximum
      +         extent possible, whether at the time of the initial grant or
      +         subsequently acquired, any and all of the rights conveyed
      +         herein.
      +
      +    1.9. "Modifications" means the Source Code and Executable form of
      +         any of the following:
      +
      +        A. Any file that results from an addition to, deletion from or
      +           modification of the contents of a file containing Original
      +           Software or previous Modifications;
      +
      +        B. Any new file that contains any part of the Original
      +           Software or previous Modifications; or
      +
      +        C. Any new file that is contributed or otherwise made
      +           available under the terms of this License.
      +
      +    1.10. "Original Software" means the Source Code and Executable
      +          form of computer software code that is originally released
      +          under this License.
      +
      +    1.11. "Patent Claims" means any patent claim(s), now owned or
      +          hereafter acquired, including without limitation, method,
      +          process, and apparatus claims, in any patent Licensable by
      +          grantor.
      +
      +    1.12. "Source Code" means (a) the common form of computer software
      +          code in which modifications are made and (b) associated
      +          documentation included in or with such code.
      +
      +    1.13. "You" (or "Your") means an individual or a legal entity
      +          exercising rights under, and complying with all of the terms
      +          of, this License.  For legal entities, "You" includes any
      +          entity which controls, is controlled by, or is under common
      +          control with You.  For purposes of this definition,
      +          "control" means (a) the power, direct or indirect, to cause
      +          the direction or management of such entity, whether by
      +          contract or otherwise, or (b) ownership of more than fifty
      +          percent (50%) of the outstanding shares or beneficial
      +          ownership of such entity.
      +
      +2. License Grants.
      +
      +    2.1. The Initial Developer Grant.
      +
      +    Conditioned upon Your compliance with Section 3.1 below and
      +    subject to third party intellectual property claims, the Initial
      +    Developer hereby grants You a world-wide, royalty-free,
      +    non-exclusive license:
      +
      +        (a) under intellectual property rights (other than patent or
      +            trademark) Licensable by Initial Developer, to use,
      +            reproduce, modify, display, perform, sublicense and
      +            distribute the Original Software (or portions thereof),
      +            with or without Modifications, and/or as part of a Larger
      +            Work; and
      +
      +        (b) under Patent Claims infringed by the making, using or
      +            selling of Original Software, to make, have made, use,
      +            practice, sell, and offer for sale, and/or otherwise
      +            dispose of the Original Software (or portions thereof).
      +
      +        (c) The licenses granted in Sections 2.1(a) and (b) are
      +            effective on the date Initial Developer first distributes
      +            or otherwise makes the Original Software available to a
      +            third party under the terms of this License.
      +
      +        (d) Notwithstanding Section 2.1(b) above, no patent license is
      +            granted: (1) for code that You delete from the Original
      +            Software, or (2) for infringements caused by: (i) the
      +            modification of the Original Software, or (ii) the
      +            combination of the Original Software with other software
      +            or devices.
      +
      +    2.2. Contributor Grant.
      +
      +    Conditioned upon Your compliance with Section 3.1 below and
      +    subject to third party intellectual property claims, each
      +    Contributor hereby grants You a world-wide, royalty-free,
      +    non-exclusive license:
      +
      +        (a) under intellectual property rights (other than patent or
      +            trademark) Licensable by Contributor to use, reproduce,
      +            modify, display, perform, sublicense and distribute the
      +            Modifications created by such Contributor (or portions
      +            thereof), either on an unmodified basis, with other
      +            Modifications, as Covered Software and/or as part of a
      +            Larger Work; and
      +
      +        (b) under Patent Claims infringed by the making, using, or
      +            selling of Modifications made by that Contributor either
      +            alone and/or in combination with its Contributor Version
      +            (or portions of such combination), to make, use, sell,
      +            offer for sale, have made, and/or otherwise dispose of:
      +            (1) Modifications made by that Contributor (or portions
      +            thereof); and (2) the combination of Modifications made by
      +            that Contributor with its Contributor Version (or portions
      +            of such combination).
      +
      +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
      +            effective on the date Contributor first distributes or
      +            otherwise makes the Modifications available to a third
      +            party.
      +
      +        (d) Notwithstanding Section 2.2(b) above, no patent license is
      +            granted: (1) for any code that Contributor has deleted
      +            from the Contributor Version; (2) for infringements caused
      +            by: (i) third party modifications of Contributor Version,
      +            or (ii) the combination of Modifications made by that
      +            Contributor with other software (except as part of the
      +            Contributor Version) or other devices; or (3) under Patent
      +            Claims infringed by Covered Software in the absence of
      +            Modifications made by that Contributor.
      +
      +3. Distribution Obligations.
      +
      +    3.1. Availability of Source Code.
      +
      +    Any Covered Software that You distribute or otherwise make
      +    available in Executable form must also be made available in Source
      +    Code form and that Source Code form must be distributed only under
      +    the terms of this License.  You must include a copy of this
      +    License with every copy of the Source Code form of the Covered
      +    Software You distribute or otherwise make available.  You must
      +    inform recipients of any such Covered Software in Executable form
      +    as to how they can obtain such Covered Software in Source Code
      +    form in a reasonable manner on or through a medium customarily
      +    used for software exchange.
      +
      +    3.2. Modifications.
      +
      +    The Modifications that You create or to which You contribute are
      +    governed by the terms of this License.  You represent that You
      +    believe Your Modifications are Your original creation(s) and/or
      +    You have sufficient rights to grant the rights conveyed by this
      +    License.
      +
      +    3.3. Required Notices.
      +
      +    You must include a notice in each of Your Modifications that
      +    identifies You as the Contributor of the Modification.  You may
      +    not remove or alter any copyright, patent or trademark notices
      +    contained within the Covered Software, or any notices of licensing
      +    or any descriptive text giving attribution to any Contributor or
      +    the Initial Developer.
      +
      +    3.4. Application of Additional Terms.
      +
      +    You may not offer or impose any terms on any Covered Software in
      +    Source Code form that alters or restricts the applicable version
      +    of this License or the recipients' rights hereunder.  You may
      +    choose to offer, and to charge a fee for, warranty, support,
      +    indemnity or liability obligations to one or more recipients of
      +    Covered Software.  However, you may do so only on Your own behalf,
      +    and not on behalf of the Initial Developer or any Contributor.
      +    You must make it absolutely clear that any such warranty, support,
      +    indemnity or liability obligation is offered by You alone, and You
      +    hereby agree to indemnify the Initial Developer and every
      +    Contributor for any liability incurred by the Initial Developer or
      +    such Contributor as a result of warranty, support, indemnity or
      +    liability terms You offer.
      +
      +    3.5. Distribution of Executable Versions.
      +
      +    You may distribute the Executable form of the Covered Software
      +    under the terms of this License or under the terms of a license of
      +    Your choice, which may contain terms different from this License,
      +    provided that You are in compliance with the terms of this License
      +    and that the license for the Executable form does not attempt to
      +    limit or alter the recipient's rights in the Source Code form from
      +    the rights set forth in this License.  If You distribute the
      +    Covered Software in Executable form under a different license, You
      +    must make it absolutely clear that any terms which differ from
      +    this License are offered by You alone, not by the Initial
      +    Developer or Contributor.  You hereby agree to indemnify the
      +    Initial Developer and every Contributor for any liability incurred
      +    by the Initial Developer or such Contributor as a result of any
      +    such terms You offer.
      +
      +    3.6. Larger Works.
      +
      +    You may create a Larger Work by combining Covered Software with
      +    other code not governed by the terms of this License and
      +    distribute the Larger Work as a single product.  In such a case,
      +    You must make sure the requirements of this License are fulfilled
      +    for the Covered Software.
      +
      +4. Versions of the License.
      +
      +    4.1. New Versions.
      +
      +    Sun Microsystems, Inc. is the initial license steward and may
      +    publish revised and/or new versions of this License from time to
      +    time.  Each version will be given a distinguishing version number.
      +    Except as provided in Section 4.3, no one other than the license
      +    steward has the right to modify this License.
      +
      +    4.2. Effect of New Versions.
      +
      +    You may always continue to use, distribute or otherwise make the
      +    Covered Software available under the terms of the version of the
      +    License under which You originally received the Covered Software.
      +    If the Initial Developer includes a notice in the Original
      +    Software prohibiting it from being distributed or otherwise made
      +    available under any subsequent version of the License, You must
      +    distribute and make the Covered Software available under the terms
      +    of the version of the License under which You originally received
      +    the Covered Software.  Otherwise, You may also choose to use,
      +    distribute or otherwise make the Covered Software available under
      +    the terms of any subsequent version of the License published by
      +    the license steward.
      +
      +    4.3. Modified Versions.
      +
      +    When You are an Initial Developer and You want to create a new
      +    license for Your Original Software, You may create and use a
      +    modified version of this License if You: (a) rename the license
      +    and remove any references to the name of the license steward
      +    (except to note that the license differs from this License); and
      +    (b) otherwise make it clear that the license contains terms which
      +    differ from this License.
      +
      +5. DISCLAIMER OF WARRANTY.
      +
      +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
      +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
      +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
      +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
      +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
      +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
      +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
      +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
      +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
      +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
      +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
      +    DISCLAIMER.
      +
      +6. TERMINATION.
      +
      +    6.1. This License and the rights granted hereunder will terminate
      +    automatically if You fail to comply with terms herein and fail to
      +    cure such breach within 30 days of becoming aware of the breach.
      +    Provisions which, by their nature, must remain in effect beyond
      +    the termination of this License shall survive.
      +
      +    6.2. If You assert a patent infringement claim (excluding
      +    declaratory judgment actions) against Initial Developer or a
      +    Contributor (the Initial Developer or Contributor against whom You
      +    assert such claim is referred to as "Participant") alleging that
      +    the Participant Software (meaning the Contributor Version where
      +    the Participant is a Contributor or the Original Software where
      +    the Participant is the Initial Developer) directly or indirectly
      +    infringes any patent, then any and all rights granted directly or
      +    indirectly to You by such Participant, the Initial Developer (if
      +    the Initial Developer is not the Participant) and all Contributors
      +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
      +    notice from Participant terminate prospectively and automatically
      +    at the expiration of such 60 day notice period, unless if within
      +    such 60 day period You withdraw Your claim with respect to the
      +    Participant Software against such Participant either unilaterally
      +    or pursuant to a written agreement with Participant.
      +
      +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
      +    all end user licenses that have been validly granted by You or any
      +    distributor hereunder prior to termination (excluding licenses
      +    granted to You by any distributor) shall survive termination.
      +
      +7. LIMITATION OF LIABILITY.
      +
      +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
      +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
      +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
      +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
      +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
      +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
      +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
      +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
      +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
      +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
      +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
      +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
      +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
      +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
      +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
      +    APPLY TO YOU.
      +
      +8. U.S. GOVERNMENT END USERS.
      +
      +    The Covered Software is a "commercial item," as that term is
      +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
      +    computer software" (as that term is defined at 48
      +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
      +    documentation" as such terms are used in 48 C.F.R. 12.212
      +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
      +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
      +    U.S. Government End Users acquire Covered Software with only those
      +    rights set forth herein.  This U.S. Government Rights clause is in
      +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
      +    provision that addresses Government rights in computer software
      +    under this License.
      +
      +9. MISCELLANEOUS.
      +
      +    This License represents the complete agreement concerning subject
      +    matter hereof.  If any provision of this License is held to be
      +    unenforceable, such provision shall be reformed only to the extent
      +    necessary to make it enforceable.  This License shall be governed
      +    by the law of the jurisdiction specified in a notice contained
      +    within the Original Software (except to the extent applicable law,
      +    if any, provides otherwise), excluding such jurisdiction's
      +    conflict-of-law provisions.  Any litigation relating to this
      +    License shall be subject to the jurisdiction of the courts located
      +    in the jurisdiction and venue specified in a notice contained
      +    within the Original Software, with the losing party responsible
      +    for costs, including, without limitation, court costs and
      +    reasonable attorneys' fees and expenses.  The application of the
      +    United Nations Convention on Contracts for the International Sale
      +    of Goods is expressly excluded.  Any law or regulation which
      +    provides that the language of a contract shall be construed
      +    against the drafter shall not apply to this License.  You agree
      +    that You alone are responsible for compliance with the United
      +    States export administration regulations (and the export control
      +    laws and regulation of any other countries) when You use,
      +    distribute or otherwise make available any Covered Software.
      +
      +10. RESPONSIBILITY FOR CLAIMS.
      +
      +    As between Initial Developer and the Contributors, each party is
      +    responsible for claims and damages arising, directly or
      +    indirectly, out of its utilization of rights under this License
      +    and You agree to work with Initial Developer and Contributors to
      +    distribute such responsibility on an equitable basis.  Nothing
      +    herein is intended or shall be deemed to constitute any admission
      +    of liability.
      +
      +--------------------------------------------------------------------
      +
      +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
      +DISTRIBUTION LICENSE (CDDL)
      +
      +For Covered Software in this distribution, this License shall
      +be governed by the laws of the State of California (excluding
      +conflict-of-law provisions).
      +
      +Any litigation relating to this License shall be subject to the
      +jurisdiction of the Federal Courts of the Northern District of
      +California and the state courts of the State of California, with
      +venue lying in Santa Clara County, California.
       
    • Community Data License Agreement Permissive 2.0

      Used by:

      # Community Data License Agreement - Permissive - Version 2.0
       
      @@ -12115,9 +15728,9 @@ insights.
                       

      ISC License

      Used by:

      -
      /* Copyright (c) 2018, Google Inc.
      +                
      /* Copyright (c) 2014, Intel Corporation.
        *
        * Permission to use, copy, modify, and/or distribute this software for any
        * purpose with or without fee is hereby granted, provided that the above
      @@ -12131,15 +15744,65 @@ insights.
        * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
       
      -#include <openssl/crypto.h>
      +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
      +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
       
      -#include <gtest/gtest.h>
      +#include "../../limbs/limbs.h"
      +
      +#define P384_LIMBS (384u / LIMB_BITS)
      +
      +typedef struct {
      +  Limb X[P384_LIMBS];
      +  Limb Y[P384_LIMBS];
      +  Limb Z[P384_LIMBS];
      +} P384_POINT;
      +
      +typedef struct {
      +  Limb X[P384_LIMBS];
      +  Limb Y[P384_LIMBS];
      +} P384_POINT_AFFINE;
       
       
      -TEST(SelfTests, KAT) {
      -#if !defined(_MSC_VER)
      -  EXPECT_TRUE(BORINGSSL_self_test());
      -#endif
      +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2015-2016 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! EdDSA Signatures.
      +
      +use super::ops::ELEM_LEN;
      +use crate::digest;
      +
      +pub mod signing;
      +pub mod verification;
      +
      +/// The length of an Ed25519 public key.
      +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
      +
      +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
      +    let mut ctx = digest::Context::new(&digest::SHA512);
      +    ctx.update(signature_r);
      +    ctx.update(public_key);
      +    ctx.update(msg);
      +    ctx.finish()
       }
       
    • @@ -12169,29 +15832,44 @@ TEST(SelfTests, KAT) {

      ISC License

      Used by:

      -
      // Copyright 2021 Brian Smith.
      +                
      // Copyright 2015-2022 Brian Smith.
       //
       // Permission to use, copy, modify, and/or distribute this software for any
       // purpose with or without fee is hereby granted, provided that the above
       // copyright notice and this permission notice appear in all copies.
       //
      -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
       // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
      -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
      -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
      -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
      -#[test]
      -fn cert_without_extensions_test() {
      -    // Check the certificate is valid with
      -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
      -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
      +use crate::limb::Limb;
       
      -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
      +#[derive(Clone, Copy)]
      +#[repr(transparent)]
      +pub struct N0([Limb; 2]);
      +
      +impl N0 {
      +    #[cfg(feature = "alloc")]
      +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
      +
      +    #[inline]
      +    pub const fn precalculated(n0: u64) -> Self {
      +        #[cfg(target_pointer_width = "64")]
      +        {
      +            Self([n0, 0])
      +        }
      +
      +        #[cfg(target_pointer_width = "32")]
      +        {
      +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
      +        }
      +    }
       }
       
      @@ -12199,21 +15877,372 @@ fn cert_without_extensions_test() {

      ISC License

      Used by:

      -
      Copyright (c) 2017 Adam Wick
      +                
      // Copyright 2015-2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
      -Permission to use, copy, modify, and/or distribute this software for any purpose
      -with or without fee is hereby granted, provided that the above copyright notice
      -and this permission notice appear in all copies.
      +use crate::{bb, error};
       
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
      -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
      -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
      -THIS SOFTWARE.
      +#[deprecated(
      +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
      +)]
      +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
      +    bb::verify_slices_are_equal(a, b)
      +}
      +
      + +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2016 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Elliptic curve operations and schemes using Curve25519.
      +
      +pub mod ed25519;
      +
      +pub mod x25519;
      +
      +mod ops;
      +mod scalar;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2016-2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +use crate::error::{KeyRejected, Unspecified};
      +
      +impl From<untrusted::EndOfInput> for Unspecified {
      +    fn from(source: untrusted::EndOfInput) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +impl From<core::array::TryFromSliceError> for Unspecified {
      +    fn from(source: core::array::TryFromSliceError) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +impl From<KeyRejected> for Unspecified {
      +    fn from(source: KeyRejected) -> Self {
      +        super::erase(source)
      +    }
      +}
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2018 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Serialization and deserialization.
      +
      +#[doc(hidden)]
      +pub mod der;
      +
      +#[cfg(feature = "alloc")]
      +mod writer;
      +
      +#[cfg(feature = "alloc")]
      +pub(crate) mod der_writer;
      +
      +pub(crate) mod positive;
      +
      +pub use self::positive::Positive;
      +
      +#[cfg(feature = "alloc")]
      +pub(crate) use self::writer::TooLongError;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2019-2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +use super::BlockLen;
      +
      +pub(super) use self::{
      +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
      +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
      +};
      +
      +pub(super) const CHAINING_WORDS: usize = 8;
      +
      +#[cfg(any(
      +    all(target_arch = "aarch64", target_endian = "little"),
      +    all(target_arch = "arm", target_endian = "little"),
      +    target_arch = "x86_64"
      +))]
      +#[macro_use]
      +mod ffi;
      +
      +pub(super) mod fallback;
      +mod sha2_32;
      +mod sha2_64;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
      +#[allow(dead_code)]
      +#[inline(always)]
      +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
      +    r
      +}
      +
      +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
      +#[allow(dead_code)]
      +#[inline(always)]
      +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
      +    r
      +}
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +//! Integration tests for non-public APIs.
      +
      +mod bits_tests;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2024 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +pub use self::{
      +    array::Array,
      +    base::{IndexError, Overlapping},
      +    partial_block::PartialBlock,
      +};
      +
      +mod array;
      +mod base;
      +mod partial_block;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
      +
      +pub(in super::super) mod mont;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +#![cfg(target_arch = "x86_64")]
      +
      +pub(in super::super::super) mod mont;
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +mod storage;
      +
      +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
      +
      +
    • +
    • +

      ISC License

      +

      Used by:

      + +
      // Copyright 2025 Brian Smith.
      +//
      +// Permission to use, copy, modify, and/or distribute this software for any
      +// purpose with or without fee is hereby granted, provided that the above
      +// copyright notice and this permission notice appear in all copies.
      +//
      +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
      +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
      +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
      +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      +
      +pub(super) mod aarch64;
      +pub(super) mod x86_64;
       
    • @@ -12241,7 +16270,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

      ISC License

      Used by:

      Copyright © 2015, Simonas Kazlauskas
       
      @@ -12261,7 +16290,7 @@ THIS SOFTWARE.
                       

      ISC License

      Used by:

      Except as otherwise noted, this project is licensed under the following
       (ISC-style) terms:
      @@ -12288,12 +16317,12 @@ third-party/chromium/LICENSE.
                       

      ISC License

      Used by:

      ISC License
       
       Copyright (c) 2016, Mapbox
      -Copyright (c) 2018, Tree Cricket
      +Copyright (c) 2023, Taku Fukada
       
       Permission to use, copy, modify, and/or distribute this software for any purpose
       with or without fee is hereby granted, provided that the above copyright notice
      @@ -12312,7 +16341,8 @@ THIS SOFTWARE.
                       

      ISC License

      Used by:

      ISC License:
       
      @@ -12328,7 +16358,581 @@ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
                       

      MIT License

      Used by:

      +
                                        MIT License
      +
      +Copyright 2024 Antoine Catton
      +Copyright 2016-2024 David Tolnay
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      # 3rd Party Notices
      +
      +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
      +
      +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
      +
      +    tectonic_cfg_support is licensed under the MIT License.
      +
      +    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.
      +---
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +//! Codegen exports used by `tonic-build`.
      +
      +pub use async_trait::async_trait;
      +pub use tokio_stream;
      +
      +pub use std::future::Future;
      +pub use std::pin::Pin;
      +pub use std::sync::Arc;
      +pub use std::task::{Context, Poll};
      +pub use tower_service::Service;
      +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
      +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
      +pub use crate::extensions::GrpcMethod;
      +pub use crate::service::interceptor::InterceptedService;
      +pub use bytes::Bytes;
      +pub use http;
      +pub use http_body::Body;
      +
      +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
      +pub type BoxStream<T> =
      +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +//! Utilities for using Tower services with Tonic.
      +
      +pub mod interceptor;
      +pub(crate) mod layered;
      +#[cfg(feature = "router")]
      +pub(crate) mod router;
      +
      +#[doc(inline)]
      +pub use self::interceptor::{Interceptor, InterceptorLayer};
      +pub use self::layered::{LayerExt, Layered};
      +#[doc(inline)]
      +#[cfg(feature = "router")]
      +pub use self::router::{Routes, RoutesBuilder};
      +#[cfg(feature = "router")]
      +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
      +
      +pub mod recover_error;
      +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +//! Various utilities used throughout tonic.
      +
      +// some combinations of features might cause things here not to be used
      +#![allow(dead_code)]
      +
      +pub(crate) mod base64 {
      +    use base64::{
      +        alphabet,
      +        engine::{
      +            DecodePaddingMode,
      +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
      +        },
      +    };
      +
      +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
      +        &alphabet::STANDARD,
      +        GeneralPurposeConfig::new()
      +            .with_encode_padding(true)
      +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
      +    );
      +
      +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
      +        &alphabet::STANDARD,
      +        GeneralPurposeConfig::new()
      +            .with_encode_padding(false)
      +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
      +    );
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +/// A gRPC Method info extension.
      +#[derive(Debug, Clone)]
      +pub struct GrpcMethod<'a> {
      +    service: &'a str,
      +    method: &'a str,
      +}
      +
      +impl<'a> GrpcMethod<'a> {
      +    /// Create a new `GrpcMethod` extension.
      +    #[doc(hidden)]
      +    pub fn new(service: &'a str, method: &'a str) -> Self {
      +        Self { service, method }
      +    }
      +
      +    /// gRPC service name
      +    pub fn service(&self) -> &str {
      +        self.service
      +    }
      +    /// gRPC method name
      +    pub fn method(&self) -> &str {
      +        self.method
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +mod add_origin;
      +use self::add_origin::AddOrigin;
      +
      +mod user_agent;
      +use self::user_agent::UserAgent;
      +
      +mod reconnect;
      +use self::reconnect::Reconnect;
      +
      +mod connection;
      +pub(super) use self::connection::Connection;
      +
      +mod discover;
      +pub use self::discover::Change;
      +pub(super) use self::discover::DynamicServiceStream;
      +
      +mod io;
      +use self::io::BoxedIo;
      +
      +mod connector;
      +pub(crate) use self::connector::Connector;
      +
      +mod executor;
      +pub(super) use self::executor::{Executor, SharedExec};
      +
      +#[cfg(feature = "_tls-any")]
      +mod tls;
      +#[cfg(feature = "_tls-any")]
      +pub(super) use self::tls::TlsConnector;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +mod io;
      +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
      +
      +#[cfg(feature = "_tls-any")]
      +mod tls;
      +#[cfg(feature = "_tls-any")]
      +pub(crate) use self::tls::TlsAcceptor;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +pub(crate) mod grpc_timeout;
      +#[cfg(feature = "_tls-any")]
      +pub(crate) mod tls;
      +
      +pub(crate) use self::grpc_timeout::GrpcTimeout;
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +use crate::transport::channel::BoxFuture;
      +use hyper_util::rt::TokioExecutor;
      +use std::{future::Future, sync::Arc};
      +
      +pub(crate) use hyper::rt::Executor;
      +
      +#[derive(Clone)]
      +pub(crate) struct SharedExec {
      +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
      +}
      +
      +impl SharedExec {
      +    pub(crate) fn new<E>(exec: E) -> Self
      +    where
      +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
      +    {
      +        Self {
      +            inner: Arc::new(exec),
      +        }
      +    }
      +
      +    pub(crate) fn tokio() -> Self {
      +        Self::new(TokioExecutor::new())
      +    }
      +}
      +
      +impl<F> Executor<F> for SharedExec
      +where
      +    F: Future<Output = ()> + Send + 'static,
      +{
      +    fn execute(&self, fut: F) {
      +        self.inner.execute(Box::pin(fut))
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      /*
      + *
      + * Copyright 2025 gRPC authors.
      + *
      + * 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.
      + *
      + */
      +
      +use super::Connected;
      +use std::sync::Arc;
      +
      +/// Connection info for Unix domain socket streams.
      +///
      +/// This type will be accessible through [request extensions][ext] if you're using
      +/// a unix stream.
      +///
      +/// See [Connected] for more details.
      +///
      +/// [ext]: crate::Request::extensions
      +#[derive(Clone, Debug)]
      +pub struct UdsConnectInfo {
      +    /// Peer address. This will be "unnamed" for client unix sockets.
      +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
      +    /// Process credentials for the unix socket.
      +    pub peer_cred: Option<tokio::net::unix::UCred>,
      +}
      +
      +impl Connected for tokio::net::UnixStream {
      +    type ConnectInfo = UdsConnectInfo;
      +
      +    fn connect_info(&self) -> Self::ConnectInfo {
      +        UdsConnectInfo {
      +            peer_addr: self.peer_addr().ok().map(Arc::new),
      +            peer_cred: self.peer_cred().ok(),
      +        }
      +    }
      +}
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      // Copyright (c) 2019 Nuclear Furnace
      +//
      +// 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
       
      @@ -12355,7 +16959,40 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      +
      Copyright (c) 2014 Alex Crichton
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2014 Carl Lerche and other MIO contributors
       
      @@ -12382,7 +17019,6 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      Copyright (c) 2014-2019 Geoffroy Couprie
      @@ -12411,9 +17047,36 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2014-2021 Sean McArthur
      +                
      Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2014-2026 Sean McArthur
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -12438,34 +17101,8 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2014-2025 Sean McArthur
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2015 Jonathan Reem
       
      @@ -12498,34 +17135,34 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2015 fangyuanziti
      -
      -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.
      +                
      Copyright (c) 2015 fangyuanziti
      +
      +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.
       
    • MIT License

      Used by:

      Copyright (c) 2015 steffengy
       
      @@ -12540,16 +17177,28 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES
                       

      MIT License

      Used by:

      -
      Copyright (c) 2016 Paul Masurel
      +                
      Copyright (c) 2015-2024 Doug Tangren
       
      -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:
      +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 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.
      -
      +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.
    • MIT License

      @@ -12611,8 +17260,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

      MIT License

      Used by:

      Copyright (c) 2017 h2 authors
       
      @@ -12645,7 +17293,7 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      Copyright (c) 2018 Carl Lerche
       
      @@ -12678,52 +17326,34 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2018 Paul Masurel
      +                
      Copyright (c) 2018 Tom Parker-Shemilt
       
      -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:
      +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 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.
      -
      +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.
    • MIT License

      Used by:

      -
      Copyright (c) 2018 by Quickwit, 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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2018-2019 Sean McArthur
       
      @@ -12814,7 +17444,7 @@ DEALINGS IN THE SOFTWARE.
                       

      Used by:

      Copyright (c) 2019 Carl Lerche
       
      @@ -12901,44 +17531,14 @@ SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019 Hyper Contributors
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      Copyright (c) 2019 Tokio Contributors
       
      @@ -12973,7 +17573,7 @@ DEALINGS IN THE SOFTWARE.
                       
                       
      Copyright (c) 2019 Tower Contributors
       
      @@ -13006,10 +17606,9 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019-2021 Tower Contributors
      +                
      Copyright (c) 2019 axum Contributors
       
       Permission is hereby granted, free of charge, to any
       person obtaining a copy of this software and associated
      @@ -13040,9 +17639,10 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
      +                
      Copyright (c) 2019-2021 Tower Contributors
       
       Permission is hereby granted, free of charge, to any
       person obtaining a copy of this software and associated
      @@ -13106,7 +17706,94 @@ DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      +
      Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias
      +
      +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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright (c) 2021 Metrics Contributors
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Copyright (c) 2023-2025 Sean McArthur
       
      @@ -13127,36 +17814,6 @@ 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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2024 by Quickwit 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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      - -
      Copyright (c) 2024-Present Paul Masurel
      -
      -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.
       
    • @@ -13164,6 +17821,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

      Used by:

      Copyright 2016 Nika Layzell
       
      @@ -13171,6 +17829,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
       
       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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2019 gRPC authors.
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2020 David Koloski
      +
      +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.
       
    • @@ -13193,25 +17893,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

      MIT License

      Used by:

      -
      Includes portions of humantime
      -Copyright (c) 2016 The humantime Developers
      +                
      Copyright 2021 David Koloski
       
       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.
      -
      -
       
    • MIT License

      Used by:

      +
      Copyright 2023 David Koloski
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2023 David Koloski
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      Copyright 2024 David Koloski
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13234,6 +17982,65 @@ 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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2016 Michael Ma
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2016 fengcen
      +Copyright (c) 2019 svartalf
      +
      +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.
      +
    • MIT License

      @@ -13356,9 +18163,41 @@ SOFTWARE.

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2017 Sam Rijs
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13374,6 +18213,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2018 Canop
      +
      +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
      @@ -13417,7 +18285,36 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2018 sgodwincs
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13446,7 +18343,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13475,36 +18372,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      -
      MIT License
      -
      -Copyright (c) 2019 Aeledfyr
      -
      -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.
      -
      -
    • -
    • -

      MIT License

      -

      Used by:

      -
      MIT License
       
      @@ -13533,8 +18401,37 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2019 Kornel
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13563,7 +18460,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13617,6 +18514,40 @@ 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.
       
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2019–2025 axum Contributors
      +
      +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.
    • MIT License

      @@ -13651,11 +18582,31 @@ SOFTWARE.

      MIT License

      Used by:

      MIT License
       
      -Copyright (c) 2020 David Purdum
      +Copyright (c) 2020 Katharos Technology
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020 Scripta Qumranica Electronica
      +
      +Created by Bronson Brown-deVost
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -13680,13 +18631,11 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      -Copyright (c) 2020 Scripta Qumranica Electronica
      -
      -Created by Bronson Brown-deVost
      +Copyright (c) 2020 magiclen.org (Ron Li)
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -13727,6 +18676,93 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020-2022 Oliver Margetts
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2020-2026 Nugine
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2021 Adel Prokurov
      +
      +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
      @@ -13756,6 +18792,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2022 Arthur Silva
      +
      +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
      @@ -13770,6 +18835,7 @@ SOFTWARE.
                       

      Used by:

      MIT License
       
      @@ -13785,6 +18851,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2022 Jeroen Van Der Donckt
      +
      +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
      @@ -13826,7 +18921,36 @@ SOFTWARE.

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2022 sarah
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13855,8 +18979,8 @@ SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13885,8 +19009,66 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) 2023 sarah
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2024 Spire Team
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      MIT License
       
      @@ -13910,30 +19092,67 @@ 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.
       
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      MIT License
      +
      +Copyright (c) 2025 rutrum
      +
      +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.
    • MIT License

      Used by:

      MIT License
      @@ -13960,9 +19179,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      MIT License
       
      @@ -13991,7 +19210,100 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      MIT License
      +
      +Copyright (c) [2021] [Marvin Countryman]
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      Permission is hereby granted, free of charge, to any person obtaining
       a copy of this software and associated documentation files (the
      @@ -14017,12 +19329,42 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      -
      The MIT License (MIT)
      +                
      Portions of this project are derived from atty, which bears the following
      +copyright notice and permission notice:
       
      -Copyright (c) 2014 Benjamin Sago
      -Copyright (c) 2021-2022 The Nushell Project Developers
      +Copyright (c) 2015-2019 Doug Tangren
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License
      +
      +Copyright 2015 The Fancy Regex Authors.
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14031,23 +19373,24 @@ 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 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.
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      +THE SOFTWARE.
       
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14070,13 +19413,63 @@ 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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Mathijs van de Nes
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Y. T. CHUNG
      +
      +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.
      +
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14104,21 +19497,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
       
      -Copyright (c) 2015 Andrew Gallant
      +Copyright (c) 2015 
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14127,28 +19510,39 @@ 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 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.
      +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      +SOFTWARE.
      +
       
    • MIT License

      Used by:

      The MIT License (MIT)
       
       Copyright (c) 2015 Andrew Gallant
      -Copyright (c) 2019 Paul Masurel
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14198,6 +19592,37 @@ 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.
       
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Carl Lerche + nix-rust Authors
      +
      +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.
       
    • @@ -14229,6 +19654,64 @@ 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. +
    • + +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Gerd Zellweger
      +
      +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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Guillaume Gomez
      +
      +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.
      +
       
    • @@ -14264,11 +19747,102 @@ SOFTWARE.

      MIT License

      Used by:

      The MIT License (MIT)
       
      -Copyright (c) 2015 Vincent Prouillet
      +Copyright (c) 2015 Katsu Kawakami & Rustyline authors
      +
      +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.
      +
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Markus Westerlind
      +
      +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.
      +
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015 Michael Sproul
      +
      +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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2015-2020 the fiat-crypto authors (see
      +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
       
       Permission is hereby granted, free of charge, to any person obtaining a copy
       of this software and associated documentation files (the "Software"), to deal
      @@ -14293,7 +19867,7 @@ SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14309,6 +19883,35 @@ 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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2016 nabijaczleweli
      +
      +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
      @@ -14352,6 +19955,7 @@ THE SOFTWARE.
                       

      MIT License

      Used by:

      The MIT License (MIT)
      @@ -14382,8 +19986,36 @@ SOFTWARE.
                       

      MIT License

      Used by:

      +
      The MIT License (MIT)
      +
      +Copyright (c) 2019 Simon Heath
      +
      +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.
      +
    • +
    • +

      MIT License

      +

      Used by:

      +
      The MIT License (MIT)
       
      @@ -14450,6 +20082,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
       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.
      +
      +
    • +
    • +

      MIT License

      +

      Used by:

      + +
      The MIT License (MIT)
      +
      +Copyright (c) 2014 Benjamin Sago
      +Copyright (c) 2021-2022 The Nushell Project Developers
      +
      +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.
       
    • @@ -14514,8 +20176,9 @@ SOFTWARE.
    • MIT License

      Used by:

      The MIT License (MIT)
       
      @@ -14568,6 +20231,387 @@ 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.
      +
      + +
    • +

      Mozilla Public License 2.0

      +

      Used by:

      + +
      Mozilla Public License Version 2.0
      +==================================
      +
      +1. Definitions
      +--------------
      +
      +1.1. "Contributor"
      +    means each individual or legal entity that creates, contributes to
      +    the creation of, or owns Covered Software.
      +
      +1.2. "Contributor Version"
      +    means the combination of the Contributions of others (if any) used
      +    by a Contributor and that particular Contributor's Contribution.
      +
      +1.3. "Contribution"
      +    means Covered Software of a particular Contributor.
      +
      +1.4. "Covered Software"
      +    means Source Code Form to which the initial Contributor has attached
      +    the notice in Exhibit A, the Executable Form of such Source Code
      +    Form, and Modifications of such Source Code Form, in each case
      +    including portions thereof.
      +
      +1.5. "Incompatible With Secondary Licenses"
      +    means
      +
      +    (a) that the initial Contributor has attached the notice described
      +        in Exhibit B to the Covered Software; or
      +
      +    (b) that the Covered Software was made available under the terms of
      +        version 1.1 or earlier of the License, but not also under the
      +        terms of a Secondary License.
      +
      +1.6. "Executable Form"
      +    means any form of the work other than Source Code Form.
      +
      +1.7. "Larger Work"
      +    means a work that combines Covered Software with other material, in 
      +    a separate file or files, that is not Covered Software.
      +
      +1.8. "License"
      +    means this document.
      +
      +1.9. "Licensable"
      +    means having the right to grant, to the maximum extent possible,
      +    whether at the time of the initial grant or subsequently, any and
      +    all of the rights conveyed by this License.
      +
      +1.10. "Modifications"
      +    means any of the following:
      +
      +    (a) any file in Source Code Form that results from an addition to,
      +        deletion from, or modification of the contents of Covered
      +        Software; or
      +
      +    (b) any new file in Source Code Form that contains any Covered
      +        Software.
      +
      +1.11. "Patent Claims" of a Contributor
      +    means any patent claim(s), including without limitation, method,
      +    process, and apparatus claims, in any patent Licensable by such
      +    Contributor that would be infringed, but for the grant of the
      +    License, by the making, using, selling, offering for sale, having
      +    made, import, or transfer of either its Contributions or its
      +    Contributor Version.
      +
      +1.12. "Secondary License"
      +    means either the GNU General Public License, Version 2.0, the GNU
      +    Lesser General Public License, Version 2.1, the GNU Affero General
      +    Public License, Version 3.0, or any later versions of those
      +    licenses.
      +
      +1.13. "Source Code Form"
      +    means the form of the work preferred for making modifications.
      +
      +1.14. "You" (or "Your")
      +    means an individual or a legal entity exercising rights under this
      +    License. For legal entities, "You" includes any entity that
      +    controls, is controlled by, or is under common control with You. For
      +    purposes of this definition, "control" means (a) the power, direct
      +    or indirect, to cause the direction or management of such entity,
      +    whether by contract or otherwise, or (b) ownership of more than
      +    fifty percent (50%) of the outstanding shares or beneficial
      +    ownership of such entity.
      +
      +2. License Grants and Conditions
      +--------------------------------
      +
      +2.1. Grants
      +
      +Each Contributor hereby grants You a world-wide, royalty-free,
      +non-exclusive license:
      +
      +(a) under intellectual property rights (other than patent or trademark)
      +    Licensable by such Contributor to use, reproduce, make available,
      +    modify, display, perform, distribute, and otherwise exploit its
      +    Contributions, either on an unmodified basis, with Modifications, or
      +    as part of a Larger Work; and
      +
      +(b) under Patent Claims of such Contributor to make, use, sell, offer
      +    for sale, have made, import, and otherwise transfer either its
      +    Contributions or its Contributor Version.
      +
      +2.2. Effective Date
      +
      +The licenses granted in Section 2.1 with respect to any Contribution
      +become effective for each Contribution on the date the Contributor first
      +distributes such Contribution.
      +
      +2.3. Limitations on Grant Scope
      +
      +The licenses granted in this Section 2 are the only rights granted under
      +this License. No additional rights or licenses will be implied from the
      +distribution or licensing of Covered Software under this License.
      +Notwithstanding Section 2.1(b) above, no patent license is granted by a
      +Contributor:
      +
      +(a) for any code that a Contributor has removed from Covered Software;
      +    or
      +
      +(b) for infringements caused by: (i) Your and any other third party's
      +    modifications of Covered Software, or (ii) the combination of its
      +    Contributions with other software (except as part of its Contributor
      +    Version); or
      +
      +(c) under Patent Claims infringed by Covered Software in the absence of
      +    its Contributions.
      +
      +This License does not grant any rights in the trademarks, service marks,
      +or logos of any Contributor (except as may be necessary to comply with
      +the notice requirements in Section 3.4).
      +
      +2.4. Subsequent Licenses
      +
      +No Contributor makes additional grants as a result of Your choice to
      +distribute the Covered Software under a subsequent version of this
      +License (see Section 10.2) or under the terms of a Secondary License (if
      +permitted under the terms of Section 3.3).
      +
      +2.5. Representation
      +
      +Each Contributor represents that the Contributor believes its
      +Contributions are its original creation(s) or it has sufficient rights
      +to grant the rights to its Contributions conveyed by this License.
      +
      +2.6. Fair Use
      +
      +This License is not intended to limit any rights You have under
      +applicable copyright doctrines of fair use, fair dealing, or other
      +equivalents.
      +
      +2.7. Conditions
      +
      +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
      +in Section 2.1.
      +
      +3. Responsibilities
      +-------------------
      +
      +3.1. Distribution of Source Form
      +
      +All distribution of Covered Software in Source Code Form, including any
      +Modifications that You create or to which You contribute, must be under
      +the terms of this License. You must inform recipients that the Source
      +Code Form of the Covered Software is governed by the terms of this
      +License, and how they can obtain a copy of this License. You may not
      +attempt to alter or restrict the recipients' rights in the Source Code
      +Form.
      +
      +3.2. Distribution of Executable Form
      +
      +If You distribute Covered Software in Executable Form then:
      +
      +(a) such Covered Software must also be made available in Source Code
      +    Form, as described in Section 3.1, and You must inform recipients of
      +    the Executable Form how they can obtain a copy of such Source Code
      +    Form by reasonable means in a timely manner, at a charge no more
      +    than the cost of distribution to the recipient; and
      +
      +(b) You may distribute such Executable Form under the terms of this
      +    License, or sublicense it under different terms, provided that the
      +    license for the Executable Form does not attempt to limit or alter
      +    the recipients' rights in the Source Code Form under this License.
      +
      +3.3. Distribution of a Larger Work
      +
      +You may create and distribute a Larger Work under terms of Your choice,
      +provided that You also comply with the requirements of this License for
      +the Covered Software. If the Larger Work is a combination of Covered
      +Software with a work governed by one or more Secondary Licenses, and the
      +Covered Software is not Incompatible With Secondary Licenses, this
      +License permits You to additionally distribute such Covered Software
      +under the terms of such Secondary License(s), so that the recipient of
      +the Larger Work may, at their option, further distribute the Covered
      +Software under the terms of either this License or such Secondary
      +License(s).
      +
      +3.4. Notices
      +
      +You may not remove or alter the substance of any license notices
      +(including copyright notices, patent notices, disclaimers of warranty,
      +or limitations of liability) contained within the Source Code Form of
      +the Covered Software, except that You may alter any license notices to
      +the extent required to remedy known factual inaccuracies.
      +
      +3.5. Application of Additional Terms
      +
      +You may choose to offer, and to charge a fee for, warranty, support,
      +indemnity or liability obligations to one or more recipients of Covered
      +Software. However, You may do so only on Your own behalf, and not on
      +behalf of any Contributor. You must make it absolutely clear that any
      +such warranty, support, indemnity, or liability obligation is offered by
      +You alone, and You hereby agree to indemnify every Contributor for any
      +liability incurred by such Contributor as a result of warranty, support,
      +indemnity or liability terms You offer. You may include additional
      +disclaimers of warranty and limitations of liability specific to any
      +jurisdiction.
      +
      +4. Inability to Comply Due to Statute or Regulation
      +---------------------------------------------------
      +
      +If it is impossible for You to comply with any of the terms of this
      +License with respect to some or all of the Covered Software due to
      +statute, judicial order, or regulation then You must: (a) comply with
      +the terms of this License to the maximum extent possible; and (b)
      +describe the limitations and the code they affect. Such description must
      +be placed in a text file included with all distributions of the Covered
      +Software under this License. Except to the extent prohibited by statute
      +or regulation, such description must be sufficiently detailed for a
      +recipient of ordinary skill to be able to understand it.
      +
      +5. Termination
      +--------------
      +
      +5.1. The rights granted under this License will terminate automatically
      +if You fail to comply with any of its terms. However, if You become
      +compliant, then the rights granted under this License from a particular
      +Contributor are reinstated (a) provisionally, unless and until such
      +Contributor explicitly and finally terminates Your grants, and (b) on an
      +ongoing basis, if such Contributor fails to notify You of the
      +non-compliance by some reasonable means prior to 60 days after You have
      +come back into compliance. Moreover, Your grants from a particular
      +Contributor are reinstated on an ongoing basis if such Contributor
      +notifies You of the non-compliance by some reasonable means, this is the
      +first time You have received notice of non-compliance with this License
      +from such Contributor, and You become compliant prior to 30 days after
      +Your receipt of the notice.
      +
      +5.2. If You initiate litigation against any entity by asserting a patent
      +infringement claim (excluding declaratory judgment actions,
      +counter-claims, and cross-claims) alleging that a Contributor Version
      +directly or indirectly infringes any patent, then the rights granted to
      +You by any and all Contributors for the Covered Software under Section
      +2.1 of this License shall terminate.
      +
      +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
      +end user license agreements (excluding distributors and resellers) which
      +have been validly granted by You or Your distributors under this License
      +prior to termination shall survive termination.
      +
      +************************************************************************
      +*                                                                      *
      +*  6. Disclaimer of Warranty                                           *
      +*  -------------------------                                           *
      +*                                                                      *
      +*  Covered Software is provided under this License on an "as is"       *
      +*  basis, without warranty of any kind, either expressed, implied, or  *
      +*  statutory, including, without limitation, warranties that the       *
      +*  Covered Software is free of defects, merchantable, fit for a        *
      +*  particular purpose or non-infringing. The entire risk as to the     *
      +*  quality and performance of the Covered Software is with You.        *
      +*  Should any Covered Software prove defective in any respect, You     *
      +*  (not any Contributor) assume the cost of any necessary servicing,   *
      +*  repair, or correction. This disclaimer of warranty constitutes an   *
      +*  essential part of this License. No use of any Covered Software is   *
      +*  authorized under this License except under this disclaimer.         *
      +*                                                                      *
      +************************************************************************
      +
      +************************************************************************
      +*                                                                      *
      +*  7. Limitation of Liability                                          *
      +*  --------------------------                                          *
      +*                                                                      *
      +*  Under no circumstances and under no legal theory, whether tort      *
      +*  (including negligence), contract, or otherwise, shall any           *
      +*  Contributor, or anyone who distributes Covered Software as          *
      +*  permitted above, be liable to You for any direct, indirect,         *
      +*  special, incidental, or consequential damages of any character      *
      +*  including, without limitation, damages for lost profits, loss of    *
      +*  goodwill, work stoppage, computer failure or malfunction, or any    *
      +*  and all other commercial damages or losses, even if such party      *
      +*  shall have been informed of the possibility of such damages. This   *
      +*  limitation of liability shall not apply to liability for death or   *
      +*  personal injury resulting from such party's negligence to the       *
      +*  extent applicable law prohibits such limitation. Some               *
      +*  jurisdictions do not allow the exclusion or limitation of           *
      +*  incidental or consequential damages, so this exclusion and          *
      +*  limitation may not apply to You.                                    *
      +*                                                                      *
      +************************************************************************
      +
      +8. Litigation
      +-------------
      +
      +Any litigation relating to this License may be brought only in the
      +courts of a jurisdiction where the defendant maintains its principal
      +place of business and such litigation shall be governed by laws of that
      +jurisdiction, without reference to its conflict-of-law provisions.
      +Nothing in this Section shall prevent a party's ability to bring
      +cross-claims or counter-claims.
      +
      +9. Miscellaneous
      +----------------
      +
      +This License represents the complete agreement concerning the subject
      +matter hereof. If any provision of this License is held to be
      +unenforceable, such provision shall be reformed only to the extent
      +necessary to make it enforceable. Any law or regulation which provides
      +that the language of a contract shall be construed against the drafter
      +shall not be used to construe this License against a Contributor.
      +
      +10. Versions of the License
      +---------------------------
      +
      +10.1. New Versions
      +
      +Mozilla Foundation is the license steward. Except as provided in Section
      +10.3, no one other than the license steward has the right to modify or
      +publish new versions of this License. Each version will be given a
      +distinguishing version number.
      +
      +10.2. Effect of New Versions
      +
      +You may distribute the Covered Software under the terms of the version
      +of the License under which You originally received the Covered Software,
      +or under the terms of any subsequent version published by the license
      +steward.
      +
      +10.3. Modified Versions
      +
      +If you create software not governed by this License, and you want to
      +create a new license for such software, you may create and use a
      +modified version of this License if you rename the license and remove
      +any references to the name of the license steward (except to note that
      +such modified license differs from this License).
      +
      +10.4. Distributing Source Code Form that is Incompatible With Secondary
      +Licenses
      +
      +If You choose to distribute Source Code Form that is Incompatible With
      +Secondary Licenses under the terms of this version of the License, the
      +notice described in Exhibit B of this License must be attached.
      +
      +Exhibit A - Source Code Form License Notice
      +-------------------------------------------
      +
      +  This Source Code Form is subject to the terms of the Mozilla Public
      +  License, v. 2.0. If a copy of the MPL was not distributed with this
      +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
      +
      +If it is not possible or desirable to put the notice in a particular
      +file, then You may include the notice in a location (such as a LICENSE
      +file in a relevant directory) where a recipient would be likely to look
      +for such a notice.
      +
      +You may add additional accurate notices of copyright ownership.
      +
      +Exhibit B - "Incompatible With Secondary Licenses" Notice
      +---------------------------------------------------------
      +
      +  This Source Code Form is "Incompatible With Secondary Licenses", as
      +  defined by the Mozilla Public License, v. 2.0.
       
    • @@ -14949,187 +20993,13 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -
    • - -
    • -

      OpenSSL License

      -

      Used by:

      - -
      /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
      - * All rights reserved.
      - *
      - * This package is an SSL implementation written
      - * by Eric Young (eay@cryptsoft.com).
      - * The implementation was written so as to conform with Netscapes SSL.
      - *
      - * This library is free for commercial and non-commercial use as long as
      - * the following conditions are aheared to.  The following conditions
      - * apply to all code found in this distribution, be it the RC4, RSA,
      - * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
      - * included with this distribution is covered by the same copyright terms
      - * except that the holder is Tim Hudson (tjh@cryptsoft.com).
      - *
      - * Copyright remains Eric Young's, and as such any Copyright notices in
      - * the code are not to be removed.
      - * If this package is used in a product, Eric Young should be given attribution
      - * as the author of the parts of the library used.
      - * This can be in the form of a textual message at program startup or
      - * in documentation (online or textual) provided with the package.
      - *
      - * Redistribution and use in source and binary forms, with or without
      - * modification, are permitted provided that the following conditions
      - * are met:
      - * 1. Redistributions of source code must retain the copyright
      - *    notice, this list of conditions and the following disclaimer.
      - * 2. Redistributions in binary form must reproduce the above copyright
      - *    notice, this list of conditions and the following disclaimer in the
      - *    documentation and/or other materials provided with the distribution.
      - * 3. All advertising materials mentioning features or use of this software
      - *    must display the following acknowledgement:
      - *    "This product includes cryptographic software written by
      - *     Eric Young (eay@cryptsoft.com)"
      - *    The word 'cryptographic' can be left out if the rouines from the library
      - *    being used are not cryptographic related :-).
      - * 4. If you include any Windows specific code (or a derivative thereof) from
      - *    the apps directory (application code) you must include an acknowledgement:
      - *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
      - *
      - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
      - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
      - * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
      - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
      - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
      - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
      - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
      - * SUCH DAMAGE.
      - *
      - * The licence and distribution terms for any publically available version or
      - * derivative of this code cannot be changed.  i.e. this code cannot simply be
      - * copied and put under another distribution licence
      - * [including the GNU Public Licence.]
      - */
      -/* ====================================================================
      - * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
      - *
      - * Redistribution and use in source and binary forms, with or without
      - * modification, are permitted provided that the following conditions
      - * are met:
      - *
      - * 1. Redistributions of source code must retain the above copyright
      - *    notice, this list of conditions and the following disclaimer.
      - *
      - * 2. Redistributions in binary form must reproduce the above copyright
      - *    notice, this list of conditions and the following disclaimer in
      - *    the documentation and/or other materials provided with the
      - *    distribution.
      - *
      - * 3. All advertising materials mentioning features or use of this
      - *    software must display the following acknowledgment:
      - *    "This product includes software developed by the OpenSSL Project
      - *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
      - *
      - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
      - *    endorse or promote products derived from this software without
      - *    prior written permission. For written permission, please contact
      - *    openssl-core@openssl.org.
      - *
      - * 5. Products derived from this software may not be called "OpenSSL"
      - *    nor may "OpenSSL" appear in their names without prior written
      - *    permission of the OpenSSL Project.
      - *
      - * 6. Redistributions of any form whatsoever must retain the following
      - *    acknowledgment:
      - *    "This product includes software developed by the OpenSSL Project
      - *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
      - *
      - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
      - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
      - * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
      - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
      - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
      - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
      - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
      - * OF THE POSSIBILITY OF SUCH DAMAGE.
      - * ====================================================================
      - *
      - * This product includes cryptographic software written by Eric Young
      - * (eay@cryptsoft.com).  This product includes software written by Tim
      - * Hudson (tjh@cryptsoft.com).
      - *
      - */
      -
      -#include <openssl/ssl.h>
      -
      -#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_PNACL) && \
      -    !defined(OPENSSL_NO_FILESYSTEM)
      -
      -#include <dirent.h>
      -#include <errno.h>
      -#include <string.h>
      -
      -#include <openssl/err.h>
      -#include <openssl/mem.h>
      -
      -
      -int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
      -                                       const char *path) {
      -  DIR *dir = opendir(path);
      -  if (dir == NULL) {
      -    OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
      -    ERR_add_error_data(3, "opendir('", dir, "')");
      -    return 0;
      -  }
      -
      -  int ret = 0;
      -  for (;;) {
      -    // |readdir| may fail with or without setting |errno|.
      -    errno = 0;
      -    struct dirent *dirent = readdir(dir);
      -    if (dirent == NULL) {
      -      if (errno) {
      -        OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
      -        ERR_add_error_data(3, "readdir('", path, "')");
      -      } else {
      -        ret = 1;
      -      }
      -      break;
      -    }
      -
      -    char buf[1024];
      -    if (strlen(path) + strlen(dirent->d_name) + 2 > sizeof(buf)) {
      -      OPENSSL_PUT_ERROR(SSL, SSL_R_PATH_TOO_LONG);
      -      break;
      -    }
      -
      -    int r = snprintf(buf, sizeof(buf), "%s/%s", path, dirent->d_name);
      -    if (r <= 0 ||
      -        r >= (int)sizeof(buf) ||
      -        !SSL_add_file_cert_subjects_to_stack(stack, buf)) {
      -      break;
      -    }
      -  }
      -
      -  closedir(dir);
      -  return ret;
      -}
      -
      -#endif  // !WINDOWS && !PNACL && !OPENSSL_NO_FILESYSTEM
       
    • Unicode License v3

      Used by:

      UNICODE LICENSE V3
       
      @@ -15176,24 +21046,28 @@ authorization of the copyright holder.
                       

      Unicode License v3

      Used by:

      UNICODE LICENSE V3
       
      @@ -15242,12 +21116,63 @@ SPDX-License-Identifier: Unicode-3.0
       Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
       ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
       
      +
    • +
    • +

      zlib License

      +

      Used by:

      + +
      Copyright (c) 2021 Matias Rodriguez.
      +
      +This software is provided 'as-is', without any express or implied
      +warranty. In no event will the authors be held liable for any damages
      +arising from the use of this software.
      +
      +Permission is granted to anyone to use this software for any purpose,
      +including commercial applications, and to alter it and redistribute it
      +freely, subject to the following restrictions:
      +
      +1. The origin of this software must not be misrepresented; you must not
      +   claim that you wrote the original software. If you use this software
      +   in a product, an acknowledgment in the product documentation would be
      +   appreciated but is not required.
      +2. Altered source versions must be plainly marked as such, and must not be
      +   misrepresented as being the original software.
      +3. This notice may not be removed or altered from any source distribution.
      +
    • +
    • +

      zlib License

      +

      Used by:

      + +
      Copyright (c) 2023 Matias Rodriguez.
      +
      +This software is provided 'as-is', without any express or implied
      +warranty. In no event will the authors be held liable for any damages
      +arising from the use of this software.
      +
      +Permission is granted to anyone to use this software for any purpose,
      +including commercial applications, and to alter it and redistribute it
      +freely, subject to the following restrictions:
      +
      +1. The origin of this software must not be misrepresented; you must not
      +   claim that you wrote the original software. If you use this software
      +   in a product, an acknowledgment in the product documentation would be
      +   appreciated but is not required.
      +2. Altered source versions must be plainly marked as such, and must not be
      +   misrepresented as being the original software.
      +3. This notice may not be removed or altered from any source distribution.
    • zlib License

      Used by:

      Copyright (c) 2024 Orson Peters
       
      diff --git a/docs/src/js/classes/Index.md b/docs/src/js/classes/Index.md
      index e613882e4..b3fcf5ec3 100644
      --- a/docs/src/js/classes/Index.md
      +++ b/docs/src/js/classes/Index.md
      @@ -258,3 +258,51 @@ using an underlying bitmap index.
       #### Returns
       
       [`Index`](Index.md)
      +
      +***
      +
      +### rtree()
      +
      +```ts
      +static rtree(options?): Index
      +```
      +
      +Create an RTree index.
      +
      +An RTree index is a scalar index on a GeoArrow geometry column, that is, a
      +column whose Arrow field metadata sets `ARROW:extension:name` to a GeoArrow
      +type such as `geoarrow.point`, `geoarrow.polygon` or `geoarrow.wkb`. It
      +stores the bounding box of each geometry and accelerates spatial filters.
      +
      +The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`,
      +`ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy`
      +between the indexed column and a constant geometry, in either argument
      +order, for example
      +`ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))`, as well as
      +`geom IS NULL`. These filters can be combined with other conditions using
      +`AND`.
      +
      +See the R-tree section of https://docs.lancedb.com/indexing/scalar-index
      +for storing geometry, the other spatial functions, and spatial filters on
      +vector search.
      +
      +Remote tables send the `RTREE` index type to the server, which must
      +support it.
      +
      +#### Parameters
      +
      +* **options?**: `Partial`<[`RTreeOptions`](../interfaces/RTreeOptions.md)>
      +
      +#### Returns
      +
      +[`Index`](Index.md)
      +
      +#### Example
      +
      +```ts
      +await table.createIndex("geom", { config: Index.rtree() });
      +await table
      +  .query()
      +  .where("ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))")
      +  .toArray();
      +```
      diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md
      index 0a0742389..2aab45c12 100644
      --- a/docs/src/js/globals.md
      +++ b/docs/src/js/globals.md
      @@ -137,6 +137,7 @@
       - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md)
       - [RTEStats](interfaces/RTEStats.md)
       - [RTEWriteSpec](interfaces/RTEWriteSpec.md)
      +- [RTreeOptions](interfaces/RTreeOptions.md)
       - [RefreshColumnOptions](interfaces/RefreshColumnOptions.md)
       - [RefreshColumnResult](interfaces/RefreshColumnResult.md)
       - [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md)
      diff --git a/docs/src/js/interfaces/RTreeOptions.md b/docs/src/js/interfaces/RTreeOptions.md
      new file mode 100644
      index 000000000..ad0a8d1ce
      --- /dev/null
      +++ b/docs/src/js/interfaces/RTreeOptions.md
      @@ -0,0 +1,21 @@
      +[**@lancedb/lancedb**](../README.md) • **Docs**
      +
      +***
      +
      +[@lancedb/lancedb](../globals.md) / RTreeOptions
      +
      +# Interface: RTreeOptions
      +
      +Options to create an `RTREE` index
      +
      +## Properties
      +
      +### pageSize?
      +
      +```ts
      +optional pageSize: number;
      +```
      +
      +The maximum number of entries in each R-tree page.
      +
      +Must be at least 2. The default is 4096.
      diff --git a/docs/web-tests/py/test_indexing.py b/docs/web-tests/py/test_indexing.py
      index f342f1b3b..bb40283ff 100644
      --- a/docs/web-tests/py/test_indexing.py
      +++ b/docs/web-tests/py/test_indexing.py
      @@ -561,6 +561,83 @@ def test_scalar_index_uuid(tmp_db):
           assert len(result) == n + len(new_users)
       
       
      +def test_scalar_index_rtree(tmp_db):
      +    db = tmp_db
      +
      +    # --8<-- [start:scalar_index_rtree_data]
      +    import pyarrow as pa
      +
      +    point = pa.struct([("x", pa.float64()), ("y", pa.float64())])
      +    schema = pa.schema(
      +        [
      +            pa.field("name", pa.string()),
      +            pa.field(
      +                "location", point, metadata={"ARROW:extension:name": "geoarrow.point"}
      +            ),
      +            pa.field("vector", pa.list_(pa.float32(), 2)),
      +        ]
      +    )
      +    places = [
      +        ("Ferry Building", -122.3937, 37.7955, [0.7, 0.3]),
      +        ("Golden Gate Park", -122.4862, 37.7694, [0.1, 0.9]),
      +        ("Oakland Museum", -122.2638, 37.7987, [1.0, 0.05]),
      +    ]
      +    data = pa.Table.from_pylist(
      +        [
      +            {"name": name, "location": {"x": x, "y": y}, "vector": vector}
      +            for name, x, y, vector in places
      +        ],
      +        schema=schema,
      +    )
      +    table = db.create_table("places", data)
      +    # --8<-- [end:scalar_index_rtree_data]
      +
      +    # --8<-- [start:scalar_index_rtree_create]
      +    from lancedb.index import RTree
      +
      +    table.create_index("location", config=RTree())
      +    # --8<-- [end:scalar_index_rtree_create]
      +
      +    # --8<-- [start:scalar_index_rtree_filter]
      +    san_francisco = (
      +        "ST_GeomFromText('POLYGON ((-122.52 37.70, -122.35 37.70, "
      +        "-122.35 37.83, -122.52 37.83, -122.52 37.70))')"
      +    )
      +    in_san_francisco = f"ST_Within(location, {san_francisco})"
      +
      +    places_in_sf = table.search().where(in_san_francisco).select(["name"]).to_list()
      +    # [{'name': 'Ferry Building'}, {'name': 'Golden Gate Park'}]
      +    # --8<-- [end:scalar_index_rtree_filter]
      +
      +    assert sorted(row["name"] for row in places_in_sf) == [
      +        "Ferry Building",
      +        "Golden Gate Park",
      +    ]
      +
      +    # --8<-- [start:scalar_index_rtree_vector]
      +    # The nearest place overall is in Oakland; the spatial prefilter keeps the
      +    # search inside San Francisco.
      +    nearest_in_sf = (
      +        table.search([1.0, 0.0])
      +        .where(in_san_francisco)
      +        .select(["name", "_distance"])
      +        .limit(1)
      +        .to_list()
      +    )
      +    # [{'name': 'Ferry Building', '_distance': 0.18}]
      +    # --8<-- [end:scalar_index_rtree_vector]
      +
      +    assert nearest_in_sf[0]["name"] == "Ferry Building"
      +    assert nearest_in_sf[0]["_distance"] == pytest.approx(0.18, abs=1e-6)
      +    nearest = table.search([1.0, 0.0]).select(["name", "_distance"]).limit(1)
      +    assert nearest.to_list()[0]["name"] == "Oakland Museum"
      +
      +    # --8<-- [start:scalar_index_rtree_explain]
      +    plan = table.search().where(in_san_francisco).explain_plan(verbose=True)
      +    assert "ScalarIndexQuery" in plan
      +    # --8<-- [end:scalar_index_rtree_explain]
      +
      +
       @pytest.mark.asyncio
       async def test_scalar_index_nested_fields(mem_db_async):
           db = mem_db_async
      diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx
      index 3d7b3a864..a3bf06957 100644
      --- a/docs/web/indexing/scalar-index.mdx
      +++ b/docs/web/indexing/scalar-index.mdx
      @@ -20,19 +20,25 @@ import {
           PyScalarIndexUuidWait as ScalarIndexUuidWait,
           PyScalarIndexUuidUpsert as ScalarIndexUuidUpsert,
           PyScalarIndexNestedFields as ScalarIndexNestedFields,
      +    PyScalarIndexRtreeData as ScalarIndexRtreeData,
      +    PyScalarIndexRtreeCreate as ScalarIndexRtreeCreate,
      +    PyScalarIndexRtreeFilter as ScalarIndexRtreeFilter,
      +    PyScalarIndexRtreeVector as ScalarIndexRtreeVector,
      +    PyScalarIndexRtreeExplain as ScalarIndexRtreeExplain,
       } from '/snippets/indexing.mdx';
       
       Scalar indexes accelerate filters on values such as numbers, categories and
       strings. Use them for selective table queries or metadata filters combined
       with vector and full-text search.
       
      -LanceDB supports five types of scalar indexes:
      +LanceDB supports these scalar index types, among others:
       
       - `BTREE`: Stores column data in sorted order for binary search. Best for columns with many unique values.
       - `BITMAP`: Uses bitmaps to track value presence. Ideal for columns with few unique values (e.g., categories, tags).
       - `LABEL_LIST`: Special index for `List` and `LargeList` columns of primitive values supporting `array_has_all` and `array_has_any` queries.
       - `FM`: FM-Index over string or binary columns that accelerates substring search via `contains(col, 'needle')`.
       - `NGRAM`: Trigram index over UTF-8 string columns that accelerates substring search via `contains(col, 'needle')`, along with some `LIKE` and regular-expression filters.
      +- `RTREE`: R-tree over GeoArrow geometry columns that accelerates spatial filters such as `ST_Intersects` and `ST_Within`.
       
       
       Use scalar indexes with:
      @@ -52,6 +58,7 @@ Use scalar indexes with:
       | List of low cardinality of numbers or strings                   | `array_has_any`, `array_has_all`          | `LABEL_LIST` |
       | String or binary (`Utf8`, `LargeUtf8`, `Binary`, `LargeBinary`) | `contains(col, 'needle')`                 | `FM`         |
       | String (`Utf8`, `LargeUtf8`)                                    | `contains(col, 'needle')`, `LIKE`, regex  | `NGRAM`      |
      +| GeoArrow geometry (`geoarrow.point`, `geoarrow.polygon`, `geoarrow.wkb`, ...) | `ST_Intersects`, `ST_Within`, `ST_Contains` and other spatial relationships, `is null` | `RTREE` |
       
       ## Scalar Index Operations
       
      @@ -222,6 +229,139 @@ before consolidating their segments. Consolidation rejects these legacy
       row-ID segments. Tables without stable row IDs retain the earlier index format.
       
       
      +## R-tree index for geospatial filters {#rtree}
      +
      +The `RTREE` index is a scalar index over a column of GeoArrow geometries. It
      +stores the bounding box of every geometry and accelerates spatial filters, on
      +their own or as the prefilter of a vector search. Use it when queries restrict
      +results to a region, such as the scenes over an area of interest, the places
      +inside a city, or the log records along a route.
      +
      +### Store geometry as GeoArrow {#rtree-geoarrow}
      +
      +A column holds geometry when its Arrow field carries GeoArrow extension
      +metadata: `ARROW:extension:name` names the geometry type, such as
      +`geoarrow.point`, `geoarrow.linestring`, `geoarrow.polygon` or
      +`geoarrow.multipolygon` for native coordinates, or `geoarrow.wkb` for
      +well-known binary. LanceDB keeps that metadata when it stores the column.
      +
      +You can build the field with PyArrow alone. A point is a struct of `x` and `y`
      +coordinates:
      +
      +
      +    
      +    {ScalarIndexRtreeData}
      +    
      +
      +
      +Libraries such as [`geoarrow-rust-core`](https://pypi.org/project/geoarrow-rust-core/)
      +(`geoarrow.rust.core`) produce arrays with this metadata already, so a table
      +built from them works the same way.
      +
      +### Create an R-tree index {#rtree-create}
      +
      +Pass the `RTree` config in Python, `Index.rtree()` in TypeScript, or
      +`Index::RTree` in Rust. The optional page size sets the maximum number of
      +entries in each R-tree page; it must be at least 2 and defaults to 4096.
      +
      +
      +    
      +    {ScalarIndexRtreeCreate}
      +    
      +
      +```typescript TypeScript icon="square-js"
      +import { Index } from "@lancedb/lancedb";
      +
      +await table.createIndex("location", { config: Index.rtree() });
      +```
      +
      +```rust Rust icon="rust"
      +use lancedb::index::Index;
      +use lancedb::index::scalar::RTreeIndexBuilder;
      +
      +table
      +    .create_index(&["location"], Index::RTree(RTreeIndexBuilder::default()))
      +    .execute()
      +    .await?;
      +```
      +
      +
      +`list_indices()` reports the index type as `"RTree"`, and `index_stats()`
      +reports it as `"RTREE"`. In the Rust crate, building the index on a local
      +table requires the `geo` feature; the Python and TypeScript packages include
      +it. In the embedded library, `optimize()` adds new rows to the index. Rows
      +that are not indexed yet are still filtered, just without the index.
      +
      +### Filter with spatial predicates {#rtree-filter}
      +
      +Spatial predicates go in `where()` like any other filter. Build constant
      +geometries with `ST_GeomFromText('')` or `ST_Point(x, y)`:
      +
      +
      +    
      +    {ScalarIndexRtreeFilter}
      +    
      +
      +
      +The index answers `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`,
      +`ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` between the
      +indexed column and a constant geometry, in either argument order, as well as
      +`IS NULL` on the column. A spatial predicate combined
      +with other conditions through `AND` still uses the index; one combined through
      +`OR` with a condition on an unindexed column does not.
      +
      +The R-tree compares bounding boxes, so it returns a superset of the answer:
      +every row whose bounding box overlaps the query geometry's bounding box. LanceDB
      +then evaluates the exact predicate on those candidate rows, so the results are
      +the same with or without the index. A point just outside a triangle but inside
      +the triangle's bounding box is read, then discarded.
      +
      +Other spatial functions, such as `ST_Distance(location, ST_Point(x, y)) < d`
      +for a radius filter, work in filters but are evaluated row by row, without the
      +index. `ST_DWithin` is not available. To use the index for a radius filter,
      +pair the distance check with an indexed predicate on a bounding polygon:
      +`ST_Intersects(location, ) AND ST_Distance(location, 
      ) < d`. + +Spatial functions are planar: they treat coordinates as points on a flat +plane, and `ST_Distance` returns a distance in the units of the column's +coordinates. For longitude and latitude, `d` is in degrees, not meters, and a +degree of longitude shrinks toward the poles. Project the data to a metric +coordinate system first if you need distances in meters. + +### Combine with vector search {#rtree-vector-search} + +A spatial filter on a vector search is a prefilter by default: the R-tree +narrows the candidates first, and the nearest neighbors are found among the +rows that match. + + + + {ScalarIndexRtreeVector} + + + +With `prefilter=False` in Python, or `postfilter()` in TypeScript, the filter +is applied to the nearest neighbors instead, without the index, so it can +return fewer rows than the limit. + +### Check that the index is used {#rtree-explain} + +An indexed spatial filter appears as a `ScalarIndexQuery` on the R-tree in the +query plan: + + + + {ScalarIndexRtreeExplain} + + + + +On a remote table, `create_index` sends the request with the `RTREE` index +type, and spatial filters are sent to the server as written. Whether the +server can build the index and evaluate `ST_*` functions depends on its +version. + + ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. diff --git a/docs/web/snippets/indexing.mdx b/docs/web/snippets/indexing.mdx index dfa43b6ce..bd3b7af7f 100644 --- a/docs/web/snippets/indexing.mdx +++ b/docs/web/snippets/indexing.mdx @@ -26,6 +26,16 @@ export const PyScalarIndexOptimize = "table.add([{\"vector\": [7, 8], \"book_id\ export const PyScalarIndexPrefilter = "table = db.open_table(\"book_with_embeddings\")\ntable.search([1.2] * 2).where(\"book_id != 3\").limit(10).to_pandas()\n"; +export const PyScalarIndexRtreeCreate = "from lancedb.index import RTree\n\ntable.create_index(\"location\", config=RTree())\n"; + +export const PyScalarIndexRtreeData = "import pyarrow as pa\n\npoint = pa.struct([(\"x\", pa.float64()), (\"y\", pa.float64())])\nschema = pa.schema(\n [\n pa.field(\"name\", pa.string()),\n pa.field(\n \"location\", point, metadata={\"ARROW:extension:name\": \"geoarrow.point\"}\n ),\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n ]\n)\nplaces = [\n (\"Ferry Building\", -122.3937, 37.7955, [0.7, 0.3]),\n (\"Golden Gate Park\", -122.4862, 37.7694, [0.1, 0.9]),\n (\"Oakland Museum\", -122.2638, 37.7987, [1.0, 0.05]),\n]\ndata = pa.Table.from_pylist(\n [\n {\"name\": name, \"location\": {\"x\": x, \"y\": y}, \"vector\": vector}\n for name, x, y, vector in places\n ],\n schema=schema,\n)\ntable = db.create_table(\"places\", data)\n"; + +export const PyScalarIndexRtreeExplain = "plan = table.search().where(in_san_francisco).explain_plan(verbose=True)\nassert \"ScalarIndexQuery\" in plan\n"; + +export const PyScalarIndexRtreeFilter = "san_francisco = (\n \"ST_GeomFromText('POLYGON ((-122.52 37.70, -122.35 37.70, \"\n \"-122.35 37.83, -122.52 37.83, -122.52 37.70))')\"\n)\nin_san_francisco = f\"ST_Within(location, {san_francisco})\"\n\nplaces_in_sf = table.search().where(in_san_francisco).select([\"name\"]).to_list()\n# [{'name': 'Ferry Building'}, {'name': 'Golden Gate Park'}]\n"; + +export const PyScalarIndexRtreeVector = "# The nearest place overall is in Oakland; the spatial prefilter keeps the\n# search inside San Francisco.\nnearest_in_sf = (\n table.search([1.0, 0.0])\n .where(in_san_francisco)\n .select([\"name\", \"_distance\"])\n .limit(1)\n .to_list()\n)\n# [{'name': 'Ferry Building', '_distance': 0.18}]\n"; + export const PyScalarIndexUuidData = "def generate_random_names():\n base_names = [\"Alice\", \"Bob\", \"Carla\", \"David\", \"Eve\", \"Frank\", \"Grace\"]\n letter = random.choice(string.ascii_uppercase)\n return f\"{random.choice(base_names)} {letter}.\"\n\ndef generate_uuids(num_items):\n return [uuid.uuid4().bytes for _ in range(num_items)]\n\n# Generate some UUIDs and random names\nn = 7\nuuids = generate_uuids(n)\nnames = [generate_random_names() for _ in range(n)]\n"; export const PyScalarIndexUuidTable = "table_name = \"index-on-uuid\"\n\nuuid_array = pa.array(uuids, pa.uuid())\nname_array = pa.array(names, pa.string())\nschema = pa.schema(\n [\n pa.field(\"id\", pa.uuid()),\n pa.field(\"name\", pa.string()),\n ]\n)\ndata_table = pa.Table.from_arrays([uuid_array, name_array], schema=schema)\ntable = db.create_table(table_name, data=data_table, mode=\"overwrite\")\n"; diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 6de370ef1..540d53c04 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -46,7 +46,7 @@ aws-lc-rs = "=1.18.1" napi-build = "2.3.1" [features] -default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel"] +default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"] fp16kernels = ["lancedb/fp16kernels"] remote = ["lancedb/remote"] experimental-functions = ["lancedb/experimental-functions"] diff --git a/nodejs/RUST_THIRD_PARTY_LICENSES.html b/nodejs/RUST_THIRD_PARTY_LICENSES.html index 461fb2715..d9ca180c5 100644 --- a/nodejs/RUST_THIRD_PARTY_LICENSES.html +++ b/nodejs/RUST_THIRD_PARTY_LICENSES.html @@ -44,19 +44,19 @@

      Overview of licenses:

      All license text:

      @@ -65,230 +65,20 @@

      BSD Zero Clause License

      Used by:

      -
      Copyright (C) 2020 by museun <museun@outlook.com>
      +                
      Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
       
      -Permission to use, copy, modify, and/or distribute this software for any purpose
      -with or without fee is hereby granted.
      +Permission to use, copy, modify, and/or distribute this software for
      +any purpose with or without fee is hereby granted.
       
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
      -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
      -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
      -THIS SOFTWARE.
      -
      -
    • -
    • -

      Apache License 2.0

      -

      Used by:

      - -
      -                                 Apache License
      -                           Version 2.0, January 2004
      -                        http://www.apache.org/licenses/
      -
      -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      -
      -   1. Definitions.
      -
      -      "License" shall mean the terms and conditions for use, reproduction,
      -      and distribution as defined by Sections 1 through 9 of this document.
      -
      -      "Licensor" shall mean the copyright owner or entity authorized by
      -      the copyright owner that is granting the License.
      -
      -      "Legal Entity" shall mean the union of the acting entity and all
      -      other entities that control, are controlled by, or are under common
      -      control with that entity. For the purposes of this definition,
      -      "control" means (i) the power, direct or indirect, to cause the
      -      direction or management of such entity, whether by contract or
      -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      -      outstanding shares, or (iii) beneficial ownership of such entity.
      -
      -      "You" (or "Your") shall mean an individual or Legal Entity
      -      exercising permissions granted by this License.
      -
      -      "Source" form shall mean the preferred form for making modifications,
      -      including but not limited to software source code, documentation
      -      source, and configuration files.
      -
      -      "Object" form shall mean any form resulting from mechanical
      -      transformation or translation of a Source form, including but
      -      not limited to compiled object code, generated documentation,
      -      and conversions to other media types.
      -
      -      "Work" shall mean the work of authorship, whether in Source or
      -      Object form, made available under the License, as indicated by a
      -      copyright notice that is included in or attached to the work
      -      (an example is provided in the Appendix below).
      -
      -      "Derivative Works" shall mean any work, whether in Source or Object
      -      form, that is based on (or derived from) the Work and for which the
      -      editorial revisions, annotations, elaborations, or other modifications
      -      represent, as a whole, an original work of authorship. For the purposes
      -      of this License, Derivative Works shall not include works that remain
      -      separable from, or merely link (or bind by name) to the interfaces of,
      -      the Work and Derivative Works thereof.
      -
      -      "Contribution" shall mean any work of authorship, including
      -      the original version of the Work and any modifications or additions
      -      to that Work or Derivative Works thereof, that is intentionally
      -      submitted to Licensor for inclusion in the Work by the copyright owner
      -      or by an individual or Legal Entity authorized to submit on behalf of
      -      the copyright owner. For the purposes of this definition, "submitted"
      -      means any form of electronic, verbal, or written communication sent
      -      to the Licensor or its representatives, including but not limited to
      -      communication on electronic mailing lists, source code control systems,
      -      and issue tracking systems that are managed by, or on behalf of, the
      -      Licensor for the purpose of discussing and improving the Work, but
      -      excluding communication that is conspicuously marked or otherwise
      -      designated in writing by the copyright owner as "Not a Contribution."
      -
      -      "Contributor" shall mean Licensor and any individual or Legal Entity
      -      on behalf of whom a Contribution has been received by Licensor and
      -      subsequently incorporated within the Work.
      -
      -   2. Grant of Copyright License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      copyright license to reproduce, prepare Derivative Works of,
      -      publicly display, publicly perform, sublicense, and distribute the
      -      Work and such Derivative Works in Source or Object form.
      -
      -   3. Grant of Patent License. Subject to the terms and conditions of
      -      this License, each Contributor hereby grants to You a perpetual,
      -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      -      (except as stated in this section) patent license to make, have made,
      -      use, offer to sell, sell, import, and otherwise transfer the Work,
      -      where such license applies only to those patent claims licensable
      -      by such Contributor that are necessarily infringed by their
      -      Contribution(s) alone or by combination of their Contribution(s)
      -      with the Work to which such Contribution(s) was submitted. If You
      -      institute patent litigation against any entity (including a
      -      cross-claim or counterclaim in a lawsuit) alleging that the Work
      -      or a Contribution incorporated within the Work constitutes direct
      -      or contributory patent infringement, then any patent licenses
      -      granted to You under this License for that Work shall terminate
      -      as of the date such litigation is filed.
      -
      -   4. Redistribution. You may reproduce and distribute copies of the
      -      Work or Derivative Works thereof in any medium, with or without
      -      modifications, and in Source or Object form, provided that You
      -      meet the following conditions:
      -
      -      (a) You must give any other recipients of the Work or
      -          Derivative Works a copy of this License; and
      -
      -      (b) You must cause any modified files to carry prominent notices
      -          stating that You changed the files; and
      -
      -      (c) You must retain, in the Source form of any Derivative Works
      -          that You distribute, all copyright, patent, trademark, and
      -          attribution notices from the Source form of the Work,
      -          excluding those notices that do not pertain to any part of
      -          the Derivative Works; and
      -
      -      (d) If the Work includes a "NOTICE" text file as part of its
      -          distribution, then any Derivative Works that You distribute must
      -          include a readable copy of the attribution notices contained
      -          within such NOTICE file, excluding those notices that do not
      -          pertain to any part of the Derivative Works, in at least one
      -          of the following places: within a NOTICE text file distributed
      -          as part of the Derivative Works; within the Source form or
      -          documentation, if provided along with the Derivative Works; or,
      -          within a display generated by the Derivative Works, if and
      -          wherever such third-party notices normally appear. The contents
      -          of the NOTICE file are for informational purposes only and
      -          do not modify the License. You may add Your own attribution
      -          notices within Derivative Works that You distribute, alongside
      -          or as an addendum to the NOTICE text from the Work, provided
      -          that such additional attribution notices cannot be construed
      -          as modifying the License.
      -
      -      You may add Your own copyright statement to Your modifications and
      -      may provide additional or different license terms and conditions
      -      for use, reproduction, or distribution of Your modifications, or
      -      for any such Derivative Works as a whole, provided Your use,
      -      reproduction, and distribution of the Work otherwise complies with
      -      the conditions stated in this License.
      -
      -   5. Submission of Contributions. Unless You explicitly state otherwise,
      -      any Contribution intentionally submitted for inclusion in the Work
      -      by You to the Licensor shall be under the terms and conditions of
      -      this License, without any additional terms or conditions.
      -      Notwithstanding the above, nothing herein shall supersede or modify
      -      the terms of any separate license agreement you may have executed
      -      with Licensor regarding such Contributions.
      -
      -   6. Trademarks. This License does not grant permission to use the trade
      -      names, trademarks, service marks, or product names of the Licensor,
      -      except as required for reasonable and customary use in describing the
      -      origin of the Work and reproducing the content of the NOTICE file.
      -
      -   7. Disclaimer of Warranty. Unless required by applicable law or
      -      agreed to in writing, Licensor provides the Work (and each
      -      Contributor provides its Contributions) on an "AS IS" BASIS,
      -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      -      implied, including, without limitation, any warranties or conditions
      -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      -      PARTICULAR PURPOSE. You are solely responsible for determining the
      -      appropriateness of using or redistributing the Work and assume any
      -      risks associated with Your exercise of permissions under this License.
      -
      -   8. Limitation of Liability. In no event and under no legal theory,
      -      whether in tort (including negligence), contract, or otherwise,
      -      unless required by applicable law (such as deliberate and grossly
      -      negligent acts) or agreed to in writing, shall any Contributor be
      -      liable to You for damages, including any direct, indirect, special,
      -      incidental, or consequential damages of any character arising as a
      -      result of this License or out of the use or inability to use the
      -      Work (including but not limited to damages for loss of goodwill,
      -      work stoppage, computer failure or malfunction, or any and all
      -      other commercial damages or losses), even if such Contributor
      -      has been advised of the possibility of such damages.
      -
      -   9. Accepting Warranty or Additional Liability. While redistributing
      -      the Work or Derivative Works thereof, You may choose to offer,
      -      and charge a fee for, acceptance of support, warranty, indemnity,
      -      or other liability obligations and/or rights consistent with this
      -      License. However, in accepting such obligations, You may act only
      -      on Your own behalf and on Your sole responsibility, not on behalf
      -      of any other Contributor, and only if You agree to indemnify,
      -      defend, and hold each Contributor harmless for any liability
      -      incurred by, or claims asserted against, such Contributor by reason
      -      of your accepting any such warranty or additional liability.
      -
      -   END OF TERMS AND CONDITIONS
      -
      -   APPENDIX: How to apply the Apache License to your work.
      -
      -      To apply the Apache License to your work, attach the following
      -      boilerplate notice, with the fields enclosed by brackets "[]"
      -      replaced with your own identifying information. (Don't include
      -      the brackets!)  The text should be enclosed in the appropriate
      -      comment syntax for the file format. We also recommend that a
      -      file or class name and description of purpose be included on the
      -      same "printed page" as the copyright notice for easier
      -      identification within third-party archives.
      -
      -   Copyright 2023 Jacob Pratt
      -
      -   Licensed under the Apache License, Version 2.0 (the "License");
      -   you may not use this file except in compliance with the License.
      -   You may obtain a copy of the License at
      -
      -       http://www.apache.org/licenses/LICENSE-2.0
      -
      -   Unless required by applicable law or agreed to in writing, software
      -   distributed under the License is distributed on an "AS IS" BASIS,
      -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      -   See the License for the specific language governing permissions and
      -   limitations under the License.
      +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
      +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
      +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
      +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
       
    • @@ -505,7 +295,7 @@ THIS SOFTWARE.

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -715,23 +505,224 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

      +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + @@ -943,7 +934,8 @@ THIS SOFTWARE.

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1155,34 +1147,549 @@ THIS SOFTWARE.
                       

      Apache License 2.0

      Used by:

      +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +--- LLVM Exceptions to the Apache 2.0 License ----
      +
      +As an exception, if, as a result of your compiling your source code, portions
      +of this Software are embedded into an Object form of such source code, you
      +may redistribute such embedded portions in such Object form without complying
      +with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
      +
      +In addition, if you combine or link compiled forms of this Software with
      +software that is licensed under the GPLv2 ("Combined Software") and if a
      +court of competent jurisdiction determines that the patent provision (Section
      +3), the indemnity provision (Section 9) or other Section of the License
      +conflicts with the conditions of the GPLv2, you may retroactively and
      +prospectively choose to deem waived or otherwise exclude such Section(s) of
      +the License, but only in their entirety and only with respect to the Combined
      +Software.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +Licenses for support code
      +-------------------------
      +
      +Parts of the TLS test suite are under the Go license. This code is not included
      +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
      +distributing code linked against BoringSSL does not trigger this license:
      +
      +Copyright (c) 2009 The Go Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
      +BoringSSL uses the Chromium test infrastructure to run a continuous build,
      +trybots etc. The scripts which manage this, and the script for generating build
      +metadata, are under the Chromium license. Distributing code linked against
      +BoringSSL does not trigger this license.
      +
      +Copyright 2015 The Chromium Authors. All rights reserved.
      +
      +Redistribution and use in source and binary forms, with or without
      +modification, are permitted provided that the following conditions are
      +met:
      +
      +   * Redistributions of source code must retain the above copyright
      +notice, this list of conditions and the following disclaimer.
      +   * Redistributions in binary form must reproduce the above
      +copyright notice, this list of conditions and the following disclaimer
      +in the documentation and/or other materials provided with the
      +distribution.
      +   * Neither the name of Google Inc. nor the names of its
      +contributors may be used to endorse or promote products derived from
      +this software without specific prior written permission.
      +
      +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                        Apache License
      @@ -1396,6 +1903,237 @@ This project includes code from Apache Aurora.
       Copyright: 2016 The Apache Software Foundation.
       Home page: https://aurora.apache.org/
       License: http://www.apache.org/licenses/LICENSE-2.0
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
      +                                 Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +--------------------------------------------------------------------------------
      +
      +arrow-array/src/delta.rs: MIT
      +
      +This file is derived from the chronoutil crate. The full MIT license
      +text is in arrow-array/LICENSE-MIT.
       
    • @@ -1403,9 +2141,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

      Used by:

                                        Apache License
      @@ -1615,7 +2351,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                        Apache License
      @@ -1815,7 +2551,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Used by:

                                        Apache License
      @@ -2025,41 +2760,30 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2268,7 +2992,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2477,7 +3201,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2667,7 +3392,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
             same "printed page" as the copyright notice for easier
             identification within third-party archives.
       
      -   Copyright 2020 - 2025 Tatsuya Kawano
      +   Copyright 2019 TiKV Project Authors.
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 - 2026 Tatsuya Kawano
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
       
          Licensed under the Apache License, Version 2.0 (the "License");
          you may not use this file except in compliance with the License.
      @@ -2687,7 +3830,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -2895,8 +4037,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3315,7 +4457,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3524,9 +4666,20 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -3735,7 +4888,455 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +------------------------------------------------------------------------------------
      +This product bundles third-party components under other open source licenses.
      +This section summarizes those components and their licenses. See the referenced
      +license files for text of these licenses.
      +
      +
      +Creative Commons Zero v1.0 Universal
      +------------------------------------
      +
      +bindings/dotnet/.gitignore
      +
      +The above file is derived from VisualStudio.gitignore in
      +https://github.com/github/gitignore. Its license text is in
      +bindings/dotnet/LICENSE-CC0-1.0.txt.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright [yyyy] [name of copyright owner]
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +   
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
                                  Version 2.0, January 2004
      @@ -3944,6 +5545,218 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "{}"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright Individual contributors
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                       Apache License
      @@ -4153,22 +5966,28 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                       Apache License
                                  Version 2.0, January 2004
      @@ -4378,12 +6197,221 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

      +
                                       Apache License
      +                           Version 2.0, January 2004
      +                        http://www.apache.org/licenses/
      +
      +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +   1. Definitions.
      +
      +      "License" shall mean the terms and conditions for use, reproduction,
      +      and distribution as defined by Sections 1 through 9 of this document.
      +
      +      "Licensor" shall mean the copyright owner or entity authorized by
      +      the copyright owner that is granting the License.
      +
      +      "Legal Entity" shall mean the union of the acting entity and all
      +      other entities that control, are controlled by, or are under common
      +      control with that entity. For the purposes of this definition,
      +      "control" means (i) the power, direct or indirect, to cause the
      +      direction or management of such entity, whether by contract or
      +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +      outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +      "You" (or "Your") shall mean an individual or Legal Entity
      +      exercising permissions granted by this License.
      +
      +      "Source" form shall mean the preferred form for making modifications,
      +      including but not limited to software source code, documentation
      +      source, and configuration files.
      +
      +      "Object" form shall mean any form resulting from mechanical
      +      transformation or translation of a Source form, including but
      +      not limited to compiled object code, generated documentation,
      +      and conversions to other media types.
      +
      +      "Work" shall mean the work of authorship, whether in Source or
      +      Object form, made available under the License, as indicated by a
      +      copyright notice that is included in or attached to the work
      +      (an example is provided in the Appendix below).
      +
      +      "Derivative Works" shall mean any work, whether in Source or Object
      +      form, that is based on (or derived from) the Work and for which the
      +      editorial revisions, annotations, elaborations, or other modifications
      +      represent, as a whole, an original work of authorship. For the purposes
      +      of this License, Derivative Works shall not include works that remain
      +      separable from, or merely link (or bind by name) to the interfaces of,
      +      the Work and Derivative Works thereof.
      +
      +      "Contribution" shall mean any work of authorship, including
      +      the original version of the Work and any modifications or additions
      +      to that Work or Derivative Works thereof, that is intentionally
      +      submitted to Licensor for inclusion in the Work by the copyright owner
      +      or by an individual or Legal Entity authorized to submit on behalf of
      +      the copyright owner. For the purposes of this definition, "submitted"
      +      means any form of electronic, verbal, or written communication sent
      +      to the Licensor or its representatives, including but not limited to
      +      communication on electronic mailing lists, source code control systems,
      +      and issue tracking systems that are managed by, or on behalf of, the
      +      Licensor for the purpose of discussing and improving the Work, but
      +      excluding communication that is conspicuously marked or otherwise
      +      designated in writing by the copyright owner as "Not a Contribution."
      +
      +      "Contributor" shall mean Licensor and any individual or Legal Entity
      +      on behalf of whom a Contribution has been received by Licensor and
      +      subsequently incorporated within the Work.
      +
      +   2. Grant of Copyright License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      copyright license to reproduce, prepare Derivative Works of,
      +      publicly display, publicly perform, sublicense, and distribute the
      +      Work and such Derivative Works in Source or Object form.
      +
      +   3. Grant of Patent License. Subject to the terms and conditions of
      +      this License, each Contributor hereby grants to You a perpetual,
      +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +      (except as stated in this section) patent license to make, have made,
      +      use, offer to sell, sell, import, and otherwise transfer the Work,
      +      where such license applies only to those patent claims licensable
      +      by such Contributor that are necessarily infringed by their
      +      Contribution(s) alone or by combination of their Contribution(s)
      +      with the Work to which such Contribution(s) was submitted. If You
      +      institute patent litigation against any entity (including a
      +      cross-claim or counterclaim in a lawsuit) alleging that the Work
      +      or a Contribution incorporated within the Work constitutes direct
      +      or contributory patent infringement, then any patent licenses
      +      granted to You under this License for that Work shall terminate
      +      as of the date such litigation is filed.
      +
      +   4. Redistribution. You may reproduce and distribute copies of the
      +      Work or Derivative Works thereof in any medium, with or without
      +      modifications, and in Source or Object form, provided that You
      +      meet the following conditions:
      +
      +      (a) You must give any other recipients of the Work or
      +          Derivative Works a copy of this License; and
      +
      +      (b) You must cause any modified files to carry prominent notices
      +          stating that You changed the files; and
      +
      +      (c) You must retain, in the Source form of any Derivative Works
      +          that You distribute, all copyright, patent, trademark, and
      +          attribution notices from the Source form of the Work,
      +          excluding those notices that do not pertain to any part of
      +          the Derivative Works; and
      +
      +      (d) If the Work includes a "NOTICE" text file as part of its
      +          distribution, then any Derivative Works that You distribute must
      +          include a readable copy of the attribution notices contained
      +          within such NOTICE file, excluding those notices that do not
      +          pertain to any part of the Derivative Works, in at least one
      +          of the following places: within a NOTICE text file distributed
      +          as part of the Derivative Works; within the Source form or
      +          documentation, if provided along with the Derivative Works; or,
      +          within a display generated by the Derivative Works, if and
      +          wherever such third-party notices normally appear. The contents
      +          of the NOTICE file are for informational purposes only and
      +          do not modify the License. You may add Your own attribution
      +          notices within Derivative Works that You distribute, alongside
      +          or as an addendum to the NOTICE text from the Work, provided
      +          that such additional attribution notices cannot be construed
      +          as modifying the License.
      +
      +      You may add Your own copyright statement to Your modifications and
      +      may provide additional or different license terms and conditions
      +      for use, reproduction, or distribution of Your modifications, or
      +      for any such Derivative Works as a whole, provided Your use,
      +      reproduction, and distribution of the Work otherwise complies with
      +      the conditions stated in this License.
      +
      +   5. Submission of Contributions. Unless You explicitly state otherwise,
      +      any Contribution intentionally submitted for inclusion in the Work
      +      by You to the Licensor shall be under the terms and conditions of
      +      this License, without any additional terms or conditions.
      +      Notwithstanding the above, nothing herein shall supersede or modify
      +      the terms of any separate license agreement you may have executed
      +      with Licensor regarding such Contributions.
      +
      +   6. Trademarks. This License does not grant permission to use the trade
      +      names, trademarks, service marks, or product names of the Licensor,
      +      except as required for reasonable and customary use in describing the
      +      origin of the Work and reproducing the content of the NOTICE file.
      +
      +   7. Disclaimer of Warranty. Unless required by applicable law or
      +      agreed to in writing, Licensor provides the Work (and each
      +      Contributor provides its Contributions) on an "AS IS" BASIS,
      +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +      implied, including, without limitation, any warranties or conditions
      +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +      PARTICULAR PURPOSE. You are solely responsible for determining the
      +      appropriateness of using or redistributing the Work and assume any
      +      risks associated with Your exercise of permissions under this License.
      +
      +   8. Limitation of Liability. In no event and under no legal theory,
      +      whether in tort (including negligence), contract, or otherwise,
      +      unless required by applicable law (such as deliberate and grossly
      +      negligent acts) or agreed to in writing, shall any Contributor be
      +      liable to You for damages, including any direct, indirect, special,
      +      incidental, or consequential damages of any character arising as a
      +      result of this License or out of the use or inability to use the
      +      Work (including but not limited to damages for loss of goodwill,
      +      work stoppage, computer failure or malfunction, or any and all
      +      other commercial damages or losses), even if such Contributor
      +      has been advised of the possibility of such damages.
      +
      +   9. Accepting Warranty or Additional Liability. While redistributing
      +      the Work or Derivative Works thereof, You may choose to offer,
      +      and charge a fee for, acceptance of support, warranty, indemnity,
      +      or other liability obligations and/or rights consistent with this
      +      License. However, in accepting such obligations, You may act only
      +      on Your own behalf and on Your sole responsibility, not on behalf
      +      of any other Contributor, and only if You agree to indemnify,
      +      defend, and hold each Contributor harmless for any liability
      +      incurred by, or claims asserted against, such Contributor by reason
      +      of your accepting any such warranty or additional liability.
      +
      +   END OF TERMS AND CONDITIONS
      +
      +   APPENDIX: How to apply the Apache License to your work.
      +
      +      To apply the Apache License to your work, attach the following
      +      boilerplate notice, with the fields enclosed by brackets "[]"
      +      replaced with your own identifying information. (Don't include
      +      the brackets!)  The text should be enclosed in the appropriate
      +      comment syntax for the file format. We also recommend that a
      +      file or class name and description of purpose be included on the
      +      same "printed page" as the copyright notice for easier
      +      identification within third-party archives.
      +
      +   Copyright 2020 Sébastien Crozet
      +
      +   Licensed under the Apache License, Version 2.0 (the "License");
      +   you may not use this file except in compliance with the License.
      +   You may obtain a copy of the License at
      +
      +       http://www.apache.org/licenses/LICENSE-2.0
      +
      +   Unless required by applicable law or agreed to in writing, software
      +   distributed under the License is distributed on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +   See the License for the specific language governing permissions and
      +   limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                      Apache License
                                  Version 2.0, January 2004
      @@ -4593,7 +6621,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                       

      Apache License 2.0

      Used by:

                                     Apache License
                                  Version 2.0, January 2004
      @@ -5011,15 +7039,15 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5229,7 +7257,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5437,7 +7465,8 @@ limitations under the License.

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5646,8 +7675,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -5856,7 +7884,6 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
      @@ -6066,7 +8093,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6256,7 +8283,7 @@ APPENDIX: How to apply the Apache License to your work.
          same "printed page" as the copyright notice for easier
          identification within third-party archives.
       
      -Copyright 2018 The pin-utils authors
      +Copyright 2018 Brian Myers
       
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
      @@ -6275,8 +8302,8 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6683,6 +8710,215 @@ You may obtain a copy of the License at
       
          http://www.apache.org/licenses/LICENSE-2.0
       
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      + +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2019 quininer kel
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      @@ -6695,7 +8931,9 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -6905,7 +9143,7 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7323,7 +9561,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7532,7 +9770,7 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -7743,7 +9981,216 @@ limitations under the License.
                       

      Apache License 2.0

      Used by:

      +
                                    Apache License
      +                        Version 2.0, January 2004
      +                     http://www.apache.org/licenses/
      +
      +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
      +
      +1. Definitions.
      +
      +   "License" shall mean the terms and conditions for use, reproduction,
      +   and distribution as defined by Sections 1 through 9 of this document.
      +
      +   "Licensor" shall mean the copyright owner or entity authorized by
      +   the copyright owner that is granting the License.
      +
      +   "Legal Entity" shall mean the union of the acting entity and all
      +   other entities that control, are controlled by, or are under common
      +   control with that entity. For the purposes of this definition,
      +   "control" means (i) the power, direct or indirect, to cause the
      +   direction or management of such entity, whether by contract or
      +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
      +   outstanding shares, or (iii) beneficial ownership of such entity.
      +
      +   "You" (or "Your") shall mean an individual or Legal Entity
      +   exercising permissions granted by this License.
      +
      +   "Source" form shall mean the preferred form for making modifications,
      +   including but not limited to software source code, documentation
      +   source, and configuration files.
      +
      +   "Object" form shall mean any form resulting from mechanical
      +   transformation or translation of a Source form, including but
      +   not limited to compiled object code, generated documentation,
      +   and conversions to other media types.
      +
      +   "Work" shall mean the work of authorship, whether in Source or
      +   Object form, made available under the License, as indicated by a
      +   copyright notice that is included in or attached to the work
      +   (an example is provided in the Appendix below).
      +
      +   "Derivative Works" shall mean any work, whether in Source or Object
      +   form, that is based on (or derived from) the Work and for which the
      +   editorial revisions, annotations, elaborations, or other modifications
      +   represent, as a whole, an original work of authorship. For the purposes
      +   of this License, Derivative Works shall not include works that remain
      +   separable from, or merely link (or bind by name) to the interfaces of,
      +   the Work and Derivative Works thereof.
      +
      +   "Contribution" shall mean any work of authorship, including
      +   the original version of the Work and any modifications or additions
      +   to that Work or Derivative Works thereof, that is intentionally
      +   submitted to Licensor for inclusion in the Work by the copyright owner
      +   or by an individual or Legal Entity authorized to submit on behalf of
      +   the copyright owner. For the purposes of this definition, "submitted"
      +   means any form of electronic, verbal, or written communication sent
      +   to the Licensor or its representatives, including but not limited to
      +   communication on electronic mailing lists, source code control systems,
      +   and issue tracking systems that are managed by, or on behalf of, the
      +   Licensor for the purpose of discussing and improving the Work, but
      +   excluding communication that is conspicuously marked or otherwise
      +   designated in writing by the copyright owner as "Not a Contribution."
      +
      +   "Contributor" shall mean Licensor and any individual or Legal Entity
      +   on behalf of whom a Contribution has been received by Licensor and
      +   subsequently incorporated within the Work.
      +
      +2. Grant of Copyright License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   copyright license to reproduce, prepare Derivative Works of,
      +   publicly display, publicly perform, sublicense, and distribute the
      +   Work and such Derivative Works in Source or Object form.
      +
      +3. Grant of Patent License. Subject to the terms and conditions of
      +   this License, each Contributor hereby grants to You a perpetual,
      +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      +   (except as stated in this section) patent license to make, have made,
      +   use, offer to sell, sell, import, and otherwise transfer the Work,
      +   where such license applies only to those patent claims licensable
      +   by such Contributor that are necessarily infringed by their
      +   Contribution(s) alone or by combination of their Contribution(s)
      +   with the Work to which such Contribution(s) was submitted. If You
      +   institute patent litigation against any entity (including a
      +   cross-claim or counterclaim in a lawsuit) alleging that the Work
      +   or a Contribution incorporated within the Work constitutes direct
      +   or contributory patent infringement, then any patent licenses
      +   granted to You under this License for that Work shall terminate
      +   as of the date such litigation is filed.
      +
      +4. Redistribution. You may reproduce and distribute copies of the
      +   Work or Derivative Works thereof in any medium, with or without
      +   modifications, and in Source or Object form, provided that You
      +   meet the following conditions:
      +
      +   (a) You must give any other recipients of the Work or
      +       Derivative Works a copy of this License; and
      +
      +   (b) You must cause any modified files to carry prominent notices
      +       stating that You changed the files; and
      +
      +   (c) You must retain, in the Source form of any Derivative Works
      +       that You distribute, all copyright, patent, trademark, and
      +       attribution notices from the Source form of the Work,
      +       excluding those notices that do not pertain to any part of
      +       the Derivative Works; and
      +
      +   (d) If the Work includes a "NOTICE" text file as part of its
      +       distribution, then any Derivative Works that You distribute must
      +       include a readable copy of the attribution notices contained
      +       within such NOTICE file, excluding those notices that do not
      +       pertain to any part of the Derivative Works, in at least one
      +       of the following places: within a NOTICE text file distributed
      +       as part of the Derivative Works; within the Source form or
      +       documentation, if provided along with the Derivative Works; or,
      +       within a display generated by the Derivative Works, if and
      +       wherever such third-party notices normally appear. The contents
      +       of the NOTICE file are for informational purposes only and
      +       do not modify the License. You may add Your own attribution
      +       notices within Derivative Works that You distribute, alongside
      +       or as an addendum to the NOTICE text from the Work, provided
      +       that such additional attribution notices cannot be construed
      +       as modifying the License.
      +
      +   You may add Your own copyright statement to Your modifications and
      +   may provide additional or different license terms and conditions
      +   for use, reproduction, or distribution of Your modifications, or
      +   for any such Derivative Works as a whole, provided Your use,
      +   reproduction, and distribution of the Work otherwise complies with
      +   the conditions stated in this License.
      +
      +5. Submission of Contributions. Unless You explicitly state otherwise,
      +   any Contribution intentionally submitted for inclusion in the Work
      +   by You to the Licensor shall be under the terms and conditions of
      +   this License, without any additional terms or conditions.
      +   Notwithstanding the above, nothing herein shall supersede or modify
      +   the terms of any separate license agreement you may have executed
      +   with Licensor regarding such Contributions.
      +
      +6. Trademarks. This License does not grant permission to use the trade
      +   names, trademarks, service marks, or product names of the Licensor,
      +   except as required for reasonable and customary use in describing the
      +   origin of the Work and reproducing the content of the NOTICE file.
      +
      +7. Disclaimer of Warranty. Unless required by applicable law or
      +   agreed to in writing, Licensor provides the Work (and each
      +   Contributor provides its Contributions) on an "AS IS" BASIS,
      +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      +   implied, including, without limitation, any warranties or conditions
      +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      +   PARTICULAR PURPOSE. You are solely responsible for determining the
      +   appropriateness of using or redistributing the Work and assume any
      +   risks associated with Your exercise of permissions under this License.
      +
      +8. Limitation of Liability. In no event and under no legal theory,
      +   whether in tort (including negligence), contract, or otherwise,
      +   unless required by applicable law (such as deliberate and grossly
      +   negligent acts) or agreed to in writing, shall any Contributor be
      +   liable to You for damages, including any direct, indirect, special,
      +   incidental, or consequential damages of any character arising as a
      +   result of this License or out of the use or inability to use the
      +   Work (including but not limited to damages for loss of goodwill,
      +   work stoppage, computer failure or malfunction, or any and all
      +   other commercial damages or losses), even if such Contributor
      +   has been advised of the possibility of such damages.
      +
      +9. Accepting Warranty or Additional Liability. While redistributing
      +   the Work or Derivative Works thereof, You may choose to offer,
      +   and charge a fee for, acceptance of support, warranty, indemnity,
      +   or other liability obligations and/or rights consistent with this
      +   License. However, in accepting such obligations, You may act only
      +   on Your own behalf and on Your sole responsibility, not on behalf
      +   of any other Contributor, and only if You agree to indemnify,
      +   defend, and hold each Contributor harmless for any liability
      +   incurred by, or claims asserted against, such Contributor by reason
      +   of your accepting any such warranty or additional liability.
      +
      +END OF TERMS AND CONDITIONS
      +
      +APPENDIX: How to apply the Apache License to your work.
      +
      +   To apply the Apache License to your work, attach the following
      +   boilerplate notice, with the fields enclosed by brackets "[]"
      +   replaced with your own identifying information. (Don't include
      +   the brackets!)  The text should be enclosed in the appropriate
      +   comment syntax for the file format. We also recommend that a
      +   file or class name and description of purpose be included on the
      +   same "printed page" as the copyright notice for easier
      +   identification within third-party archives.
      +
      +Copyright 2024 Liam Gray <gmail@liamg.me>
      +
      +Licensed under the Apache License, Version 2.0 (the "License");
      +you may not use this file except in compliance with the License.
      +You may obtain a copy of the License at
      +
      +	http://www.apache.org/licenses/LICENSE-2.0
      +
      +Unless required by applicable law or agreed to in writing, software
      +distributed under the License is distributed on an "AS IS" BASIS,
      +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +See the License for the specific language governing permissions and
      +limitations under the License.
      +
      +
    • +
    • +

      Apache License 2.0

      +

      Used by:

      +
                                    Apache License
                               Version 2.0, January 2004
      @@ -7953,7 +10400,8 @@ limitations under the License.
                       

      Used by:

                                    Apache License
                               Version 2.0, January 2004
      @@ -8161,156 +10609,171 @@ limitations under the License.

      Apache License 2.0

      Used by:

        +
      • addr2line 0.25.1
      • ahash 0.8.12
      • -
      • arc-swap 1.7.1
      • -
      • arrayvec 0.7.6
      • +
      • arc-swap 1.9.3
      • +
      • arrayvec 0.7.8
      • async-channel 2.5.0
      • -
      • async-compression 0.4.19
      • -
      • async-lock 3.4.1
      • +
      • async-compression 0.4.42
      • +
      • async-lock 3.4.2
      • atomic-waker 1.1.2
      • autocfg 1.5.0
      • -
      • base64 0.21.7
      • +
      • backtrace 0.3.76
      • base64 0.22.1
      • -
      • bitflags 2.9.4
      • -
      • bumpalo 3.19.0
      • +
      • base64 0.23.1
      • +
      • bitflags 1.3.2
      • +
      • bitflags 2.11.1
      • +
      • bstr 1.12.1
      • +
      • bumpalo 3.20.2
      • bytes-utils 0.1.4
      • -
      • cc 1.2.40
      • -
      • cexpr 0.6.0
      • -
      • cfg-if 1.0.3
      • -
      • cmake 0.1.54
      • +
      • cast 0.3.0
      • +
      • cc 1.2.62
      • +
      • cfg-if 0.1.10
      • +
      • cfg-if 1.0.4
      • +
      • cmake 0.1.58
      • +
      • compression-codecs 0.4.38
      • +
      • compression-core 0.4.32
      • concurrent-queue 2.5.0
      • const-random-macro 0.1.16
      • const-random 0.1.18
      • core-foundation-sys 0.8.7
      • core-foundation 0.10.1
      • core-foundation 0.9.4
      • +
      • cpp_demangle 0.4.5
      • +
      • criterion-plot 0.8.2
      • +
      • criterion 0.8.2
      • crossbeam-channel 0.5.15
      • crossbeam-deque 0.8.6
      • -
      • crossbeam-epoch 0.9.18
      • +
      • crossbeam-epoch 0.9.20
      • crossbeam-queue 0.3.12
      • +
      • crossbeam-skiplist 0.1.3
      • crossbeam-utils 0.8.21
      • +
      • debugid 0.8.0
      • displaydoc 0.2.5
      • either 1.15.0
      • +
      • encoding_rs_io 0.1.7
      • equivalent 1.0.2
      • errno 0.3.14
      • event-listener-strategy 0.5.4
      • -
      • event-listener 5.4.1
      • -
      • fastrand 2.3.0
      • -
      • find-msvc-tools 0.1.3
      • +
      • event-listener 5.4.2
      • +
      • fastrand 2.4.1
      • +
      • find-msvc-tools 0.1.9
      • +
      • findshlibs 0.10.2
      • fixedbitset 0.5.7
      • +
      • flate2 1.1.9
      • fnv 1.0.7
      • form_urlencoded 1.2.2
      • -
      • fs4 0.8.4
      • +
      • foyer-intrusive-collections 0.10.0-dev
      • +
      • fs4 0.13.1
      • futures-timer 3.0.3
      • -
      • geohash 0.13.1
      • +
      • geohash 0.13.2
      • +
      • gimli 0.32.3
      • glob 0.3.3
      • -
      • group 0.12.1
      • +
      • group 0.14.0
      • hash32 0.3.1
      • hashbrown 0.14.5
      • hashbrown 0.15.5
      • -
      • hashbrown 0.16.0
      • +
      • hashbrown 0.16.1
      • +
      • hashbrown 0.17.1
      • heapless 0.8.0
      • heck 0.5.0
      • hermit-abi 0.5.2
      • httparse 1.10.1
      • -
      • hyper-rustls 0.24.2
      • -
      • hyper-rustls 0.27.7
      • +
      • hyper-rustls 0.27.9
      • +
      • hyper-timeout 0.5.2
      • idna 1.1.0
      • -
      • idna_adapter 1.2.1
      • -
      • indexmap 2.12.0
      • -
      • itertools 0.11.0
      • -
      • itertools 0.12.1
      • +
      • idna_adapter 1.2.2
      • +
      • indexmap 2.14.0
      • itertools 0.13.0
      • itertools 0.14.0
      • +
      • itertools 0.15.0
      • jobserver 0.1.34
      • -
      • js-sys 0.3.81
      • +
      • js-sys 0.3.107
      • lazy_static 1.5.0
      • -
      • lazycell 1.3.0
      • -
      • linux-raw-sys 0.11.0
      • -
      • linux-raw-sys 0.4.15
      • +
      • linux-raw-sys 0.12.1
      • lock_api 0.4.14
      • -
      • log 0.4.28
      • +
      • log 0.4.34
      • lzma-sys 0.1.20
      • matrixmultiply 0.3.10
      • mime 0.3.17
      • -
      • multimap 0.10.1
      • ndarray 0.16.1
      • -
      • num-bigint-dig 0.8.4
      • +
      • num-bigint-dig 0.8.6
      • num-bigint 0.4.6
      • +
      • num-bigint 0.5.1
      • num-complex 0.4.6
      • num-integer 0.1.46
      • num-iter 0.1.45
      • +
      • num-rational 0.4.2
      • num-traits 0.2.19
      • num_cpus 1.17.0
      • -
      • once_cell 1.21.3
      • -
      • openssl-probe 0.1.6
      • +
      • oauth2 5.0.0
      • +
      • object 0.37.3
      • +
      • once_cell 1.21.4
      • +
      • openssl-probe 0.2.1
      • parking 2.2.1
      • parking_lot 0.12.5
      • parking_lot_core 0.9.12
      • percent-encoding 2.3.2
      • petgraph 0.8.3
      • -
      • pkg-config 0.3.32
      • -
      • prost-build 0.14.3
      • -
      • prost-derive 0.14.3
      • +
      • pkg-config 0.3.33
      • +
      • prost-derive 0.14.4
      • prost-types 0.14.3
      • -
      • prost 0.14.3
      • +
      • prost 0.14.4
      • +
      • rand_xoshiro 0.6.0
      • rawpointer 0.2.1
      • rayon-core 1.13.0
      • -
      • rayon 1.11.0
      • -
      • regex-automata 0.4.13
      • -
      • regex-lite 0.1.7
      • -
      • regex-syntax 0.8.6
      • -
      • regex 1.12.2
      • +
      • rayon 1.12.0
      • +
      • regex-automata 0.4.16
      • +
      • regex-lite 0.1.9
      • +
      • regex-syntax 0.8.11
      • +
      • regex 1.13.1
      • ring 0.17.14
      • +
      • roaring 0.11.5
      • robust 1.2.0
      • -
      • rustc-hash 1.1.0
      • +
      • rustc-demangle 0.1.27
      • rustc_version 0.4.1
      • -
      • rustix 0.38.44
      • -
      • rustix 1.1.2
      • -
      • rustls-native-certs 0.6.3
      • -
      • rustls-native-certs 0.8.1
      • -
      • rustls-pemfile 1.0.4
      • -
      • rustls-pemfile 2.2.0
      • -
      • rustls 0.21.12
      • -
      • rustls 0.23.31
      • +
      • rustix 1.1.4
      • +
      • rustls-native-certs 0.8.3
      • +
      • rustls 0.23.46
      • scoped-tls 1.0.1
      • scopeguard 1.2.0
      • -
      • sct 0.7.1
      • -
      • security-framework-sys 2.15.0
      • -
      • security-framework 2.11.1
      • -
      • security-framework 3.5.1
      • -
      • serde_with 3.15.0
      • -
      • serde_with_macros 3.15.0
      • -
      • shellexpand 3.1.1
      • -
      • signal-hook-registry 1.4.6
      • -
      • smallvec 1.15.1
      • -
      • socket2 0.5.10
      • -
      • socket2 0.6.0
      • -
      • sqlparser 0.59.0
      • -
      • sqlparser_derive 0.3.0
      • -
      • stable_deref_trait 1.2.0
      • -
      • syn 1.0.109
      • +
      • security-framework-sys 2.17.0
      • +
      • security-framework 3.7.0
      • +
      • serde_with 3.24.0
      • +
      • serde_with_macros 3.24.0
      • +
      • shellexpand 3.1.2
      • +
      • signal-hook-registry 1.4.8
      • +
      • simd_cesu8 1.1.1
      • +
      • smallvec 1.16.5
      • +
      • socket2 0.6.3
      • +
      • sqlparser 0.62.0
      • +
      • sqlparser_derive 0.5.0
      • +
      • stable_deref_trait 1.2.1
      • +
      • str_stack 0.1.1
      • +
      • symlink 0.1.0
      • system-configuration-sys 0.6.0
      • -
      • system-configuration 0.6.1
      • -
      • tempfile 3.23.0
      • +
      • system-configuration 0.7.0
      • +
      • tempfile 3.27.0
      • thread-tree 0.3.3
      • -
      • thread_local 1.1.9
      • -
      • unicase 2.8.1
      • -
      • unicode-segmentation 1.12.0
      • -
      • unicode-width 0.2.2
      • -
      • url 2.5.7
      • -
      • uuid 1.18.1
      • +
      • thread_local 1.1.10
      • +
      • tinytemplate 1.2.1
      • +
      • unicase 2.9.0
      • +
      • unicode-normalization 0.1.25
      • +
      • unicode-segmentation 1.13.2
      • +
      • unicode-width 0.2.3
      • +
      • url 2.5.8
      • +
      • uuid 1.29.0
      • version_check 0.9.5
      • wasi 0.11.1+wasi-snapshot-preview1
      • wasi 0.14.7+wasi-0.2.4
      • -
      • wasm-bindgen-backend 0.2.104
      • -
      • wasm-bindgen-futures 0.4.54
      • -
      • wasm-bindgen-macro-support 0.2.104
      • -
      • wasm-bindgen-macro 0.2.104
      • -
      • wasm-bindgen-shared 0.2.104
      • -
      • wasm-bindgen 0.2.104
      • -
      • web-sys 0.3.81
      • -
      • wit-bindgen 0.46.0
      • +
      • wasip2 1.0.3+wasi-0.2.9
      • +
      • wasm-bindgen-futures 0.4.80
      • +
      • wasm-bindgen-macro-support 0.2.130
      • +
      • wasm-bindgen-macro 0.2.130
      • +
      • wasm-bindgen-shared 0.2.130
      • +
      • wasm-bindgen 0.2.130
      • +
      • web-sys 0.3.107
      • +
      • wit-bindgen 0.57.1
      • wkb 0.9.2
      • wkt 0.14.0
      • xmlparser 0.13.6
      • @@ -8522,7 +10985,7 @@ limitations under the License.

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8732,14 +11195,12 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8949,41 +11410,55 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9192,10 +11667,209 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +Copyright (c) 2015-2022 Amod Malviya
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        + +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                      Apache License
                                 Version 2.0, January 2004
        @@ -9390,11 +12064,13 @@ APPENDIX: How to apply the Apache License to your work.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9603,8 +12279,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -9813,7 +12488,9 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
                                    Version 2.0, January 2004
        @@ -10022,7 +12699,9 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
         Version 2.0, January 2004
        @@ -10301,128 +12980,169 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Apache License
         Version 2.0, January 2004
        @@ -10739,10 +13459,10 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        Rust-chrono is dual-licensed under The MIT License [1] and
        -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
        +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
         contributors.
         
         Nota Bene: This is same as the Rust Project's own license.
        @@ -10981,6 +13701,40 @@ See the License for the specific language governing permissions and
         limitations under the License.
         ~~~~
         
        +
        +
      • +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +1. Redistributions of source code must retain the above copyright
        +   notice, this list of conditions and the following disclaimer.
        +
        +2. Redistributions in binary form must reproduce the above copyright
        +   notice, this list of conditions and the following disclaimer in the
        +   documentation and/or other materials provided with the
        +   distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • @@ -11015,6 +13769,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • + +
      • +

        BSD 2-Clause "Simplified" License

        +

        Used by:

        + +
        Copyright (c) 2017-2020
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are met:
        +
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
        +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
        +//
        +// Redistribution and use in source and binary forms, with or without
        +// modification, are permitted provided that the following conditions are met:
        +//
        +// 1. Redistributions of source code must retain the above copyright notice, this
        +//    list of conditions and the following disclaimer.
        +//
        +// 2. Redistributions in binary form must reproduce the above copyright notice,
        +//    this list of conditions and the following disclaimer in the documentation
        +//    and/or other materials provided with the distribution.
        +//
        +// 3. Neither the name of the copyright holder nor the names of its
        +//    contributors may be used to endorse or promote products derived from
        +//    this software without specific prior written permission.
        +//
        +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +/// The PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
        +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
        +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
        +];
        +
        +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
        +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
        +    [0xA6, 0xD9],
        +    [0xA6, 0xDA],
        +    [0xA6, 0xDB],
        +    [0xA6, 0xDC],
        +    [0xA6, 0xDD],
        +    [0xA6, 0xDE],
        +    [0xA6, 0xDF],
        +    [0xA6, 0xEC],
        +    [0xA6, 0xED],
        +    [0xA6, 0xF3],
        +    [0xFE, 0x59],
        +    [0xFE, 0x61],
        +    [0xFE, 0x66],
        +    [0xFE, 0x67],
        +    [0xFE, 0x6D],
        +    [0xFE, 0x7E],
        +    [0xFE, 0x90],
        +    [0xFE, 0xA0],
        +];
         
      • @@ -11022,6 +13869,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

        Used by:

        BSD 3-Clause License
         
        @@ -11058,26 +13906,27 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        BSD 3-Clause License
         
        -Copyright (c) 2013, Jyun-Yan You
        -All rights reserved.
        +Copyright (c) 2026, Alexandre Bury
         
         Redistribution and use in source and binary forms, with or without
         modification, are permitted provided that the following conditions are met:
         
        -* Redistributions of source code must retain the above copyright notice, this
        -  list of conditions and the following disclaimer.
        +1. Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
         
        -* Redistributions in binary form must reproduce the above copyright notice,
        -  this list of conditions and the following disclaimer in the documentation
        -  and/or other materials provided with the distribution.
        +2. Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
         
        -* Neither the name of the copyright holder nor the names of its
        -  contributors may be used to endorse or promote products derived from
        -  this software without specific prior written permission.
        +3. Neither the name of the copyright holder nor the names of its
        +   contributors may be used to endorse or promote products derived from
        +   this software without specific prior written permission.
         
         THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
         AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        @@ -11095,10 +13944,50 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) 2001, Dr Martin Porter
         Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
         All rights reserved.
         
         Redistribution and use in source and binary forms, with or without
        @@ -11123,16 +14012,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
         LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
         ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
         (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
      • BSD 3-Clause "New" or "Revised" License

        Used by:

        Copyright (c) 2016 Dropbox, Inc.
         All rights reserved.
        @@ -11189,8 +14078,47 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                         

        BSD 3-Clause "New" or "Revised" License

        Used by:

        +
        Copyright (c) 2026, frostem contributors
        +Copyright (c) 2001, Dr Martin Porter
        +Copyright (c) 2004,2005, Richard Boulton
        +Copyright (c) 2013, Yoshiki Shibukawa
        +Copyright (c) 2006-2025, Olly Betts
        +All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions
        +are met:
        +
        +  1. Redistributions of source code must retain the above copyright notice,
        +     this list of conditions and the following disclaimer.
        +  2. Redistributions in binary form must reproduce the above copyright notice,
        +     this list of conditions and the following disclaimer in the documentation
        +     and/or other materials provided with the distribution.
        +  3. Neither the name of the Snowball project nor the names of its contributors
        +     may be used to endorse or promote products derived from this software
        +     without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        +
        Copyright (c) <year> <owner>. 
         
        @@ -11237,13 +14165,53 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
         CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
         OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
         OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        BSD 3-Clause "New" or "Revised" License

        +

        Used by:

        + +
        The auto-generated bindings are under the 3-clause BSD license:
        +
        +BSD License
        +
        +For Zstandard software
        +
        +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without modification,
        +are permitted provided that the following conditions are met:
        +
        + * Redistributions of source code must retain the above copyright notice, this
        +   list of conditions and the following disclaimer.
        +
        + * Redistributions in binary form must reproduce the above copyright notice,
        +   this list of conditions and the following disclaimer in the documentation
        +   and/or other materials provided with the distribution.
        +
        + * Neither the name Facebook, nor Meta, nor the names of its contributors may
        +   be used to endorse or promote products derived from this software without
        +   specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
        +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
        +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
        +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
        +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
        +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
      • Boost Software License 1.0

        Used by:

        Boost Software License - Version 1.0 - August 17th, 2003
         
        @@ -11397,13 +14365,405 @@ express Statement of Purpose.
          d. Affirmer understands and acknowledges that Creative Commons is not a
             party to this document and has no duty or obligation with respect to
             this CC0 or use of the Work.
        +
        +
      • +
      • +

        Common Development and Distribution License 1.0

        +

        Used by:

        + +
        Unless otherwise noted, all files in this distribution are released
        +under the Common Development and Distribution License (CDDL).
        +Exceptions are noted within the associated source files.
        +
        +--------------------------------------------------------------------
        +
        +
        +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
        +
        +1. Definitions.
        +
        +    1.1. "Contributor" means each individual or entity that creates
        +         or contributes to the creation of Modifications.
        +
        +    1.2. "Contributor Version" means the combination of the Original
        +         Software, prior Modifications used by a Contributor (if any),
        +         and the Modifications made by that particular Contributor.
        +
        +    1.3. "Covered Software" means (a) the Original Software, or (b)
        +         Modifications, or (c) the combination of files containing
        +         Original Software with files containing Modifications, in
        +         each case including portions thereof.
        +
        +    1.4. "Executable" means the Covered Software in any form other
        +         than Source Code.
        +
        +    1.5. "Initial Developer" means the individual or entity that first
        +         makes Original Software available under this License.
        +
        +    1.6. "Larger Work" means a work which combines Covered Software or
        +         portions thereof with code not governed by the terms of this
        +         License.
        +
        +    1.7. "License" means this document.
        +
        +    1.8. "Licensable" means having the right to grant, to the maximum
        +         extent possible, whether at the time of the initial grant or
        +         subsequently acquired, any and all of the rights conveyed
        +         herein.
        +
        +    1.9. "Modifications" means the Source Code and Executable form of
        +         any of the following:
        +
        +        A. Any file that results from an addition to, deletion from or
        +           modification of the contents of a file containing Original
        +           Software or previous Modifications;
        +
        +        B. Any new file that contains any part of the Original
        +           Software or previous Modifications; or
        +
        +        C. Any new file that is contributed or otherwise made
        +           available under the terms of this License.
        +
        +    1.10. "Original Software" means the Source Code and Executable
        +          form of computer software code that is originally released
        +          under this License.
        +
        +    1.11. "Patent Claims" means any patent claim(s), now owned or
        +          hereafter acquired, including without limitation, method,
        +          process, and apparatus claims, in any patent Licensable by
        +          grantor.
        +
        +    1.12. "Source Code" means (a) the common form of computer software
        +          code in which modifications are made and (b) associated
        +          documentation included in or with such code.
        +
        +    1.13. "You" (or "Your") means an individual or a legal entity
        +          exercising rights under, and complying with all of the terms
        +          of, this License.  For legal entities, "You" includes any
        +          entity which controls, is controlled by, or is under common
        +          control with You.  For purposes of this definition,
        +          "control" means (a) the power, direct or indirect, to cause
        +          the direction or management of such entity, whether by
        +          contract or otherwise, or (b) ownership of more than fifty
        +          percent (50%) of the outstanding shares or beneficial
        +          ownership of such entity.
        +
        +2. License Grants.
        +
        +    2.1. The Initial Developer Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, the Initial
        +    Developer hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Initial Developer, to use,
        +            reproduce, modify, display, perform, sublicense and
        +            distribute the Original Software (or portions thereof),
        +            with or without Modifications, and/or as part of a Larger
        +            Work; and
        +
        +        (b) under Patent Claims infringed by the making, using or
        +            selling of Original Software, to make, have made, use,
        +            practice, sell, and offer for sale, and/or otherwise
        +            dispose of the Original Software (or portions thereof).
        +
        +        (c) The licenses granted in Sections 2.1(a) and (b) are
        +            effective on the date Initial Developer first distributes
        +            or otherwise makes the Original Software available to a
        +            third party under the terms of this License.
        +
        +        (d) Notwithstanding Section 2.1(b) above, no patent license is
        +            granted: (1) for code that You delete from the Original
        +            Software, or (2) for infringements caused by: (i) the
        +            modification of the Original Software, or (ii) the
        +            combination of the Original Software with other software
        +            or devices.
        +
        +    2.2. Contributor Grant.
        +
        +    Conditioned upon Your compliance with Section 3.1 below and
        +    subject to third party intellectual property claims, each
        +    Contributor hereby grants You a world-wide, royalty-free,
        +    non-exclusive license:
        +
        +        (a) under intellectual property rights (other than patent or
        +            trademark) Licensable by Contributor to use, reproduce,
        +            modify, display, perform, sublicense and distribute the
        +            Modifications created by such Contributor (or portions
        +            thereof), either on an unmodified basis, with other
        +            Modifications, as Covered Software and/or as part of a
        +            Larger Work; and
        +
        +        (b) under Patent Claims infringed by the making, using, or
        +            selling of Modifications made by that Contributor either
        +            alone and/or in combination with its Contributor Version
        +            (or portions of such combination), to make, use, sell,
        +            offer for sale, have made, and/or otherwise dispose of:
        +            (1) Modifications made by that Contributor (or portions
        +            thereof); and (2) the combination of Modifications made by
        +            that Contributor with its Contributor Version (or portions
        +            of such combination).
        +
        +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
        +            effective on the date Contributor first distributes or
        +            otherwise makes the Modifications available to a third
        +            party.
        +
        +        (d) Notwithstanding Section 2.2(b) above, no patent license is
        +            granted: (1) for any code that Contributor has deleted
        +            from the Contributor Version; (2) for infringements caused
        +            by: (i) third party modifications of Contributor Version,
        +            or (ii) the combination of Modifications made by that
        +            Contributor with other software (except as part of the
        +            Contributor Version) or other devices; or (3) under Patent
        +            Claims infringed by Covered Software in the absence of
        +            Modifications made by that Contributor.
        +
        +3. Distribution Obligations.
        +
        +    3.1. Availability of Source Code.
        +
        +    Any Covered Software that You distribute or otherwise make
        +    available in Executable form must also be made available in Source
        +    Code form and that Source Code form must be distributed only under
        +    the terms of this License.  You must include a copy of this
        +    License with every copy of the Source Code form of the Covered
        +    Software You distribute or otherwise make available.  You must
        +    inform recipients of any such Covered Software in Executable form
        +    as to how they can obtain such Covered Software in Source Code
        +    form in a reasonable manner on or through a medium customarily
        +    used for software exchange.
        +
        +    3.2. Modifications.
        +
        +    The Modifications that You create or to which You contribute are
        +    governed by the terms of this License.  You represent that You
        +    believe Your Modifications are Your original creation(s) and/or
        +    You have sufficient rights to grant the rights conveyed by this
        +    License.
        +
        +    3.3. Required Notices.
        +
        +    You must include a notice in each of Your Modifications that
        +    identifies You as the Contributor of the Modification.  You may
        +    not remove or alter any copyright, patent or trademark notices
        +    contained within the Covered Software, or any notices of licensing
        +    or any descriptive text giving attribution to any Contributor or
        +    the Initial Developer.
        +
        +    3.4. Application of Additional Terms.
        +
        +    You may not offer or impose any terms on any Covered Software in
        +    Source Code form that alters or restricts the applicable version
        +    of this License or the recipients' rights hereunder.  You may
        +    choose to offer, and to charge a fee for, warranty, support,
        +    indemnity or liability obligations to one or more recipients of
        +    Covered Software.  However, you may do so only on Your own behalf,
        +    and not on behalf of the Initial Developer or any Contributor.
        +    You must make it absolutely clear that any such warranty, support,
        +    indemnity or liability obligation is offered by You alone, and You
        +    hereby agree to indemnify the Initial Developer and every
        +    Contributor for any liability incurred by the Initial Developer or
        +    such Contributor as a result of warranty, support, indemnity or
        +    liability terms You offer.
        +
        +    3.5. Distribution of Executable Versions.
        +
        +    You may distribute the Executable form of the Covered Software
        +    under the terms of this License or under the terms of a license of
        +    Your choice, which may contain terms different from this License,
        +    provided that You are in compliance with the terms of this License
        +    and that the license for the Executable form does not attempt to
        +    limit or alter the recipient's rights in the Source Code form from
        +    the rights set forth in this License.  If You distribute the
        +    Covered Software in Executable form under a different license, You
        +    must make it absolutely clear that any terms which differ from
        +    this License are offered by You alone, not by the Initial
        +    Developer or Contributor.  You hereby agree to indemnify the
        +    Initial Developer and every Contributor for any liability incurred
        +    by the Initial Developer or such Contributor as a result of any
        +    such terms You offer.
        +
        +    3.6. Larger Works.
        +
        +    You may create a Larger Work by combining Covered Software with
        +    other code not governed by the terms of this License and
        +    distribute the Larger Work as a single product.  In such a case,
        +    You must make sure the requirements of this License are fulfilled
        +    for the Covered Software.
        +
        +4. Versions of the License.
        +
        +    4.1. New Versions.
        +
        +    Sun Microsystems, Inc. is the initial license steward and may
        +    publish revised and/or new versions of this License from time to
        +    time.  Each version will be given a distinguishing version number.
        +    Except as provided in Section 4.3, no one other than the license
        +    steward has the right to modify this License.
        +
        +    4.2. Effect of New Versions.
        +
        +    You may always continue to use, distribute or otherwise make the
        +    Covered Software available under the terms of the version of the
        +    License under which You originally received the Covered Software.
        +    If the Initial Developer includes a notice in the Original
        +    Software prohibiting it from being distributed or otherwise made
        +    available under any subsequent version of the License, You must
        +    distribute and make the Covered Software available under the terms
        +    of the version of the License under which You originally received
        +    the Covered Software.  Otherwise, You may also choose to use,
        +    distribute or otherwise make the Covered Software available under
        +    the terms of any subsequent version of the License published by
        +    the license steward.
        +
        +    4.3. Modified Versions.
        +
        +    When You are an Initial Developer and You want to create a new
        +    license for Your Original Software, You may create and use a
        +    modified version of this License if You: (a) rename the license
        +    and remove any references to the name of the license steward
        +    (except to note that the license differs from this License); and
        +    (b) otherwise make it clear that the license contains terms which
        +    differ from this License.
        +
        +5. DISCLAIMER OF WARRANTY.
        +
        +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
        +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
        +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
        +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
        +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
        +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
        +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
        +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
        +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
        +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
        +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
        +    DISCLAIMER.
        +
        +6. TERMINATION.
        +
        +    6.1. This License and the rights granted hereunder will terminate
        +    automatically if You fail to comply with terms herein and fail to
        +    cure such breach within 30 days of becoming aware of the breach.
        +    Provisions which, by their nature, must remain in effect beyond
        +    the termination of this License shall survive.
        +
        +    6.2. If You assert a patent infringement claim (excluding
        +    declaratory judgment actions) against Initial Developer or a
        +    Contributor (the Initial Developer or Contributor against whom You
        +    assert such claim is referred to as "Participant") alleging that
        +    the Participant Software (meaning the Contributor Version where
        +    the Participant is a Contributor or the Original Software where
        +    the Participant is the Initial Developer) directly or indirectly
        +    infringes any patent, then any and all rights granted directly or
        +    indirectly to You by such Participant, the Initial Developer (if
        +    the Initial Developer is not the Participant) and all Contributors
        +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
        +    notice from Participant terminate prospectively and automatically
        +    at the expiration of such 60 day notice period, unless if within
        +    such 60 day period You withdraw Your claim with respect to the
        +    Participant Software against such Participant either unilaterally
        +    or pursuant to a written agreement with Participant.
        +
        +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
        +    all end user licenses that have been validly granted by You or any
        +    distributor hereunder prior to termination (excluding licenses
        +    granted to You by any distributor) shall survive termination.
        +
        +7. LIMITATION OF LIABILITY.
        +
        +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
        +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
        +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
        +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
        +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
        +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
        +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
        +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
        +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
        +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
        +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
        +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
        +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
        +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
        +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
        +    APPLY TO YOU.
        +
        +8. U.S. GOVERNMENT END USERS.
        +
        +    The Covered Software is a "commercial item," as that term is
        +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
        +    computer software" (as that term is defined at 48
        +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
        +    documentation" as such terms are used in 48 C.F.R. 12.212
        +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
        +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
        +    U.S. Government End Users acquire Covered Software with only those
        +    rights set forth herein.  This U.S. Government Rights clause is in
        +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
        +    provision that addresses Government rights in computer software
        +    under this License.
        +
        +9. MISCELLANEOUS.
        +
        +    This License represents the complete agreement concerning subject
        +    matter hereof.  If any provision of this License is held to be
        +    unenforceable, such provision shall be reformed only to the extent
        +    necessary to make it enforceable.  This License shall be governed
        +    by the law of the jurisdiction specified in a notice contained
        +    within the Original Software (except to the extent applicable law,
        +    if any, provides otherwise), excluding such jurisdiction's
        +    conflict-of-law provisions.  Any litigation relating to this
        +    License shall be subject to the jurisdiction of the courts located
        +    in the jurisdiction and venue specified in a notice contained
        +    within the Original Software, with the losing party responsible
        +    for costs, including, without limitation, court costs and
        +    reasonable attorneys' fees and expenses.  The application of the
        +    United Nations Convention on Contracts for the International Sale
        +    of Goods is expressly excluded.  Any law or regulation which
        +    provides that the language of a contract shall be construed
        +    against the drafter shall not apply to this License.  You agree
        +    that You alone are responsible for compliance with the United
        +    States export administration regulations (and the export control
        +    laws and regulation of any other countries) when You use,
        +    distribute or otherwise make available any Covered Software.
        +
        +10. RESPONSIBILITY FOR CLAIMS.
        +
        +    As between Initial Developer and the Contributors, each party is
        +    responsible for claims and damages arising, directly or
        +    indirectly, out of its utilization of rights under this License
        +    and You agree to work with Initial Developer and Contributors to
        +    distribute such responsibility on an equitable basis.  Nothing
        +    herein is intended or shall be deemed to constitute any admission
        +    of liability.
        +
        +--------------------------------------------------------------------
        +
        +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
        +DISTRIBUTION LICENSE (CDDL)
        +
        +For Covered Software in this distribution, this License shall
        +be governed by the laws of the State of California (excluding
        +conflict-of-law provisions).
        +
        +Any litigation relating to this License shall be subject to the
        +jurisdiction of the Federal Courts of the Northern District of
        +California and the state courts of the State of California, with
        +venue lying in Santa Clara County, California.
         
      • Community Data License Agreement Permissive 2.0

        Used by:

        # Community Data License Agreement - Permissive - Version 2.0
         
        @@ -11472,9 +14832,9 @@ insights.
                         

        ISC License

        Used by:

        -
        /* Copyright (c) 2018, Google Inc.
        +                
        /* Copyright (c) 2014, Intel Corporation.
          *
          * Permission to use, copy, modify, and/or distribute this software for any
          * purpose with or without fee is hereby granted, provided that the above
        @@ -11488,15 +14848,65 @@ insights.
          * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
         
        -#include <openssl/crypto.h>
        +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
         
        -#include <gtest/gtest.h>
        +#include "../../limbs/limbs.h"
        +
        +#define P384_LIMBS (384u / LIMB_BITS)
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +  Limb Z[P384_LIMBS];
        +} P384_POINT;
        +
        +typedef struct {
        +  Limb X[P384_LIMBS];
        +  Limb Y[P384_LIMBS];
        +} P384_POINT_AFFINE;
         
         
        -TEST(SelfTests, KAT) {
        -#if !defined(_MSC_VER)
        -  EXPECT_TRUE(BORINGSSL_self_test());
        -#endif
        +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2015-2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! EdDSA Signatures.
        +
        +use super::ops::ELEM_LEN;
        +use crate::digest;
        +
        +pub mod signing;
        +pub mod verification;
        +
        +/// The length of an Ed25519 public key.
        +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
        +
        +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
        +    let mut ctx = digest::Context::new(&digest::SHA512);
        +    ctx.update(signature_r);
        +    ctx.update(public_key);
        +    ctx.update(msg);
        +    ctx.finish()
         }
         
      • @@ -11526,29 +14936,44 @@ TEST(SelfTests, KAT) {

        ISC License

        Used by:

        -
        // Copyright 2021 Brian Smith.
        +                
        // Copyright 2015-2022 Brian Smith.
         //
         // Permission to use, copy, modify, and/or distribute this software for any
         // purpose with or without fee is hereby granted, provided that the above
         // copyright notice and this permission notice appear in all copies.
         //
        -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
         // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
        -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
        -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
        -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -#[test]
        -fn cert_without_extensions_test() {
        -    // Check the certificate is valid with
        -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
        -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
        +use crate::limb::Limb;
         
        -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
        +#[derive(Clone, Copy)]
        +#[repr(transparent)]
        +pub struct N0([Limb; 2]);
        +
        +impl N0 {
        +    #[cfg(feature = "alloc")]
        +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
        +
        +    #[inline]
        +    pub const fn precalculated(n0: u64) -> Self {
        +        #[cfg(target_pointer_width = "64")]
        +        {
        +            Self([n0, 0])
        +        }
        +
        +        #[cfg(target_pointer_width = "32")]
        +        {
        +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
        +        }
        +    }
         }
         
        @@ -11556,21 +14981,372 @@ fn cert_without_extensions_test() {

        ISC License

        Used by:

        -
        Copyright (c) 2017 Adam Wick
        +                
        // Copyright 2015-2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
        -Permission to use, copy, modify, and/or distribute this software for any purpose
        -with or without fee is hereby granted, provided that the above copyright notice
        -and this permission notice appear in all copies.
        +use crate::{bb, error};
         
        -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
        -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
        -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
        -THIS SOFTWARE.
        +#[deprecated(
        +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
        +)]
        +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
        +    bb::verify_slices_are_equal(a, b)
        +}
        +
        + +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Elliptic curve operations and schemes using Curve25519.
        +
        +pub mod ed25519;
        +
        +pub mod x25519;
        +
        +mod ops;
        +mod scalar;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2016-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use crate::error::{KeyRejected, Unspecified};
        +
        +impl From<untrusted::EndOfInput> for Unspecified {
        +    fn from(source: untrusted::EndOfInput) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<core::array::TryFromSliceError> for Unspecified {
        +    fn from(source: core::array::TryFromSliceError) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +impl From<KeyRejected> for Unspecified {
        +    fn from(source: KeyRejected) -> Self {
        +        super::erase(source)
        +    }
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2018 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Serialization and deserialization.
        +
        +#[doc(hidden)]
        +pub mod der;
        +
        +#[cfg(feature = "alloc")]
        +mod writer;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) mod der_writer;
        +
        +pub(crate) mod positive;
        +
        +pub use self::positive::Positive;
        +
        +#[cfg(feature = "alloc")]
        +pub(crate) use self::writer::TooLongError;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2019-2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +use super::BlockLen;
        +
        +pub(super) use self::{
        +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
        +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
        +};
        +
        +pub(super) const CHAINING_WORDS: usize = 8;
        +
        +#[cfg(any(
        +    all(target_arch = "aarch64", target_endian = "little"),
        +    all(target_arch = "arm", target_endian = "little"),
        +    target_arch = "x86_64"
        +))]
        +#[macro_use]
        +mod ffi;
        +
        +pub(super) mod fallback;
        +mod sha2_32;
        +mod sha2_64;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
        +    r
        +}
        +
        +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
        +#[allow(dead_code)]
        +#[inline(always)]
        +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
        +    r
        +}
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +//! Integration tests for non-public APIs.
        +
        +mod bits_tests;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2024 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub use self::{
        +    array::Array,
        +    base::{IndexError, Overlapping},
        +    partial_block::PartialBlock,
        +};
        +
        +mod array;
        +mod base;
        +mod partial_block;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
        +
        +pub(in super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +#![cfg(target_arch = "x86_64")]
        +
        +pub(in super::super::super) mod mont;
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +mod storage;
        +
        +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
        +
        +
      • +
      • +

        ISC License

        +

        Used by:

        + +
        // Copyright 2025 Brian Smith.
        +//
        +// Permission to use, copy, modify, and/or distribute this software for any
        +// purpose with or without fee is hereby granted, provided that the above
        +// copyright notice and this permission notice appear in all copies.
        +//
        +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
        +
        +pub(super) mod aarch64;
        +pub(super) mod x86_64;
         
      • @@ -11598,7 +15374,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

        ISC License

        Used by:

        Copyright © 2015, Simonas Kazlauskas
         
        @@ -11618,7 +15394,7 @@ THIS SOFTWARE.
                         

        ISC License

        Used by:

        Except as otherwise noted, this project is licensed under the following
         (ISC-style) terms:
        @@ -11645,12 +15421,12 @@ third-party/chromium/LICENSE.
                         

        ISC License

        Used by:

        ISC License
         
         Copyright (c) 2016, Mapbox
        -Copyright (c) 2018, Tree Cricket
        +Copyright (c) 2023, Taku Fukada
         
         Permission to use, copy, modify, and/or distribute this software for any purpose
         with or without fee is hereby granted, provided that the above copyright notice
        @@ -11669,7 +15445,8 @@ THIS SOFTWARE.
                         

        ISC License

        Used by:

        ISC License:
         
        @@ -11685,7 +15462,580 @@ THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
                         

        MIT License

        Used by:

        +
                                          MIT License
        +
        +Copyright 2024 Antoine Catton
        +Copyright 2016-2024 David Tolnay
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        # 3rd Party Notices
        +
        +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
        +
        +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
        +
        +    tectonic_cfg_support is licensed under the MIT License.
        +
        +    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.
        +---
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Codegen exports used by `tonic-build`.
        +
        +pub use async_trait::async_trait;
        +pub use tokio_stream;
        +
        +pub use std::future::Future;
        +pub use std::pin::Pin;
        +pub use std::sync::Arc;
        +pub use std::task::{Context, Poll};
        +pub use tower_service::Service;
        +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
        +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
        +pub use crate::extensions::GrpcMethod;
        +pub use crate::service::interceptor::InterceptedService;
        +pub use bytes::Bytes;
        +pub use http;
        +pub use http_body::Body;
        +
        +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
        +pub type BoxStream<T> =
        +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Utilities for using Tower services with Tonic.
        +
        +pub mod interceptor;
        +pub(crate) mod layered;
        +#[cfg(feature = "router")]
        +pub(crate) mod router;
        +
        +#[doc(inline)]
        +pub use self::interceptor::{Interceptor, InterceptorLayer};
        +pub use self::layered::{LayerExt, Layered};
        +#[doc(inline)]
        +#[cfg(feature = "router")]
        +pub use self::router::{Routes, RoutesBuilder};
        +#[cfg(feature = "router")]
        +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
        +
        +pub mod recover_error;
        +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +//! Various utilities used throughout tonic.
        +
        +// some combinations of features might cause things here not to be used
        +#![allow(dead_code)]
        +
        +pub(crate) mod base64 {
        +    use base64::{
        +        alphabet,
        +        engine::{
        +            DecodePaddingMode,
        +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
        +        },
        +    };
        +
        +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(true)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +
        +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
        +        &alphabet::STANDARD,
        +        GeneralPurposeConfig::new()
        +            .with_encode_padding(false)
        +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
        +    );
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +/// A gRPC Method info extension.
        +#[derive(Debug, Clone)]
        +pub struct GrpcMethod<'a> {
        +    service: &'a str,
        +    method: &'a str,
        +}
        +
        +impl<'a> GrpcMethod<'a> {
        +    /// Create a new `GrpcMethod` extension.
        +    #[doc(hidden)]
        +    pub fn new(service: &'a str, method: &'a str) -> Self {
        +        Self { service, method }
        +    }
        +
        +    /// gRPC service name
        +    pub fn service(&self) -> &str {
        +        self.service
        +    }
        +    /// gRPC method name
        +    pub fn method(&self) -> &str {
        +        self.method
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +mod add_origin;
        +use self::add_origin::AddOrigin;
        +
        +mod user_agent;
        +use self::user_agent::UserAgent;
        +
        +mod reconnect;
        +use self::reconnect::Reconnect;
        +
        +mod connection;
        +pub(super) use self::connection::Connection;
        +
        +mod discover;
        +pub use self::discover::Change;
        +pub(super) use self::discover::DynamicServiceStream;
        +
        +mod io;
        +use self::io::BoxedIo;
        +
        +mod connector;
        +pub(crate) use self::connector::Connector;
        +
        +mod executor;
        +pub(super) use self::executor::{Executor, SharedExec};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(super) use self::tls::TlsConnector;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +mod io;
        +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
        +
        +#[cfg(feature = "_tls-any")]
        +mod tls;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) use self::tls::TlsAcceptor;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +pub(crate) mod grpc_timeout;
        +#[cfg(feature = "_tls-any")]
        +pub(crate) mod tls;
        +
        +pub(crate) use self::grpc_timeout::GrpcTimeout;
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +use crate::transport::channel::BoxFuture;
        +use hyper_util::rt::TokioExecutor;
        +use std::{future::Future, sync::Arc};
        +
        +pub(crate) use hyper::rt::Executor;
        +
        +#[derive(Clone)]
        +pub(crate) struct SharedExec {
        +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
        +}
        +
        +impl SharedExec {
        +    pub(crate) fn new<E>(exec: E) -> Self
        +    where
        +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
        +    {
        +        Self {
        +            inner: Arc::new(exec),
        +        }
        +    }
        +
        +    pub(crate) fn tokio() -> Self {
        +        Self::new(TokioExecutor::new())
        +    }
        +}
        +
        +impl<F> Executor<F> for SharedExec
        +where
        +    F: Future<Output = ()> + Send + 'static,
        +{
        +    fn execute(&self, fut: F) {
        +        self.inner.execute(Box::pin(fut))
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        /*
        + *
        + * Copyright 2025 gRPC authors.
        + *
        + * 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.
        + *
        + */
        +
        +use super::Connected;
        +use std::sync::Arc;
        +
        +/// Connection info for Unix domain socket streams.
        +///
        +/// This type will be accessible through [request extensions][ext] if you're using
        +/// a unix stream.
        +///
        +/// See [Connected] for more details.
        +///
        +/// [ext]: crate::Request::extensions
        +#[derive(Clone, Debug)]
        +pub struct UdsConnectInfo {
        +    /// Peer address. This will be "unnamed" for client unix sockets.
        +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
        +    /// Process credentials for the unix socket.
        +    pub peer_cred: Option<tokio::net::unix::UCred>,
        +}
        +
        +impl Connected for tokio::net::UnixStream {
        +    type ConnectInfo = UdsConnectInfo;
        +
        +    fn connect_info(&self) -> Self::ConnectInfo {
        +        UdsConnectInfo {
        +            peer_addr: self.peer_addr().ok().map(Arc::new),
        +            peer_cred: self.peer_cred().ok(),
        +        }
        +    }
        +}
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        // Copyright (c) 2019 Nuclear Furnace
        +//
        +// 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
         
        @@ -11712,7 +16062,7 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014 Carl Lerche and other MIO contributors
         
        @@ -11739,7 +16089,6 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2014-2019 Geoffroy Couprie
        @@ -11768,9 +16117,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2021 Sean McArthur
        +                
        Copyright (c) 2014-2026 Sean McArthur
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -11795,34 +16144,8 @@ THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2014-2025 Sean McArthur
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2015 Jonathan Reem
         
        @@ -11855,34 +16178,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2015 fangyuanziti
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2015 steffengy
         
        @@ -11897,16 +16193,27 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES
                         

        MIT License

        Used by:

        -
        Copyright (c) 2016 Paul Masurel
        +                
        Copyright (c) 2017 Gilad Naaman
         
        -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:
        +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 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.
        -
        +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.
      • MIT License

        @@ -11942,8 +16249,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

        MIT License

        Used by:

        Copyright (c) 2017 h2 authors
         
        @@ -11976,7 +16282,7 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        Copyright (c) 2018 Carl Lerche
         
        @@ -12009,52 +16315,34 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2018 Paul Masurel
        +                
        Copyright (c) 2018 Tom Parker-Shemilt
         
        -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:
        +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 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.
        -
        +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.
      • MIT License

        Used by:

        -
        Copyright (c) 2018 by Quickwit, 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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2018-2019 Sean McArthur
         
        @@ -12145,7 +16433,7 @@ DEALINGS IN THE SOFTWARE.
                         

        Used by:

        Copyright (c) 2019 Carl Lerche
         
        @@ -12232,44 +16520,13 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019 Hyper Contributors
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        Copyright (c) 2019 Tokio Contributors
         
        @@ -12304,7 +16561,7 @@ DEALINGS IN THE SOFTWARE.
                         
                         
        Copyright (c) 2019 Tower Contributors
         
        @@ -12337,10 +16594,9 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2021 Tower Contributors
        +                
        Copyright (c) 2019 axum Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12371,9 +16627,10 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
        +                
        Copyright (c) 2019-2021 Tower Contributors
         
         Permission is hereby granted, free of charge, to any
         person obtaining a copy of this software and associated
        @@ -12437,7 +16694,68 @@ DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        +
        Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright (c) 2021 Metrics Contributors
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Copyright (c) 2023-2025 Sean McArthur
         
        @@ -12458,36 +16776,6 @@ 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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024 by Quickwit 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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        - -
        Copyright (c) 2024-Present Paul Masurel
        -
        -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.
         
      • @@ -12495,6 +16783,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        Used by:

        Copyright 2016 Nika Layzell
         
        @@ -12502,6 +16791,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         
         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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2019 gRPC authors.
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2020 David Koloski
        +
        +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.
         
      • @@ -12524,25 +16855,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

        MIT License

        Used by:

        -
        Includes portions of humantime
        -Copyright (c) 2016 The humantime Developers
        +                
        Copyright 2021 David Koloski
         
         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.
        -
        -
         
      • MIT License

        Used by:

        +
        Copyright 2023 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2023 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        Copyright 2024 David Koloski
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12565,6 +16944,65 @@ 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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 Michael Ma
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2016 fengcen
        +Copyright (c) 2019 svartalf
        +
        +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.
        +
      • MIT License

        @@ -12687,9 +17125,41 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2017 Sam Rijs
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12748,7 +17218,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2018 sgodwincs
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12777,7 +17276,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -12806,36 +17305,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        -
        MIT License
        -
        -Copyright (c) 2019 Aeledfyr
        -
        -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.
        -
        -
      • -
      • -

        MIT License

        -

        Used by:

        -
        MIT License
         
        @@ -12864,8 +17334,37 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2019 Kornel
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -12894,7 +17393,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -12948,6 +17447,40 @@ 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.
         
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2019–2025 axum Contributors
        +
        +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.
      • MIT License

        @@ -12982,11 +17515,30 @@ SOFTWARE.

        MIT License

        Used by:

        MIT License
         
        -Copyright (c) 2020 David Purdum
        +Copyright (c) 2020 Katharos Technology
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020 Scripta Qumranica Electronica
        +
        +Created by Bronson Brown-deVost
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13011,13 +17563,11 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        -Copyright (c) 2020 Scripta Qumranica Electronica
        -
        -Created by Bronson Brown-deVost
        +Copyright (c) 2020 magiclen.org (Ron Li)
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13058,6 +17608,93 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2022 Oliver Margetts
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2020-2026 Nugine
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2021 Adel Prokurov
        +
        +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
        @@ -13087,6 +17724,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Arthur Silva
        +
        +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
        @@ -13101,6 +17767,7 @@ SOFTWARE.
                         

        Used by:

        MIT License
         
        @@ -13116,6 +17783,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2022 Jeroen Van Der Donckt
        +
        +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
        @@ -13157,7 +17853,36 @@ SOFTWARE.

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2022 sarah
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13186,8 +17911,8 @@ SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13216,8 +17941,66 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) 2023 sarah
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2024 Spire Team
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        MIT License
         
        @@ -13241,30 +18024,64 @@ 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.
         
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        MIT License
        +
        +Copyright (c) 2025 rutrum
        +
        +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.
      • MIT License

        Used by:

        MIT License
        @@ -13291,9 +18108,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        MIT License
         
        @@ -13322,7 +18139,99 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        MIT License
        +
        +Copyright (c) [2021] [Marvin Countryman]
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        Permission is hereby granted, free of charge, to any person obtaining
         a copy of this software and associated documentation files (the
        @@ -13348,37 +18257,39 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        -
        The MIT License (MIT)
        +                
        Portions of this project are derived from atty, which bears the following
        +copyright notice and permission notice:
         
        -Copyright (c) 2014 Benjamin Sago
        -Copyright (c) 2021-2022 The Nushell Project Developers
        +Copyright (c) 2015-2019 Doug Tangren
         
        -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:
        +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 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.
        +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.
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13401,13 +18312,63 @@ 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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Mathijs van de Nes
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Y. T. CHUNG
        +
        +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.
        +
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13435,21 +18396,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Andrew Gallant
        +Copyright (c) 2015 
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13458,28 +18409,39 @@ 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 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.
        +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        +SOFTWARE.
        +
         
      • MIT License

        Used by:

        The MIT License (MIT)
         
         Copyright (c) 2015 Andrew Gallant
        -Copyright (c) 2019 Paul Masurel
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13529,6 +18491,36 @@ 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.
         
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Carl Lerche + nix-rust Authors
        +
        +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.
         
      • @@ -13560,6 +18552,64 @@ 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. +
      • + +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Gerd Zellweger
        +
        +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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Guillaume Gomez
        +
        +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.
        +
         
      • @@ -13595,11 +18645,72 @@ SOFTWARE.

        MIT License

        Used by:

        The MIT License (MIT)
         
        -Copyright (c) 2015 Vincent Prouillet
        +Copyright (c) 2015 Markus Westerlind
        +
        +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.
        +
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015 Michael Sproul
        +
        +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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2015-2020 the fiat-crypto authors (see
        +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
        @@ -13624,7 +18735,7 @@ SOFTWARE.
                         

        MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13640,6 +18751,35 @@ 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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2016 nabijaczleweli
        +
        +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
        @@ -13713,8 +18853,36 @@ SOFTWARE.
                         

        MIT License

        Used by:

        +
        The MIT License (MIT)
        +
        +Copyright (c) 2019 Simon Heath
        +
        +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.
        +
      • +
      • +

        MIT License

        +

        Used by:

        +
        The MIT License (MIT)
         
        @@ -13781,6 +18949,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
         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.
        +
        +
      • +
      • +

        MIT License

        +

        Used by:

        + +
        The MIT License (MIT)
        +
        +Copyright (c) 2014 Benjamin Sago
        +Copyright (c) 2021-2022 The Nushell Project Developers
        +
        +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.
         
      • @@ -13845,8 +19043,9 @@ SOFTWARE.
      • MIT License

        Used by:

        The MIT License (MIT)
         
        @@ -13899,6 +19098,387 @@ 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.
        +
        + +
      • +

        Mozilla Public License 2.0

        +

        Used by:

        + +
        Mozilla Public License Version 2.0
        +==================================
        +
        +1. Definitions
        +--------------
        +
        +1.1. "Contributor"
        +    means each individual or legal entity that creates, contributes to
        +    the creation of, or owns Covered Software.
        +
        +1.2. "Contributor Version"
        +    means the combination of the Contributions of others (if any) used
        +    by a Contributor and that particular Contributor's Contribution.
        +
        +1.3. "Contribution"
        +    means Covered Software of a particular Contributor.
        +
        +1.4. "Covered Software"
        +    means Source Code Form to which the initial Contributor has attached
        +    the notice in Exhibit A, the Executable Form of such Source Code
        +    Form, and Modifications of such Source Code Form, in each case
        +    including portions thereof.
        +
        +1.5. "Incompatible With Secondary Licenses"
        +    means
        +
        +    (a) that the initial Contributor has attached the notice described
        +        in Exhibit B to the Covered Software; or
        +
        +    (b) that the Covered Software was made available under the terms of
        +        version 1.1 or earlier of the License, but not also under the
        +        terms of a Secondary License.
        +
        +1.6. "Executable Form"
        +    means any form of the work other than Source Code Form.
        +
        +1.7. "Larger Work"
        +    means a work that combines Covered Software with other material, in 
        +    a separate file or files, that is not Covered Software.
        +
        +1.8. "License"
        +    means this document.
        +
        +1.9. "Licensable"
        +    means having the right to grant, to the maximum extent possible,
        +    whether at the time of the initial grant or subsequently, any and
        +    all of the rights conveyed by this License.
        +
        +1.10. "Modifications"
        +    means any of the following:
        +
        +    (a) any file in Source Code Form that results from an addition to,
        +        deletion from, or modification of the contents of Covered
        +        Software; or
        +
        +    (b) any new file in Source Code Form that contains any Covered
        +        Software.
        +
        +1.11. "Patent Claims" of a Contributor
        +    means any patent claim(s), including without limitation, method,
        +    process, and apparatus claims, in any patent Licensable by such
        +    Contributor that would be infringed, but for the grant of the
        +    License, by the making, using, selling, offering for sale, having
        +    made, import, or transfer of either its Contributions or its
        +    Contributor Version.
        +
        +1.12. "Secondary License"
        +    means either the GNU General Public License, Version 2.0, the GNU
        +    Lesser General Public License, Version 2.1, the GNU Affero General
        +    Public License, Version 3.0, or any later versions of those
        +    licenses.
        +
        +1.13. "Source Code Form"
        +    means the form of the work preferred for making modifications.
        +
        +1.14. "You" (or "Your")
        +    means an individual or a legal entity exercising rights under this
        +    License. For legal entities, "You" includes any entity that
        +    controls, is controlled by, or is under common control with You. For
        +    purposes of this definition, "control" means (a) the power, direct
        +    or indirect, to cause the direction or management of such entity,
        +    whether by contract or otherwise, or (b) ownership of more than
        +    fifty percent (50%) of the outstanding shares or beneficial
        +    ownership of such entity.
        +
        +2. License Grants and Conditions
        +--------------------------------
        +
        +2.1. Grants
        +
        +Each Contributor hereby grants You a world-wide, royalty-free,
        +non-exclusive license:
        +
        +(a) under intellectual property rights (other than patent or trademark)
        +    Licensable by such Contributor to use, reproduce, make available,
        +    modify, display, perform, distribute, and otherwise exploit its
        +    Contributions, either on an unmodified basis, with Modifications, or
        +    as part of a Larger Work; and
        +
        +(b) under Patent Claims of such Contributor to make, use, sell, offer
        +    for sale, have made, import, and otherwise transfer either its
        +    Contributions or its Contributor Version.
        +
        +2.2. Effective Date
        +
        +The licenses granted in Section 2.1 with respect to any Contribution
        +become effective for each Contribution on the date the Contributor first
        +distributes such Contribution.
        +
        +2.3. Limitations on Grant Scope
        +
        +The licenses granted in this Section 2 are the only rights granted under
        +this License. No additional rights or licenses will be implied from the
        +distribution or licensing of Covered Software under this License.
        +Notwithstanding Section 2.1(b) above, no patent license is granted by a
        +Contributor:
        +
        +(a) for any code that a Contributor has removed from Covered Software;
        +    or
        +
        +(b) for infringements caused by: (i) Your and any other third party's
        +    modifications of Covered Software, or (ii) the combination of its
        +    Contributions with other software (except as part of its Contributor
        +    Version); or
        +
        +(c) under Patent Claims infringed by Covered Software in the absence of
        +    its Contributions.
        +
        +This License does not grant any rights in the trademarks, service marks,
        +or logos of any Contributor (except as may be necessary to comply with
        +the notice requirements in Section 3.4).
        +
        +2.4. Subsequent Licenses
        +
        +No Contributor makes additional grants as a result of Your choice to
        +distribute the Covered Software under a subsequent version of this
        +License (see Section 10.2) or under the terms of a Secondary License (if
        +permitted under the terms of Section 3.3).
        +
        +2.5. Representation
        +
        +Each Contributor represents that the Contributor believes its
        +Contributions are its original creation(s) or it has sufficient rights
        +to grant the rights to its Contributions conveyed by this License.
        +
        +2.6. Fair Use
        +
        +This License is not intended to limit any rights You have under
        +applicable copyright doctrines of fair use, fair dealing, or other
        +equivalents.
        +
        +2.7. Conditions
        +
        +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
        +in Section 2.1.
        +
        +3. Responsibilities
        +-------------------
        +
        +3.1. Distribution of Source Form
        +
        +All distribution of Covered Software in Source Code Form, including any
        +Modifications that You create or to which You contribute, must be under
        +the terms of this License. You must inform recipients that the Source
        +Code Form of the Covered Software is governed by the terms of this
        +License, and how they can obtain a copy of this License. You may not
        +attempt to alter or restrict the recipients' rights in the Source Code
        +Form.
        +
        +3.2. Distribution of Executable Form
        +
        +If You distribute Covered Software in Executable Form then:
        +
        +(a) such Covered Software must also be made available in Source Code
        +    Form, as described in Section 3.1, and You must inform recipients of
        +    the Executable Form how they can obtain a copy of such Source Code
        +    Form by reasonable means in a timely manner, at a charge no more
        +    than the cost of distribution to the recipient; and
        +
        +(b) You may distribute such Executable Form under the terms of this
        +    License, or sublicense it under different terms, provided that the
        +    license for the Executable Form does not attempt to limit or alter
        +    the recipients' rights in the Source Code Form under this License.
        +
        +3.3. Distribution of a Larger Work
        +
        +You may create and distribute a Larger Work under terms of Your choice,
        +provided that You also comply with the requirements of this License for
        +the Covered Software. If the Larger Work is a combination of Covered
        +Software with a work governed by one or more Secondary Licenses, and the
        +Covered Software is not Incompatible With Secondary Licenses, this
        +License permits You to additionally distribute such Covered Software
        +under the terms of such Secondary License(s), so that the recipient of
        +the Larger Work may, at their option, further distribute the Covered
        +Software under the terms of either this License or such Secondary
        +License(s).
        +
        +3.4. Notices
        +
        +You may not remove or alter the substance of any license notices
        +(including copyright notices, patent notices, disclaimers of warranty,
        +or limitations of liability) contained within the Source Code Form of
        +the Covered Software, except that You may alter any license notices to
        +the extent required to remedy known factual inaccuracies.
        +
        +3.5. Application of Additional Terms
        +
        +You may choose to offer, and to charge a fee for, warranty, support,
        +indemnity or liability obligations to one or more recipients of Covered
        +Software. However, You may do so only on Your own behalf, and not on
        +behalf of any Contributor. You must make it absolutely clear that any
        +such warranty, support, indemnity, or liability obligation is offered by
        +You alone, and You hereby agree to indemnify every Contributor for any
        +liability incurred by such Contributor as a result of warranty, support,
        +indemnity or liability terms You offer. You may include additional
        +disclaimers of warranty and limitations of liability specific to any
        +jurisdiction.
        +
        +4. Inability to Comply Due to Statute or Regulation
        +---------------------------------------------------
        +
        +If it is impossible for You to comply with any of the terms of this
        +License with respect to some or all of the Covered Software due to
        +statute, judicial order, or regulation then You must: (a) comply with
        +the terms of this License to the maximum extent possible; and (b)
        +describe the limitations and the code they affect. Such description must
        +be placed in a text file included with all distributions of the Covered
        +Software under this License. Except to the extent prohibited by statute
        +or regulation, such description must be sufficiently detailed for a
        +recipient of ordinary skill to be able to understand it.
        +
        +5. Termination
        +--------------
        +
        +5.1. The rights granted under this License will terminate automatically
        +if You fail to comply with any of its terms. However, if You become
        +compliant, then the rights granted under this License from a particular
        +Contributor are reinstated (a) provisionally, unless and until such
        +Contributor explicitly and finally terminates Your grants, and (b) on an
        +ongoing basis, if such Contributor fails to notify You of the
        +non-compliance by some reasonable means prior to 60 days after You have
        +come back into compliance. Moreover, Your grants from a particular
        +Contributor are reinstated on an ongoing basis if such Contributor
        +notifies You of the non-compliance by some reasonable means, this is the
        +first time You have received notice of non-compliance with this License
        +from such Contributor, and You become compliant prior to 30 days after
        +Your receipt of the notice.
        +
        +5.2. If You initiate litigation against any entity by asserting a patent
        +infringement claim (excluding declaratory judgment actions,
        +counter-claims, and cross-claims) alleging that a Contributor Version
        +directly or indirectly infringes any patent, then the rights granted to
        +You by any and all Contributors for the Covered Software under Section
        +2.1 of this License shall terminate.
        +
        +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
        +end user license agreements (excluding distributors and resellers) which
        +have been validly granted by You or Your distributors under this License
        +prior to termination shall survive termination.
        +
        +************************************************************************
        +*                                                                      *
        +*  6. Disclaimer of Warranty                                           *
        +*  -------------------------                                           *
        +*                                                                      *
        +*  Covered Software is provided under this License on an "as is"       *
        +*  basis, without warranty of any kind, either expressed, implied, or  *
        +*  statutory, including, without limitation, warranties that the       *
        +*  Covered Software is free of defects, merchantable, fit for a        *
        +*  particular purpose or non-infringing. The entire risk as to the     *
        +*  quality and performance of the Covered Software is with You.        *
        +*  Should any Covered Software prove defective in any respect, You     *
        +*  (not any Contributor) assume the cost of any necessary servicing,   *
        +*  repair, or correction. This disclaimer of warranty constitutes an   *
        +*  essential part of this License. No use of any Covered Software is   *
        +*  authorized under this License except under this disclaimer.         *
        +*                                                                      *
        +************************************************************************
        +
        +************************************************************************
        +*                                                                      *
        +*  7. Limitation of Liability                                          *
        +*  --------------------------                                          *
        +*                                                                      *
        +*  Under no circumstances and under no legal theory, whether tort      *
        +*  (including negligence), contract, or otherwise, shall any           *
        +*  Contributor, or anyone who distributes Covered Software as          *
        +*  permitted above, be liable to You for any direct, indirect,         *
        +*  special, incidental, or consequential damages of any character      *
        +*  including, without limitation, damages for lost profits, loss of    *
        +*  goodwill, work stoppage, computer failure or malfunction, or any    *
        +*  and all other commercial damages or losses, even if such party      *
        +*  shall have been informed of the possibility of such damages. This   *
        +*  limitation of liability shall not apply to liability for death or   *
        +*  personal injury resulting from such party's negligence to the       *
        +*  extent applicable law prohibits such limitation. Some               *
        +*  jurisdictions do not allow the exclusion or limitation of           *
        +*  incidental or consequential damages, so this exclusion and          *
        +*  limitation may not apply to You.                                    *
        +*                                                                      *
        +************************************************************************
        +
        +8. Litigation
        +-------------
        +
        +Any litigation relating to this License may be brought only in the
        +courts of a jurisdiction where the defendant maintains its principal
        +place of business and such litigation shall be governed by laws of that
        +jurisdiction, without reference to its conflict-of-law provisions.
        +Nothing in this Section shall prevent a party's ability to bring
        +cross-claims or counter-claims.
        +
        +9. Miscellaneous
        +----------------
        +
        +This License represents the complete agreement concerning the subject
        +matter hereof. If any provision of this License is held to be
        +unenforceable, such provision shall be reformed only to the extent
        +necessary to make it enforceable. Any law or regulation which provides
        +that the language of a contract shall be construed against the drafter
        +shall not be used to construe this License against a Contributor.
        +
        +10. Versions of the License
        +---------------------------
        +
        +10.1. New Versions
        +
        +Mozilla Foundation is the license steward. Except as provided in Section
        +10.3, no one other than the license steward has the right to modify or
        +publish new versions of this License. Each version will be given a
        +distinguishing version number.
        +
        +10.2. Effect of New Versions
        +
        +You may distribute the Covered Software under the terms of the version
        +of the License under which You originally received the Covered Software,
        +or under the terms of any subsequent version published by the license
        +steward.
        +
        +10.3. Modified Versions
        +
        +If you create software not governed by this License, and you want to
        +create a new license for such software, you may create and use a
        +modified version of this License if you rename the license and remove
        +any references to the name of the license steward (except to note that
        +such modified license differs from this License).
        +
        +10.4. Distributing Source Code Form that is Incompatible With Secondary
        +Licenses
        +
        +If You choose to distribute Source Code Form that is Incompatible With
        +Secondary Licenses under the terms of this version of the License, the
        +notice described in Exhibit B of this License must be attached.
        +
        +Exhibit A - Source Code Form License Notice
        +-------------------------------------------
        +
        +  This Source Code Form is subject to the terms of the Mozilla Public
        +  License, v. 2.0. If a copy of the MPL was not distributed with this
        +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
        +
        +If it is not possible or desirable to put the notice in a particular
        +file, then You may include the notice in a location (such as a LICENSE
        +file in a relevant directory) where a recipient would be likely to look
        +for such a notice.
        +
        +You may add additional accurate notices of copyright ownership.
        +
        +Exhibit B - "Incompatible With Secondary Licenses" Notice
        +---------------------------------------------------------
        +
        +  This Source Code Form is "Incompatible With Secondary Licenses", as
        +  defined by the Mozilla Public License, v. 2.0.
         
      • @@ -14280,187 +19860,13 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -
      • - -
      • -

        OpenSSL License

        -

        Used by:

        - -
        /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
        - * All rights reserved.
        - *
        - * This package is an SSL implementation written
        - * by Eric Young (eay@cryptsoft.com).
        - * The implementation was written so as to conform with Netscapes SSL.
        - *
        - * This library is free for commercial and non-commercial use as long as
        - * the following conditions are aheared to.  The following conditions
        - * apply to all code found in this distribution, be it the RC4, RSA,
        - * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
        - * included with this distribution is covered by the same copyright terms
        - * except that the holder is Tim Hudson (tjh@cryptsoft.com).
        - *
        - * Copyright remains Eric Young's, and as such any Copyright notices in
        - * the code are not to be removed.
        - * If this package is used in a product, Eric Young should be given attribution
        - * as the author of the parts of the library used.
        - * This can be in the form of a textual message at program startup or
        - * in documentation (online or textual) provided with the package.
        - *
        - * Redistribution and use in source and binary forms, with or without
        - * modification, are permitted provided that the following conditions
        - * are met:
        - * 1. Redistributions of source code must retain the copyright
        - *    notice, this list of conditions and the following disclaimer.
        - * 2. Redistributions in binary form must reproduce the above copyright
        - *    notice, this list of conditions and the following disclaimer in the
        - *    documentation and/or other materials provided with the distribution.
        - * 3. All advertising materials mentioning features or use of this software
        - *    must display the following acknowledgement:
        - *    "This product includes cryptographic software written by
        - *     Eric Young (eay@cryptsoft.com)"
        - *    The word 'cryptographic' can be left out if the rouines from the library
        - *    being used are not cryptographic related :-).
        - * 4. If you include any Windows specific code (or a derivative thereof) from
        - *    the apps directory (application code) you must include an acknowledgement:
        - *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
        - *
        - * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
        - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
        - * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
        - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
        - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
        - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
        - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
        - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
        - * SUCH DAMAGE.
        - *
        - * The licence and distribution terms for any publically available version or
        - * derivative of this code cannot be changed.  i.e. this code cannot simply be
        - * copied and put under another distribution licence
        - * [including the GNU Public Licence.]
        - */
        -/* ====================================================================
        - * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
        - *
        - * Redistribution and use in source and binary forms, with or without
        - * modification, are permitted provided that the following conditions
        - * are met:
        - *
        - * 1. Redistributions of source code must retain the above copyright
        - *    notice, this list of conditions and the following disclaimer.
        - *
        - * 2. Redistributions in binary form must reproduce the above copyright
        - *    notice, this list of conditions and the following disclaimer in
        - *    the documentation and/or other materials provided with the
        - *    distribution.
        - *
        - * 3. All advertising materials mentioning features or use of this
        - *    software must display the following acknowledgment:
        - *    "This product includes software developed by the OpenSSL Project
        - *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
        - *
        - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
        - *    endorse or promote products derived from this software without
        - *    prior written permission. For written permission, please contact
        - *    openssl-core@openssl.org.
        - *
        - * 5. Products derived from this software may not be called "OpenSSL"
        - *    nor may "OpenSSL" appear in their names without prior written
        - *    permission of the OpenSSL Project.
        - *
        - * 6. Redistributions of any form whatsoever must retain the following
        - *    acknowledgment:
        - *    "This product includes software developed by the OpenSSL Project
        - *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
        - *
        - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
        - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        - * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
        - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
        - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
        - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
        - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
        - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
        - * OF THE POSSIBILITY OF SUCH DAMAGE.
        - * ====================================================================
        - *
        - * This product includes cryptographic software written by Eric Young
        - * (eay@cryptsoft.com).  This product includes software written by Tim
        - * Hudson (tjh@cryptsoft.com).
        - *
        - */
        -
        -#include <openssl/ssl.h>
        -
        -#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_PNACL) && \
        -    !defined(OPENSSL_NO_FILESYSTEM)
        -
        -#include <dirent.h>
        -#include <errno.h>
        -#include <string.h>
        -
        -#include <openssl/err.h>
        -#include <openssl/mem.h>
        -
        -
        -int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
        -                                       const char *path) {
        -  DIR *dir = opendir(path);
        -  if (dir == NULL) {
        -    OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
        -    ERR_add_error_data(3, "opendir('", dir, "')");
        -    return 0;
        -  }
        -
        -  int ret = 0;
        -  for (;;) {
        -    // |readdir| may fail with or without setting |errno|.
        -    errno = 0;
        -    struct dirent *dirent = readdir(dir);
        -    if (dirent == NULL) {
        -      if (errno) {
        -        OPENSSL_PUT_ERROR(SSL, ERR_R_SYS_LIB);
        -        ERR_add_error_data(3, "readdir('", path, "')");
        -      } else {
        -        ret = 1;
        -      }
        -      break;
        -    }
        -
        -    char buf[1024];
        -    if (strlen(path) + strlen(dirent->d_name) + 2 > sizeof(buf)) {
        -      OPENSSL_PUT_ERROR(SSL, SSL_R_PATH_TOO_LONG);
        -      break;
        -    }
        -
        -    int r = snprintf(buf, sizeof(buf), "%s/%s", path, dirent->d_name);
        -    if (r <= 0 ||
        -        r >= (int)sizeof(buf) ||
        -        !SSL_add_file_cert_subjects_to_stack(stack, buf)) {
        -      break;
        -    }
        -  }
        -
        -  closedir(dir);
        -  return ret;
        -}
        -
        -#endif  // !WINDOWS && !PNACL && !OPENSSL_NO_FILESYSTEM
         
      • Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14507,24 +19913,28 @@ authorization of the copyright holder.
                         

        Unicode License v3

        Used by:

        UNICODE LICENSE V3
         
        @@ -14573,12 +19983,63 @@ SPDX-License-Identifier: Unicode-3.0
         Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
         ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
         
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2021 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
        +
      • +
      • +

        zlib License

        +

        Used by:

        + +
        Copyright (c) 2023 Matias Rodriguez.
        +
        +This software is provided 'as-is', without any express or implied
        +warranty. In no event will the authors be held liable for any damages
        +arising from the use of this software.
        +
        +Permission is granted to anyone to use this software for any purpose,
        +including commercial applications, and to alter it and redistribute it
        +freely, subject to the following restrictions:
        +
        +1. The origin of this software must not be misrepresented; you must not
        +   claim that you wrote the original software. If you use this software
        +   in a product, an acknowledgment in the product documentation would be
        +   appreciated but is not required.
        +2. Altered source versions must be plainly marked as such, and must not be
        +   misrepresented as being the original software.
        +3. This notice may not be removed or altered from any source distribution.
      • zlib License

        Used by:

        Copyright (c) 2024 Orson Peters
         
        diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts
        index 18bf0f1ce..eccfb9ffd 100644
        --- a/nodejs/__test__/remote.test.ts
        +++ b/nodejs/__test__/remote.test.ts
        @@ -1435,6 +1435,87 @@ describe("remote connection", () => {
             expect(createIndexBody?.["custom_stop_words"]).toEqual(["the"]);
           });
         
        +  it("sends RTree options to remote tables", async () => {
        +    const createIndexBodies: Record[] = [];
        +
        +    await withMockDatabase(
        +      (req, res) => {
        +        const path = req.url ?? "";
        +        if (path.endsWith("/describe/")) {
        +          res.writeHead(200, { "Content-Type": "application/json" }).end(
        +            JSON.stringify({
        +              name: "t",
        +              version: 1,
        +              schema: {
        +                fields: [
        +                  {
        +                    name: "geom",
        +                    type: {
        +                      type: "struct",
        +                      fields: [
        +                        {
        +                          name: "x",
        +                          type: { type: "double" },
        +                          nullable: false,
        +                        },
        +                        {
        +                          name: "y",
        +                          type: { type: "double" },
        +                          nullable: false,
        +                        },
        +                      ],
        +                    },
        +                    nullable: true,
        +                    metadata: { "ARROW:extension:name": "geoarrow.point" },
        +                  },
        +                ],
        +              },
        +            }),
        +          );
        +          return;
        +        }
        +
        +        if (path.endsWith("/create_index/")) {
        +          let raw = "";
        +          req.on("data", (chunk) => {
        +            raw += chunk;
        +          });
        +          req.on("end", () => {
        +            createIndexBodies.push(JSON.parse(raw));
        +            res.writeHead(200).end();
        +          });
        +          return;
        +        }
        +
        +        res.writeHead(404).end();
        +      },
        +      async (db) => {
        +        const table = await db.openTable("t");
        +        await table.createIndex("geom", { config: Index.rtree() });
        +        await table.createIndex("geom", {
        +          config: Index.rtree({ pageSize: 1024 }),
        +          name: "geom_rtree",
        +        });
        +      },
        +    );
        +
        +    expect(createIndexBodies).toEqual([
        +      {
        +        column: "geom",
        +        // biome-ignore lint/style/useNamingConvention: server wire format
        +        index_type: "RTREE",
        +      },
        +      {
        +        column: "geom",
        +        // biome-ignore lint/style/useNamingConvention: server wire format
        +        index_type: "RTREE",
        +        name: "geom_rtree",
        +        // biome-ignore lint/style/useNamingConvention: server wire format
        +        page_size: 1024,
        +      },
        +    ]);
        +  });
        +
           it("diffs and cherry-picks remote branches", async () => {
             const sampleDiff = {
               fromBranch: "exp",
        diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts
        index bfe69e931..7aac3864c 100644
        --- a/nodejs/__test__/table.test.ts
        +++ b/nodejs/__test__/table.test.ts
        @@ -1833,6 +1833,104 @@ describe("When creating an index", () => {
             expect(fs.readdirSync(indexDir)).toHaveLength(1);
           });
         
        +  describe("on a GeoArrow column", () => {
        +    // Row `10 * y + x` sits at (x, y). The triangle's bounding box covers the
        +    // 25 points with x <= 4 and y <= 4, but only the 15 with x + y <= 4
        +    // intersect the triangle itself.
        +    const inTriangle =
        +      "ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))";
        +    const triangleIds = [0, 1, 2, 3, 4, 10, 11, 12, 13, 20, 21, 22, 30, 31, 40];
        +    let geoTbl: Table;
        +
        +    beforeEach(async () => {
        +      const point = new Struct([
        +        new Field("x", new Float64(), false),
        +        new Field("y", new Float64(), false),
        +      ]);
        +      const geoSchema = new Schema([
        +        new Field("id", new Int32(), false),
        +        new Field(
        +          "geom",
        +          point,
        +          true,
        +          new Map([
        +            ["ARROW:extension:name", "geoarrow.point"],
        +            ["ARROW:extension:metadata", "{}"],
        +          ]),
        +        ),
        +        new Field(
        +          "vec",
        +          new FixedSizeList(2, new Field("item", new Float32())),
        +        ),
        +      ]);
        +      const data = makeArrowTable(
        +        Array.from({ length: 100 }, (_, i) => ({
        +          id: i,
        +          geom: { x: i % 10, y: Math.floor(i / 10) },
        +          vec: [i, i],
        +        })),
        +        { schema: geoSchema },
        +      );
        +      const db = await connect(tmpDir.name);
        +      geoTbl = await db.createTable("points", data);
        +    });
        +
        +    const ids = (rows: { id: number }[]) => rows.map((row) => row.id);
        +
        +    test("create an RTree index and filter with it", async () => {
        +      await geoTbl.createIndex("geom", { config: Index.rtree() });
        +      expect(await geoTbl.listIndices()).toEqual([
        +        expect.objectContaining({
        +          name: "geom_idx",
        +          indexType: "RTree",
        +          columns: ["geom"],
        +        }),
        +      ]);
        +      const stats = await geoTbl.indexStats("geom_idx");
        +      expect(stats?.indexType).toEqual("RTREE");
        +      expect(stats?.numIndexedRows).toEqual(100);
        +
        +      const query = geoTbl.query().where(inTriangle);
        +      expect(await query.explainPlan(true)).toContain("ScalarIndexQuery");
        +      expect(ids(await query.toArray()).sort((a, b) => a - b)).toEqual(
        +        triangleIds,
        +      );
        +    });
        +
        +    test("prefilter a vector search with an RTree index", async () => {
        +      await geoTbl.createIndex("geom", {
        +        config: Index.rtree({ pageSize: 16 }),
        +      });
        +      // Row 99 sits outside the triangle; its nearest vectors are 98, 97, ...
        +      const prefiltered = geoTbl
        +        .query()
        +        .nearestTo([99, 99])
        +        .where(inTriangle)
        +        .limit(5);
        +      expect(await prefiltered.explainPlan(true)).toContain("ScalarIndexQuery");
        +      expect(ids(await prefiltered.toArray())).toEqual([40, 31, 30, 22, 21]);
        +
        +      const postfiltered = geoTbl
        +        .query()
        +        .nearestTo([99, 99])
        +        .where(inTriangle)
        +        .postfilter()
        +        .limit(5);
        +      expect(await postfiltered.toArray()).toEqual([]);
        +    });
        +
        +    test("reject invalid RTree options", async () => {
        +      for (const pageSize of [1, 0, -1, 2.5, Number.NaN, 2 ** 32]) {
        +        expect(() => Index.rtree({ pageSize })).toThrow(
        +          "page_size must be at least 2",
        +        );
        +      }
        +      await expect(
        +        geoTbl.createIndex("id", { config: Index.rtree() }),
        +      ).rejects.toThrow("GeoArrow");
        +    });
        +  });
        +
           test("should be able to get index stats", async () => {
             await tbl.createIndex("id");
         
        diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts
        index b99d856cc..aa51c2b56 100644
        --- a/nodejs/lancedb/index.ts
        +++ b/nodejs/lancedb/index.ts
        @@ -153,6 +153,7 @@ export {
           HnswPqOptions,
           HnswSqOptions,
           FtsOptions,
        +  RTreeOptions,
           BaseTokenizer,
         } from "./indices";
         
        diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts
        index 53cbf8a4d..d743827da 100644
        --- a/nodejs/lancedb/indices.ts
        +++ b/nodejs/lancedb/indices.ts
        @@ -678,6 +678,18 @@ export interface FtsOptions {
           blockSize?: 128 | 256;
         }
         
        +/**
        + * Options to create an `RTREE` index
        + */
        +export interface RTreeOptions {
        +  /**
        +   * The maximum number of entries in each R-tree page.
        +   *
        +   * Must be at least 2. The default is 4096.
        +   */
        +  pageSize?: number;
        +}
        +
         export class Index {
           private readonly inner: LanceDbIndex;
           private constructor(inner: LanceDbIndex) {
        @@ -834,6 +846,53 @@ export class Index {
             return new Index(LanceDbIndex.fm());
           }
         
        +  /**
        +   * Create an RTree index.
        +   *
        +   * An RTree index is a scalar index on a GeoArrow geometry column, that is, a
        +   * column whose Arrow field metadata sets `ARROW:extension:name` to a GeoArrow
        +   * type such as `geoarrow.point`, `geoarrow.polygon` or `geoarrow.wkb`. It
        +   * stores the bounding box of each geometry and accelerates spatial filters.
        +   *
        +   * The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`,
        +   * `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy`
        +   * between the indexed column and a constant geometry, in either argument
        +   * order, for example
        +   * `ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))`, as well as
        +   * `geom IS NULL`. These filters can be combined with other conditions using
        +   * `AND`.
        +   *
        +   * See the R-tree section of https://docs.lancedb.com/indexing/scalar-index
        +   * for storing geometry, the other spatial functions, and spatial filters on
        +   * vector search.
        +   *
        +   * Remote tables send the `RTREE` index type to the server, which must
        +   * support it.
        +   *
        +   * @example
        +   * ```ts
        +   * await table.createIndex("geom", { config: Index.rtree() });
        +   * await table
        +   *   .query()
        +   *   .where("ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))'))")
        +   *   .toArray();
        +   * ```
        +   */
        +  static rtree(options?: Partial) {
        +    const pageSize = options?.pageSize;
        +    // napi converts a number to u32 by wrapping, so -1 would arrive as
        +    // 4294967295; reject anything that is not a valid page size first.
        +    if (
        +      pageSize !== undefined &&
        +      !(Number.isInteger(pageSize) && pageSize >= 2 && pageSize <= 0xffffffff)
        +    ) {
        +      throw new Error(
        +        `RTree page_size must be at least 2, at most 4294967295, and an integer, got ${pageSize}`,
        +      );
        +    }
        +    return new Index(LanceDbIndex.rtree(pageSize));
        +  }
        +
           /**
            * Create a full text search index
            *
        diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs
        index 39aa6f8b8..80107b0b4 100644
        --- a/nodejs/src/index.rs
        +++ b/nodejs/src/index.rs
        @@ -4,7 +4,9 @@
         use std::sync::Mutex;
         
         use lancedb::index::Index as LanceDbIndex;
        -use lancedb::index::scalar::{BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder};
        +use lancedb::index::scalar::{
        +    BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, RTreeIndexBuilder,
        +};
         use lancedb::index::vector::{
             IvfFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder,
             IvfRqIndexBuilder,
        @@ -226,6 +228,17 @@ impl Index {
                 }
             }
         
        +    #[napi(factory)]
        +    pub fn rtree(page_size: Option) -> napi::Result {
        +        let mut builder = RTreeIndexBuilder::default();
        +        if let Some(page_size) = page_size {
        +            builder = builder.page_size(page_size).default_error()?;
        +        }
        +        Ok(Self {
        +            inner: Mutex::new(Some(LanceDbIndex::RTree(builder))),
        +        })
        +    }
        +
             #[napi(factory)]
             #[allow(clippy::too_many_arguments)]
             pub fn fts(
        diff --git a/python/Cargo.toml b/python/Cargo.toml
        index 8604daabf..631340ce2 100644
        --- a/python/Cargo.toml
        +++ b/python/Cargo.toml
        @@ -51,7 +51,7 @@ libc = "0.2"
         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"]
        +default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"]
         fp16kernels = ["lancedb/fp16kernels"]
         remote = ["lancedb/remote"]
         experimental-functions = ["lancedb/experimental-functions"]
        diff --git a/python/RUST_THIRD_PARTY_LICENSES.html b/python/RUST_THIRD_PARTY_LICENSES.html
        index f5e8197fd..2e0c1f20c 100644
        --- a/python/RUST_THIRD_PARTY_LICENSES.html
        +++ b/python/RUST_THIRD_PARTY_LICENSES.html
        @@ -44,18 +44,19 @@
             
                 

        Overview of licenses:

        All license text:

        @@ -64,230 +65,20 @@

        BSD Zero Clause License

        Used by:

        -
        Copyright (C) 2020 by museun <museun@outlook.com>
        +                
        Copyright (C) Jonas Schievink <jonasschievink@gmail.com>
         
        -Permission to use, copy, modify, and/or distribute this software for any purpose
        -with or without fee is hereby granted.
        +Permission to use, copy, modify, and/or distribute this software for
        +any purpose with or without fee is hereby granted.
         
        -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
        -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
        -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
        -THIS SOFTWARE.
        -
        -
      • -
      • -

        Apache License 2.0

        -

        Used by:

        - -
        -                                 Apache License
        -                           Version 2.0, January 2004
        -                        http://www.apache.org/licenses/
        -
        -   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        -
        -   1. Definitions.
        -
        -      "License" shall mean the terms and conditions for use, reproduction,
        -      and distribution as defined by Sections 1 through 9 of this document.
        -
        -      "Licensor" shall mean the copyright owner or entity authorized by
        -      the copyright owner that is granting the License.
        -
        -      "Legal Entity" shall mean the union of the acting entity and all
        -      other entities that control, are controlled by, or are under common
        -      control with that entity. For the purposes of this definition,
        -      "control" means (i) the power, direct or indirect, to cause the
        -      direction or management of such entity, whether by contract or
        -      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        -      outstanding shares, or (iii) beneficial ownership of such entity.
        -
        -      "You" (or "Your") shall mean an individual or Legal Entity
        -      exercising permissions granted by this License.
        -
        -      "Source" form shall mean the preferred form for making modifications,
        -      including but not limited to software source code, documentation
        -      source, and configuration files.
        -
        -      "Object" form shall mean any form resulting from mechanical
        -      transformation or translation of a Source form, including but
        -      not limited to compiled object code, generated documentation,
        -      and conversions to other media types.
        -
        -      "Work" shall mean the work of authorship, whether in Source or
        -      Object form, made available under the License, as indicated by a
        -      copyright notice that is included in or attached to the work
        -      (an example is provided in the Appendix below).
        -
        -      "Derivative Works" shall mean any work, whether in Source or Object
        -      form, that is based on (or derived from) the Work and for which the
        -      editorial revisions, annotations, elaborations, or other modifications
        -      represent, as a whole, an original work of authorship. For the purposes
        -      of this License, Derivative Works shall not include works that remain
        -      separable from, or merely link (or bind by name) to the interfaces of,
        -      the Work and Derivative Works thereof.
        -
        -      "Contribution" shall mean any work of authorship, including
        -      the original version of the Work and any modifications or additions
        -      to that Work or Derivative Works thereof, that is intentionally
        -      submitted to Licensor for inclusion in the Work by the copyright owner
        -      or by an individual or Legal Entity authorized to submit on behalf of
        -      the copyright owner. For the purposes of this definition, "submitted"
        -      means any form of electronic, verbal, or written communication sent
        -      to the Licensor or its representatives, including but not limited to
        -      communication on electronic mailing lists, source code control systems,
        -      and issue tracking systems that are managed by, or on behalf of, the
        -      Licensor for the purpose of discussing and improving the Work, but
        -      excluding communication that is conspicuously marked or otherwise
        -      designated in writing by the copyright owner as "Not a Contribution."
        -
        -      "Contributor" shall mean Licensor and any individual or Legal Entity
        -      on behalf of whom a Contribution has been received by Licensor and
        -      subsequently incorporated within the Work.
        -
        -   2. Grant of Copyright License. Subject to the terms and conditions of
        -      this License, each Contributor hereby grants to You a perpetual,
        -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        -      copyright license to reproduce, prepare Derivative Works of,
        -      publicly display, publicly perform, sublicense, and distribute the
        -      Work and such Derivative Works in Source or Object form.
        -
        -   3. Grant of Patent License. Subject to the terms and conditions of
        -      this License, each Contributor hereby grants to You a perpetual,
        -      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        -      (except as stated in this section) patent license to make, have made,
        -      use, offer to sell, sell, import, and otherwise transfer the Work,
        -      where such license applies only to those patent claims licensable
        -      by such Contributor that are necessarily infringed by their
        -      Contribution(s) alone or by combination of their Contribution(s)
        -      with the Work to which such Contribution(s) was submitted. If You
        -      institute patent litigation against any entity (including a
        -      cross-claim or counterclaim in a lawsuit) alleging that the Work
        -      or a Contribution incorporated within the Work constitutes direct
        -      or contributory patent infringement, then any patent licenses
        -      granted to You under this License for that Work shall terminate
        -      as of the date such litigation is filed.
        -
        -   4. Redistribution. You may reproduce and distribute copies of the
        -      Work or Derivative Works thereof in any medium, with or without
        -      modifications, and in Source or Object form, provided that You
        -      meet the following conditions:
        -
        -      (a) You must give any other recipients of the Work or
        -          Derivative Works a copy of this License; and
        -
        -      (b) You must cause any modified files to carry prominent notices
        -          stating that You changed the files; and
        -
        -      (c) You must retain, in the Source form of any Derivative Works
        -          that You distribute, all copyright, patent, trademark, and
        -          attribution notices from the Source form of the Work,
        -          excluding those notices that do not pertain to any part of
        -          the Derivative Works; and
        -
        -      (d) If the Work includes a "NOTICE" text file as part of its
        -          distribution, then any Derivative Works that You distribute must
        -          include a readable copy of the attribution notices contained
        -          within such NOTICE file, excluding those notices that do not
        -          pertain to any part of the Derivative Works, in at least one
        -          of the following places: within a NOTICE text file distributed
        -          as part of the Derivative Works; within the Source form or
        -          documentation, if provided along with the Derivative Works; or,
        -          within a display generated by the Derivative Works, if and
        -          wherever such third-party notices normally appear. The contents
        -          of the NOTICE file are for informational purposes only and
        -          do not modify the License. You may add Your own attribution
        -          notices within Derivative Works that You distribute, alongside
        -          or as an addendum to the NOTICE text from the Work, provided
        -          that such additional attribution notices cannot be construed
        -          as modifying the License.
        -
        -      You may add Your own copyright statement to Your modifications and
        -      may provide additional or different license terms and conditions
        -      for use, reproduction, or distribution of Your modifications, or
        -      for any such Derivative Works as a whole, provided Your use,
        -      reproduction, and distribution of the Work otherwise complies with
        -      the conditions stated in this License.
        -
        -   5. Submission of Contributions. Unless You explicitly state otherwise,
        -      any Contribution intentionally submitted for inclusion in the Work
        -      by You to the Licensor shall be under the terms and conditions of
        -      this License, without any additional terms or conditions.
        -      Notwithstanding the above, nothing herein shall supersede or modify
        -      the terms of any separate license agreement you may have executed
        -      with Licensor regarding such Contributions.
        -
        -   6. Trademarks. This License does not grant permission to use the trade
        -      names, trademarks, service marks, or product names of the Licensor,
        -      except as required for reasonable and customary use in describing the
        -      origin of the Work and reproducing the content of the NOTICE file.
        -
        -   7. Disclaimer of Warranty. Unless required by applicable law or
        -      agreed to in writing, Licensor provides the Work (and each
        -      Contributor provides its Contributions) on an "AS IS" BASIS,
        -      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        -      implied, including, without limitation, any warranties or conditions
        -      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        -      PARTICULAR PURPOSE. You are solely responsible for determining the
        -      appropriateness of using or redistributing the Work and assume any
        -      risks associated with Your exercise of permissions under this License.
        -
        -   8. Limitation of Liability. In no event and under no legal theory,
        -      whether in tort (including negligence), contract, or otherwise,
        -      unless required by applicable law (such as deliberate and grossly
        -      negligent acts) or agreed to in writing, shall any Contributor be
        -      liable to You for damages, including any direct, indirect, special,
        -      incidental, or consequential damages of any character arising as a
        -      result of this License or out of the use or inability to use the
        -      Work (including but not limited to damages for loss of goodwill,
        -      work stoppage, computer failure or malfunction, or any and all
        -      other commercial damages or losses), even if such Contributor
        -      has been advised of the possibility of such damages.
        -
        -   9. Accepting Warranty or Additional Liability. While redistributing
        -      the Work or Derivative Works thereof, You may choose to offer,
        -      and charge a fee for, acceptance of support, warranty, indemnity,
        -      or other liability obligations and/or rights consistent with this
        -      License. However, in accepting such obligations, You may act only
        -      on Your own behalf and on Your sole responsibility, not on behalf
        -      of any other Contributor, and only if You agree to indemnify,
        -      defend, and hold each Contributor harmless for any liability
        -      incurred by, or claims asserted against, such Contributor by reason
        -      of your accepting any such warranty or additional liability.
        -
        -   END OF TERMS AND CONDITIONS
        -
        -   APPENDIX: How to apply the Apache License to your work.
        -
        -      To apply the Apache License to your work, attach the following
        -      boilerplate notice, with the fields enclosed by brackets "[]"
        -      replaced with your own identifying information. (Don't include
        -      the brackets!)  The text should be enclosed in the appropriate
        -      comment syntax for the file format. We also recommend that a
        -      file or class name and description of purpose be included on the
        -      same "printed page" as the copyright notice for easier
        -      identification within third-party archives.
        -
        -   Copyright 2023 Jacob Pratt
        -
        -   Licensed under the Apache License, Version 2.0 (the "License");
        -   you may not use this file except in compliance with the License.
        -   You may obtain a copy of the License at
        -
        -       http://www.apache.org/licenses/LICENSE-2.0
        -
        -   Unless required by applicable law or agreed to in writing, software
        -   distributed under the License is distributed on an "AS IS" BASIS,
        -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        -   See the License for the specific language governing permissions and
        -   limitations under the License.
        +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
        +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
        +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
        +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
         
      • @@ -504,7 +295,7 @@ THIS SOFTWARE.

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -714,7 +505,8 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -923,24 +715,18 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

        @@ -1151,7 +937,8 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -1363,7 +1150,13 @@ THIS SOFTWARE.
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -1591,34 +1384,316 @@ Software.
                         

        Apache License 2.0

        Used by:

        +
        +                                 Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
        +Licenses for support code
        +-------------------------
        +
        +Parts of the TLS test suite are under the Go license. This code is not included
        +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
        +distributing code linked against BoringSSL does not trigger this license:
        +
        +Copyright (c) 2009 The Go Authors. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +   * Redistributions of source code must retain the above copyright
        +notice, this list of conditions and the following disclaimer.
        +   * Redistributions in binary form must reproduce the above
        +copyright notice, this list of conditions and the following disclaimer
        +in the documentation and/or other materials provided with the
        +distribution.
        +   * Neither the name of Google Inc. nor the names of its
        +contributors may be used to endorse or promote products derived from
        +this software without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
        +BoringSSL uses the Chromium test infrastructure to run a continuous build,
        +trybots etc. The scripts which manage this, and the script for generating build
        +metadata, are under the Chromium license. Distributing code linked against
        +BoringSSL does not trigger this license.
        +
        +Copyright 2015 The Chromium Authors. All rights reserved.
        +
        +Redistribution and use in source and binary forms, with or without
        +modification, are permitted provided that the following conditions are
        +met:
        +
        +   * Redistributions of source code must retain the above copyright
        +notice, this list of conditions and the following disclaimer.
        +   * Redistributions in binary form must reproduce the above
        +copyright notice, this list of conditions and the following disclaimer
        +in the documentation and/or other materials provided with the
        +distribution.
        +   * Neither the name of Google Inc. nor the names of its
        +contributors may be used to endorse or promote products derived from
        +this software without specific prior written permission.
        +
        +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
        +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
        +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
        +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
        +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
        +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
        +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
        +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                          Apache License
        @@ -1832,6 +1907,238 @@ This project includes code from Apache Aurora.
         Copyright: 2016 The Apache Software Foundation.
         Home page: https://aurora.apache.org/
         License: http://www.apache.org/licenses/LICENSE-2.0
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
        +                                 Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +--------------------------------------------------------------------------------
        +
        +arrow-array/src/delta.rs: MIT
        +
        +This file is derived from the chronoutil crate. The full MIT license
        +text is in arrow-array/LICENSE-MIT.
         
      • @@ -1839,9 +2146,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0

        Used by:

                                          Apache License
        @@ -2051,7 +2356,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                          Apache License
        @@ -2460,41 +2765,30 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -2703,7 +2997,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -2912,7 +3206,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3102,7 +3397,425 @@ License: http://www.apache.org/licenses/LICENSE-2.0
               same "printed page" as the copyright notice for easier
               identification within third-party archives.
         
        -   Copyright 2020 - 2025 Tatsuya Kawano
        +   Copyright 2019 TiKV Project Authors.
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright 2020 - 2026 Tatsuya Kawano
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright 2020 Sébastien Crozet
         
            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
        @@ -3122,7 +3835,6 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3330,8 +4042,8 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3750,7 +4462,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -3959,9 +4671,21 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -4170,7 +4894,456 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

        +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
        +------------------------------------------------------------------------------------
        +This product bundles third-party components under other open source licenses.
        +This section summarizes those components and their licenses. See the referenced
        +license files for text of these licenses.
        +
        +
        +Creative Commons Zero v1.0 Universal
        +------------------------------------
        +
        +bindings/dotnet/.gitignore
        +
        +The above file is derived from VisualStudio.gitignore in
        +https://github.com/github/gitignore. Its license text is in
        +bindings/dotnet/LICENSE-CC0-1.0.txt.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright [yyyy] [name of copyright owner]
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +   
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                         Apache License
                                    Version 2.0, January 2004
        @@ -4379,6 +5552,218 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

        +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "{}"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright Individual contributors
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                         Apache License
        @@ -4588,22 +5973,28 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                         Apache License
                                    Version 2.0, January 2004
        @@ -4813,12 +6204,221 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

        +
                                         Apache License
        +                           Version 2.0, January 2004
        +                        http://www.apache.org/licenses/
        +
        +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +   1. Definitions.
        +
        +      "License" shall mean the terms and conditions for use, reproduction,
        +      and distribution as defined by Sections 1 through 9 of this document.
        +
        +      "Licensor" shall mean the copyright owner or entity authorized by
        +      the copyright owner that is granting the License.
        +
        +      "Legal Entity" shall mean the union of the acting entity and all
        +      other entities that control, are controlled by, or are under common
        +      control with that entity. For the purposes of this definition,
        +      "control" means (i) the power, direct or indirect, to cause the
        +      direction or management of such entity, whether by contract or
        +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +      outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +      "You" (or "Your") shall mean an individual or Legal Entity
        +      exercising permissions granted by this License.
        +
        +      "Source" form shall mean the preferred form for making modifications,
        +      including but not limited to software source code, documentation
        +      source, and configuration files.
        +
        +      "Object" form shall mean any form resulting from mechanical
        +      transformation or translation of a Source form, including but
        +      not limited to compiled object code, generated documentation,
        +      and conversions to other media types.
        +
        +      "Work" shall mean the work of authorship, whether in Source or
        +      Object form, made available under the License, as indicated by a
        +      copyright notice that is included in or attached to the work
        +      (an example is provided in the Appendix below).
        +
        +      "Derivative Works" shall mean any work, whether in Source or Object
        +      form, that is based on (or derived from) the Work and for which the
        +      editorial revisions, annotations, elaborations, or other modifications
        +      represent, as a whole, an original work of authorship. For the purposes
        +      of this License, Derivative Works shall not include works that remain
        +      separable from, or merely link (or bind by name) to the interfaces of,
        +      the Work and Derivative Works thereof.
        +
        +      "Contribution" shall mean any work of authorship, including
        +      the original version of the Work and any modifications or additions
        +      to that Work or Derivative Works thereof, that is intentionally
        +      submitted to Licensor for inclusion in the Work by the copyright owner
        +      or by an individual or Legal Entity authorized to submit on behalf of
        +      the copyright owner. For the purposes of this definition, "submitted"
        +      means any form of electronic, verbal, or written communication sent
        +      to the Licensor or its representatives, including but not limited to
        +      communication on electronic mailing lists, source code control systems,
        +      and issue tracking systems that are managed by, or on behalf of, the
        +      Licensor for the purpose of discussing and improving the Work, but
        +      excluding communication that is conspicuously marked or otherwise
        +      designated in writing by the copyright owner as "Not a Contribution."
        +
        +      "Contributor" shall mean Licensor and any individual or Legal Entity
        +      on behalf of whom a Contribution has been received by Licensor and
        +      subsequently incorporated within the Work.
        +
        +   2. Grant of Copyright License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      copyright license to reproduce, prepare Derivative Works of,
        +      publicly display, publicly perform, sublicense, and distribute the
        +      Work and such Derivative Works in Source or Object form.
        +
        +   3. Grant of Patent License. Subject to the terms and conditions of
        +      this License, each Contributor hereby grants to You a perpetual,
        +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +      (except as stated in this section) patent license to make, have made,
        +      use, offer to sell, sell, import, and otherwise transfer the Work,
        +      where such license applies only to those patent claims licensable
        +      by such Contributor that are necessarily infringed by their
        +      Contribution(s) alone or by combination of their Contribution(s)
        +      with the Work to which such Contribution(s) was submitted. If You
        +      institute patent litigation against any entity (including a
        +      cross-claim or counterclaim in a lawsuit) alleging that the Work
        +      or a Contribution incorporated within the Work constitutes direct
        +      or contributory patent infringement, then any patent licenses
        +      granted to You under this License for that Work shall terminate
        +      as of the date such litigation is filed.
        +
        +   4. Redistribution. You may reproduce and distribute copies of the
        +      Work or Derivative Works thereof in any medium, with or without
        +      modifications, and in Source or Object form, provided that You
        +      meet the following conditions:
        +
        +      (a) You must give any other recipients of the Work or
        +          Derivative Works a copy of this License; and
        +
        +      (b) You must cause any modified files to carry prominent notices
        +          stating that You changed the files; and
        +
        +      (c) You must retain, in the Source form of any Derivative Works
        +          that You distribute, all copyright, patent, trademark, and
        +          attribution notices from the Source form of the Work,
        +          excluding those notices that do not pertain to any part of
        +          the Derivative Works; and
        +
        +      (d) If the Work includes a "NOTICE" text file as part of its
        +          distribution, then any Derivative Works that You distribute must
        +          include a readable copy of the attribution notices contained
        +          within such NOTICE file, excluding those notices that do not
        +          pertain to any part of the Derivative Works, in at least one
        +          of the following places: within a NOTICE text file distributed
        +          as part of the Derivative Works; within the Source form or
        +          documentation, if provided along with the Derivative Works; or,
        +          within a display generated by the Derivative Works, if and
        +          wherever such third-party notices normally appear. The contents
        +          of the NOTICE file are for informational purposes only and
        +          do not modify the License. You may add Your own attribution
        +          notices within Derivative Works that You distribute, alongside
        +          or as an addendum to the NOTICE text from the Work, provided
        +          that such additional attribution notices cannot be construed
        +          as modifying the License.
        +
        +      You may add Your own copyright statement to Your modifications and
        +      may provide additional or different license terms and conditions
        +      for use, reproduction, or distribution of Your modifications, or
        +      for any such Derivative Works as a whole, provided Your use,
        +      reproduction, and distribution of the Work otherwise complies with
        +      the conditions stated in this License.
        +
        +   5. Submission of Contributions. Unless You explicitly state otherwise,
        +      any Contribution intentionally submitted for inclusion in the Work
        +      by You to the Licensor shall be under the terms and conditions of
        +      this License, without any additional terms or conditions.
        +      Notwithstanding the above, nothing herein shall supersede or modify
        +      the terms of any separate license agreement you may have executed
        +      with Licensor regarding such Contributions.
        +
        +   6. Trademarks. This License does not grant permission to use the trade
        +      names, trademarks, service marks, or product names of the Licensor,
        +      except as required for reasonable and customary use in describing the
        +      origin of the Work and reproducing the content of the NOTICE file.
        +
        +   7. Disclaimer of Warranty. Unless required by applicable law or
        +      agreed to in writing, Licensor provides the Work (and each
        +      Contributor provides its Contributions) on an "AS IS" BASIS,
        +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +      implied, including, without limitation, any warranties or conditions
        +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +      PARTICULAR PURPOSE. You are solely responsible for determining the
        +      appropriateness of using or redistributing the Work and assume any
        +      risks associated with Your exercise of permissions under this License.
        +
        +   8. Limitation of Liability. In no event and under no legal theory,
        +      whether in tort (including negligence), contract, or otherwise,
        +      unless required by applicable law (such as deliberate and grossly
        +      negligent acts) or agreed to in writing, shall any Contributor be
        +      liable to You for damages, including any direct, indirect, special,
        +      incidental, or consequential damages of any character arising as a
        +      result of this License or out of the use or inability to use the
        +      Work (including but not limited to damages for loss of goodwill,
        +      work stoppage, computer failure or malfunction, or any and all
        +      other commercial damages or losses), even if such Contributor
        +      has been advised of the possibility of such damages.
        +
        +   9. Accepting Warranty or Additional Liability. While redistributing
        +      the Work or Derivative Works thereof, You may choose to offer,
        +      and charge a fee for, acceptance of support, warranty, indemnity,
        +      or other liability obligations and/or rights consistent with this
        +      License. However, in accepting such obligations, You may act only
        +      on Your own behalf and on Your sole responsibility, not on behalf
        +      of any other Contributor, and only if You agree to indemnify,
        +      defend, and hold each Contributor harmless for any liability
        +      incurred by, or claims asserted against, such Contributor by reason
        +      of your accepting any such warranty or additional liability.
        +
        +   END OF TERMS AND CONDITIONS
        +
        +   APPENDIX: How to apply the Apache License to your work.
        +
        +      To apply the Apache License to your work, attach the following
        +      boilerplate notice, with the fields enclosed by brackets "[]"
        +      replaced with your own identifying information. (Don't include
        +      the brackets!)  The text should be enclosed in the appropriate
        +      comment syntax for the file format. We also recommend that a
        +      file or class name and description of purpose be included on the
        +      same "printed page" as the copyright notice for easier
        +      identification within third-party archives.
        +
        +   Copyright 2020 Sébastien Crozet
        +
        +   Licensed under the Apache License, Version 2.0 (the "License");
        +   you may not use this file except in compliance with the License.
        +   You may obtain a copy of the License at
        +
        +       http://www.apache.org/licenses/LICENSE-2.0
        +
        +   Unless required by applicable law or agreed to in writing, software
        +   distributed under the License is distributed on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +   See the License for the specific language governing permissions and
        +   limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                        Apache License
                                    Version 2.0, January 2004
        @@ -5028,7 +6628,7 @@ License: http://www.apache.org/licenses/LICENSE-2.0
                         

        Apache License 2.0

        Used by:

                                       Apache License
                                    Version 2.0, January 2004
        @@ -5446,15 +7046,15 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -5664,7 +7264,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -5872,7 +7472,8 @@ limitations under the License.

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -6081,8 +7682,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -6291,7 +7891,6 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
        @@ -6501,7 +8100,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -6691,7 +8290,7 @@ APPENDIX: How to apply the Apache License to your work.
            same "printed page" as the copyright notice for easier
            identification within third-party archives.
         
        -Copyright 2018 The pin-utils authors
        +Copyright 2018 Brian Myers
         
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
        @@ -6710,8 +8309,8 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7118,6 +8717,215 @@ You may obtain a copy of the License at
         
            http://www.apache.org/licenses/LICENSE-2.0
         
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        + +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +APPENDIX: How to apply the Apache License to your work.
        +
        +   To apply the Apache License to your work, attach the following
        +   boilerplate notice, with the fields enclosed by brackets "[]"
        +   replaced with your own identifying information. (Don't include
        +   the brackets!)  The text should be enclosed in the appropriate
        +   comment syntax for the file format. We also recommend that a
        +   file or class name and description of purpose be included on the
        +   same "printed page" as the copyright notice for easier
        +   identification within third-party archives.
        +
        +Copyright 2019 quininer kel
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
         Unless required by applicable law or agreed to in writing, software
         distributed under the License is distributed on an "AS IS" BASIS,
         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -7130,7 +8938,9 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7340,7 +9150,7 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7758,7 +9568,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -7967,7 +9777,7 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8178,7 +9988,216 @@ limitations under the License.
                         

        Apache License 2.0

        Used by:

        +
                                      Apache License
        +                        Version 2.0, January 2004
        +                     http://www.apache.org/licenses/
        +
        +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        +
        +1. Definitions.
        +
        +   "License" shall mean the terms and conditions for use, reproduction,
        +   and distribution as defined by Sections 1 through 9 of this document.
        +
        +   "Licensor" shall mean the copyright owner or entity authorized by
        +   the copyright owner that is granting the License.
        +
        +   "Legal Entity" shall mean the union of the acting entity and all
        +   other entities that control, are controlled by, or are under common
        +   control with that entity. For the purposes of this definition,
        +   "control" means (i) the power, direct or indirect, to cause the
        +   direction or management of such entity, whether by contract or
        +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
        +   outstanding shares, or (iii) beneficial ownership of such entity.
        +
        +   "You" (or "Your") shall mean an individual or Legal Entity
        +   exercising permissions granted by this License.
        +
        +   "Source" form shall mean the preferred form for making modifications,
        +   including but not limited to software source code, documentation
        +   source, and configuration files.
        +
        +   "Object" form shall mean any form resulting from mechanical
        +   transformation or translation of a Source form, including but
        +   not limited to compiled object code, generated documentation,
        +   and conversions to other media types.
        +
        +   "Work" shall mean the work of authorship, whether in Source or
        +   Object form, made available under the License, as indicated by a
        +   copyright notice that is included in or attached to the work
        +   (an example is provided in the Appendix below).
        +
        +   "Derivative Works" shall mean any work, whether in Source or Object
        +   form, that is based on (or derived from) the Work and for which the
        +   editorial revisions, annotations, elaborations, or other modifications
        +   represent, as a whole, an original work of authorship. For the purposes
        +   of this License, Derivative Works shall not include works that remain
        +   separable from, or merely link (or bind by name) to the interfaces of,
        +   the Work and Derivative Works thereof.
        +
        +   "Contribution" shall mean any work of authorship, including
        +   the original version of the Work and any modifications or additions
        +   to that Work or Derivative Works thereof, that is intentionally
        +   submitted to Licensor for inclusion in the Work by the copyright owner
        +   or by an individual or Legal Entity authorized to submit on behalf of
        +   the copyright owner. For the purposes of this definition, "submitted"
        +   means any form of electronic, verbal, or written communication sent
        +   to the Licensor or its representatives, including but not limited to
        +   communication on electronic mailing lists, source code control systems,
        +   and issue tracking systems that are managed by, or on behalf of, the
        +   Licensor for the purpose of discussing and improving the Work, but
        +   excluding communication that is conspicuously marked or otherwise
        +   designated in writing by the copyright owner as "Not a Contribution."
        +
        +   "Contributor" shall mean Licensor and any individual or Legal Entity
        +   on behalf of whom a Contribution has been received by Licensor and
        +   subsequently incorporated within the Work.
        +
        +2. Grant of Copyright License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   copyright license to reproduce, prepare Derivative Works of,
        +   publicly display, publicly perform, sublicense, and distribute the
        +   Work and such Derivative Works in Source or Object form.
        +
        +3. Grant of Patent License. Subject to the terms and conditions of
        +   this License, each Contributor hereby grants to You a perpetual,
        +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        +   (except as stated in this section) patent license to make, have made,
        +   use, offer to sell, sell, import, and otherwise transfer the Work,
        +   where such license applies only to those patent claims licensable
        +   by such Contributor that are necessarily infringed by their
        +   Contribution(s) alone or by combination of their Contribution(s)
        +   with the Work to which such Contribution(s) was submitted. If You
        +   institute patent litigation against any entity (including a
        +   cross-claim or counterclaim in a lawsuit) alleging that the Work
        +   or a Contribution incorporated within the Work constitutes direct
        +   or contributory patent infringement, then any patent licenses
        +   granted to You under this License for that Work shall terminate
        +   as of the date such litigation is filed.
        +
        +4. Redistribution. You may reproduce and distribute copies of the
        +   Work or Derivative Works thereof in any medium, with or without
        +   modifications, and in Source or Object form, provided that You
        +   meet the following conditions:
        +
        +   (a) You must give any other recipients of the Work or
        +       Derivative Works a copy of this License; and
        +
        +   (b) You must cause any modified files to carry prominent notices
        +       stating that You changed the files; and
        +
        +   (c) You must retain, in the Source form of any Derivative Works
        +       that You distribute, all copyright, patent, trademark, and
        +       attribution notices from the Source form of the Work,
        +       excluding those notices that do not pertain to any part of
        +       the Derivative Works; and
        +
        +   (d) If the Work includes a "NOTICE" text file as part of its
        +       distribution, then any Derivative Works that You distribute must
        +       include a readable copy of the attribution notices contained
        +       within such NOTICE file, excluding those notices that do not
        +       pertain to any part of the Derivative Works, in at least one
        +       of the following places: within a NOTICE text file distributed
        +       as part of the Derivative Works; within the Source form or
        +       documentation, if provided along with the Derivative Works; or,
        +       within a display generated by the Derivative Works, if and
        +       wherever such third-party notices normally appear. The contents
        +       of the NOTICE file are for informational purposes only and
        +       do not modify the License. You may add Your own attribution
        +       notices within Derivative Works that You distribute, alongside
        +       or as an addendum to the NOTICE text from the Work, provided
        +       that such additional attribution notices cannot be construed
        +       as modifying the License.
        +
        +   You may add Your own copyright statement to Your modifications and
        +   may provide additional or different license terms and conditions
        +   for use, reproduction, or distribution of Your modifications, or
        +   for any such Derivative Works as a whole, provided Your use,
        +   reproduction, and distribution of the Work otherwise complies with
        +   the conditions stated in this License.
        +
        +5. Submission of Contributions. Unless You explicitly state otherwise,
        +   any Contribution intentionally submitted for inclusion in the Work
        +   by You to the Licensor shall be under the terms and conditions of
        +   this License, without any additional terms or conditions.
        +   Notwithstanding the above, nothing herein shall supersede or modify
        +   the terms of any separate license agreement you may have executed
        +   with Licensor regarding such Contributions.
        +
        +6. Trademarks. This License does not grant permission to use the trade
        +   names, trademarks, service marks, or product names of the Licensor,
        +   except as required for reasonable and customary use in describing the
        +   origin of the Work and reproducing the content of the NOTICE file.
        +
        +7. Disclaimer of Warranty. Unless required by applicable law or
        +   agreed to in writing, Licensor provides the Work (and each
        +   Contributor provides its Contributions) on an "AS IS" BASIS,
        +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        +   implied, including, without limitation, any warranties or conditions
        +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        +   PARTICULAR PURPOSE. You are solely responsible for determining the
        +   appropriateness of using or redistributing the Work and assume any
        +   risks associated with Your exercise of permissions under this License.
        +
        +8. Limitation of Liability. In no event and under no legal theory,
        +   whether in tort (including negligence), contract, or otherwise,
        +   unless required by applicable law (such as deliberate and grossly
        +   negligent acts) or agreed to in writing, shall any Contributor be
        +   liable to You for damages, including any direct, indirect, special,
        +   incidental, or consequential damages of any character arising as a
        +   result of this License or out of the use or inability to use the
        +   Work (including but not limited to damages for loss of goodwill,
        +   work stoppage, computer failure or malfunction, or any and all
        +   other commercial damages or losses), even if such Contributor
        +   has been advised of the possibility of such damages.
        +
        +9. Accepting Warranty or Additional Liability. While redistributing
        +   the Work or Derivative Works thereof, You may choose to offer,
        +   and charge a fee for, acceptance of support, warranty, indemnity,
        +   or other liability obligations and/or rights consistent with this
        +   License. However, in accepting such obligations, You may act only
        +   on Your own behalf and on Your sole responsibility, not on behalf
        +   of any other Contributor, and only if You agree to indemnify,
        +   defend, and hold each Contributor harmless for any liability
        +   incurred by, or claims asserted against, such Contributor by reason
        +   of your accepting any such warranty or additional liability.
        +
        +END OF TERMS AND CONDITIONS
        +
        +APPENDIX: How to apply the Apache License to your work.
        +
        +   To apply the Apache License to your work, attach the following
        +   boilerplate notice, with the fields enclosed by brackets "[]"
        +   replaced with your own identifying information. (Don't include
        +   the brackets!)  The text should be enclosed in the appropriate
        +   comment syntax for the file format. We also recommend that a
        +   file or class name and description of purpose be included on the
        +   same "printed page" as the copyright notice for easier
        +   identification within third-party archives.
        +
        +Copyright 2024 Liam Gray <gmail@liamg.me>
        +
        +Licensed under the Apache License, Version 2.0 (the "License");
        +you may not use this file except in compliance with the License.
        +You may obtain a copy of the License at
        +
        +	http://www.apache.org/licenses/LICENSE-2.0
        +
        +Unless required by applicable law or agreed to in writing, software
        +distributed under the License is distributed on an "AS IS" BASIS,
        +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        +See the License for the specific language governing permissions and
        +limitations under the License.
        +
        +
      • +
      • +

        Apache License 2.0

        +

        Used by:

        +
                                      Apache License
                                 Version 2.0, January 2004
        @@ -8388,7 +10407,8 @@ limitations under the License.
                         

        Used by:

                                      Apache License
                                 Version 2.0, January 2004
        @@ -8596,150 +10616,170 @@ limitations under the License.

        Apache License 2.0

        Used by:

          +
        • addr2line 0.25.1
        • ahash 0.8.12
        • -
        • arc-swap 1.7.1
        • -
        • arrayvec 0.7.6
        • +
        • arc-swap 1.9.3
        • +
        • arrayvec 0.7.8
        • async-channel 2.5.0
        • -
        • async-compression 0.4.19
        • -
        • async-lock 3.4.1
        • +
        • async-compression 0.4.42
        • +
        • async-lock 3.4.2
        • atomic-waker 1.1.2
        • autocfg 1.5.0
        • -
        • base64 0.21.7
        • +
        • backtrace 0.3.76
        • base64 0.22.1
        • -
        • bitflags 2.9.4
        • -
        • bumpalo 3.19.0
        • +
        • base64 0.23.1
        • +
        • bitflags 1.3.2
        • +
        • bitflags 2.11.1
        • +
        • bstr 1.12.1
        • +
        • bumpalo 3.20.2
        • bytes-utils 0.1.4
        • -
        • cc 1.2.40
        • -
        • cfg-if 1.0.3
        • +
        • cast 0.3.0
        • +
        • cc 1.2.62
        • +
        • cfg-if 0.1.10
        • +
        • cfg-if 1.0.4
        • +
        • cmake 0.1.58
        • +
        • compression-codecs 0.4.38
        • +
        • compression-core 0.4.32
        • concurrent-queue 2.5.0
        • const-random-macro 0.1.16
        • const-random 0.1.18
        • core-foundation-sys 0.8.7
        • core-foundation 0.10.1
        • core-foundation 0.9.4
        • +
        • cpp_demangle 0.4.5
        • +
        • criterion-plot 0.8.2
        • +
        • criterion 0.8.2
        • crossbeam-channel 0.5.15
        • crossbeam-deque 0.8.6
        • -
        • crossbeam-epoch 0.9.18
        • +
        • crossbeam-epoch 0.9.20
        • crossbeam-queue 0.3.12
        • +
        • crossbeam-skiplist 0.1.3
        • crossbeam-utils 0.8.21
        • +
        • debugid 0.8.0
        • displaydoc 0.2.5
        • either 1.15.0
        • +
        • encoding_rs_io 0.1.7
        • equivalent 1.0.2
        • errno 0.3.14
        • event-listener-strategy 0.5.4
        • -
        • event-listener 5.4.1
        • -
        • fastrand 2.3.0
        • -
        • find-msvc-tools 0.1.3
        • +
        • event-listener 5.4.2
        • +
        • fastrand 2.4.1
        • +
        • find-msvc-tools 0.1.9
        • +
        • findshlibs 0.10.2
        • fixedbitset 0.5.7
        • +
        • flate2 1.1.9
        • fnv 1.0.7
        • form_urlencoded 1.2.2
        • -
        • fs4 0.8.4
        • +
        • foyer-intrusive-collections 0.10.0-dev
        • +
        • fs4 0.13.1
        • futures-timer 3.0.3
        • -
        • geohash 0.13.1
        • +
        • geohash 0.13.2
        • +
        • gimli 0.32.3
        • glob 0.3.3
        • -
        • group 0.12.1
        • +
        • group 0.14.0
        • hash32 0.3.1
        • hashbrown 0.14.5
        • hashbrown 0.15.5
        • -
        • hashbrown 0.16.0
        • +
        • hashbrown 0.16.1
        • +
        • hashbrown 0.17.1
        • heapless 0.8.0
        • heck 0.5.0
        • hermit-abi 0.5.2
        • httparse 1.10.1
        • -
        • hyper-rustls 0.24.2
        • -
        • hyper-rustls 0.27.7
        • +
        • hyper-rustls 0.27.9
        • +
        • hyper-timeout 0.5.2
        • idna 1.1.0
        • -
        • idna_adapter 1.2.1
        • -
        • indexmap 2.12.0
        • -
        • itertools 0.11.0
        • +
        • idna_adapter 1.2.2
        • +
        • indexmap 2.14.0
        • itertools 0.13.0
        • itertools 0.14.0
        • +
        • itertools 0.15.0
        • jobserver 0.1.34
        • -
        • js-sys 0.3.81
        • +
        • js-sys 0.3.107
        • lazy_static 1.5.0
        • -
        • linux-raw-sys 0.11.0
        • -
        • linux-raw-sys 0.4.15
        • +
        • linux-raw-sys 0.12.1
        • lock_api 0.4.14
        • -
        • log 0.4.28
        • +
        • log 0.4.34
        • matrixmultiply 0.3.10
        • mime 0.3.17
        • -
        • multimap 0.10.1
        • ndarray 0.16.1
        • -
        • num-bigint-dig 0.8.4
        • +
        • num-bigint-dig 0.8.6
        • num-bigint 0.4.6
        • +
        • num-bigint 0.5.1
        • num-complex 0.4.6
        • num-integer 0.1.46
        • num-iter 0.1.45
        • +
        • num-rational 0.4.2
        • num-traits 0.2.19
        • num_cpus 1.17.0
        • -
        • once_cell 1.21.3
        • -
        • openssl-probe 0.1.6
        • +
        • oauth2 5.0.0
        • +
        • object 0.37.3
        • +
        • once_cell 1.21.4
        • +
        • openssl-probe 0.2.1
        • parking 2.2.1
        • parking_lot 0.12.5
        • parking_lot_core 0.9.12
        • percent-encoding 2.3.2
        • petgraph 0.8.3
        • -
        • pkg-config 0.3.32
        • -
        • prost-build 0.14.3
        • -
        • prost-derive 0.14.3
        • +
        • pkg-config 0.3.33
        • +
        • prost-derive 0.14.4
        • prost-types 0.14.3
        • -
        • prost 0.14.3
        • +
        • prost 0.14.4
        • +
        • rand_xoshiro 0.6.0
        • rawpointer 0.2.1
        • rayon-core 1.13.0
        • -
        • rayon 1.11.0
        • -
        • regex-automata 0.4.13
        • -
        • regex-lite 0.1.7
        • -
        • regex-syntax 0.8.6
        • -
        • regex 1.12.2
        • +
        • rayon 1.12.0
        • +
        • regex-automata 0.4.16
        • +
        • regex-lite 0.1.9
        • +
        • regex-syntax 0.8.11
        • +
        • regex 1.13.1
        • ring 0.17.14
        • +
        • roaring 0.11.5
        • robust 1.2.0
        • +
        • rustc-demangle 0.1.27
        • rustc_version 0.4.1
        • -
        • rustix 0.38.44
        • -
        • rustix 1.1.2
        • -
        • rustls-native-certs 0.6.3
        • -
        • rustls-native-certs 0.8.1
        • -
        • rustls-pemfile 1.0.4
        • -
        • rustls-pemfile 2.2.0
        • -
        • rustls 0.21.12
        • -
        • rustls 0.23.31
        • +
        • rustix 1.1.4
        • +
        • rustls-native-certs 0.8.3
        • +
        • rustls 0.23.46
        • scoped-tls 1.0.1
        • scopeguard 1.2.0
        • -
        • sct 0.7.1
        • -
        • security-framework-sys 2.15.0
        • -
        • security-framework 2.11.1
        • -
        • security-framework 3.5.1
        • -
        • serde_with 3.15.0
        • -
        • serde_with_macros 3.15.0
        • -
        • shellexpand 3.1.1
        • -
        • signal-hook-registry 1.4.6
        • -
        • smallvec 1.15.1
        • -
        • socket2 0.5.10
        • -
        • socket2 0.6.0
        • -
        • sqlparser 0.59.0
        • -
        • sqlparser_derive 0.3.0
        • -
        • stable_deref_trait 1.2.0
        • -
        • syn 1.0.109
        • +
        • security-framework-sys 2.17.0
        • +
        • security-framework 3.7.0
        • +
        • serde_with 3.24.0
        • +
        • serde_with_macros 3.24.0
        • +
        • shellexpand 3.1.2
        • +
        • signal-hook-registry 1.4.8
        • +
        • simd_cesu8 1.1.1
        • +
        • smallvec 1.16.5
        • +
        • socket2 0.6.3
        • +
        • sqlparser 0.62.0
        • +
        • sqlparser_derive 0.5.0
        • +
        • stable_deref_trait 1.2.1
        • +
        • str_stack 0.1.1
        • +
        • symlink 0.1.0
        • system-configuration-sys 0.6.0
        • -
        • system-configuration 0.6.1
        • -
        • tempfile 3.23.0
        • +
        • system-configuration 0.7.0
        • +
        • tempfile 3.27.0
        • thread-tree 0.3.3
        • -
        • thread_local 1.1.9
        • -
        • unicase 2.8.1
        • -
        • unicode-segmentation 1.12.0
        • -
        • unicode-width 0.2.2
        • -
        • url 2.5.7
        • -
        • uuid 1.18.1
        • +
        • thread_local 1.1.10
        • +
        • tinytemplate 1.2.1
        • +
        • unicase 2.9.0
        • +
        • unicode-normalization 0.1.25
        • +
        • unicode-segmentation 1.13.2
        • +
        • unicode-width 0.2.3
        • +
        • url 2.5.8
        • +
        • uuid 1.29.0
        • version_check 0.9.5
        • wasi 0.11.1+wasi-snapshot-preview1
        • wasi 0.14.7+wasi-0.2.4
        • -
        • wasm-bindgen-backend 0.2.104
        • -
        • wasm-bindgen-futures 0.4.54
        • -
        • wasm-bindgen-macro-support 0.2.104
        • -
        • wasm-bindgen-macro 0.2.104
        • -
        • wasm-bindgen-shared 0.2.104
        • -
        • wasm-bindgen 0.2.104
        • -
        • web-sys 0.3.81
        • -
        • wit-bindgen 0.46.0
        • +
        • wasip2 1.0.3+wasi-0.2.9
        • +
        • wasm-bindgen-futures 0.4.80
        • +
        • wasm-bindgen-macro-support 0.2.130
        • +
        • wasm-bindgen-macro 0.2.130
        • +
        • wasm-bindgen-shared 0.2.130
        • +
        • wasm-bindgen 0.2.130
        • +
        • web-sys 0.3.107
        • +
        • wit-bindgen 0.57.1
        • wkb 0.9.2
        • wkt 0.14.0
        • xmlparser 0.13.6
        • @@ -8951,7 +10991,7 @@ limitations under the License.

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -9161,14 +11201,14 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -9378,41 +11418,56 @@ limitations under the License.
                           

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -9621,10 +11676,209 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          +
                                        Apache License
          +                        Version 2.0, January 2004
          +                     http://www.apache.org/licenses/
          +
          +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
          +
          +1. Definitions.
          +
          +   "License" shall mean the terms and conditions for use, reproduction,
          +   and distribution as defined by Sections 1 through 9 of this document.
          +
          +   "Licensor" shall mean the copyright owner or entity authorized by
          +   the copyright owner that is granting the License.
          +
          +   "Legal Entity" shall mean the union of the acting entity and all
          +   other entities that control, are controlled by, or are under common
          +   control with that entity. For the purposes of this definition,
          +   "control" means (i) the power, direct or indirect, to cause the
          +   direction or management of such entity, whether by contract or
          +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
          +   outstanding shares, or (iii) beneficial ownership of such entity.
          +
          +   "You" (or "Your") shall mean an individual or Legal Entity
          +   exercising permissions granted by this License.
          +
          +   "Source" form shall mean the preferred form for making modifications,
          +   including but not limited to software source code, documentation
          +   source, and configuration files.
          +
          +   "Object" form shall mean any form resulting from mechanical
          +   transformation or translation of a Source form, including but
          +   not limited to compiled object code, generated documentation,
          +   and conversions to other media types.
          +
          +   "Work" shall mean the work of authorship, whether in Source or
          +   Object form, made available under the License, as indicated by a
          +   copyright notice that is included in or attached to the work
          +   (an example is provided in the Appendix below).
          +
          +   "Derivative Works" shall mean any work, whether in Source or Object
          +   form, that is based on (or derived from) the Work and for which the
          +   editorial revisions, annotations, elaborations, or other modifications
          +   represent, as a whole, an original work of authorship. For the purposes
          +   of this License, Derivative Works shall not include works that remain
          +   separable from, or merely link (or bind by name) to the interfaces of,
          +   the Work and Derivative Works thereof.
          +
          +   "Contribution" shall mean any work of authorship, including
          +   the original version of the Work and any modifications or additions
          +   to that Work or Derivative Works thereof, that is intentionally
          +   submitted to Licensor for inclusion in the Work by the copyright owner
          +   or by an individual or Legal Entity authorized to submit on behalf of
          +   the copyright owner. For the purposes of this definition, "submitted"
          +   means any form of electronic, verbal, or written communication sent
          +   to the Licensor or its representatives, including but not limited to
          +   communication on electronic mailing lists, source code control systems,
          +   and issue tracking systems that are managed by, or on behalf of, the
          +   Licensor for the purpose of discussing and improving the Work, but
          +   excluding communication that is conspicuously marked or otherwise
          +   designated in writing by the copyright owner as "Not a Contribution."
          +
          +   "Contributor" shall mean Licensor and any individual or Legal Entity
          +   on behalf of whom a Contribution has been received by Licensor and
          +   subsequently incorporated within the Work.
          +
          +2. Grant of Copyright License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   copyright license to reproduce, prepare Derivative Works of,
          +   publicly display, publicly perform, sublicense, and distribute the
          +   Work and such Derivative Works in Source or Object form.
          +
          +3. Grant of Patent License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   (except as stated in this section) patent license to make, have made,
          +   use, offer to sell, sell, import, and otherwise transfer the Work,
          +   where such license applies only to those patent claims licensable
          +   by such Contributor that are necessarily infringed by their
          +   Contribution(s) alone or by combination of their Contribution(s)
          +   with the Work to which such Contribution(s) was submitted. If You
          +   institute patent litigation against any entity (including a
          +   cross-claim or counterclaim in a lawsuit) alleging that the Work
          +   or a Contribution incorporated within the Work constitutes direct
          +   or contributory patent infringement, then any patent licenses
          +   granted to You under this License for that Work shall terminate
          +   as of the date such litigation is filed.
          +
          +4. Redistribution. You may reproduce and distribute copies of the
          +   Work or Derivative Works thereof in any medium, with or without
          +   modifications, and in Source or Object form, provided that You
          +   meet the following conditions:
          +
          +   (a) You must give any other recipients of the Work or
          +       Derivative Works a copy of this License; and
          +
          +   (b) You must cause any modified files to carry prominent notices
          +       stating that You changed the files; and
          +
          +   (c) You must retain, in the Source form of any Derivative Works
          +       that You distribute, all copyright, patent, trademark, and
          +       attribution notices from the Source form of the Work,
          +       excluding those notices that do not pertain to any part of
          +       the Derivative Works; and
          +
          +   (d) If the Work includes a "NOTICE" text file as part of its
          +       distribution, then any Derivative Works that You distribute must
          +       include a readable copy of the attribution notices contained
          +       within such NOTICE file, excluding those notices that do not
          +       pertain to any part of the Derivative Works, in at least one
          +       of the following places: within a NOTICE text file distributed
          +       as part of the Derivative Works; within the Source form or
          +       documentation, if provided along with the Derivative Works; or,
          +       within a display generated by the Derivative Works, if and
          +       wherever such third-party notices normally appear. The contents
          +       of the NOTICE file are for informational purposes only and
          +       do not modify the License. You may add Your own attribution
          +       notices within Derivative Works that You distribute, alongside
          +       or as an addendum to the NOTICE text from the Work, provided
          +       that such additional attribution notices cannot be construed
          +       as modifying the License.
          +
          +   You may add Your own copyright statement to Your modifications and
          +   may provide additional or different license terms and conditions
          +   for use, reproduction, or distribution of Your modifications, or
          +   for any such Derivative Works as a whole, provided Your use,
          +   reproduction, and distribution of the Work otherwise complies with
          +   the conditions stated in this License.
          +
          +5. Submission of Contributions. Unless You explicitly state otherwise,
          +   any Contribution intentionally submitted for inclusion in the Work
          +   by You to the Licensor shall be under the terms and conditions of
          +   this License, without any additional terms or conditions.
          +   Notwithstanding the above, nothing herein shall supersede or modify
          +   the terms of any separate license agreement you may have executed
          +   with Licensor regarding such Contributions.
          +
          +6. Trademarks. This License does not grant permission to use the trade
          +   names, trademarks, service marks, or product names of the Licensor,
          +   except as required for reasonable and customary use in describing the
          +   origin of the Work and reproducing the content of the NOTICE file.
          +
          +7. Disclaimer of Warranty. Unless required by applicable law or
          +   agreed to in writing, Licensor provides the Work (and each
          +   Contributor provides its Contributions) on an "AS IS" BASIS,
          +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          +   implied, including, without limitation, any warranties or conditions
          +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          +   PARTICULAR PURPOSE. You are solely responsible for determining the
          +   appropriateness of using or redistributing the Work and assume any
          +   risks associated with Your exercise of permissions under this License.
          +
          +8. Limitation of Liability. In no event and under no legal theory,
          +   whether in tort (including negligence), contract, or otherwise,
          +   unless required by applicable law (such as deliberate and grossly
          +   negligent acts) or agreed to in writing, shall any Contributor be
          +   liable to You for damages, including any direct, indirect, special,
          +   incidental, or consequential damages of any character arising as a
          +   result of this License or out of the use or inability to use the
          +   Work (including but not limited to damages for loss of goodwill,
          +   work stoppage, computer failure or malfunction, or any and all
          +   other commercial damages or losses), even if such Contributor
          +   has been advised of the possibility of such damages.
          +
          +9. Accepting Warranty or Additional Liability. While redistributing
          +   the Work or Derivative Works thereof, You may choose to offer,
          +   and charge a fee for, acceptance of support, warranty, indemnity,
          +   or other liability obligations and/or rights consistent with this
          +   License. However, in accepting such obligations, You may act only
          +   on Your own behalf and on Your sole responsibility, not on behalf
          +   of any other Contributor, and only if You agree to indemnify,
          +   defend, and hold each Contributor harmless for any liability
          +   incurred by, or claims asserted against, such Contributor by reason
          +   of your accepting any such warranty or additional liability.
          +
          +END OF TERMS AND CONDITIONS
          +
          +Copyright (c) 2015-2022 Amod Malviya
          +
          +Licensed under the Apache License, Version 2.0 (the "License");
          +you may not use this file except in compliance with the License.
          +You may obtain a copy of the License at
          +
          +	http://www.apache.org/licenses/LICENSE-2.0
          +
          +Unless required by applicable law or agreed to in writing, software
          +distributed under the License is distributed on an "AS IS" BASIS,
          +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          +See the License for the specific language governing permissions and
          +limitations under the License.
          +
          + +
        • +

          Apache License 2.0

          +

          Used by:

          +
                                        Apache License
                                   Version 2.0, January 2004
          @@ -9819,11 +12073,13 @@ APPENDIX: How to apply the Apache License to your work.
                           

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -10032,8 +12288,7 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

                                        Apache License
                                   Version 2.0, January 2004
          @@ -10242,7 +12497,217 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          +
                                        Apache License
          +                        Version 2.0, January 2004
          +                     http://www.apache.org/licenses/
          +
          +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
          +
          +1. Definitions.
          +
          +   "License" shall mean the terms and conditions for use, reproduction,
          +   and distribution as defined by Sections 1 through 9 of this document.
          +
          +   "Licensor" shall mean the copyright owner or entity authorized by
          +   the copyright owner that is granting the License.
          +
          +   "Legal Entity" shall mean the union of the acting entity and all
          +   other entities that control, are controlled by, or are under common
          +   control with that entity. For the purposes of this definition,
          +   "control" means (i) the power, direct or indirect, to cause the
          +   direction or management of such entity, whether by contract or
          +   otherwise, or (ii) ownership of fifty percent (50%) or more of the
          +   outstanding shares, or (iii) beneficial ownership of such entity.
          +
          +   "You" (or "Your") shall mean an individual or Legal Entity
          +   exercising permissions granted by this License.
          +
          +   "Source" form shall mean the preferred form for making modifications,
          +   including but not limited to software source code, documentation
          +   source, and configuration files.
          +
          +   "Object" form shall mean any form resulting from mechanical
          +   transformation or translation of a Source form, including but
          +   not limited to compiled object code, generated documentation,
          +   and conversions to other media types.
          +
          +   "Work" shall mean the work of authorship, whether in Source or
          +   Object form, made available under the License, as indicated by a
          +   copyright notice that is included in or attached to the work
          +   (an example is provided in the Appendix below).
          +
          +   "Derivative Works" shall mean any work, whether in Source or Object
          +   form, that is based on (or derived from) the Work and for which the
          +   editorial revisions, annotations, elaborations, or other modifications
          +   represent, as a whole, an original work of authorship. For the purposes
          +   of this License, Derivative Works shall not include works that remain
          +   separable from, or merely link (or bind by name) to the interfaces of,
          +   the Work and Derivative Works thereof.
          +
          +   "Contribution" shall mean any work of authorship, including
          +   the original version of the Work and any modifications or additions
          +   to that Work or Derivative Works thereof, that is intentionally
          +   submitted to Licensor for inclusion in the Work by the copyright owner
          +   or by an individual or Legal Entity authorized to submit on behalf of
          +   the copyright owner. For the purposes of this definition, "submitted"
          +   means any form of electronic, verbal, or written communication sent
          +   to the Licensor or its representatives, including but not limited to
          +   communication on electronic mailing lists, source code control systems,
          +   and issue tracking systems that are managed by, or on behalf of, the
          +   Licensor for the purpose of discussing and improving the Work, but
          +   excluding communication that is conspicuously marked or otherwise
          +   designated in writing by the copyright owner as "Not a Contribution."
          +
          +   "Contributor" shall mean Licensor and any individual or Legal Entity
          +   on behalf of whom a Contribution has been received by Licensor and
          +   subsequently incorporated within the Work.
          +
          +2. Grant of Copyright License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   copyright license to reproduce, prepare Derivative Works of,
          +   publicly display, publicly perform, sublicense, and distribute the
          +   Work and such Derivative Works in Source or Object form.
          +
          +3. Grant of Patent License. Subject to the terms and conditions of
          +   this License, each Contributor hereby grants to You a perpetual,
          +   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +   (except as stated in this section) patent license to make, have made,
          +   use, offer to sell, sell, import, and otherwise transfer the Work,
          +   where such license applies only to those patent claims licensable
          +   by such Contributor that are necessarily infringed by their
          +   Contribution(s) alone or by combination of their Contribution(s)
          +   with the Work to which such Contribution(s) was submitted. If You
          +   institute patent litigation against any entity (including a
          +   cross-claim or counterclaim in a lawsuit) alleging that the Work
          +   or a Contribution incorporated within the Work constitutes direct
          +   or contributory patent infringement, then any patent licenses
          +   granted to You under this License for that Work shall terminate
          +   as of the date such litigation is filed.
          +
          +4. Redistribution. You may reproduce and distribute copies of the
          +   Work or Derivative Works thereof in any medium, with or without
          +   modifications, and in Source or Object form, provided that You
          +   meet the following conditions:
          +
          +   (a) You must give any other recipients of the Work or
          +       Derivative Works a copy of this License; and
          +
          +   (b) You must cause any modified files to carry prominent notices
          +       stating that You changed the files; and
          +
          +   (c) You must retain, in the Source form of any Derivative Works
          +       that You distribute, all copyright, patent, trademark, and
          +       attribution notices from the Source form of the Work,
          +       excluding those notices that do not pertain to any part of
          +       the Derivative Works; and
          +
          +   (d) If the Work includes a "NOTICE" text file as part of its
          +       distribution, then any Derivative Works that You distribute must
          +       include a readable copy of the attribution notices contained
          +       within such NOTICE file, excluding those notices that do not
          +       pertain to any part of the Derivative Works, in at least one
          +       of the following places: within a NOTICE text file distributed
          +       as part of the Derivative Works; within the Source form or
          +       documentation, if provided along with the Derivative Works; or,
          +       within a display generated by the Derivative Works, if and
          +       wherever such third-party notices normally appear. The contents
          +       of the NOTICE file are for informational purposes only and
          +       do not modify the License. You may add Your own attribution
          +       notices within Derivative Works that You distribute, alongside
          +       or as an addendum to the NOTICE text from the Work, provided
          +       that such additional attribution notices cannot be construed
          +       as modifying the License.
          +
          +   You may add Your own copyright statement to Your modifications and
          +   may provide additional or different license terms and conditions
          +   for use, reproduction, or distribution of Your modifications, or
          +   for any such Derivative Works as a whole, provided Your use,
          +   reproduction, and distribution of the Work otherwise complies with
          +   the conditions stated in this License.
          +
          +5. Submission of Contributions. Unless You explicitly state otherwise,
          +   any Contribution intentionally submitted for inclusion in the Work
          +   by You to the Licensor shall be under the terms and conditions of
          +   this License, without any additional terms or conditions.
          +   Notwithstanding the above, nothing herein shall supersede or modify
          +   the terms of any separate license agreement you may have executed
          +   with Licensor regarding such Contributions.
          +
          +6. Trademarks. This License does not grant permission to use the trade
          +   names, trademarks, service marks, or product names of the Licensor,
          +   except as required for reasonable and customary use in describing the
          +   origin of the Work and reproducing the content of the NOTICE file.
          +
          +7. Disclaimer of Warranty. Unless required by applicable law or
          +   agreed to in writing, Licensor provides the Work (and each
          +   Contributor provides its Contributions) on an "AS IS" BASIS,
          +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          +   implied, including, without limitation, any warranties or conditions
          +   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          +   PARTICULAR PURPOSE. You are solely responsible for determining the
          +   appropriateness of using or redistributing the Work and assume any
          +   risks associated with Your exercise of permissions under this License.
          +
          +8. Limitation of Liability. In no event and under no legal theory,
          +   whether in tort (including negligence), contract, or otherwise,
          +   unless required by applicable law (such as deliberate and grossly
          +   negligent acts) or agreed to in writing, shall any Contributor be
          +   liable to You for damages, including any direct, indirect, special,
          +   incidental, or consequential damages of any character arising as a
          +   result of this License or out of the use or inability to use the
          +   Work (including but not limited to damages for loss of goodwill,
          +   work stoppage, computer failure or malfunction, or any and all
          +   other commercial damages or losses), even if such Contributor
          +   has been advised of the possibility of such damages.
          +
          +9. Accepting Warranty or Additional Liability. While redistributing
          +   the Work or Derivative Works thereof, You may choose to offer,
          +   and charge a fee for, acceptance of support, warranty, indemnity,
          +   or other liability obligations and/or rights consistent with this
          +   License. However, in accepting such obligations, You may act only
          +   on Your own behalf and on Your sole responsibility, not on behalf
          +   of any other Contributor, and only if You agree to indemnify,
          +   defend, and hold each Contributor harmless for any liability
          +   incurred by, or claims asserted against, such Contributor by reason
          +   of your accepting any such warranty or additional liability.
          +
          +END OF TERMS AND CONDITIONS
          +
          +APPENDIX: How to apply the Apache License to your work.
          +
          +   To apply the Apache License to your work, attach the following
          +   boilerplate notice, with the fields enclosed by brackets "[]"
          +   replaced with your own identifying information. (Don't include
          +   the brackets!)  The text should be enclosed in the appropriate
          +   comment syntax for the file format. We also recommend that a
          +   file or class name and description of purpose be included on the
          +   same "printed page" as the copyright notice for easier
          +   identification within third-party archives.
          +
          +Copyright [yyyy] [name of copyright owner]
          +
          +Licensed under the Apache License, Version 2.0 (the "License");
          +you may not use this file except in compliance with the License.
          +You may obtain a copy of the License at
          +
          +	http://www.apache.org/licenses/LICENSE-2.0
          +
          +Unless required by applicable law or agreed to in writing, software
          +distributed under the License is distributed on an "AS IS" BASIS,
          +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          +See the License for the specific language governing permissions and
          +limitations under the License.
          +
          +
        • +
        • +

          Apache License 2.0

          +

          Used by:

          +
             Copyright (c) 2017-present PyO3 Project and Contributors.  https://github.com/PyO3
           
          @@ -10439,7 +12904,220 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          +
          Apache License
          +                           Version 2.0, January 2004
          +                        http://www.apache.org/licenses/
          +
          +   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
          +
          +   1. Definitions.
          +
          +      "License" shall mean the terms and conditions for use, reproduction,
          +      and distribution as defined by Sections 1 through 9 of this document.
          +
          +      "Licensor" shall mean the copyright owner or entity authorized by
          +      the copyright owner that is granting the License.
          +
          +      "Legal Entity" shall mean the union of the acting entity and all
          +      other entities that control, are controlled by, or are under common
          +      control with that entity. For the purposes of this definition,
          +      "control" means (i) the power, direct or indirect, to cause the
          +      direction or management of such entity, whether by contract or
          +      otherwise, or (ii) ownership of fifty percent (50%) or more of the
          +      outstanding shares, or (iii) beneficial ownership of such entity.
          +
          +      "You" (or "Your") shall mean an individual or Legal Entity
          +      exercising permissions granted by this License.
          +
          +      "Source" form shall mean the preferred form for making modifications,
          +      including but not limited to software source code, documentation
          +      source, and configuration files.
          +
          +      "Object" form shall mean any form resulting from mechanical
          +      transformation or translation of a Source form, including but
          +      not limited to compiled object code, generated documentation,
          +      and conversions to other media types.
          +
          +      "Work" shall mean the work of authorship, whether in Source or
          +      Object form, made available under the License, as indicated by a
          +      copyright notice that is included in or attached to the work
          +      (an example is provided in the Appendix below).
          +
          +      "Derivative Works" shall mean any work, whether in Source or Object
          +      form, that is based on (or derived from) the Work and for which the
          +      editorial revisions, annotations, elaborations, or other modifications
          +      represent, as a whole, an original work of authorship. For the purposes
          +      of this License, Derivative Works shall not include works that remain
          +      separable from, or merely link (or bind by name) to the interfaces of,
          +      the Work and Derivative Works thereof.
          +
          +      "Contribution" shall mean any work of authorship, including
          +      the original version of the Work and any modifications or additions
          +      to that Work or Derivative Works thereof, that is intentionally
          +      submitted to Licensor for inclusion in the Work by the copyright owner
          +      or by an individual or Legal Entity authorized to submit on behalf of
          +      the copyright owner. For the purposes of this definition, "submitted"
          +      means any form of electronic, verbal, or written communication sent
          +      to the Licensor or its representatives, including but not limited to
          +      communication on electronic mailing lists, source code control systems,
          +      and issue tracking systems that are managed by, or on behalf of, the
          +      Licensor for the purpose of discussing and improving the Work, but
          +      excluding communication that is conspicuously marked or otherwise
          +      designated in writing by the copyright owner as "Not a Contribution."
          +
          +      "Contributor" shall mean Licensor and any individual or Legal Entity
          +      on behalf of whom a Contribution has been received by Licensor and
          +      subsequently incorporated within the Work.
          +
          +   2. Grant of Copyright License. Subject to the terms and conditions of
          +      this License, each Contributor hereby grants to You a perpetual,
          +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +      copyright license to reproduce, prepare Derivative Works of,
          +      publicly display, publicly perform, sublicense, and distribute the
          +      Work and such Derivative Works in Source or Object form.
          +
          +   3. Grant of Patent License. Subject to the terms and conditions of
          +      this License, each Contributor hereby grants to You a perpetual,
          +      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          +      (except as stated in this section) patent license to make, have made,
          +      use, offer to sell, sell, import, and otherwise transfer the Work,
          +      where such license applies only to those patent claims licensable
          +      by such Contributor that are necessarily infringed by their
          +      Contribution(s) alone or by combination of their Contribution(s)
          +      with the Work to which such Contribution(s) was submitted. If You
          +      institute patent litigation against any entity (including a
          +      cross-claim or counterclaim in a lawsuit) alleging that the Work
          +      or a Contribution incorporated within the Work constitutes direct
          +      or contributory patent infringement, then any patent licenses
          +      granted to You under this License for that Work shall terminate
          +      as of the date such litigation is filed.
          +
          +   4. Redistribution. You may reproduce and distribute copies of the
          +      Work or Derivative Works thereof in any medium, with or without
          +      modifications, and in Source or Object form, provided that You
          +      meet the following conditions:
          +
          +      (a) You must give any other recipients of the Work or
          +          Derivative Works a copy of this License; and
          +
          +      (b) You must cause any modified files to carry prominent notices
          +          stating that You changed the files; and
          +
          +      (c) You must retain, in the Source form of any Derivative Works
          +          that You distribute, all copyright, patent, trademark, and
          +          attribution notices from the Source form of the Work,
          +          excluding those notices that do not pertain to any part of
          +          the Derivative Works; and
          +
          +      (d) If the Work includes a "NOTICE" text file as part of its
          +          distribution, then any Derivative Works that You distribute must
          +          include a readable copy of the attribution notices contained
          +          within such NOTICE file, excluding those notices that do not
          +          pertain to any part of the Derivative Works, in at least one
          +          of the following places: within a NOTICE text file distributed
          +          as part of the Derivative Works; within the Source form or
          +          documentation, if provided along with the Derivative Works; or,
          +          within a display generated by the Derivative Works, if and
          +          wherever such third-party notices normally appear. The contents
          +          of the NOTICE file are for informational purposes only and
          +          do not modify the License. You may add Your own attribution
          +          notices within Derivative Works that You distribute, alongside
          +          or as an addendum to the NOTICE text from the Work, provided
          +          that such additional attribution notices cannot be construed
          +          as modifying the License.
          +
          +      You may add Your own copyright statement to Your modifications and
          +      may provide additional or different license terms and conditions
          +      for use, reproduction, or distribution of Your modifications, or
          +      for any such Derivative Works as a whole, provided Your use,
          +      reproduction, and distribution of the Work otherwise complies with
          +      the conditions stated in this License.
          +
          +   5. Submission of Contributions. Unless You explicitly state otherwise,
          +      any Contribution intentionally submitted for inclusion in the Work
          +      by You to the Licensor shall be under the terms and conditions of
          +      this License, without any additional terms or conditions.
          +      Notwithstanding the above, nothing herein shall supersede or modify
          +      the terms of any separate license agreement you may have executed
          +      with Licensor regarding such Contributions.
          +
          +   6. Trademarks. This License does not grant permission to use the trade
          +      names, trademarks, service marks, or product names of the Licensor,
          +      except as required for reasonable and customary use in describing the
          +      origin of the Work and reproducing the content of the NOTICE file.
          +
          +   7. Disclaimer of Warranty. Unless required by applicable law or
          +      agreed to in writing, Licensor provides the Work (and each
          +      Contributor provides its Contributions) on an "AS IS" BASIS,
          +      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          +      implied, including, without limitation, any warranties or conditions
          +      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          +      PARTICULAR PURPOSE. You are solely responsible for determining the
          +      appropriateness of using or redistributing the Work and assume any
          +      risks associated with Your exercise of permissions under this License.
          +
          +   8. Limitation of Liability. In no event and under no legal theory,
          +      whether in tort (including negligence), contract, or otherwise,
          +      unless required by applicable law (such as deliberate and grossly
          +      negligent acts) or agreed to in writing, shall any Contributor be
          +      liable to You for damages, including any direct, indirect, special,
          +      incidental, or consequential damages of any character arising as a
          +      result of this License or out of the use or inability to use the
          +      Work (including but not limited to damages for loss of goodwill,
          +      work stoppage, computer failure or malfunction, or any and all
          +      other commercial damages or losses), even if such Contributor
          +      has been advised of the possibility of such damages.
          +
          +   9. Accepting Warranty or Additional Liability. While redistributing
          +      the Work or Derivative Works thereof, You may choose to offer,
          +      and charge a fee for, acceptance of support, warranty, indemnity,
          +      or other liability obligations and/or rights consistent with this
          +      License. However, in accepting such obligations, You may act only
          +      on Your own behalf and on Your sole responsibility, not on behalf
          +      of any other Contributor, and only if You agree to indemnify,
          +      defend, and hold each Contributor harmless for any liability
          +      incurred by, or claims asserted against, such Contributor by reason
          +      of your accepting any such warranty or additional liability.
          +
          +   END OF TERMS AND CONDITIONS
          +
          +   APPENDIX: How to apply the Apache License to your work.
          +
          +      To apply the Apache License to your work, attach the following
          +      boilerplate notice, with the fields enclosed by brackets "{}"
          +      replaced with your own identifying information. (Don't include
          +      the brackets!)  The text should be enclosed in the appropriate
          +      comment syntax for the file format. We also recommend that a
          +      file or class name and description of purpose be included on the
          +      same "printed page" as the copyright notice for easier
          +      identification within third-party archives.
          +
          +   Copyright {yyyy} {name of copyright owner}
          +
          +   Licensed under the Apache License, Version 2.0 (the "License");
          +   you may not use this file except in compliance with the License.
          +   You may obtain a copy of the License at
          +
          +       http://www.apache.org/licenses/LICENSE-2.0
          +
          +   Unless required by applicable law or agreed to in writing, software
          +   distributed under the License is distributed on an "AS IS" BASIS,
          +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          +   See the License for the specific language governing permissions and
          +   limitations under the License.
          +
          +
        • +
        • +

          Apache License 2.0

          +

          Used by:

          +
          Apache License
           Version 2.0, January 2004
          @@ -10718,135 +13396,182 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          Apache License
           Version 2.0, January 2004
          @@ -11163,10 +13888,10 @@ limitations under the License.
                           

          Apache License 2.0

          Used by:

          Rust-chrono is dual-licensed under The MIT License [1] and
          -Apache 2.0 License [2]. Copyright (c) 2014--2025, Kang Seonghoon and
          +Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and
           contributors.
           
           Nota Bene: This is same as the Rust Project's own license.
          @@ -11405,6 +14130,40 @@ See the License for the specific language governing permissions and
           limitations under the License.
           ~~~~
           
          +
          +
        • +
        • +

          BSD 2-Clause "Simplified" License

          +

          Used by:

          + +
          Copyright (c) 2013-2014, Naoki Yoshinaga, Paul Meng
          +All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions are
          +met:
          +
          +1. Redistributions of source code must retain the above copyright
          +   notice, this list of conditions and the following disclaimer.
          +
          +2. Redistributions in binary form must reproduce the above copyright
          +   notice, this list of conditions and the following disclaimer in the
          +   documentation and/or other materials provided with the
          +   distribution.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
          +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
          +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
          +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
          +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
          +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
          +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
          +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
          +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
          +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
           
        • @@ -11439,6 +14198,99 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
        • + +
        • +

          BSD 2-Clause "Simplified" License

          +

          Used by:

          + +
          Copyright (c) 2017-2020
          +All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions are met:
          +
          +1. Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +2. Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
          +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          + +
          // Copyright © WHATWG (Apple, Google, Mozilla, Microsoft).
          +//
          +// Redistribution and use in source and binary forms, with or without
          +// modification, are permitted provided that the following conditions are met:
          +//
          +// 1. Redistributions of source code must retain the above copyright notice, this
          +//    list of conditions and the following disclaimer.
          +//
          +// 2. Redistributions in binary form must reproduce the above copyright notice,
          +//    this list of conditions and the following disclaimer in the documentation
          +//    and/or other materials provided with the distribution.
          +//
          +// 3. Neither the name of the copyright holder nor the names of its
          +//    contributors may be used to endorse or promote products derived from
          +//    this software without specific prior written permission.
          +//
          +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
          +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
          +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
          +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
          +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
          +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
          +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
          +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
          +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +/// The PUA code points special-cased in the GB18030 encoder.
          +pub(crate) static GB18030_2022_OVERRIDE_PUA: [u16; 18] = [
          +    0xE78D, 0xE78E, 0xE78F, 0xE790, 0xE791, 0xE792, 0xE793, 0xE794, 0xE795, 0xE796, 0xE81E, 0xE826,
          +    0xE82B, 0xE82C, 0xE832, 0xE843, 0xE854, 0xE864,
          +];
          +
          +/// The bytes corresponding to the PUA code points special-cased in the GB18030 encoder.
          +pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
          +    [0xA6, 0xD9],
          +    [0xA6, 0xDA],
          +    [0xA6, 0xDB],
          +    [0xA6, 0xDC],
          +    [0xA6, 0xDD],
          +    [0xA6, 0xDE],
          +    [0xA6, 0xDF],
          +    [0xA6, 0xEC],
          +    [0xA6, 0xED],
          +    [0xA6, 0xF3],
          +    [0xFE, 0x59],
          +    [0xFE, 0x61],
          +    [0xFE, 0x66],
          +    [0xFE, 0x67],
          +    [0xFE, 0x6D],
          +    [0xFE, 0x7E],
          +    [0xFE, 0x90],
          +    [0xFE, 0xA0],
          +];
           
        • @@ -11446,6 +14298,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

          Used by:

          BSD 3-Clause License
           
          @@ -11482,10 +14335,88 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                           

          BSD 3-Clause "New" or "Revised" License

          Used by:

          +
          BSD 3-Clause License
          +
          +Copyright (c) 2026, Alexandre Bury
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions are met:
          +
          +1. Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +
          +2. Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          +3. Neither the name of the copyright holder nor the names of its
          +   contributors may be used to endorse or promote products derived from
          +   this software without specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
          +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
          +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
          +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
          +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
          +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
          +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
          +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
          +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          + +
          BSD License
          +
          +For Zstandard software
          +
          +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without modification,
          +are permitted provided that the following conditions are met:
          +
          + * Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +
          + * Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          + * Neither the name Facebook, nor Meta, nor the names of its contributors may
          +   be used to endorse or promote products derived from this software without
          +   specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
          +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          +
          Copyright (c) 2001, Dr Martin Porter
           Copyright (c) 2004,2005, Richard Boulton
          +Copyright (c) 2013, Yoshiki Shibukawa
          +Copyright (c) 2006-2025, Olly Betts
           All rights reserved.
           
           Redistribution and use in source and binary forms, with or without
          @@ -11510,16 +14441,16 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
           LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
           ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
           (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +
        • BSD 3-Clause "New" or "Revised" License

          Used by:

          Copyright (c) 2016 Dropbox, Inc.
           All rights reserved.
          @@ -11576,8 +14507,53 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                           

          BSD 3-Clause "New" or "Revised" License

          Used by:

          +
          Copyright (c) 2026, frostem contributors
          +Copyright (c) 2001, Dr Martin Porter
          +Copyright (c) 2004,2005, Richard Boulton
          +Copyright (c) 2013, Yoshiki Shibukawa
          +Copyright (c) 2006-2025, Olly Betts
          +All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without
          +modification, are permitted provided that the following conditions
          +are met:
          +
          +  1. Redistributions of source code must retain the above copyright notice,
          +     this list of conditions and the following disclaimer.
          +  2. Redistributions in binary form must reproduce the above copyright notice,
          +     this list of conditions and the following disclaimer in the documentation
          +     and/or other materials provided with the distribution.
          +  3. Neither the name of the Snowball project nor the names of its contributors
          +     may be used to endorse or promote products derived from this software
          +     without specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
          +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          +
          Copyright (c) <year> <owner>. 
           
          @@ -11624,13 +14600,53 @@ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
           CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
           OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
           OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
          +
          +
        • +
        • +

          BSD 3-Clause "New" or "Revised" License

          +

          Used by:

          + +
          The auto-generated bindings are under the 3-clause BSD license:
          +
          +BSD License
          +
          +For Zstandard software
          +
          +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
          +
          +Redistribution and use in source and binary forms, with or without modification,
          +are permitted provided that the following conditions are met:
          +
          + * Redistributions of source code must retain the above copyright notice, this
          +   list of conditions and the following disclaimer.
          +
          + * Redistributions in binary form must reproduce the above copyright notice,
          +   this list of conditions and the following disclaimer in the documentation
          +   and/or other materials provided with the distribution.
          +
          + * Neither the name Facebook, nor Meta, nor the names of its contributors may
          +   be used to endorse or promote products derived from this software without
          +   specific prior written permission.
          +
          +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
          +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
          +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
          +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
          +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
          +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
          +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
          +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
          +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
          +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
           
        • Boost Software License 1.0

          Used by:

          Boost Software License - Version 1.0 - August 17th, 2003
           
          @@ -11784,13 +14800,405 @@ express Statement of Purpose.
            d. Affirmer understands and acknowledges that Creative Commons is not a
               party to this document and has no duty or obligation with respect to
               this CC0 or use of the Work.
          +
          +
        • +
        • +

          Common Development and Distribution License 1.0

          +

          Used by:

          + +
          Unless otherwise noted, all files in this distribution are released
          +under the Common Development and Distribution License (CDDL).
          +Exceptions are noted within the associated source files.
          +
          +--------------------------------------------------------------------
          +
          +
          +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
          +
          +1. Definitions.
          +
          +    1.1. "Contributor" means each individual or entity that creates
          +         or contributes to the creation of Modifications.
          +
          +    1.2. "Contributor Version" means the combination of the Original
          +         Software, prior Modifications used by a Contributor (if any),
          +         and the Modifications made by that particular Contributor.
          +
          +    1.3. "Covered Software" means (a) the Original Software, or (b)
          +         Modifications, or (c) the combination of files containing
          +         Original Software with files containing Modifications, in
          +         each case including portions thereof.
          +
          +    1.4. "Executable" means the Covered Software in any form other
          +         than Source Code.
          +
          +    1.5. "Initial Developer" means the individual or entity that first
          +         makes Original Software available under this License.
          +
          +    1.6. "Larger Work" means a work which combines Covered Software or
          +         portions thereof with code not governed by the terms of this
          +         License.
          +
          +    1.7. "License" means this document.
          +
          +    1.8. "Licensable" means having the right to grant, to the maximum
          +         extent possible, whether at the time of the initial grant or
          +         subsequently acquired, any and all of the rights conveyed
          +         herein.
          +
          +    1.9. "Modifications" means the Source Code and Executable form of
          +         any of the following:
          +
          +        A. Any file that results from an addition to, deletion from or
          +           modification of the contents of a file containing Original
          +           Software or previous Modifications;
          +
          +        B. Any new file that contains any part of the Original
          +           Software or previous Modifications; or
          +
          +        C. Any new file that is contributed or otherwise made
          +           available under the terms of this License.
          +
          +    1.10. "Original Software" means the Source Code and Executable
          +          form of computer software code that is originally released
          +          under this License.
          +
          +    1.11. "Patent Claims" means any patent claim(s), now owned or
          +          hereafter acquired, including without limitation, method,
          +          process, and apparatus claims, in any patent Licensable by
          +          grantor.
          +
          +    1.12. "Source Code" means (a) the common form of computer software
          +          code in which modifications are made and (b) associated
          +          documentation included in or with such code.
          +
          +    1.13. "You" (or "Your") means an individual or a legal entity
          +          exercising rights under, and complying with all of the terms
          +          of, this License.  For legal entities, "You" includes any
          +          entity which controls, is controlled by, or is under common
          +          control with You.  For purposes of this definition,
          +          "control" means (a) the power, direct or indirect, to cause
          +          the direction or management of such entity, whether by
          +          contract or otherwise, or (b) ownership of more than fifty
          +          percent (50%) of the outstanding shares or beneficial
          +          ownership of such entity.
          +
          +2. License Grants.
          +
          +    2.1. The Initial Developer Grant.
          +
          +    Conditioned upon Your compliance with Section 3.1 below and
          +    subject to third party intellectual property claims, the Initial
          +    Developer hereby grants You a world-wide, royalty-free,
          +    non-exclusive license:
          +
          +        (a) under intellectual property rights (other than patent or
          +            trademark) Licensable by Initial Developer, to use,
          +            reproduce, modify, display, perform, sublicense and
          +            distribute the Original Software (or portions thereof),
          +            with or without Modifications, and/or as part of a Larger
          +            Work; and
          +
          +        (b) under Patent Claims infringed by the making, using or
          +            selling of Original Software, to make, have made, use,
          +            practice, sell, and offer for sale, and/or otherwise
          +            dispose of the Original Software (or portions thereof).
          +
          +        (c) The licenses granted in Sections 2.1(a) and (b) are
          +            effective on the date Initial Developer first distributes
          +            or otherwise makes the Original Software available to a
          +            third party under the terms of this License.
          +
          +        (d) Notwithstanding Section 2.1(b) above, no patent license is
          +            granted: (1) for code that You delete from the Original
          +            Software, or (2) for infringements caused by: (i) the
          +            modification of the Original Software, or (ii) the
          +            combination of the Original Software with other software
          +            or devices.
          +
          +    2.2. Contributor Grant.
          +
          +    Conditioned upon Your compliance with Section 3.1 below and
          +    subject to third party intellectual property claims, each
          +    Contributor hereby grants You a world-wide, royalty-free,
          +    non-exclusive license:
          +
          +        (a) under intellectual property rights (other than patent or
          +            trademark) Licensable by Contributor to use, reproduce,
          +            modify, display, perform, sublicense and distribute the
          +            Modifications created by such Contributor (or portions
          +            thereof), either on an unmodified basis, with other
          +            Modifications, as Covered Software and/or as part of a
          +            Larger Work; and
          +
          +        (b) under Patent Claims infringed by the making, using, or
          +            selling of Modifications made by that Contributor either
          +            alone and/or in combination with its Contributor Version
          +            (or portions of such combination), to make, use, sell,
          +            offer for sale, have made, and/or otherwise dispose of:
          +            (1) Modifications made by that Contributor (or portions
          +            thereof); and (2) the combination of Modifications made by
          +            that Contributor with its Contributor Version (or portions
          +            of such combination).
          +
          +        (c) The licenses granted in Sections 2.2(a) and 2.2(b) are
          +            effective on the date Contributor first distributes or
          +            otherwise makes the Modifications available to a third
          +            party.
          +
          +        (d) Notwithstanding Section 2.2(b) above, no patent license is
          +            granted: (1) for any code that Contributor has deleted
          +            from the Contributor Version; (2) for infringements caused
          +            by: (i) third party modifications of Contributor Version,
          +            or (ii) the combination of Modifications made by that
          +            Contributor with other software (except as part of the
          +            Contributor Version) or other devices; or (3) under Patent
          +            Claims infringed by Covered Software in the absence of
          +            Modifications made by that Contributor.
          +
          +3. Distribution Obligations.
          +
          +    3.1. Availability of Source Code.
          +
          +    Any Covered Software that You distribute or otherwise make
          +    available in Executable form must also be made available in Source
          +    Code form and that Source Code form must be distributed only under
          +    the terms of this License.  You must include a copy of this
          +    License with every copy of the Source Code form of the Covered
          +    Software You distribute or otherwise make available.  You must
          +    inform recipients of any such Covered Software in Executable form
          +    as to how they can obtain such Covered Software in Source Code
          +    form in a reasonable manner on or through a medium customarily
          +    used for software exchange.
          +
          +    3.2. Modifications.
          +
          +    The Modifications that You create or to which You contribute are
          +    governed by the terms of this License.  You represent that You
          +    believe Your Modifications are Your original creation(s) and/or
          +    You have sufficient rights to grant the rights conveyed by this
          +    License.
          +
          +    3.3. Required Notices.
          +
          +    You must include a notice in each of Your Modifications that
          +    identifies You as the Contributor of the Modification.  You may
          +    not remove or alter any copyright, patent or trademark notices
          +    contained within the Covered Software, or any notices of licensing
          +    or any descriptive text giving attribution to any Contributor or
          +    the Initial Developer.
          +
          +    3.4. Application of Additional Terms.
          +
          +    You may not offer or impose any terms on any Covered Software in
          +    Source Code form that alters or restricts the applicable version
          +    of this License or the recipients' rights hereunder.  You may
          +    choose to offer, and to charge a fee for, warranty, support,
          +    indemnity or liability obligations to one or more recipients of
          +    Covered Software.  However, you may do so only on Your own behalf,
          +    and not on behalf of the Initial Developer or any Contributor.
          +    You must make it absolutely clear that any such warranty, support,
          +    indemnity or liability obligation is offered by You alone, and You
          +    hereby agree to indemnify the Initial Developer and every
          +    Contributor for any liability incurred by the Initial Developer or
          +    such Contributor as a result of warranty, support, indemnity or
          +    liability terms You offer.
          +
          +    3.5. Distribution of Executable Versions.
          +
          +    You may distribute the Executable form of the Covered Software
          +    under the terms of this License or under the terms of a license of
          +    Your choice, which may contain terms different from this License,
          +    provided that You are in compliance with the terms of this License
          +    and that the license for the Executable form does not attempt to
          +    limit or alter the recipient's rights in the Source Code form from
          +    the rights set forth in this License.  If You distribute the
          +    Covered Software in Executable form under a different license, You
          +    must make it absolutely clear that any terms which differ from
          +    this License are offered by You alone, not by the Initial
          +    Developer or Contributor.  You hereby agree to indemnify the
          +    Initial Developer and every Contributor for any liability incurred
          +    by the Initial Developer or such Contributor as a result of any
          +    such terms You offer.
          +
          +    3.6. Larger Works.
          +
          +    You may create a Larger Work by combining Covered Software with
          +    other code not governed by the terms of this License and
          +    distribute the Larger Work as a single product.  In such a case,
          +    You must make sure the requirements of this License are fulfilled
          +    for the Covered Software.
          +
          +4. Versions of the License.
          +
          +    4.1. New Versions.
          +
          +    Sun Microsystems, Inc. is the initial license steward and may
          +    publish revised and/or new versions of this License from time to
          +    time.  Each version will be given a distinguishing version number.
          +    Except as provided in Section 4.3, no one other than the license
          +    steward has the right to modify this License.
          +
          +    4.2. Effect of New Versions.
          +
          +    You may always continue to use, distribute or otherwise make the
          +    Covered Software available under the terms of the version of the
          +    License under which You originally received the Covered Software.
          +    If the Initial Developer includes a notice in the Original
          +    Software prohibiting it from being distributed or otherwise made
          +    available under any subsequent version of the License, You must
          +    distribute and make the Covered Software available under the terms
          +    of the version of the License under which You originally received
          +    the Covered Software.  Otherwise, You may also choose to use,
          +    distribute or otherwise make the Covered Software available under
          +    the terms of any subsequent version of the License published by
          +    the license steward.
          +
          +    4.3. Modified Versions.
          +
          +    When You are an Initial Developer and You want to create a new
          +    license for Your Original Software, You may create and use a
          +    modified version of this License if You: (a) rename the license
          +    and remove any references to the name of the license steward
          +    (except to note that the license differs from this License); and
          +    (b) otherwise make it clear that the license contains terms which
          +    differ from this License.
          +
          +5. DISCLAIMER OF WARRANTY.
          +
          +    COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
          +    BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
          +    INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
          +    SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
          +    PURPOSE OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND
          +    PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.  SHOULD ANY
          +    COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
          +    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
          +    NECESSARY SERVICING, REPAIR OR CORRECTION.  THIS DISCLAIMER OF
          +    WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.  NO USE OF
          +    ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
          +    DISCLAIMER.
          +
          +6. TERMINATION.
          +
          +    6.1. This License and the rights granted hereunder will terminate
          +    automatically if You fail to comply with terms herein and fail to
          +    cure such breach within 30 days of becoming aware of the breach.
          +    Provisions which, by their nature, must remain in effect beyond
          +    the termination of this License shall survive.
          +
          +    6.2. If You assert a patent infringement claim (excluding
          +    declaratory judgment actions) against Initial Developer or a
          +    Contributor (the Initial Developer or Contributor against whom You
          +    assert such claim is referred to as "Participant") alleging that
          +    the Participant Software (meaning the Contributor Version where
          +    the Participant is a Contributor or the Original Software where
          +    the Participant is the Initial Developer) directly or indirectly
          +    infringes any patent, then any and all rights granted directly or
          +    indirectly to You by such Participant, the Initial Developer (if
          +    the Initial Developer is not the Participant) and all Contributors
          +    under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
          +    notice from Participant terminate prospectively and automatically
          +    at the expiration of such 60 day notice period, unless if within
          +    such 60 day period You withdraw Your claim with respect to the
          +    Participant Software against such Participant either unilaterally
          +    or pursuant to a written agreement with Participant.
          +
          +    6.3. In the event of termination under Sections 6.1 or 6.2 above,
          +    all end user licenses that have been validly granted by You or any
          +    distributor hereunder prior to termination (excluding licenses
          +    granted to You by any distributor) shall survive termination.
          +
          +7. LIMITATION OF LIABILITY.
          +
          +    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
          +    (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
          +    INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
          +    COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
          +    LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
          +    CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
          +    LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
          +    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
          +    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
          +    INFORMED OF THE POSSIBILITY OF SUCH DAMAGES.  THIS LIMITATION OF
          +    LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
          +    INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
          +    APPLICABLE LAW PROHIBITS SUCH LIMITATION.  SOME JURISDICTIONS DO
          +    NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
          +    CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
          +    APPLY TO YOU.
          +
          +8. U.S. GOVERNMENT END USERS.
          +
          +    The Covered Software is a "commercial item," as that term is
          +    defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
          +    computer software" (as that term is defined at 48
          +    C.F.R. 252.227-7014(a)(1)) and "commercial computer software
          +    documentation" as such terms are used in 48 C.F.R. 12.212
          +    (Sept. 1995).  Consistent with 48 C.F.R. 12.212 and 48
          +    C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
          +    U.S. Government End Users acquire Covered Software with only those
          +    rights set forth herein.  This U.S. Government Rights clause is in
          +    lieu of, and supersedes, any other FAR, DFAR, or other clause or
          +    provision that addresses Government rights in computer software
          +    under this License.
          +
          +9. MISCELLANEOUS.
          +
          +    This License represents the complete agreement concerning subject
          +    matter hereof.  If any provision of this License is held to be
          +    unenforceable, such provision shall be reformed only to the extent
          +    necessary to make it enforceable.  This License shall be governed
          +    by the law of the jurisdiction specified in a notice contained
          +    within the Original Software (except to the extent applicable law,
          +    if any, provides otherwise), excluding such jurisdiction's
          +    conflict-of-law provisions.  Any litigation relating to this
          +    License shall be subject to the jurisdiction of the courts located
          +    in the jurisdiction and venue specified in a notice contained
          +    within the Original Software, with the losing party responsible
          +    for costs, including, without limitation, court costs and
          +    reasonable attorneys' fees and expenses.  The application of the
          +    United Nations Convention on Contracts for the International Sale
          +    of Goods is expressly excluded.  Any law or regulation which
          +    provides that the language of a contract shall be construed
          +    against the drafter shall not apply to this License.  You agree
          +    that You alone are responsible for compliance with the United
          +    States export administration regulations (and the export control
          +    laws and regulation of any other countries) when You use,
          +    distribute or otherwise make available any Covered Software.
          +
          +10. RESPONSIBILITY FOR CLAIMS.
          +
          +    As between Initial Developer and the Contributors, each party is
          +    responsible for claims and damages arising, directly or
          +    indirectly, out of its utilization of rights under this License
          +    and You agree to work with Initial Developer and Contributors to
          +    distribute such responsibility on an equitable basis.  Nothing
          +    herein is intended or shall be deemed to constitute any admission
          +    of liability.
          +
          +--------------------------------------------------------------------
          +
          +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
          +DISTRIBUTION LICENSE (CDDL)
          +
          +For Covered Software in this distribution, this License shall
          +be governed by the laws of the State of California (excluding
          +conflict-of-law provisions).
          +
          +Any litigation relating to this License shall be subject to the
          +jurisdiction of the Federal Courts of the Northern District of
          +California and the state courts of the State of California, with
          +venue lying in Santa Clara County, California.
           
        • Community Data License Agreement Permissive 2.0

          Used by:

          # Community Data License Agreement - Permissive - Version 2.0
           
          @@ -11853,6 +15261,88 @@ agreement.
           5.4. "Results" means any outcome obtained by computational analysis
           of Data, including for example machine learning models and models'
           insights.
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          /* Copyright (c) 2014, Intel Corporation.
          + *
          + * Permission to use, copy, modify, and/or distribute this software for any
          + * purpose with or without fee is hereby granted, provided that the above
          + * copyright notice and this permission notice appear in all copies.
          + *
          + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
          +
          +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
          +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
          +
          +#include "../../limbs/limbs.h"
          +
          +#define P384_LIMBS (384u / LIMB_BITS)
          +
          +typedef struct {
          +  Limb X[P384_LIMBS];
          +  Limb Y[P384_LIMBS];
          +  Limb Z[P384_LIMBS];
          +} P384_POINT;
          +
          +typedef struct {
          +  Limb X[P384_LIMBS];
          +  Limb Y[P384_LIMBS];
          +} P384_POINT_AFFINE;
          +
          +
          +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2015-2016 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! EdDSA Signatures.
          +
          +use super::ops::ELEM_LEN;
          +use crate::digest;
          +
          +pub mod signing;
          +pub mod verification;
          +
          +/// The length of an Ed25519 public key.
          +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
          +
          +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
          +    let mut ctx = digest::Context::new(&digest::SHA512);
          +    ctx.update(signature_r);
          +    ctx.update(public_key);
          +    ctx.update(msg);
          +    ctx.finish()
          +}
           
        • @@ -11880,29 +15370,44 @@ insights.

          ISC License

          Used by:

          -
          // Copyright 2021 Brian Smith.
          +                
          // Copyright 2015-2022 Brian Smith.
           //
           // Permission to use, copy, modify, and/or distribute this software for any
           // purpose with or without fee is hereby granted, provided that the above
           // copyright notice and this permission notice appear in all copies.
           //
          -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
           // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
          -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
          -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
          -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
           
          -#[test]
          -fn cert_without_extensions_test() {
          -    // Check the certificate is valid with
          -    // `openssl x509 -in cert_without_extensions.der -inform DER -text -noout`
          -    const CERT_WITHOUT_EXTENSIONS_DER: &[u8] = include_bytes!("cert_without_extensions.der");
          +use crate::limb::Limb;
           
          -    assert!(webpki::EndEntityCert::try_from(CERT_WITHOUT_EXTENSIONS_DER).is_ok());
          +#[derive(Clone, Copy)]
          +#[repr(transparent)]
          +pub struct N0([Limb; 2]);
          +
          +impl N0 {
          +    #[cfg(feature = "alloc")]
          +    pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
          +
          +    #[inline]
          +    pub const fn precalculated(n0: u64) -> Self {
          +        #[cfg(target_pointer_width = "64")]
          +        {
          +            Self([n0, 0])
          +        }
          +
          +        #[cfg(target_pointer_width = "32")]
          +        {
          +            Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
          +        }
          +    }
           }
           
        • @@ -11910,21 +15415,372 @@ fn cert_without_extensions_test() {

          ISC License

          Used by:

          -
          Copyright (c) 2017 Adam Wick
          +                
          // Copyright 2015-2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
           
          -Permission to use, copy, modify, and/or distribute this software for any purpose
          -with or without fee is hereby granted, provided that the above copyright notice
          -and this permission notice appear in all copies.
          +use crate::{bb, error};
           
          -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
          -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
          -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
          -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
          -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
          -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
          -THIS SOFTWARE.
          +#[deprecated(
          +    note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
          +)]
          +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
          +    bb::verify_slices_are_equal(a, b)
          +}
          +
          + +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2016 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! Elliptic curve operations and schemes using Curve25519.
          +
          +pub mod ed25519;
          +
          +pub mod x25519;
          +
          +mod ops;
          +mod scalar;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2016-2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +use crate::error::{KeyRejected, Unspecified};
          +
          +impl From<untrusted::EndOfInput> for Unspecified {
          +    fn from(source: untrusted::EndOfInput) -> Self {
          +        super::erase(source)
          +    }
          +}
          +
          +impl From<core::array::TryFromSliceError> for Unspecified {
          +    fn from(source: core::array::TryFromSliceError) -> Self {
          +        super::erase(source)
          +    }
          +}
          +
          +impl From<KeyRejected> for Unspecified {
          +    fn from(source: KeyRejected) -> Self {
          +        super::erase(source)
          +    }
          +}
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2018 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! Serialization and deserialization.
          +
          +#[doc(hidden)]
          +pub mod der;
          +
          +#[cfg(feature = "alloc")]
          +mod writer;
          +
          +#[cfg(feature = "alloc")]
          +pub(crate) mod der_writer;
          +
          +pub(crate) mod positive;
          +
          +pub use self::positive::Positive;
          +
          +#[cfg(feature = "alloc")]
          +pub(crate) use self::writer::TooLongError;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2019-2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +use super::BlockLen;
          +
          +pub(super) use self::{
          +    sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
          +    sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
          +};
          +
          +pub(super) const CHAINING_WORDS: usize = 8;
          +
          +#[cfg(any(
          +    all(target_arch = "aarch64", target_endian = "little"),
          +    all(target_arch = "arm", target_endian = "little"),
          +    target_arch = "x86_64"
          +))]
          +#[macro_use]
          +mod ffi;
          +
          +pub(super) mod fallback;
          +mod sha2_32;
          +mod sha2_64;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
          +#[allow(dead_code)]
          +#[inline(always)]
          +pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
          +    r
          +}
          +
          +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
          +#[allow(dead_code)]
          +#[inline(always)]
          +pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
          +    r
          +}
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +//! Integration tests for non-public APIs.
          +
          +mod bits_tests;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2024 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +pub use self::{
          +    array::Array,
          +    base::{IndexError, Overlapping},
          +    partial_block::PartialBlock,
          +};
          +
          +mod array;
          +mod base;
          +mod partial_block;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
          +
          +pub(in super::super) mod mont;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +#![cfg(target_arch = "x86_64")]
          +
          +pub(in super::super::super) mod mont;
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +mod storage;
          +
          +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          // Copyright 2025 Brian Smith.
          +//
          +// Permission to use, copy, modify, and/or distribute this software for any
          +// purpose with or without fee is hereby granted, provided that the above
          +// copyright notice and this permission notice appear in all copies.
          +//
          +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
          +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
          +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
          +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
          +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
          +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
          +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
          +
          +pub(super) mod aarch64;
          +pub(super) mod x86_64;
           
        • @@ -11952,7 +15808,7 @@ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

          ISC License

          Used by:

          Except as otherwise noted, this project is licensed under the following
           (ISC-style) terms:
          @@ -11979,12 +15835,12 @@ third-party/chromium/LICENSE.
                           

          ISC License

          Used by:

          ISC License
           
           Copyright (c) 2016, Mapbox
          -Copyright (c) 2018, Tree Cricket
          +Copyright (c) 2023, Taku Fukada
           
           Permission to use, copy, modify, and/or distribute this software for any purpose
           with or without fee is hereby granted, provided that the above copyright notice
          @@ -11997,13 +15853,603 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
           OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
           TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
           THIS SOFTWARE.
          +
          +
        • +
        • +

          ISC License

          +

          Used by:

          + +
          ISC License:
          +
          +Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC")
          +Copyright (c) 1995-2003 by Internet Software Consortium
          +
          +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
          +
          +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
           
        • MIT License

          Used by:

          +
                                            MIT License
          +
          +Copyright 2024 Antoine Catton
          +Copyright 2016-2024 David Tolnay
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          # 3rd Party Notices
          +
          +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license:
          +
          +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166
          +
          +    tectonic_cfg_support is licensed under the MIT License.
          +
          +    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.
          +---
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +//! Codegen exports used by `tonic-build`.
          +
          +pub use async_trait::async_trait;
          +pub use tokio_stream;
          +
          +pub use std::future::Future;
          +pub use std::pin::Pin;
          +pub use std::sync::Arc;
          +pub use std::task::{Context, Poll};
          +pub use tower_service::Service;
          +pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
          +pub use crate::codec::{CompressionEncoding, EnabledCompressionEncodings};
          +pub use crate::extensions::GrpcMethod;
          +pub use crate::service::interceptor::InterceptedService;
          +pub use bytes::Bytes;
          +pub use http;
          +pub use http_body::Body;
          +
          +pub type BoxFuture<T, E> = self::Pin<Box<dyn self::Future<Output = Result<T, E>> + Send + 'static>>;
          +pub type BoxStream<T> =
          +    self::Pin<Box<dyn tokio_stream::Stream<Item = Result<T, crate::Status>> + Send + 'static>>;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +//! Utilities for using Tower services with Tonic.
          +
          +pub mod interceptor;
          +pub(crate) mod layered;
          +#[cfg(feature = "router")]
          +pub(crate) mod router;
          +
          +#[doc(inline)]
          +pub use self::interceptor::{Interceptor, InterceptorLayer};
          +pub use self::layered::{LayerExt, Layered};
          +#[doc(inline)]
          +#[cfg(feature = "router")]
          +pub use self::router::{Routes, RoutesBuilder};
          +#[cfg(feature = "router")]
          +pub use axum::{Router as AxumRouter, body::Body as AxumBody};
          +
          +pub mod recover_error;
          +pub use self::recover_error::{RecoverError, RecoverErrorLayer};
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +//! Various utilities used throughout tonic.
          +
          +// some combinations of features might cause things here not to be used
          +#![allow(dead_code)]
          +
          +pub(crate) mod base64 {
          +    use base64::{
          +        alphabet,
          +        engine::{
          +            DecodePaddingMode,
          +            general_purpose::{GeneralPurpose, GeneralPurposeConfig},
          +        },
          +    };
          +
          +    pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new(
          +        &alphabet::STANDARD,
          +        GeneralPurposeConfig::new()
          +            .with_encode_padding(true)
          +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
          +    );
          +
          +    pub(crate) const STANDARD_NO_PAD: GeneralPurpose = GeneralPurpose::new(
          +        &alphabet::STANDARD,
          +        GeneralPurposeConfig::new()
          +            .with_encode_padding(false)
          +            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
          +    );
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +/// A gRPC Method info extension.
          +#[derive(Debug, Clone)]
          +pub struct GrpcMethod<'a> {
          +    service: &'a str,
          +    method: &'a str,
          +}
          +
          +impl<'a> GrpcMethod<'a> {
          +    /// Create a new `GrpcMethod` extension.
          +    #[doc(hidden)]
          +    pub fn new(service: &'a str, method: &'a str) -> Self {
          +        Self { service, method }
          +    }
          +
          +    /// gRPC service name
          +    pub fn service(&self) -> &str {
          +        self.service
          +    }
          +    /// gRPC method name
          +    pub fn method(&self) -> &str {
          +        self.method
          +    }
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +mod add_origin;
          +use self::add_origin::AddOrigin;
          +
          +mod user_agent;
          +use self::user_agent::UserAgent;
          +
          +mod reconnect;
          +use self::reconnect::Reconnect;
          +
          +mod connection;
          +pub(super) use self::connection::Connection;
          +
          +mod discover;
          +pub use self::discover::Change;
          +pub(super) use self::discover::DynamicServiceStream;
          +
          +mod io;
          +use self::io::BoxedIo;
          +
          +mod connector;
          +pub(crate) use self::connector::Connector;
          +
          +mod executor;
          +pub(super) use self::executor::{Executor, SharedExec};
          +
          +#[cfg(feature = "_tls-any")]
          +mod tls;
          +#[cfg(feature = "_tls-any")]
          +pub(super) use self::tls::TlsConnector;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +mod io;
          +pub(crate) use self::io::{ConnectInfoLayer, ServerIo};
          +
          +#[cfg(feature = "_tls-any")]
          +mod tls;
          +#[cfg(feature = "_tls-any")]
          +pub(crate) use self::tls::TlsAcceptor;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +pub(crate) mod grpc_timeout;
          +#[cfg(feature = "_tls-any")]
          +pub(crate) mod tls;
          +
          +pub(crate) use self::grpc_timeout::GrpcTimeout;
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +use crate::transport::channel::BoxFuture;
          +use hyper_util::rt::TokioExecutor;
          +use std::{future::Future, sync::Arc};
          +
          +pub(crate) use hyper::rt::Executor;
          +
          +#[derive(Clone)]
          +pub(crate) struct SharedExec {
          +    inner: Arc<dyn Executor<BoxFuture<'static, ()>> + Send + Sync + 'static>,
          +}
          +
          +impl SharedExec {
          +    pub(crate) fn new<E>(exec: E) -> Self
          +    where
          +        E: Executor<BoxFuture<'static, ()>> + Send + Sync + 'static,
          +    {
          +        Self {
          +            inner: Arc::new(exec),
          +        }
          +    }
          +
          +    pub(crate) fn tokio() -> Self {
          +        Self::new(TokioExecutor::new())
          +    }
          +}
          +
          +impl<F> Executor<F> for SharedExec
          +where
          +    F: Future<Output = ()> + Send + 'static,
          +{
          +    fn execute(&self, fut: F) {
          +        self.inner.execute(Box::pin(fut))
          +    }
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          /*
          + *
          + * Copyright 2025 gRPC authors.
          + *
          + * 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.
          + *
          + */
          +
          +use super::Connected;
          +use std::sync::Arc;
          +
          +/// Connection info for Unix domain socket streams.
          +///
          +/// This type will be accessible through [request extensions][ext] if you're using
          +/// a unix stream.
          +///
          +/// See [Connected] for more details.
          +///
          +/// [ext]: crate::Request::extensions
          +#[derive(Clone, Debug)]
          +pub struct UdsConnectInfo {
          +    /// Peer address. This will be "unnamed" for client unix sockets.
          +    pub peer_addr: Option<Arc<tokio::net::unix::SocketAddr>>,
          +    /// Process credentials for the unix socket.
          +    pub peer_cred: Option<tokio::net::unix::UCred>,
          +}
          +
          +impl Connected for tokio::net::UnixStream {
          +    type ConnectInfo = UdsConnectInfo;
          +
          +    fn connect_info(&self) -> Self::ConnectInfo {
          +        UdsConnectInfo {
          +            peer_addr: self.peer_addr().ok().map(Arc::new),
          +            peer_cred: self.peer_cred().ok(),
          +        }
          +    }
          +}
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          // Copyright (c) 2019 Nuclear Furnace
          +//
          +// 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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
           
          @@ -12030,7 +16476,7 @@ THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2014 Carl Lerche and other MIO contributors
           
          @@ -12057,7 +16503,6 @@ THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2014-2019 Geoffroy Couprie
          @@ -12086,9 +16531,36 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2014-2021 Sean McArthur
          +                
          Copyright (c) 2014-2020 Optimal Computing (NZ) Ltd
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright (c) 2014-2026 Sean McArthur
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -12113,34 +16585,8 @@ THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2014-2025 Sean McArthur
          -
          -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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          Copyright (c) 2015 Jonathan Reem
           
          @@ -12173,7 +16619,7 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2015 steffengy
           
          @@ -12181,21 +16627,6 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
           
           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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2016 Paul Masurel
          -
          -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.
           
        • @@ -12259,8 +16690,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

          MIT License

          Used by:

          Copyright (c) 2017 h2 authors
           
          @@ -12293,7 +16723,7 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          Copyright (c) 2018 Carl Lerche
           
          @@ -12326,52 +16756,34 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2018 Paul Masurel
          +                
          Copyright (c) 2018 Tom Parker-Shemilt
           
          -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:
          +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 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.
          -
          +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.
        • MIT License

          Used by:

          -
          Copyright (c) 2018 by Quickwit, 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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2018 by the project authors, as listed in the AUTHORS file. 
          -
          -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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          Copyright (c) 2018-2019 Sean McArthur
           
          @@ -12462,7 +16874,7 @@ DEALINGS IN THE SOFTWARE.
                           

          Used by:

          Copyright (c) 2019 Carl Lerche
           
          @@ -12549,44 +16961,13 @@ SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2019 Hyper Contributors
          -
          -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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          Copyright (c) 2019 Tokio Contributors
           
          @@ -12621,7 +17002,7 @@ DEALINGS IN THE SOFTWARE.
                           
                           
          Copyright (c) 2019 Tower Contributors
           
          @@ -12654,10 +17035,9 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2019-2021 Tower Contributors
          +                
          Copyright (c) 2019 axum Contributors
           
           Permission is hereby granted, free of charge, to any
           person obtaining a copy of this software and associated
          @@ -12688,9 +17068,10 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          Copyright (c) 2019-2024 Sean McArthur & Hyper Contributors
          +                
          Copyright (c) 2019-2021 Tower Contributors
           
           Permission is hereby granted, free of charge, to any
           person obtaining a copy of this software and associated
          @@ -12754,7 +17135,68 @@ DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          +
          Copyright (c) 2019-2026 Sean McArthur & Hyper Contributors
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright (c) 2021 Metrics Contributors
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          Copyright (c) 2023-2025 Sean McArthur
           
          @@ -12775,36 +17217,6 @@ 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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2024 by Quickwit 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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          - -
          Copyright (c) 2024-Present Paul Masurel
          -
          -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.
           
        • @@ -12812,6 +17224,7 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

          Used by:

          Copyright 2016 Nika Layzell
           
          @@ -12819,6 +17232,48 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
           
           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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2019 gRPC authors.
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2020 David Koloski
          +
          +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.
           
        • @@ -12841,25 +17296,73 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES

          MIT License

          Used by:

          -
          Includes portions of humantime
          -Copyright (c) 2016 The humantime Developers
          +                
          Copyright 2021 David Koloski
           
           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.
          -
          -
           
        • MIT License

          Used by:

          +
          Copyright 2023 David Koloski
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2023 David Koloski
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          Copyright 2024 David Koloski
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -12882,6 +17385,65 @@ 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.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2016 Michael Ma
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2016 fengcen
          +Copyright (c) 2019 svartalf
          +
          +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.
          +
        • MIT License

          @@ -12903,6 +17465,35 @@ 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. +
        • + +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2017 Denis Kurilenko
          +
          +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
          @@ -12975,9 +17566,41 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2017 Sam Rijs
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -12993,6 +17616,35 @@ 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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2018 Canop
          +
          +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
          @@ -13036,7 +17688,36 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2018 sgodwincs
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13065,7 +17746,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13094,36 +17775,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          -
          MIT License
          -
          -Copyright (c) 2019 Aeledfyr
          -
          -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.
          -
          -
        • -
        • -

          MIT License

          -

          Used by:

          -
          MIT License
           
          @@ -13152,8 +17804,37 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2019 Kornel
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13182,7 +17863,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13236,6 +17917,40 @@ 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.
           
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2019–2025 axum Contributors
          +
          +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.
        • MIT License

          @@ -13270,7 +17985,24 @@ SOFTWARE.

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2020 Katharos Technology
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13288,6 +18020,35 @@ 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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2020 magiclen.org (Ron Li)
          +
          +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
          @@ -13317,6 +18078,93 @@ 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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2020-2022 Oliver Margetts
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2020-2026 Nugine
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2021 Adel Prokurov
          +
          +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
          @@ -13346,6 +18194,35 @@ 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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2022 Arthur Silva
          +
          +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
          @@ -13360,6 +18237,7 @@ SOFTWARE.
                           

          Used by:

          MIT License
           
          @@ -13375,6 +18253,35 @@ 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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2022 Jeroen Van Der Donckt
          +
          +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
          @@ -13416,7 +18323,36 @@ SOFTWARE.

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2022 sarah
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13445,8 +18381,8 @@ SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13475,8 +18411,66 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) 2023 sarah
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          MIT License
          +
          +Copyright (c) 2024 Spire Team
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          MIT License
           
          @@ -13506,19 +18500,28 @@ SOFTWARE.
                           

          Used by:

          MIT License
          @@ -13545,9 +18548,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          MIT License
           
          @@ -13576,7 +18579,99 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          MIT License
          +
          +Copyright (c) [2021] [Marvin Countryman]
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          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.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          Permission is hereby granted, free of charge, to any person obtaining
           a copy of this software and associated documentation files (the
          @@ -13602,12 +18697,42 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          -
          The MIT License (MIT)
          +                
          Portions of this project are derived from atty, which bears the following
          +copyright notice and permission notice:
           
          -Copyright (c) 2014 Benjamin Sago
          -Copyright (c) 2021-2022 The Nushell Project Developers
          +Copyright (c) 2015-2019 Doug Tangren
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License
          +
          +Copyright 2015 The Fancy Regex Authors.
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13616,23 +18741,24 @@ 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 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.
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
          +THE SOFTWARE.
           
        • MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -13655,13 +18781,63 @@ 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.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2014 Mathijs van de Nes
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2014 Y. T. CHUNG
          +
          +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.
          +
        • MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -13689,21 +18865,11 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                           

          MIT License

          Used by:

          The MIT License (MIT)
           
          -Copyright (c) 2015 Andrew Gallant
          +Copyright (c) 2015 
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13712,28 +18878,39 @@ 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 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.
          +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
          +SOFTWARE.
          +
           
        • MIT License

          Used by:

          The MIT License (MIT)
           
           Copyright (c) 2015 Andrew Gallant
          -Copyright (c) 2019 Paul Masurel
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13783,6 +18960,36 @@ 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.
           
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Carl Lerche + nix-rust Authors
          +
          +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.
           
        • @@ -13814,6 +19021,64 @@ 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. +
        • + +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Gerd Zellweger
          +
          +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.
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Guillaume Gomez
          +
          +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.
          +
           
        • @@ -13849,11 +19114,72 @@ SOFTWARE.

          MIT License

          Used by:

          The MIT License (MIT)
           
          -Copyright (c) 2015 Vincent Prouillet
          +Copyright (c) 2015 Markus Westerlind
          +
          +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.
          +
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015 Michael Sproul
          +
          +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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2015-2020 the fiat-crypto authors (see
          +https://github.com/mit-plv/fiat-crypto/blob/master/AUTHORS).
           
           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
          @@ -13878,7 +19204,7 @@ SOFTWARE.
                           

          MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -13894,6 +19220,35 @@ 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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2016 nabijaczleweli
          +
          +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
          @@ -13967,8 +19322,36 @@ SOFTWARE.
                           

          MIT License

          Used by:

          +
          The MIT License (MIT)
          +
          +Copyright (c) 2019 Simon Heath
          +
          +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.
          +
        • +
        • +

          MIT License

          +

          Used by:

          +
          The MIT License (MIT)
           
          @@ -14035,6 +19418,36 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
           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.
          +
          +
        • +
        • +

          MIT License

          +

          Used by:

          + +
          The MIT License (MIT)
          +
          +Copyright (c) 2014 Benjamin Sago
          +Copyright (c) 2021-2022 The Nushell Project Developers
          +
          +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.
           
        • @@ -14099,8 +19512,9 @@ SOFTWARE.
        • MIT License

          Used by:

          The MIT License (MIT)
           
          @@ -14153,6 +19567,387 @@ 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.
          +
          + +
        • +

          Mozilla Public License 2.0

          +

          Used by:

          + +
          Mozilla Public License Version 2.0
          +==================================
          +
          +1. Definitions
          +--------------
          +
          +1.1. "Contributor"
          +    means each individual or legal entity that creates, contributes to
          +    the creation of, or owns Covered Software.
          +
          +1.2. "Contributor Version"
          +    means the combination of the Contributions of others (if any) used
          +    by a Contributor and that particular Contributor's Contribution.
          +
          +1.3. "Contribution"
          +    means Covered Software of a particular Contributor.
          +
          +1.4. "Covered Software"
          +    means Source Code Form to which the initial Contributor has attached
          +    the notice in Exhibit A, the Executable Form of such Source Code
          +    Form, and Modifications of such Source Code Form, in each case
          +    including portions thereof.
          +
          +1.5. "Incompatible With Secondary Licenses"
          +    means
          +
          +    (a) that the initial Contributor has attached the notice described
          +        in Exhibit B to the Covered Software; or
          +
          +    (b) that the Covered Software was made available under the terms of
          +        version 1.1 or earlier of the License, but not also under the
          +        terms of a Secondary License.
          +
          +1.6. "Executable Form"
          +    means any form of the work other than Source Code Form.
          +
          +1.7. "Larger Work"
          +    means a work that combines Covered Software with other material, in 
          +    a separate file or files, that is not Covered Software.
          +
          +1.8. "License"
          +    means this document.
          +
          +1.9. "Licensable"
          +    means having the right to grant, to the maximum extent possible,
          +    whether at the time of the initial grant or subsequently, any and
          +    all of the rights conveyed by this License.
          +
          +1.10. "Modifications"
          +    means any of the following:
          +
          +    (a) any file in Source Code Form that results from an addition to,
          +        deletion from, or modification of the contents of Covered
          +        Software; or
          +
          +    (b) any new file in Source Code Form that contains any Covered
          +        Software.
          +
          +1.11. "Patent Claims" of a Contributor
          +    means any patent claim(s), including without limitation, method,
          +    process, and apparatus claims, in any patent Licensable by such
          +    Contributor that would be infringed, but for the grant of the
          +    License, by the making, using, selling, offering for sale, having
          +    made, import, or transfer of either its Contributions or its
          +    Contributor Version.
          +
          +1.12. "Secondary License"
          +    means either the GNU General Public License, Version 2.0, the GNU
          +    Lesser General Public License, Version 2.1, the GNU Affero General
          +    Public License, Version 3.0, or any later versions of those
          +    licenses.
          +
          +1.13. "Source Code Form"
          +    means the form of the work preferred for making modifications.
          +
          +1.14. "You" (or "Your")
          +    means an individual or a legal entity exercising rights under this
          +    License. For legal entities, "You" includes any entity that
          +    controls, is controlled by, or is under common control with You. For
          +    purposes of this definition, "control" means (a) the power, direct
          +    or indirect, to cause the direction or management of such entity,
          +    whether by contract or otherwise, or (b) ownership of more than
          +    fifty percent (50%) of the outstanding shares or beneficial
          +    ownership of such entity.
          +
          +2. License Grants and Conditions
          +--------------------------------
          +
          +2.1. Grants
          +
          +Each Contributor hereby grants You a world-wide, royalty-free,
          +non-exclusive license:
          +
          +(a) under intellectual property rights (other than patent or trademark)
          +    Licensable by such Contributor to use, reproduce, make available,
          +    modify, display, perform, distribute, and otherwise exploit its
          +    Contributions, either on an unmodified basis, with Modifications, or
          +    as part of a Larger Work; and
          +
          +(b) under Patent Claims of such Contributor to make, use, sell, offer
          +    for sale, have made, import, and otherwise transfer either its
          +    Contributions or its Contributor Version.
          +
          +2.2. Effective Date
          +
          +The licenses granted in Section 2.1 with respect to any Contribution
          +become effective for each Contribution on the date the Contributor first
          +distributes such Contribution.
          +
          +2.3. Limitations on Grant Scope
          +
          +The licenses granted in this Section 2 are the only rights granted under
          +this License. No additional rights or licenses will be implied from the
          +distribution or licensing of Covered Software under this License.
          +Notwithstanding Section 2.1(b) above, no patent license is granted by a
          +Contributor:
          +
          +(a) for any code that a Contributor has removed from Covered Software;
          +    or
          +
          +(b) for infringements caused by: (i) Your and any other third party's
          +    modifications of Covered Software, or (ii) the combination of its
          +    Contributions with other software (except as part of its Contributor
          +    Version); or
          +
          +(c) under Patent Claims infringed by Covered Software in the absence of
          +    its Contributions.
          +
          +This License does not grant any rights in the trademarks, service marks,
          +or logos of any Contributor (except as may be necessary to comply with
          +the notice requirements in Section 3.4).
          +
          +2.4. Subsequent Licenses
          +
          +No Contributor makes additional grants as a result of Your choice to
          +distribute the Covered Software under a subsequent version of this
          +License (see Section 10.2) or under the terms of a Secondary License (if
          +permitted under the terms of Section 3.3).
          +
          +2.5. Representation
          +
          +Each Contributor represents that the Contributor believes its
          +Contributions are its original creation(s) or it has sufficient rights
          +to grant the rights to its Contributions conveyed by this License.
          +
          +2.6. Fair Use
          +
          +This License is not intended to limit any rights You have under
          +applicable copyright doctrines of fair use, fair dealing, or other
          +equivalents.
          +
          +2.7. Conditions
          +
          +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
          +in Section 2.1.
          +
          +3. Responsibilities
          +-------------------
          +
          +3.1. Distribution of Source Form
          +
          +All distribution of Covered Software in Source Code Form, including any
          +Modifications that You create or to which You contribute, must be under
          +the terms of this License. You must inform recipients that the Source
          +Code Form of the Covered Software is governed by the terms of this
          +License, and how they can obtain a copy of this License. You may not
          +attempt to alter or restrict the recipients' rights in the Source Code
          +Form.
          +
          +3.2. Distribution of Executable Form
          +
          +If You distribute Covered Software in Executable Form then:
          +
          +(a) such Covered Software must also be made available in Source Code
          +    Form, as described in Section 3.1, and You must inform recipients of
          +    the Executable Form how they can obtain a copy of such Source Code
          +    Form by reasonable means in a timely manner, at a charge no more
          +    than the cost of distribution to the recipient; and
          +
          +(b) You may distribute such Executable Form under the terms of this
          +    License, or sublicense it under different terms, provided that the
          +    license for the Executable Form does not attempt to limit or alter
          +    the recipients' rights in the Source Code Form under this License.
          +
          +3.3. Distribution of a Larger Work
          +
          +You may create and distribute a Larger Work under terms of Your choice,
          +provided that You also comply with the requirements of this License for
          +the Covered Software. If the Larger Work is a combination of Covered
          +Software with a work governed by one or more Secondary Licenses, and the
          +Covered Software is not Incompatible With Secondary Licenses, this
          +License permits You to additionally distribute such Covered Software
          +under the terms of such Secondary License(s), so that the recipient of
          +the Larger Work may, at their option, further distribute the Covered
          +Software under the terms of either this License or such Secondary
          +License(s).
          +
          +3.4. Notices
          +
          +You may not remove or alter the substance of any license notices
          +(including copyright notices, patent notices, disclaimers of warranty,
          +or limitations of liability) contained within the Source Code Form of
          +the Covered Software, except that You may alter any license notices to
          +the extent required to remedy known factual inaccuracies.
          +
          +3.5. Application of Additional Terms
          +
          +You may choose to offer, and to charge a fee for, warranty, support,
          +indemnity or liability obligations to one or more recipients of Covered
          +Software. However, You may do so only on Your own behalf, and not on
          +behalf of any Contributor. You must make it absolutely clear that any
          +such warranty, support, indemnity, or liability obligation is offered by
          +You alone, and You hereby agree to indemnify every Contributor for any
          +liability incurred by such Contributor as a result of warranty, support,
          +indemnity or liability terms You offer. You may include additional
          +disclaimers of warranty and limitations of liability specific to any
          +jurisdiction.
          +
          +4. Inability to Comply Due to Statute or Regulation
          +---------------------------------------------------
          +
          +If it is impossible for You to comply with any of the terms of this
          +License with respect to some or all of the Covered Software due to
          +statute, judicial order, or regulation then You must: (a) comply with
          +the terms of this License to the maximum extent possible; and (b)
          +describe the limitations and the code they affect. Such description must
          +be placed in a text file included with all distributions of the Covered
          +Software under this License. Except to the extent prohibited by statute
          +or regulation, such description must be sufficiently detailed for a
          +recipient of ordinary skill to be able to understand it.
          +
          +5. Termination
          +--------------
          +
          +5.1. The rights granted under this License will terminate automatically
          +if You fail to comply with any of its terms. However, if You become
          +compliant, then the rights granted under this License from a particular
          +Contributor are reinstated (a) provisionally, unless and until such
          +Contributor explicitly and finally terminates Your grants, and (b) on an
          +ongoing basis, if such Contributor fails to notify You of the
          +non-compliance by some reasonable means prior to 60 days after You have
          +come back into compliance. Moreover, Your grants from a particular
          +Contributor are reinstated on an ongoing basis if such Contributor
          +notifies You of the non-compliance by some reasonable means, this is the
          +first time You have received notice of non-compliance with this License
          +from such Contributor, and You become compliant prior to 30 days after
          +Your receipt of the notice.
          +
          +5.2. If You initiate litigation against any entity by asserting a patent
          +infringement claim (excluding declaratory judgment actions,
          +counter-claims, and cross-claims) alleging that a Contributor Version
          +directly or indirectly infringes any patent, then the rights granted to
          +You by any and all Contributors for the Covered Software under Section
          +2.1 of this License shall terminate.
          +
          +5.3. In the event of termination under Sections 5.1 or 5.2 above, all
          +end user license agreements (excluding distributors and resellers) which
          +have been validly granted by You or Your distributors under this License
          +prior to termination shall survive termination.
          +
          +************************************************************************
          +*                                                                      *
          +*  6. Disclaimer of Warranty                                           *
          +*  -------------------------                                           *
          +*                                                                      *
          +*  Covered Software is provided under this License on an "as is"       *
          +*  basis, without warranty of any kind, either expressed, implied, or  *
          +*  statutory, including, without limitation, warranties that the       *
          +*  Covered Software is free of defects, merchantable, fit for a        *
          +*  particular purpose or non-infringing. The entire risk as to the     *
          +*  quality and performance of the Covered Software is with You.        *
          +*  Should any Covered Software prove defective in any respect, You     *
          +*  (not any Contributor) assume the cost of any necessary servicing,   *
          +*  repair, or correction. This disclaimer of warranty constitutes an   *
          +*  essential part of this License. No use of any Covered Software is   *
          +*  authorized under this License except under this disclaimer.         *
          +*                                                                      *
          +************************************************************************
          +
          +************************************************************************
          +*                                                                      *
          +*  7. Limitation of Liability                                          *
          +*  --------------------------                                          *
          +*                                                                      *
          +*  Under no circumstances and under no legal theory, whether tort      *
          +*  (including negligence), contract, or otherwise, shall any           *
          +*  Contributor, or anyone who distributes Covered Software as          *
          +*  permitted above, be liable to You for any direct, indirect,         *
          +*  special, incidental, or consequential damages of any character      *
          +*  including, without limitation, damages for lost profits, loss of    *
          +*  goodwill, work stoppage, computer failure or malfunction, or any    *
          +*  and all other commercial damages or losses, even if such party      *
          +*  shall have been informed of the possibility of such damages. This   *
          +*  limitation of liability shall not apply to liability for death or   *
          +*  personal injury resulting from such party's negligence to the       *
          +*  extent applicable law prohibits such limitation. Some               *
          +*  jurisdictions do not allow the exclusion or limitation of           *
          +*  incidental or consequential damages, so this exclusion and          *
          +*  limitation may not apply to You.                                    *
          +*                                                                      *
          +************************************************************************
          +
          +8. Litigation
          +-------------
          +
          +Any litigation relating to this License may be brought only in the
          +courts of a jurisdiction where the defendant maintains its principal
          +place of business and such litigation shall be governed by laws of that
          +jurisdiction, without reference to its conflict-of-law provisions.
          +Nothing in this Section shall prevent a party's ability to bring
          +cross-claims or counter-claims.
          +
          +9. Miscellaneous
          +----------------
          +
          +This License represents the complete agreement concerning the subject
          +matter hereof. If any provision of this License is held to be
          +unenforceable, such provision shall be reformed only to the extent
          +necessary to make it enforceable. Any law or regulation which provides
          +that the language of a contract shall be construed against the drafter
          +shall not be used to construe this License against a Contributor.
          +
          +10. Versions of the License
          +---------------------------
          +
          +10.1. New Versions
          +
          +Mozilla Foundation is the license steward. Except as provided in Section
          +10.3, no one other than the license steward has the right to modify or
          +publish new versions of this License. Each version will be given a
          +distinguishing version number.
          +
          +10.2. Effect of New Versions
          +
          +You may distribute the Covered Software under the terms of the version
          +of the License under which You originally received the Covered Software,
          +or under the terms of any subsequent version published by the license
          +steward.
          +
          +10.3. Modified Versions
          +
          +If you create software not governed by this License, and you want to
          +create a new license for such software, you may create and use a
          +modified version of this License if you rename the license and remove
          +any references to the name of the license steward (except to note that
          +such modified license differs from this License).
          +
          +10.4. Distributing Source Code Form that is Incompatible With Secondary
          +Licenses
          +
          +If You choose to distribute Source Code Form that is Incompatible With
          +Secondary Licenses under the terms of this version of the License, the
          +notice described in Exhibit B of this License must be attached.
          +
          +Exhibit A - Source Code Form License Notice
          +-------------------------------------------
          +
          +  This Source Code Form is subject to the terms of the Mozilla Public
          +  License, v. 2.0. If a copy of the MPL was not distributed with this
          +  file, You can obtain one at http://mozilla.org/MPL/2.0/.
          +
          +If it is not possible or desirable to put the notice in a particular
          +file, then You may include the notice in a location (such as a LICENSE
          +file in a relevant directory) where a recipient would be likely to look
          +for such a notice.
          +
          +You may add additional accurate notices of copyright ownership.
          +
          +Exhibit B - "Incompatible With Secondary Licenses" Notice
          +---------------------------------------------------------
          +
          +  This Source Code Form is "Incompatible With Secondary Licenses", as
          +  defined by the Mozilla Public License, v. 2.0.
           
        • @@ -14540,7 +20335,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice

          Unicode License v3

          Used by:

          UNICODE LICENSE V3
           
          @@ -14587,24 +20382,28 @@ authorization of the copyright holder.
                           

          Unicode License v3

          Used by:

          UNICODE LICENSE V3
           
          @@ -14653,12 +20452,63 @@ SPDX-License-Identifier: Unicode-3.0
           Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
           ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
           
          +
        • +
        • +

          zlib License

          +

          Used by:

          + +
          Copyright (c) 2021 Matias Rodriguez.
          +
          +This software is provided 'as-is', without any express or implied
          +warranty. In no event will the authors be held liable for any damages
          +arising from the use of this software.
          +
          +Permission is granted to anyone to use this software for any purpose,
          +including commercial applications, and to alter it and redistribute it
          +freely, subject to the following restrictions:
          +
          +1. The origin of this software must not be misrepresented; you must not
          +   claim that you wrote the original software. If you use this software
          +   in a product, an acknowledgment in the product documentation would be
          +   appreciated but is not required.
          +2. Altered source versions must be plainly marked as such, and must not be
          +   misrepresented as being the original software.
          +3. This notice may not be removed or altered from any source distribution.
          +
        • +
        • +

          zlib License

          +

          Used by:

          + +
          Copyright (c) 2023 Matias Rodriguez.
          +
          +This software is provided 'as-is', without any express or implied
          +warranty. In no event will the authors be held liable for any damages
          +arising from the use of this software.
          +
          +Permission is granted to anyone to use this software for any purpose,
          +including commercial applications, and to alter it and redistribute it
          +freely, subject to the following restrictions:
          +
          +1. The origin of this software must not be misrepresented; you must not
          +   claim that you wrote the original software. If you use this software
          +   in a product, an acknowledgment in the product documentation would be
          +   appreciated but is not required.
          +2. Altered source versions must be plainly marked as such, and must not be
          +   misrepresented as being the original software.
          +3. This notice may not be removed or altered from any source distribution.
        • zlib License

          Used by:

          Copyright (c) 2024 Orson Peters
           
          diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi
          index 98936e0a2..54b9f8083 100644
          --- a/python/python/lancedb/_lancedb.pyi
          +++ b/python/python/lancedb/_lancedb.pyi
          @@ -26,6 +26,7 @@ from .index import (
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               HnswPq,
               HnswSq,
               HnswFlat,
          @@ -604,6 +605,7 @@ class Table:
                       Fm,
                       NGram,
                       ZoneMap,
          +            RTree,
                       FTS,
                   ],
                   replace: Optional[bool],
          @@ -629,6 +631,7 @@ class Table:
                       Fm,
                       NGram,
                       ZoneMap,
          +            RTree,
                       FTS,
                   ],
                   replace: Optional[bool],
          diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py
          index f1626c540..321a1b151 100644
          --- a/python/python/lancedb/index.py
          +++ b/python/python/lancedb/index.py
          @@ -147,6 +147,45 @@ class ZoneMap:
               pass
           
           
          +@dataclass
          +class RTree:
          +    """Describe an RTree index configuration.
          +
          +    `RTree` is a scalar index on a GeoArrow geometry column, that is, a column
          +    whose Arrow field metadata sets ``ARROW:extension:name`` to a GeoArrow type
          +    such as ``geoarrow.point``, ``geoarrow.polygon`` or ``geoarrow.wkb``. It
          +    stores the bounding box of each geometry and accelerates spatial filters
          +    passed to ``where()``.
          +
          +    The index accelerates ``ST_Intersects``, ``ST_Contains``, ``ST_Within``,
          +    ``ST_Touches``, ``ST_Crosses``, ``ST_Overlaps``, ``ST_Covers`` and
          +    ``ST_CoveredBy`` between the indexed column and a constant geometry, in
          +    either argument order, for example
          +    ``ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))``, as well as
          +    ``geom IS NULL``. These filters can be combined with other conditions
          +    using ``AND``.
          +
          +    See the R-tree section of 
          +    for storing geometry, the other spatial functions, and spatial filters on
          +    vector search.
          +
          +    Remote tables send the ``RTREE`` index type to the server, which must
          +    support it.
          +
          +    Examples
          +    --------
          +    >>> config = RTree(page_size=1024)
          +
          +    Attributes
          +    ----------
          +    page_size : int, optional
          +        The maximum number of entries in each R-tree page. Must be at least 2.
          +        ``None`` uses Lance's default of 4096.
          +    """
          +
          +    page_size: Optional[int] = None
          +
          +
           @dataclass
           class FTS:
               """Describe a FTS index configuration.
          @@ -1001,4 +1040,5 @@ __all__ = [
               "LabelList",
               "Fm",
               "NGram",
          +    "RTree",
           ]
          diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py
          index 214d2255f..dee2a480d 100644
          --- a/python/python/lancedb/query.py
          +++ b/python/python/lancedb/query.py
          @@ -1647,6 +1647,10 @@ class LanceQueryBuilder(ABC):
                   -----
                   Calling this multiple times combines the filters with a logical AND
                   rather than replacing the previous filter.
          +
          +        Spatial predicates such as ``ST_Intersects(geom, ST_GeomFromText(...))``
          +        work on GeoArrow columns and use an [RTree][lancedb.index.RTree] index
          +        when one exists.
                   """
                   self._where = _combine_where(self._where, where)
                   self._postfilter = not prefilter
          @@ -4293,9 +4297,11 @@ class AsyncStandardQuery(AsyncQueryBase):
                   >>> predicate = "x > 10"
                   >>> predicate = "y > 0 AND y < 100"
                   >>> predicate = "x > 5 OR y = 'test'"
          +        >>> predicate = "ST_Intersects(geom, ST_GeomFromText('POINT (1 2)'))"
           
                   Filtering performance can often be improved by creating a scalar index
          -        on the filter column(s).
          +        on the filter column(s). Spatial predicates on GeoArrow columns use an
          +        [RTree][lancedb.index.RTree] index.
           
                   Calling this multiple times combines the filters with a logical AND
                   rather than replacing the previous filter.
          diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py
          index f984b47fb..51a656a52 100644
          --- a/python/python/lancedb/remote/table.py
          +++ b/python/python/lancedb/remote/table.py
          @@ -604,7 +604,7 @@ class RemoteTable(Table):
                   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.
          +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                   replace : bool, default True
                       Whether to replace an existing index on this column.
                   wait_timeout : timedelta, optional
          diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py
          index dfb1d1cde..ff014396c 100644
          --- a/python/python/lancedb/table.py
          +++ b/python/python/lancedb/table.py
          @@ -80,6 +80,7 @@ from .index import (
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               HnswPq,
               HnswSq,
               HnswFlat,
          @@ -344,6 +345,7 @@ IndexConfigType = Union[
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               FTS,
           ]
           
          @@ -1961,7 +1963,7 @@ class Table(ABC):
                   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, NGram, ZoneMap, FTS.
          +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                   replace : bool, default True
                       Whether to replace an existing index on this column.
                   exist_ok : bool, default False
          @@ -4760,7 +4762,7 @@ class LanceTable(Table):
                   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, NGram, ZoneMap, FTS.
          +            BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
                   replace : bool, default True
                       Whether to replace an existing index on this column.
                   exist_ok : bool, default False
          @@ -7347,6 +7349,7 @@ class AsyncTable:
                           Fm,
                           NGram,
                           ZoneMap,
          +                RTree,
                           FTS,
                       ]
                   ] = None,
          @@ -7428,13 +7431,14 @@ class AsyncTable:
                               Fm,
                               NGram,
                               ZoneMap,
          +                    RTree,
                               FTS,
                           ),
                       ):
                           raise TypeError(
                               "config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
          -                    " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, or FTS, but got "
          -                    + str(type(config))
          +                    " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, or FTS,"
          +                    " but got " + str(type(config))
                           )
                   try:
                       await self._inner.create_index(
          @@ -7474,6 +7478,7 @@ class AsyncTable:
                           Fm,
                           NGram,
                           ZoneMap,
          +                RTree,
                           FTS,
                       ]
                   ] = None,
          @@ -9820,6 +9825,7 @@ class IndexStatistics:
                   "LABEL_LIST",
                   "NGRAM",
                   "ZONEMAP",
          +        "RTREE",
               ]
               distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
               num_indices: Optional[int] = None
          diff --git a/python/python/lancedb/types.py b/python/python/lancedb/types.py
          index 3d7168dcf..7684398c2 100644
          --- a/python/python/lancedb/types.py
          +++ b/python/python/lancedb/types.py
          @@ -52,6 +52,7 @@ IndexType = Literal[
               "BITMAP",
               "LABEL_LIST",
               "NGRAM",
          +    "RTREE",
               "IVF_RQ",
           ]
           
          diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py
          index e658d18e1..d222b3f94 100644
          --- a/python/python/tests/test_index.py
          +++ b/python/python/tests/test_index.py
          @@ -3,11 +3,13 @@
           
           from datetime import timedelta
           import random
          +import struct
           from typing import get_args, get_type_hints
           
           import pyarrow as pa
           import pytest
           import pytest_asyncio
          +import lancedb
           from lancedb import AsyncConnection, AsyncTable, connect_async
           from lancedb.index import (
               BTree,
          @@ -23,6 +25,7 @@ from lancedb.index import (
               Fm,
               NGram,
               ZoneMap,
          +    RTree,
               HnswPq,
               HnswSq,
               HnswFlat,
          @@ -250,6 +253,388 @@ async def test_create_fm_index(some_table: AsyncTable):
               assert indices[0].columns == ["data"]
           
           
          +POINT_TYPE = pa.struct([("x", pa.float64()), ("y", pa.float64())])
          +POLYGON_TYPE = pa.list_(pa.field("rings", pa.list_(pa.field("vertices", POINT_TYPE))))
          +
          +
          +def geoarrow_field(name: str, extension: str, data_type: pa.DataType) -> pa.Field:
          +    return pa.field(
          +        name,
          +        data_type,
          +        metadata={
          +            "ARROW:extension:name": extension,
          +            "ARROW:extension:metadata": "{}",
          +        },
          +    )
          +
          +
          +# The triangle's bounding box covers the 25 grid points with x <= 4 and y <= 4,
          +# but only the 15 with x + y <= 4 intersect the triangle itself.
          +TRIANGLE = "ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))')"
          +INTERSECTS_TRIANGLE = f"ST_Intersects(geom, {TRIANGLE})"
          +TRIANGLE_IDS = [10 * y + x for y in range(10) for x in range(10) if x + y <= 4]
          +
          +
          +def grid_points(nrows: int) -> pa.Table:
          +    """A grid of GeoArrow points in which row ``10 * y + x`` sits at ``(x, y)``."""
          +    ids = list(range(nrows))
          +    geom = pa.StructArray.from_arrays(
          +        [
          +            pa.array([float(i % 10) for i in ids]),
          +            pa.array([float(i // 10) for i in ids]),
          +        ],
          +        names=["x", "y"],
          +    )
          +    schema = pa.schema(
          +        [
          +            pa.field("id", pa.int64()),
          +            geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
          +            pa.field("vector", pa.list_(pa.float32(), DIM)),
          +        ]
          +    )
          +    return pa.Table.from_arrays(
          +        [pa.array(ids, pa.int64()), geom, sample_fixed_size_list_array(nrows, DIM)],
          +        schema=schema,
          +    )
          +
          +
          +@pytest_asyncio.fixture
          +async def point_table(db_async):
          +    return await db_async.create_table("point_table", grid_points(100))
          +
          +
          +async def query_ids(query) -> list:
          +    return (await query.to_arrow())["id"].to_pylist()
          +
          +
          +@pytest.mark.asyncio
          +async def test_create_rtree_index(point_table: AsyncTable):
          +    assert sorted(await query_ids(point_table.query().where(INTERSECTS_TRIANGLE))) == (
          +        TRIANGLE_IDS
          +    )
          +
          +    await point_table.create_index("geom", config=RTree())
          +    indices = await point_table.list_indices()
          +    assert len(indices) == 1
          +    assert indices[0].name == "geom_idx"
          +    assert indices[0].index_type == "RTree"
          +    assert indices[0].columns == ["geom"]
          +    stats = await point_table.index_stats("geom_idx")
          +    assert stats.index_type == "RTREE"
          +    assert stats.num_indexed_rows == 100
          +    assert stats.num_unindexed_rows == 0
          +
          +    # The index narrows the scan to the bounding box; the exact predicate then
          +    # drops the candidates that fall outside the triangle.
          +    query = point_table.query().where(INTERSECTS_TRIANGLE)
          +    assert "ScalarIndexQuery" in await query.explain_plan(True)
          +    assert sorted(await query_ids(query)) == TRIANGLE_IDS
          +
          +
          +@pytest.mark.asyncio
          +@pytest.mark.parametrize(
          +    "predicate, expected_ids",
          +    [
          +        (INTERSECTS_TRIANGLE, TRIANGLE_IDS),
          +        (f"ST_Within(geom, {TRIANGLE})", [11, 12, 21]),
          +        (f"ST_CoveredBy(geom, {TRIANGLE})", TRIANGLE_IDS),
          +        (
          +            f"ST_Touches(geom, {TRIANGLE})",
          +            [0, 1, 2, 3, 4, 10, 13, 20, 22, 30, 31, 40],
          +        ),
          +        (f"ST_Intersects(geom, {TRIANGLE}) AND id > 20", [21, 22, 30, 31, 40]),
          +        ("ST_Intersects(geom, ST_Point(3.0, 3.0))", [33]),
          +        ("ST_Contains(geom, ST_Point(3.0, 3.0))", [33]),
          +        ("ST_Covers(geom, ST_Point(3.0, 3.0))", [33]),
          +    ],
          +)
          +async def test_rtree_index_accelerates_spatial_filters(
          +    point_table: AsyncTable, predicate: str, expected_ids: list
          +):
          +    unindexed = sorted(await query_ids(point_table.query().where(predicate)))
          +    assert unindexed == expected_ids
          +
          +    await point_table.create_index("geom", config=RTree())
          +    query = point_table.query().where(predicate)
          +    assert "ScalarIndexQuery" in await query.explain_plan(True)
          +    assert sorted(await query_ids(query)) == expected_ids
          +
          +
          +@pytest.mark.asyncio
          +async def test_rtree_index_prefilters_vector_search(point_table: AsyncTable):
          +    await point_table.create_index("geom", config=RTree())
          +    # Row 99 sits outside the triangle, and its nearest vectors are rows 98, 97, ...
          +    far_corner = list(range(99 * DIM, 100 * DIM))
          +
          +    prefiltered = point_table.query().nearest_to(far_corner).where(INTERSECTS_TRIANGLE)
          +    assert "ScalarIndexQuery" in await prefiltered.explain_plan(True)
          +    assert await query_ids(prefiltered.limit(5)) == [40, 31, 30, 22, 21]
          +
          +    postfiltered = (
          +        point_table.query()
          +        .nearest_to(far_corner)
          +        .where(INTERSECTS_TRIANGLE)
          +        .postfilter()
          +        .limit(5)
          +    )
          +    assert await query_ids(postfiltered) == []
          +
          +
          +def square(corner: float) -> list:
          +    """A 2 x 2 square polygon with its lower left corner at ``(corner, corner)``."""
          +    ring = [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]
          +    return [[{"x": corner + x, "y": corner + y} for x, y in ring]]
          +
          +
          +@pytest_asyncio.fixture
          +async def polygon_table(db_async):
          +    """Ten overlapping squares; row ``i`` covers ``(i, i)`` to ``(i + 2, i + 2)``."""
          +    schema = pa.schema(
          +        [
          +            pa.field("id", pa.int64()),
          +            geoarrow_field("area", "geoarrow.polygon", POLYGON_TYPE),
          +        ]
          +    )
          +    data = pa.Table.from_arrays(
          +        [
          +            pa.array(range(10), pa.int64()),
          +            pa.array([square(float(i)) for i in range(10)], POLYGON_TYPE),
          +        ],
          +        schema=schema,
          +    )
          +    return await db_async.create_table("polygons", data)
          +
          +
          +@pytest.mark.asyncio
          +@pytest.mark.parametrize(
          +    "predicate, expected_ids",
          +    [
          +        ("ST_Intersects(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
          +        ("ST_Contains(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
          +        ("ST_Covers(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
          +        ("ST_Crosses(area, ST_GeomFromText('LINESTRING (2.5 2.5, 2.5 10)'))", [1, 2]),
          +        (
          +            "ST_Overlaps(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
          +            [2, 4],
          +        ),
          +        (
          +            "ST_Touches(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
          +            [1, 5],
          +        ),
          +    ],
          +)
          +async def test_create_rtree_index_on_polygons(
          +    polygon_table: AsyncTable, predicate: str, expected_ids: list
          +):
          +    assert sorted(await query_ids(polygon_table.query().where(predicate))) == (
          +        expected_ids
          +    )
          +
          +    await polygon_table.create_index("area", config=RTree(page_size=2))
          +    assert (await polygon_table.list_indices())[0].index_type == "RTree"
          +
          +    query = polygon_table.query().where(predicate)
          +    assert "ScalarIndexQuery" in await query.explain_plan(True)
          +    assert sorted(await query_ids(query)) == expected_ids
          +
          +
          +@pytest.mark.asyncio
          +async def test_rtree_index_with_null_geometries(db_async):
          +    # Every third row has no geometry; the others sit on the diagonal at (i, i).
          +    geom = pa.array(
          +        [None if i % 3 == 0 else {"x": float(i), "y": float(i)} for i in range(10)],
          +        POINT_TYPE,
          +    )
          +    schema = pa.schema(
          +        [
          +            pa.field("id", pa.int64()),
          +            geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
          +        ]
          +    )
          +    table = await db_async.create_table(
          +        "nulls",
          +        pa.Table.from_arrays([pa.array(range(10), pa.int64()), geom], schema=schema),
          +    )
          +    box = "ST_GeomFromText('POLYGON ((-1 -1, 1.5 -1, 1.5 1.5, -1 1.5, -1 -1))')"
          +    expected = {
          +        "geom IS NULL": [0, 3, 6, 9],
          +        "geom IS NOT NULL": [1, 2, 4, 5, 7, 8],
          +        # Row 0 is inside the box but has no geometry, so it matches neither.
          +        f"ST_Intersects(geom, {box})": [1],
          +        f"NOT ST_Intersects(geom, {box})": [2, 4, 5, 7, 8],
          +    }
          +    for predicate, ids in expected.items():
          +        assert sorted(await query_ids(table.query().where(predicate))) == ids
          +
          +    await table.create_index("geom", config=RTree())
          +    for predicate, ids in expected.items():
          +        assert sorted(await query_ids(table.query().where(predicate))) == ids
          +    for predicate in ["geom IS NULL", f"ST_Intersects(geom, {box})"]:
          +        assert "ScalarIndexQuery" in await table.query().where(predicate).explain_plan(
          +            True
          +        )
          +
          +
          +@pytest.mark.asyncio
          +async def test_create_rtree_index_on_wkb(db_async):
          +    """GeoParquet and GeoPandas data usually arrives as well-known binary."""
          +
          +    def wkb_point(x: float, y: float) -> bytes:
          +        # Byte order (1 = little endian), geometry type (1 = point), x, y.
          +        return struct.pack(">) -> PyResult Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
                       "NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
                       "ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())),
          +            "RTree" => {
          +                let params = source.extract::()?;
          +                let mut builder = RTreeIndexBuilder::default();
          +                if let Some(page_size) = params.page_size {
          +                    builder = builder
          +                        .page_size(page_size)
          +                        .map_err(|err| PyValueError::new_err(err.to_string()))?;
          +                }
          +                Ok(LanceDbIndex::RTree(builder))
          +            }
                       "FTS" => {
                           let params = source.extract::()?;
                           let code_options = CodeAnalyzerOptions {
          @@ -293,7 +303,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult Err(PyValueError::new_err(format!(
          -                "Invalid index type '{}'.  Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
          +                "Invalid index type '{}'.  Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
                           not_supported
                       ))),
                   }
          @@ -327,6 +337,11 @@ struct FtsParams {
               index_operators: Option,
           }
           
          +#[derive(FromPyObject)]
          +struct RTreeParams {
          +    page_size: Option,
          +}
          +
           #[derive(FromPyObject)]
           struct IvfFlatParams {
               distance_type: String,
          
          From ae665a4655198606f86820f02321e8aa508e3ce2 Mon Sep 17 00:00:00 2001
          From: Xuanwo 
          Date: Thu, 19 Nov 2026 14:12:40 +0800
          Subject: [PATCH 169/203] docs: mark Blob v2 GA for ordinary tables in
           Enterprise 1.15.0 (#5094)
          
          The Quickstart and table guide describe Blob columns as Early access
          without naming a product version. Document general availability for
          ordinary tables starting with LanceDB Enterprise 1.15.0 and make the
          Realtime Engine and MemWAL scope visible in the table guide.
          
          Xuanwo confirmed Enterprise 1.15.0 as the first edition to document GA
          for ordinary-table Blob v2. Enterprise 1.13.0 and 1.14.0 retain their
          existing status. The Enterprise 1.15.0 edition must carry this wording
          when prepared from its release inputs. Earlier saved editions keep their
          historical guidance.
          
          Refs ENT-3556.
          ---
           docs/web/management/table.mdx | 10 +++-------
           docs/web/quickstart.mdx       |  4 ++--
           2 files changed, 5 insertions(+), 9 deletions(-)
          
          diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx
          index dba741c2b..c5dc4f8cd 100644
          --- a/docs/web/management/table.mdx
          +++ b/docs/web/management/table.mdx
          @@ -395,16 +395,12 @@ file, up to 64 KiB by default, and larger values are stored outside it.
           
           ### Blob columns {#multimodal-blob-v2}
           
          -Early access
          -
           Filter rows by their metadata first. Then read the matching blob bytes in
           Python, or copy the matching rows to another table with Enterprise SQL.
           
          -{/* Draft for Blob v2 GA. Confirm release status before removing Early access.
          -
          -Blob v2 GA supports standard tables. Tables with Realtime or MemWAL enabled
          -are outside the GA support scope.
          -*/}
          +Starting with LanceDB Enterprise 1.15.0, Blob v2 is generally available on
          +ordinary tables. Tables with Realtime Engine or MemWAL enabled are outside
          +this support scope.
           
           #### From image files to a filtered table {#photo-tutorial}
           
          diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx
          index dda4d9acc..12a57c06f 100644
          --- a/docs/web/quickstart.mdx
          +++ b/docs/web/quickstart.mdx
          @@ -370,8 +370,8 @@ Store images, audio, or other binary data alongside vectors and metadata, in a c
           For image files and larger payloads, follow the
           [Blob photo tutorial](/management/table#photo-tutorial) to create an ordinary
           Blob table, filter its metadata, save and check an image, and copy matching rows.
          -It includes an Embedded path and an Enterprise SQL path. Blob columns are in
          -Early access.
          +The tutorial covers LanceDB Embedded and Enterprise SQL. Blob v2 is generally
          +available on ordinary tables starting with LanceDB Enterprise 1.15.0.
           
           ## 8\. Train on your data {#8-train}
           
          
          From a274ecb16ee2abd4e9c734aa04bf8e631d0e6e79 Mon Sep 17 00:00:00 2001
          From: Will Jones 
          Date: Thu, 19 Nov 2026 08:50:49 -0800
          Subject: [PATCH 170/203] fix: bump yanked libsais-rs to 0.2.4 (#5093)
          MIME-Version: 1.0
          Content-Type: text/plain; charset=UTF-8
          Content-Transfer-Encoding: 8bit
          
          ## Summary
          
          The `deny` job on main fails because `libsais-rs` 0.2.0, pulled in by
          `lance-index`, was yanked from crates.io. This bumps it to 0.2.4 in
          `Cargo.lock` and `docs/web-tests/rs/Cargo.lock`. Lockfile-only change.
          
          ## Evidence
          
          Before (CI on main):
          
          ```text
          error[yanked]: detected yanked crate (try `cargo update -p libsais-rs`)
          advisories FAILED, bans ok, licenses ok, sources ok
          ```
          
          After (local, same args as CI):
          
          ```text
          $ cargo deny --all-features check advisories bans licenses sources
          advisories ok, bans ok, licenses ok, sources ok
          ```
          
          ## Merge Risk
          
          **Door:** two-way; lockfile patch bump.
          **Blast Radius:** `lance-index` code that builds suffix arrays.
          
          🤖 Generated with [Claude Code](https://claude.com/claude-code)
          
          Co-authored-by: Claude Opus 5.5 
          ---
           Cargo.lock                   | 4 ++--
           docs/web-tests/rs/Cargo.lock | 4 ++--
           2 files changed, 4 insertions(+), 4 deletions(-)
          
          diff --git a/Cargo.lock b/Cargo.lock
          index 44405cdf0..59cbf509e 100644
          --- a/Cargo.lock
          +++ b/Cargo.lock
          @@ -6338,9 +6338,9 @@ dependencies = [
           
           [[package]]
           name = "libsais-rs"
          -version = "0.2.0"
          +version = "0.2.4"
           source = "registry+https://github.com/rust-lang/crates.io-index"
          -checksum = "40fe164dbd47ea0c20e78a121c980ef673326905f1d4fba55e3645a20ef6717f"
          +checksum = "ec55b7be74ed721889b8bc62d53e6a032d2b3b9bb60a4942b45b1e8362e64583"
           dependencies = [
            "rayon",
           ]
          diff --git a/docs/web-tests/rs/Cargo.lock b/docs/web-tests/rs/Cargo.lock
          index 85384c8af..54dd5c8af 100644
          --- a/docs/web-tests/rs/Cargo.lock
          +++ b/docs/web-tests/rs/Cargo.lock
          @@ -3679,9 +3679,9 @@ dependencies = [
           
           [[package]]
           name = "libsais-rs"
          -version = "0.2.0"
          +version = "0.2.4"
           source = "registry+https://github.com/rust-lang/crates.io-index"
          -checksum = "40fe164dbd47ea0c20e78a121c980ef673326905f1d4fba55e3645a20ef6717f"
          +checksum = "ec55b7be74ed721889b8bc62d53e6a032d2b3b9bb60a4942b45b1e8362e64583"
           dependencies = [
            "rayon",
           ]
          
          From e0995c39c2334d3f08e2b5f58c82dfc5dadd45fc Mon Sep 17 00:00:00 2001
          From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
          Date: Thu, 19 Nov 2026 10:25:27 -0800
          Subject: [PATCH 171/203] chore(deps): bump @opentelemetry/sdk-metrics from
           2.12.0 to 2.12.1 in /nodejs (#5051)
          MIME-Version: 1.0
          Content-Type: text/plain; charset=UTF-8
          Content-Transfer-Encoding: 8bit
          
          Bumps the nodejs-deps group in /nodejs with 1 update:
          [@opentelemetry/sdk-metrics](https://github.com/open-telemetry/opentelemetry-js).
          
          Updates `@opentelemetry/sdk-metrics` from 2.12.0 to 2.12.1
          
          Release notes

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

          v2.12.1

          2.12.1

          :bug: Bug Fixes

          • fix(resources): specify full path for ioreg command on Darwin, and kenv command on BSD for host.id @​trentm
          • ci: update the W3C harness for Python 3.14 #7236 @​adityareddy-dev
          Changelog

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

          2.12.1

          :bug: Bug Fixes

          • fix(resources): specify full path for ioreg command on Darwin, and kenv command on BSD for host.id @​trentm
          • ci: update the W3C harness for Python 3.14 #7236 @​adityareddy-dev
          Commits
          • 8795a06 chore: prepare next v2.x release (#7296)
          • 66a9cdd ci: update W3C harness for Python 3.14 (#7236) (#7295)
          • 55398d4 fix(resources): specify full path for ioreg command on Darwin, and kenv comma...
          • f698f0c ci: drop 'latest' dist-tag option from v2.x publish workflow (#7222)
          • See full diff in compare view

          [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@opentelemetry/sdk-metrics&package-manager=npm_and_yarn&previous-version=2.12.0&new-version=2.12.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
          Dependabot commands and options
          You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions
          Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- nodejs/pnpm-lock.yaml | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index e57bb68d3..df01d672a 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -35,7 +35,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.12.0(@opentelemetry/api@1.10.0) + version: 2.12.1(@opentelemetry/api@1.10.0) '@types/axios': specifier: ^0.14.0 version: 0.14.4 @@ -1399,26 +1399,26 @@ packages: resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} engines: {node: '>=8.0.0'} - '@opentelemetry/core@2.12.0': - resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==} + '@opentelemetry/core@2.12.1': + resolution: {integrity: sha512-3hr6Pj0/G0oVgIGb97IVcw9BjZ6eudonKjrmQxw7JquyU/XmVbJelkmyoU0sT/OvHGkv+r1tcrwv8MbSX7aKHw==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/resources@2.12.0': - resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==} + '@opentelemetry/resources@2.12.1': + resolution: {integrity: sha512-IwrNcuLCvnJAnNLkXxx0Uw+rjBkVW6VGQrhd7PanNf0LavOzkTk9sDAjdqegM7p/VdxefNRrii6d+wBRJfz35g==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.12.0': - resolution: {integrity: sha512-mVMaEHwCUJuY3S4Esn+nT0yQA3qCEGh+SOPJsXygU0Gl453WcsDNjtEa8EfdewMwoLyr1tlofB4fXytVpiXuow==} + '@opentelemetry/sdk-metrics@2.12.1': + resolution: {integrity: sha512-HeSblYhpds4QWliBE7ANCfoa2p3QH83uUxX4vO2qtk6BhIcqP7qDYYT36z3LOXftEBpdfbDStZxv+Cw5mqKX5g==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.9.0 <1.10.0' - '@opentelemetry/semantic-conventions@1.43.0': - resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} + '@opentelemetry/semantic-conventions@1.45.0': + resolution: {integrity: sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw==} engines: {node: '>=14'} '@protobufjs/aspromise@1.1.2': @@ -1485,7 +1485,9 @@ packages: '@smithy/core@3.24.1': resolution: {integrity: sha512-3mT7o4qQyUWttYnVK3A0Z/u3Xha3E81tXn32Tz6vjZiUXhBrkEivpw1hBYfh84iFF9CSzkBU9Y1DJ3Q6RQ231g==} engines: {node: '>=18.0.0'} - deprecated: Deprecated due to bug in browser bundling instructions https://github.com/smithy-lang/smithy-typescript/issues/2025 + deprecated: |- + Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with this + version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393. '@smithy/credential-provider-imds@4.3.1': resolution: {integrity: sha512-0S/acwHnqX4WrjXzhdiDRxsG2s9SC0cpPIK9nZ1R6UOHd+j7uL28+4bHu22urbLk2TVw3fkp6na/+fkUt/pLNQ==} @@ -5165,24 +5167,24 @@ snapshots: '@opentelemetry/api@1.10.0': {} - '@opentelemetry/core@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/core@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/semantic-conventions': 1.45.0 - '@opentelemetry/resources@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/resources@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@opentelemetry/api': 1.10.0 - '@opentelemetry/core': 2.12.0(@opentelemetry/api@1.10.0) - '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/core': 2.12.1(@opentelemetry/api@1.10.0) + '@opentelemetry/semantic-conventions': 1.45.0 - '@opentelemetry/sdk-metrics@2.12.0(@opentelemetry/api@1.10.0)': + '@opentelemetry/sdk-metrics@2.12.1(@opentelemetry/api@1.10.0)': dependencies: '@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/core': 2.12.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 2.12.1(@opentelemetry/api@1.10.0) - '@opentelemetry/semantic-conventions@1.43.0': {} + '@opentelemetry/semantic-conventions@1.45.0': {} '@protobufjs/aspromise@1.1.2': optional: true From c136022c7b8645d5ce0d0b5db8a21e8587b6b2c9 Mon Sep 17 00:00:00 2001 From: Shu Chen Date: Thu, 19 Nov 2026 14:18:10 -0500 Subject: [PATCH 172/203] ci: pin third-party GitHub Actions to full commit SHAs (#4922) Pin every remaining third-party action reference in `.github/` to a full 40-character commit SHA, with the intended version in a trailing comment (`uses: owner/action@ # vX.Y.Z`), following the pins already in `cli.yml`, `typos.yml` and `make-release-commit.yml`. Fixes #3293. 53 references across 13 files change, covering 16 actions, including the branch refs called out in the issue (`dtolnay/rust-toolchain@master`, `@stable`) and `pypa/gh-action-pypi-publish@release/v1`. Each SHA is the commit its current tag or branch resolves to today, so the code that runs is unchanged. Comments name the most specific tag on that commit (for example `v2.9.3` for `Swatinem/rust-cache@v2`); where no such tag exists, they keep the original ref (`v1` for `srvaroa/labeler` and `rui314/setup-mold`, `v3` for `addnab/docker-run-action`, `stable`/`master` for `dtolnay/rust-toolchain`). The `stable` branch of `dtolnay/rust-toolchain` defaults its `toolchain` input to `stable`, so pinning its SHA keeps the `nodejs.yml` step that passes no toolchain on stable. GitHub-maintained `actions/*` references are left on their tags, as in the existing pins. Keeping SHAs current through Dependabot is the sibling issue and is not part of this change. Validation: - No third-party `uses:` reference in `.github/` is left without a 40-character SHA (53 before, 0 after). - For all 23 distinct third-party pins in `.github/`, `git ls-remote` against the upstream repository confirms the SHA is the commit that the commented tag or branch points to. A deliberately altered SHA and a reverted tag ref were both caught. - `pre-commit run` on the changed files passes (check-yaml, end-of-file, trailing whitespace, typos). - actionlint 1.7.12 reports the same 35 findings on `main` and on this branch, all of them existing ones (custom runner labels and composite actions under `workflows/`). It reports none for this change. --- .../workflows/build_linux_wheel/action.yml | 4 +-- .github/workflows/build_mac_wheel/action.yml | 2 +- .../workflows/build_windows_wheel/action.yml | 2 +- .github/workflows/cargo-publish.yml | 4 +-- .../codex-update-lance-dependency.yml | 2 +- .github/workflows/dev.yml | 4 +-- .github/workflows/docs.yml | 2 +- .github/workflows/gh-release.yml | 4 +-- .github/workflows/nodejs.yml | 20 ++++++------ .github/workflows/npm-publish.yml | 18 +++++------ .github/workflows/pypi-publish.yml | 4 +-- .github/workflows/python.yml | 8 ++--- .github/workflows/rust.yml | 32 +++++++++---------- 13 files changed, 53 insertions(+), 53 deletions(-) diff --git a/.github/workflows/build_linux_wheel/action.yml b/.github/workflows/build_linux_wheel/action.yml index 44ce82ee5..51cd20ab0 100644 --- a/.github/workflows/build_linux_wheel/action.yml +++ b/.github/workflows/build_linux_wheel/action.yml @@ -54,7 +54,7 @@ runs: grep '^name = ' python/pyproject.toml - name: Build x86_64 Manylinux wheel if: ${{ inputs.arm-build == 'false' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build @@ -72,7 +72,7 @@ runs: /usr/local/bin/protoc --version - name: Build Arm Manylinux Wheel if: ${{ inputs.arm-build == 'true' }} - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: build diff --git a/.github/workflows/build_mac_wheel/action.yml b/.github/workflows/build_mac_wheel/action.yml index 727cd190c..ba7b7b1c5 100644 --- a/.github/workflows/build_mac_wheel/action.yml +++ b/.github/workflows/build_mac_wheel/action.yml @@ -14,7 +14,7 @@ runs: steps: - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/build_windows_wheel/action.yml b/.github/workflows/build_windows_wheel/action.yml index 3d92d818a..0d061ac59 100644 --- a/.github/workflows/build_windows_wheel/action.yml +++ b/.github/workflows/build_windows_wheel/action.yml @@ -17,7 +17,7 @@ runs: run: git config --global core.longpaths true - uses: ./.github/actions/setup-protoc - name: Build wheel - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: command: build maturin-version: "1.12.4" diff --git a/.github/workflows/cargo-publish.yml b/.github/workflows/cargo-publish.yml index 052fb1876..83593307b 100644 --- a/.github/workflows/cargo-publish.yml +++ b/.github/workflows/cargo-publish.yml @@ -25,14 +25,14 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') steps: - uses: actions/checkout@v6 - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: rust - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rust-lang/crates-io-auth-action@v1 + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - name: Publish the package run: | diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index 79ef84364..ef59213bd 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -44,7 +44,7 @@ jobs: run: npm install -g @openai/codex - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: toolchain: stable components: clippy, rustfmt diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index eac4cc4fc..64a6971e6 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -18,7 +18,7 @@ jobs: name: Label PR runs-on: ubuntu-latest steps: - - uses: srvaroa/labeler@v1 + - uses: srvaroa/labeler@9c29ad1ef33d169f9ef33c52722faf47a566bcf3 # v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} commitlint: @@ -30,7 +30,7 @@ jobs: - uses: actions/setup-node@v6 with: node-version: "24" - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 # These rules are disabled because Github will always ensure there diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index fb3fb1d6a..3dc4dab56 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -47,7 +47,7 @@ jobs: python-version: "3.10" cache: "pip" cache-dependency-path: "docs/requirements.txt" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Build Python working-directory: python run: | diff --git a/.github/workflows/gh-release.yml b/.github/workflows/gh-release.yml index bbaade34c..eedf8450c 100644 --- a/.github/workflows/gh-release.yml +++ b/.github/workflows/gh-release.yml @@ -77,7 +77,7 @@ jobs: echo "from_tag=$FROM_TAG" >> $GITHUB_OUTPUT - name: Create Release Notes id: release_notes - uses: mikepenz/release-changelog-builder-action@v4 + uses: mikepenz/release-changelog-builder-action@32e3c96f29a6532607f638797455e9e98cfc703d # v4.2.2 with: configuration: .github/release_notes.json toTag: ${{ steps.extract_version.outputs.tag }} @@ -85,7 +85,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Create GH release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2 with: # Marking betas as pre-releases keeps them from taking the "Latest" # badge on the releases page. diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 4d28ca4a1..9a21786d2 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -42,7 +42,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -52,14 +52,14 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - name: Install dependencies run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -98,7 +98,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -110,7 +110,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -188,7 +188,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -196,7 +196,7 @@ jobs: node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Same crate, profile and target as the `linux` job above, so reuse # its cache: rust-cache keys on the job id by default, and this job @@ -249,7 +249,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - uses: actions/setup-node@v6 @@ -259,11 +259,11 @@ jobs: cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml # Use the same pinned compiler for cache selection and the native build. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: cache: false rustflags: "" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index ac95b5a47..6de291c7d 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -167,7 +167,7 @@ jobs: # Cargo also checks out Lance test fixtures below its git cache path. run: git config --global core.longpaths true - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node @@ -178,7 +178,7 @@ jobs: cache: pnpm cache-dependency-path: nodejs/pnpm-lock.yaml - name: Install - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable if: ${{ !matrix.settings.docker }} with: toolchain: stable @@ -194,7 +194,7 @@ jobs: # re-runs regardless, since the local crate changes every time, so the # win is larger on the non-LTO jobs than here. - name: Cache cargo (native builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ !matrix.settings.docker }} with: # The release profile and per-target dirs differ from what the test @@ -216,7 +216,7 @@ jobs: # that built these artifacts -- safe, since cargo fingerprints the real # one; a base-image bump just costs one cold build. - name: Cache cargo (docker builds) - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 if: ${{ matrix.settings.docker }} with: key: docker-${{ matrix.settings.target }} @@ -225,17 +225,17 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - name: Install Zig - uses: mlugg/setup-zig@v2 + uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 if: ${{ contains(matrix.settings.target, 'musl') }} with: version: 0.14.1 - name: Install cargo-zigbuild - uses: taiki-e/install-action@v2 + uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 if: ${{ contains(matrix.settings.target, 'musl') }} with: tool: cargo-zigbuild - name: Build in docker - uses: addnab/docker-run-action@v3 + uses: addnab/docker-run-action@4f65fabd2431ebc8d299f8e5a018d79a769ae185 # v3 if: ${{ matrix.settings.docker }} with: image: ${{ matrix.settings.docker }} @@ -352,7 +352,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup Node.js 24 for install @@ -404,7 +404,7 @@ jobs: steps: - uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: version: 11.1.1 - name: Setup node diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 8730e220d..304e96857 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -184,7 +184,7 @@ jobs: with: python-version: "3.12" - name: Build sdist - uses: PyO3/maturin-action@v1 + uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0 with: maturin-version: "1.12.4" command: sdist @@ -311,7 +311,7 @@ jobs: # `docker://ghcr.io/:` image reference that GHA tries to pull. - name: Publish to PyPI if: steps.choose_repo.outputs.repo == 'pypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: packages-dir: target/wheels/ report-failure: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index e208ac7cd..62da9cf6e 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -112,7 +112,7 @@ jobs: # `pip install -e .` builds the extension with maturin, which is most of # this job's ~33 minutes. It had no Rust cache, so every dependency was # recompiled from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -198,7 +198,7 @@ jobs: python-version: "3.13" # maturin runs cargo natively on macOS (docker is Linux-only), so the host # target dir is cacheable. This job had no Rust cache. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -236,7 +236,7 @@ jobs: # maturin runs cargo natively on Windows (docker is Linux-only), so the # host target dir is cacheable. This job had no Rust cache at all and so # rebuilt every dependency from scratch on every run. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. The repo sits at # GitHub's cache cap, so per-PR saves just evict main's entries. @@ -271,7 +271,7 @@ jobs: python-version: "3.10" # As with Doctest, `pip install -e .` compiles the extension and this job # had no Rust cache, which is most of its ~37 minutes. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 636c1a7bf..b3805b422 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -42,7 +42,7 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@v6 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 - name: Read the pinned Lance tag id: lance run: | @@ -108,10 +108,10 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -135,7 +135,7 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 - - uses: EmbarkStudios/cargo-deny-action@v2 + - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 with: command: check advisories bans licenses sources @@ -151,7 +151,7 @@ jobs: - uses: actions/checkout@v6 # Building without a lock file often requires the latest Rust version since downstream # dependencies may have updated their minimum Rust version. - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 with: toolchain: "stable" # The explicit cache below runs after lock removal and only saves on main. @@ -159,8 +159,8 @@ jobs: # Remove cargo.lock to force a fresh build - name: Remove Cargo.lock run: rm -f Cargo.lock - - uses: rui314/setup-mold@v1 - - uses: Swatinem/rust-cache@v2 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -208,7 +208,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -218,7 +218,7 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Make Swap run: | swapfile=/swapfile @@ -280,7 +280,7 @@ jobs: with: fetch-depth: 0 lfs: true - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Remote tests use a different feature graph from the main Linux # job. Cache downloads, but build into a fresh target directory. @@ -290,7 +290,7 @@ jobs: run: | sudo apt update sudo apt install -y protobuf-compiler libssl-dev - - uses: rui314/setup-mold@v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 - name: Run remote tests run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests @@ -317,7 +317,7 @@ jobs: python-version: "3.13" - name: CPU features run: sysctl -a | grep cpu - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # PyO3 caches the interpreter library path; runner images can differ. key: ${{ matrix.mac-runner }}-python-${{ steps.python.outputs.python-version }} @@ -358,7 +358,7 @@ jobs: run: git config --global core.longpaths true - name: Set target run: rustup target add ${{ matrix.target }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -397,7 +397,7 @@ jobs: run: git config --global core.longpaths true - name: Set target run: rustup target add aarch64-pc-windows-msvc - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes @@ -437,10 +437,10 @@ jobs: sudo apt update sudo apt install -y protobuf-compiler libssl-dev - name: Install ${{ matrix.msrv }} - uses: dtolnay/rust-toolchain@master + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master with: toolchain: ${{ matrix.msrv }} - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: # Restore everywhere, but only save from main. Per-PR saves are # unreadable outside their own branch anyway, since GitHub scopes From 7d33f7ba9442715e0b00cec8f70a1374b0647149 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 11:25:27 -0800 Subject: [PATCH 173/203] ci: prioritize Rust security updates in dependabot config (#5100) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Dependabot wasn't getting security fixes in, and its Rust PRs were failing CI: - Security updates were disabled for the repo, so ~170 open alerts never got a PR. (Now enabled in repo settings; not part of this diff.) - The `pip` entry for `/python` never touched `uv.lock`, so Python had no Dependabot PRs at all. - With `versioning-strategy: lockfile-only`, breaking bumps such as reqwest 0.12 → 0.13 (#4781), tokenizers 0.19 → 0.23 (#4905), sha2 (#4230) and base64 (#4229) write a `Cargo.lock` that the `Cargo.toml` requirements don't allow. Every `--locked` build then fails before compiling. The priority is Rust, which is statically linked into the shipped binaries. Python and npm deps are resolved in users' environments, so those are best effort. | Entry | Version updates | Security updates | |---|---|---| | cargo `/` | weekly, minor/patch, one group | grouped | | uv `/python` (was `pip`) | monthly, minor/patch, one group | grouped | | npm `/nodejs`, `/nodejs/examples` | monthly, minor/patch, one group | grouped | | docs, docs tests, `/java` | off | grouped | Breaking bumps are excluded with `allow.update-types`, which the docs say applies only to version updates. An `ignore` rule would also suppress security updates. `dependency-type: all` keeps transitive dependencies in scope for security fixes, which also means the weekly cargo PR now bumps transitive crates within their allowed ranges. A security fix that's only available as a breaking bump will still produce a failing PR and need a manual `Cargo.toml` change. ## Merge Risk **Door:** two-way; config only. **Blast Radius:** Dependabot PRs. Config errors only surface after merge, on Dependabot's next run. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .github/dependabot.yml | 165 ++++++++++++++++++++++++++++++----------- 1 file changed, 120 insertions(+), 45 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d625b0698..4f5ff4bd4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,70 +1,145 @@ version: 2 -# Scope: the root Cargo workspace, which produces the Rust binaries we -# ship to users (the Node.js and Python native extensions). The -# `rust/lancedb` library crate shares the same lockfile; its consumers -# pick their own dependency versions, but bumping transitive deps here -# keeps the binaries we ship current. +# Every entry uses `versioning-strategy: lockfile-only`: bump the lockfile, +# never widen or raise the version requirements in manifests. Those ranges are +# our library consumers' constraints, not ours. +# +# Because of that, version updates are limited to minor and patch bumps. +# A semver-breaking bump (including 0.x minor bumps such as 0.12 -> 0.13) +# can't be satisfied without editing a manifest, so Dependabot would produce a +# lockfile that fails `cargo --locked` and every CI job. We do those by hand. +# This is done with `allow` rather than `ignore` because `allow.update-types` +# only filters version updates; an `ignore` rule would also suppress security +# updates. `dependency-type: all` matters for the same reason: `allow` does +# apply to security updates otherwise, and most advisories are in transitive +# dependencies. +# +# Security updates are grouped so advisories that land together become one PR. +# They ignore `schedule` and `cooldown` and are opened as soon as an advisory +# is published. updates: + # Highest priority: the root Cargo workspace is statically linked into the + # Node.js and Python native extensions we ship, so users can't patch these + # themselves. Weekly updates keep the lockfile close to current, so security + # fixes are usually small patch bumps. - package-ecosystem: cargo directory: / schedule: interval: weekly - open-pull-requests-limit: 10 - # Only update Cargo.lock, never widen/raise the version requirements in - # Cargo.toml. The goal is keeping the lockfile (and the binaries we ship) - # current on security fixes, not forcing our library's consumers onto - # newer minimum versions. + day: wednesday + cooldown: + default-days: 2 versioning-strategy: lockfile-only - groups: - # The arrow-rs and datafusion crates are released in lockstep and have to - # move together, so keep them in one PR instead of one per sub-crate. - # Listed first: a dependency joins the first group it matches. - arrow-datafusion: - patterns: - - arrow - - arrow-* - - parquet - - parquet-* - - datafusion - - datafusion-* - - object_store - rust-minor-patch: + allow: + - dependency-type: all update-types: - - minor - - patch + - version-update:semver-minor + - version-update:semver-patch + groups: + cargo: + applies-to: version-updates + patterns: + - "*" + cargo-security: + applies-to: security-updates + patterns: + - "*" - - package-ecosystem: pip + # Python and Node.js dependencies are resolved in the user's own environment, + # so these lockfiles only affect our dev/test setup. Lower priority: monthly. + - package-ecosystem: uv directory: /python schedule: - interval: weekly - # Only update uv.lock, never widen version requirements in pyproject.toml. + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - python-deps: + python: + applies-to: version-updates patterns: - "*" - - # The npm ecosystem covers pnpm lockfiles. There are two separate installs: - # the bindings themselves and the examples, which have their own lockfile. - # As with cargo and pip above, only bump the lockfile — the version ranges - # in package.json are our consumers' constraints, not ours. - - package-ecosystem: npm - directory: /nodejs - schedule: - interval: weekly - versioning-strategy: lockfile-only - groups: - nodejs-deps: + python-security: + applies-to: security-updates patterns: - "*" - package-ecosystem: npm - directory: /nodejs/examples + directories: + - /nodejs + - /nodejs/examples schedule: - interval: weekly + interval: monthly + cooldown: + default-days: 2 versioning-strategy: lockfile-only + allow: + - dependency-type: all + update-types: + - version-update:semver-minor + - version-update:semver-patch groups: - nodejs-examples-deps: + nodejs: + applies-to: version-updates + patterns: + - "*" + nodejs-security: + applies-to: security-updates + patterns: + - "*" + + # Docs, docs tests, and Java. Security updates scan these lockfiles whether or + # not they're listed here; these entries only exist to group those PRs. + # `open-pull-requests-limit: 0` turns off version updates. + - package-ecosystem: cargo + directory: /docs/web-tests/rs + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-cargo-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: npm + directories: + - /docs/web-tests/ts + - /docs/web-tests/blob-v2/ts + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-npm-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: pip + directories: + - /docs + - /docs/web-tests/blob-v2/py + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + docs-pip-security: + applies-to: security-updates + patterns: + - "*" + + - package-ecosystem: maven + directory: /java + schedule: + interval: monthly + open-pull-requests-limit: 0 + groups: + maven-security: + applies-to: security-updates patterns: - "*" From 3e712f5105a77a210ba4ff0c172fa6c84fe7fc13 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 11:25:46 -0800 Subject: [PATCH 174/203] fix: bump blob v2 docs test to lancedb 0.42.0-beta.20 (#5102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary The blob v2 TypeScript docs test pinned `@lancedb/lancedb` `0.41.0-beta.8`, which pulls `@huggingface/transformers` 3.0.2 and `sharp` 0.33.5. Aikido flags that `sharp` with 2 critical and 1 high advisory. Bumping to `0.42.0-beta.20` brings transformers 4.3.2 and `sharp` 0.35.5, matching what the `nodejs` package already ships. The stable `0.41.0` still uses transformers 3.0.2, so it doesn't fix this. ## Evidence `npm install --package-lock-only` reports `found 0 vulnerabilities`, and `npm test` passes 4/4 locally against `0.42.0-beta.20`. ## Merge Risk **Door:** two-way; only a docs test lockfile changes. **Blast Radius:** none (docs test only, not run in PR CI). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- docs/web-tests/blob-v2/ts/package-lock.json | 872 +++++++++++--------- docs/web-tests/blob-v2/ts/package.json | 2 +- 2 files changed, 468 insertions(+), 406 deletions(-) diff --git a/docs/web-tests/blob-v2/ts/package-lock.json b/docs/web-tests/blob-v2/ts/package-lock.json index 9426f2b18..914855656 100644 --- a/docs/web-tests/blob-v2/ts/package-lock.json +++ b/docs/web-tests/blob-v2/ts/package-lock.json @@ -8,95 +8,126 @@ "name": "lancedb-blob-v2-docs", "version": "0.0.0", "dependencies": { - "@lancedb/lancedb": "0.41.0-beta.8", + "@lancedb/lancedb": "0.42.0-beta.20", "apache-arrow": "21.2.0" + }, + "engines": { + "node": ">=22.6.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", + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.13.tgz", + "integrity": "sha512-jM17MqFily1iyT/1LD3r5w8/CZiyapVB0+7vOw48PfVtzyKsXStmHE4jVTyDAD05Tqv3un1xrS9ILUU1ugQAYQ==", "optional": true, "engines": { "node": ">=18" } }, + "node_modules/@huggingface/tokenizers": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.2.0.tgz", + "integrity": "sha512-LidMHe1FpcSYH4vcSjXooda34pC0M8m1gmDOv7SQi6Iv+ib1zX7J3sHBCC9/3FPCkn2k1b55FneVqMRxrr99pg==", + "optional": true + }, "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", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-4.3.2.tgz", + "integrity": "sha512-V3+dqf3iWlRYJ9I9GreM3zGQd0lAXnnoPeddmkOQYWAEE4l/+Fi6p7tx/qVUJlKQgLXGim2W76rTOzz+eC0i7g==", "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" + "@huggingface/jinja": "^0.5.10", + "@huggingface/tokenizers": "^0.2.0", + "onnxruntime-node": "1.30.0", + "onnxruntime-web": "1.31.0-dev.20260914-8d85527a0", + "sharp": "^0.35.4" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "optional": true, + "engines": { + "node": ">=18" } }, "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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.0.4" + "@img/sharp-libvips-darwin-arm64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", "cpu": [ "x64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.0.4" + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", "cpu": [ "arm64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" @@ -106,13 +137,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ "x64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "darwin" @@ -122,16 +152,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -141,16 +167,42 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], - "libc": [ - "glibc" + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -160,16 +212,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -179,16 +227,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -198,16 +242,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -217,16 +257,12 @@ } }, "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==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", "optional": true, "os": [ "linux" @@ -236,234 +272,268 @@ } }, "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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", "cpu": [ "arm" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.0.5" + "@img/sharp-libvips-linux-arm": "1.3.4" } }, "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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.0.4" + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.0.4" + "@img/sharp-libvips-linux-s390x": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.0.4" + "@img/sharp-libvips-linux-x64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + "@img/sharp-libvips-linuxmusl-arm64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" ], "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" }, "funding": { "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + "@img/sharp-libvips-linuxmusl-x64": "1.3.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", "cpu": [ "wasm32" ], - "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "@emnapi/runtime": "^1.2.0" + "@img/sharp-wasm32": "0.35.5" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "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" + "node": "^20.9.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==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", "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" + "node": ">=20.9.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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb/-/lancedb-0.42.0-beta.20.tgz", + "integrity": "sha512-sPccnvQbxgybSu3nypRKXtbWE1pa90imQuOnxNQ1w68pz6KFISereKYp9o0HtukMqJWYfrezetYJPG+uC3KprA==", "cpu": [ "x64", "arm64" ], - "license": "Apache-2.0", "os": [ "darwin", "linux", @@ -477,14 +547,14 @@ "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", + "@huggingface/transformers": "4.3.2", + "@lancedb/lancedb-darwin-arm64": "0.42.0-beta.20", + "@lancedb/lancedb-linux-arm64-gnu": "0.42.0-beta.20", + "@lancedb/lancedb-linux-arm64-musl": "0.42.0-beta.20", + "@lancedb/lancedb-linux-x64-gnu": "0.42.0-beta.20", + "@lancedb/lancedb-linux-x64-musl": "0.42.0-beta.20", + "@lancedb/lancedb-win32-arm64-msvc": "0.42.0-beta.20", + "@lancedb/lancedb-win32-x64-msvc": "0.42.0-beta.20", "openai": "4.29.2" }, "peerDependencies": { @@ -498,13 +568,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-darwin-arm64/-/lancedb-darwin-arm64-0.42.0-beta.20.tgz", + "integrity": "sha512-UbIQknmvPdkHAn/2fXE41YDXXyZKoBjeW3TTpWMY9CdcBr6zOEvoL6hIcfIZ7ToN5B8kLePo6Vigc6SOY+Bt4w==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "darwin" @@ -514,16 +583,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-gnu/-/lancedb-linux-arm64-gnu-0.42.0-beta.20.tgz", + "integrity": "sha512-Pkn9fjIsYu5h4grzbCp+X7HT/byHd4N0/BFpvN4oRW703kjkwp9QzwSyRRvXEtgywv47diJu2W0cl8+8su5XtQ==", "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -533,16 +598,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-arm64-musl/-/lancedb-linux-arm64-musl-0.42.0-beta.20.tgz", + "integrity": "sha512-A2fKIET4p1r1geWFX5omLCtjg03c8V42QQJPtCUjuX9sG9EXcNM6tHQSSJj3En/7T4N5gSlSzS3dcy4ciYEVYQ==", "cpu": [ "arm64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -552,16 +613,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-gnu/-/lancedb-linux-x64-gnu-0.42.0-beta.20.tgz", + "integrity": "sha512-s7/l3mlktGM1tsfVT0Ioso+B+adG/Ke4sAOEPdbGtIoGRauswov6lzCBmgMnNhV13Q2lniMmnAJR6rGC4Vtg/A==", "cpu": [ "x64" ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -571,16 +628,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-linux-x64-musl/-/lancedb-linux-x64-musl-0.42.0-beta.20.tgz", + "integrity": "sha512-2YgGQjV5AqacKXC1IDJwR/WYOPJk34PuUvo1iy4d+hOdaIy+r7vQLYUy1nFx4uYx7kLCfV/cuuq6V7OkzGkx7Q==", "cpu": [ "x64" ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", "optional": true, "os": [ "linux" @@ -590,13 +643,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-arm64-msvc/-/lancedb-win32-arm64-msvc-0.42.0-beta.20.tgz", + "integrity": "sha512-VGRLcDBGtYZEw/GJAOfDJX3ad36+sWP+lQrKmnNzzHAOs4MATLcbVk50zbqRbs6ukGBc784yM0ycnKy31TbN1w==", "cpu": [ "arm64" ], - "license": "Apache-2.0", "optional": true, "os": [ "win32" @@ -606,13 +658,12 @@ } }, "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==", + "version": "0.42.0-beta.20", + "resolved": "https://registry.npmjs.org/@lancedb/lancedb-win32-x64-msvc/-/lancedb-win32-x64-msvc-0.42.0-beta.20.tgz", + "integrity": "sha512-eXoK1x9Ie2E2X/eYowGo2Daqve8zwLG8pvHexwCTzLLvVFM/o7iTK0WvSRXO9/9O4uhAsAGXBzH4I52ZY3kqqw==", "cpu": [ "x64" ], - "license": "Apache-2.0", "optional": true, "os": [ "win32" @@ -634,35 +685,30 @@ "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" @@ -672,28 +718,24 @@ "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": { @@ -729,6 +771,15 @@ "node": ">=6.5" } }, + "node_modules/adm-zip": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz", + "integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==", + "optional": true, + "engines": { + "node": ">=14.0" + } + }, "node_modules/agentkeepalive": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", @@ -794,61 +845,6 @@ "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", @@ -872,6 +868,40 @@ "node": "*" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "optional": true, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "optional": true, + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -886,7 +916,6 @@ "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" @@ -967,6 +996,18 @@ "node": ">= 0.4" } }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", @@ -1080,6 +1121,37 @@ "node": ">= 0.4" } }, + "node_modules/global-agent": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-4.1.7.tgz", + "integrity": "sha512-pxaZqdsMwPA4i7TuRKpDUONm2xGRjvYdRoidCQz7VleUKVuUfh/4p5Q3QDTGrpAE5Kz5TxxcZ+uqEgTkoKRNtg==", + "optional": true, + "dependencies": { + "globalthis": "^1.0.2", + "matcher": "^4.0.0", + "semver": "^7.3.5", + "serialize-error": "^8.1.0" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "optional": true, + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -1097,9 +1169,20 @@ "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-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "optional": true, + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-symbols": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", @@ -1152,13 +1235,6 @@ "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", @@ -1176,9 +1252,23 @@ "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/matcher": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-4.0.0.tgz", + "integrity": "sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==", + "optional": true, + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -1224,29 +1314,6 @@ "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", @@ -1296,19 +1363,26 @@ } } }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, "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", + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.30.0.tgz", + "integrity": "sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==", "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==", + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.30.0.tgz", + "integrity": "sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==", "hasInstallScript": true, - "license": "MIT", "optional": true, "os": [ "win32", @@ -1316,37 +1390,29 @@ "linux" ], "dependencies": { - "onnxruntime-common": "1.19.2", - "tar": "^7.0.1" + "adm-zip": "^0.6.0", + "global-agent": "^4.1.3", + "onnxruntime-common": "1.30.0" } }, "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", + "version": "1.31.0-dev.20260914-8d85527a0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.31.0-dev.20260914-8d85527a0.tgz", + "integrity": "sha512-Iy7rtadoBgxS/LLvDr3QW38DB1PNXRnr0GJMcL0TAt7c9qjgVQl83UlGCVyeAnK2InpmW8Uc3PL8XIuqtDeF6g==", "optional": true, "dependencies": { - "flatbuffers": "^1.12.0", + "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", - "onnxruntime-common": "1.20.0-dev.20241016-2b8fc5529b", + "onnxruntime-common": "1.31.0-dev.20260911-2a43ec07e", "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", + "version": "1.31.0-dev.20260911-2a43ec07e", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.31.0-dev.20260911-2a43ec07e.tgz", + "integrity": "sha512-gBuF6U32YErKIAt+yD7DeGBpjRxhJ1uJwako6ygjokSZULDU6Pd+KWComX8Tumk1hYVHRxjPj7mdMnD0ryAPOw==", "optional": true }, "node_modules/openai": { @@ -1391,7 +1457,6 @@ "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": { @@ -1399,7 +1464,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", @@ -1425,10 +1489,9 @@ "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", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "optional": true, "bin": { "semver": "bin/semver.js" @@ -1437,71 +1500,68 @@ "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", + "node_modules/serialize-error": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz", + "integrity": "sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==", "optional": true, "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.3", - "semver": "^7.6.3" + "type-fest": "^0.20.2" }, "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "optional": true, + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.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" + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" }, - "engines": { - "node": ">=18" + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, "node_modules/tr46": { @@ -1517,6 +1577,18 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/undici-types": { "version": "7.24.6", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", @@ -1550,16 +1622,6 @@ "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 index f39495edd..17daaeab0 100644 --- a/docs/web-tests/blob-v2/ts/package.json +++ b/docs/web-tests/blob-v2/ts/package.json @@ -10,7 +10,7 @@ "node": ">=22.6.0" }, "dependencies": { - "@lancedb/lancedb": "0.41.0-beta.8", + "@lancedb/lancedb": "0.42.0-beta.20", "apache-arrow": "21.2.0" } } From 4ac2728e73d5b47b69d7052b3c0e023a5d58a7b1 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 19 Nov 2026 14:42:22 -0800 Subject: [PATCH 175/203] ci: scope workflow permissions and drop unverified downloads (#5103) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Fixes four high-severity Aikido findings in CI and the Dockerfile. - **Workflow permissions:** `npm-publish.yml` and `codex-update-lance-dependency.yml` now set `permissions: {}` at the workflow level and grant permissions per job. - `npm-publish`: only `publish` gets `id-token: write` (npm provenance). Nothing in the workflow needed `contents: write`, so every job is now read-only. - `codex-update-lance-dependency`: keeps `contents: write`, because the branch is pushed with the checkout token. It drops `pull-requests: write` and `actions: read`, because all `gh` calls use `ROBOT_TOKEN`. - **license-header-check:** replaces `curl .../master/install.sh | bash` with `go install …@v1.5.0`. Go verifies the module against sum.golang.org, so we don't maintain a hash ourselves. Go is preinstalled on `ubuntu-latest`. - **Dockerfile:** drops the rustup `curl | sh` along with `build-essential`, `protoc`, and `git`, and runs as a non-root `lancedb` user. `lancedb` installs from prebuilt `manylinux_2_28` wheels, and the toolchain was only needed for the tantivy FTS support removed in #3282. Alternatives considered for the Dockerfile, in case we want Rust in the image: - `COPY --from=rust:-slim-bookworm@sha256:…` to copy the toolchain from the official image, pinned by digest. - Download `rustup-init` from `static.rust-lang.org` and check it against the published `.sha256`. Neither seemed worth it for an image that only runs `pip install lancedb`. ## Evidence - In a clean Python 3.12 venv, `pip install --only-binary :all: lancedb` installed 0.41.0, and building an FTS index and querying it worked. Docker wasn't available, so the image itself wasn't built. - Running `license-header-checker` v1.5.0 installed via `go install` over `rust/` reports `license_ok: 258 files`. - This PR runs both the `npm-publish` dry run and `license-header-check`, because both workflows' path filters include their own files. ## Merge Risk **Door:** two-way; CI config and an example Dockerfile only. **Blast Radius:** release automation. If `npm publish` or the Codex bump job needs a permission I removed, it will fail on the next tag or dispatch, and restoring that one permission fixes it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../codex-update-lance-dependency.yml | 8 ++--- .github/workflows/license-header-check.yml | 5 ++-- .github/workflows/npm-publish.yml | 12 ++++++-- dockerfiles/Dockerfile | 29 ++++--------------- 4 files changed, 21 insertions(+), 33 deletions(-) diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index ef59213bd..1d1890efb 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -16,14 +16,14 @@ on: default: "" type: string -permissions: - contents: write - pull-requests: write - actions: read +permissions: {} jobs: update: runs-on: ubuntu-latest + permissions: + # Pushes the branch with the checkout token. PR creation uses ROBOT_TOKEN. + contents: write steps: - name: Show inputs run: | diff --git a/.github/workflows/license-header-check.yml b/.github/workflows/license-header-check.yml index 8b8510b58..904eea2c4 100644 --- a/.github/workflows/license-header-check.yml +++ b/.github/workflows/license-header-check.yml @@ -21,11 +21,10 @@ jobs: steps: - name: Check out code uses: actions/checkout@v6 + # `go install` at a fixed version is verified against the Go checksum database. - name: Install license-header-checker - working-directory: /tmp run: | - curl -s https://raw.githubusercontent.com/lluissm/license-header-checker/master/install.sh | bash - mv /tmp/bin/license-header-checker /usr/local/bin/ + GOBIN=/usr/local/bin go install github.com/lluissm/license-header-checker/cmd/license-header-checker@v1.5.0 - name: Check license headers (rust) run: license-header-checker -a -v ./rust/license_header.txt ./ rs && [[ -z `git status -s` ]] - name: Check license headers (python) diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 6de291c7d..fbaa43201 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -4,9 +4,7 @@ env: MACOSX_DEPLOYMENT_TARGET: '10.13' CARGO_INCREMENTAL: '0' -permissions: - contents: write - id-token: write +permissions: {} on: push: @@ -33,6 +31,8 @@ concurrency: jobs: build-lancedb: + permissions: + contents: read strategy: fail-fast: false matrix: @@ -326,6 +326,8 @@ jobs: nodejs/dist/* !nodejs/dist/*.node test-lancedb: + permissions: + contents: read name: "Test: ${{ matrix.settings.target }} - node@${{ matrix.node }}" needs: - build-lancedb @@ -394,6 +396,10 @@ jobs: run: node_modules/.bin/jest --verbose publish: name: Publish + permissions: + contents: read + # npm provenance + id-token: write runs-on: ubuntu-latest defaults: run: diff --git a/dockerfiles/Dockerfile b/dockerfiles/Dockerfile index 1c223b9b8..d8cafa690 100644 --- a/dockerfiles/Dockerfile +++ b/dockerfiles/Dockerfile @@ -1,27 +1,10 @@ -# Simple base dockerfile that supports basic dependencies required to run lance with FTS and Hybrid Search +# Simple base dockerfile for running LanceDB, including FTS and Hybrid Search # Usage: docker build -t lancedb:latest -f Dockerfile . FROM python:3.12-slim-bookworm -# Install build dependencies in a single layer -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - curl \ - build-essential \ - protobuf-compiler \ - git \ - ca-certificates && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* - -# Install Rust (pinned installer, non-interactive) -RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal - -# Set the environment variable for Rust -ENV PATH="/root/.cargo/bin:${PATH}" - -# Verify installations -RUN python --version && \ - rustc --version && \ - protoc --version - +# lancedb ships prebuilt manylinux wheels, so no Rust or C toolchain is needed. RUN pip install --no-cache-dir lancedb + +RUN useradd --create-home --uid 1000 lancedb +USER lancedb +WORKDIR /home/lancedb From a9be4525a046c7b6356087adaf8fbe658995ddba Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:20:34 +0800 Subject: [PATCH 176/203] fix(python): accept optional discard_weight in split_hash (#5116) ### Problem `PermutationBuilder.split_hash()` raises `TypeError` when `discard_weight` is omitted because the Python wrapper forwards `None` while the PyO3 binding requires `u64`. The `_lancedb.pyi` stub also disagrees with the native signature: it omits `split_names` and types `discard_weight` as non-optional. ### Behavior The native binding accepts an optional `discard_weight` and treats omitted/`None` as `0`, so `split_hash(..., split_names=[...])` works without passing a discard weight. The stub now matches the binding. A regression test verifies that omitting `discard_weight` assigns every row exactly like explicit `0`. Fixes OSS-2856. --- python/python/lancedb/_lancedb.pyi | 7 ++++- python/python/tests/test_permutation.py | 35 +++++++++++++++++++++++++ python/src/permutation.rs | 5 ++-- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 54b9f8083..5a89f100b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1280,7 +1280,12 @@ class AsyncPermutationBuilder: seed: Optional[int] = None, ) -> "AsyncPermutationBuilder": ... def split_hash( - self, columns: List[str], split_weights: List[int], *, discard_weight: int = 0 + self, + columns: List[str], + split_weights: List[int], + *, + discard_weight: Optional[int] = None, + split_names: Optional[List[str]] = None, ) -> "AsyncPermutationBuilder": ... def split_sequential( self, diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 46d6493ed..165172622 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -275,6 +275,41 @@ def test_split_hash(mem_db): assert data["split_id"] == data2["split_id"] # Should be identical +def test_split_hash_default_discard_weight_matches_zero(mem_db): + """Omitting discard_weight must assign every row like discard_weight=0.""" + tbl = mem_db.create_table( + "test_table", + pa.table( + { + "id": range(100), + "category": (["A", "B", "C"] * 34)[:100], + "value": range(100), + } + ), + ) + + default = ( + permutation_builder(tbl) + .split_hash(["category"], [1, 1], split_names=["train", "test"]) + .execute() + ) + explicit_zero = ( + permutation_builder(tbl) + .split_hash( + ["category"], [1, 1], discard_weight=0, split_names=["train", "test"] + ) + .execute() + ) + + default_data = default.search(None).to_arrow().to_pydict() + explicit_data = explicit_zero.search(None).to_arrow().to_pydict() + assert default.count_rows() == 100 + assert default.count_rows() == explicit_zero.count_rows() + assert dict(zip(default_data["row_id"], default_data["split_id"])) == dict( + zip(explicit_data["row_id"], explicit_data["split_id"]) + ) + + def test_split_hash_with_discard(mem_db): """Test hash-based splitting with discard weight.""" tbl = mem_db.create_table( diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 4e07d439e..9cb4da247 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -123,14 +123,15 @@ impl PyAsyncPermutationBuilder { }) } - #[pyo3(signature = (columns, split_weights, *, discard_weight=0, split_names=None))] + #[pyo3(signature = (columns, split_weights, *, discard_weight=None, split_names=None))] pub fn split_hash( slf: PyRefMut<'_, Self>, columns: Vec, split_weights: Vec, - discard_weight: u64, + discard_weight: Option, split_names: Option>, ) -> PyResult { + let discard_weight = discard_weight.unwrap_or(0); slf.modify(|builder| { builder.with_split_strategy( SplitStrategy::Hash { From 5e9b17b639dd4d1e10e4206f5354a9d8de0b0a0e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:21:27 +0800 Subject: [PATCH 177/203] feat(python): make native tables and connections picklable (#5114) ## Summary Adds `__getstate__`/`__setstate__` to native `LanceTable` and `LanceDBConnection` so a PyTorch `Dataset` that keeps both can cross `spawn` and `forkserver` worker boundaries. `Permutation` and `StreamingDataset` now delegate to the same table state representation while retaining compatibility with older pickle payloads. ## Pickle contract - Reconnects from the serialized connection and preserves the table name, namespace path, explicit storage overrides, location, index-cache setting, managed versioning and pushdown routing. - Standard mode reopens at latest; `checkout(version)` remains pinned to the resolved branch/version; branch handles preserve their branch. Cross-branch tag checkout records the actual live branch. - `read_consistency_interval=timedelta(0)` remains distinct from `None`. - `memory://` tables keep the existing Arrow snapshot export/rebuild behavior. - `Session` and unreconstructable custom namespace clients fail at `pickle.dumps` with an explicit `TypeError`; declared namespace configurations reconstruct, including an omitted properties map. - Namespace storage options keep caller-only overrides layered over the live provider, with vended values winning conflicts. Caller options survive refresh, refreshed credentials replace old vended values, an explicit provider remains selected on open, and an empty provider response stays empty rather than restoring an expired seed. - Declared Python namespace connections reopen through their connection provider instead of turning the reconstructed client into an explicit table provider. ## Verification - Fresh binding build with `uv run --extra tests --extra dev maturin develop --extras tests,dev`. - End-to-end `DataLoader` holding `self._db` and `self._table`: spawn and forkserver passed. - `test_namespace.py`: 90 passed; `test_table.py` + `test_db.py` + `test_permutation.py`: 700 passed, 17 skipped. - Focused namespace provider/pickle regressions: passed, including caller-only and vended keys after a declared-namespace refresh. - Rust `test_namespace_connection_with_storage_options` and `test_manifest_enabled_vend_input_storage_options`: passed. - `cargo clippy -p lancedb --features remote --tests --examples`, `cargo fmt --check`, exact CI Pyright (0 errors/0 warnings), and Ruff passed. - DataLoader Workers documentation updated; Vale reports 0 findings. ## Scope Does not change the fork hard-error policy, #3851, or direct `LanceNamespaceDBConnection` pickling. It does not claim changes to the existing namespace dir `index_cache_size` behavior. This supersedes the earlier draft #3486, which only moved the table-state portion. --- docs/web/training/data-loading.mdx | 23 +- python/python/lancedb/db.py | 31 +- python/python/lancedb/namespace.py | 5 +- python/python/lancedb/permutation.py | 29 +- python/python/lancedb/table.py | 175 ++++++++++- python/python/tests/test_db.py | 24 ++ python/python/tests/test_namespace.py | 420 +++++++++++++++++++++++++ python/python/tests/test_table.py | 123 ++++++++ python/python/tests/test_torch.py | 41 +++ rust/lancedb/src/connection.rs | 69 ++++ rust/lancedb/src/database/namespace.rs | 36 ++- rust/lancedb/src/table.rs | 96 +++++- 12 files changed, 1027 insertions(+), 45 deletions(-) diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 1e4989cf9..2a3250105 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -217,12 +217,23 @@ dataloader = torch.utils.data.DataLoader( ``` -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: +By default, `StreamingDataset` and `Permutation` pickle the native table's +reopen state, including its connection, table identity, open options and +explicit storage overrides. A standard-mode handle reopens at the latest +version; `checkout(version)` and branch-scoped handles keep their pinned +version and branch. `memory://` tables are exported as an Arrow snapshot, so +workers see the data as of pickling; an in-memory connection by itself is not +picklable. + +Connections opened with a `Session` cannot be pickled. For a Session-backed +table, pass a picklable `connection_factory` to +`Permutation.with_connection_factory` or `StreamingDataset(connection_factory=...)` +so each worker creates its own connection and Session. + +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: ```py Python icon=Python diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 86001ef10..aa1d73b29 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1936,11 +1936,40 @@ class LanceDBConnection(DBConnection): "manifest_enabled": self._manifest_enabled, "namespace_client_properties": self._namespace_client_properties, "read_consistency_interval_seconds": ( - rci.total_seconds() if rci else None + rci.total_seconds() if rci is not None else None ), } ) + def _pickle_state(self) -> str: + """Serialize this connection for pickle-based workers.""" + if self._session is not None: + raise TypeError( + "Cannot pickle a LanceDBConnection created with a Session; " + "Session objects are not serializable. Create the Session in " + "each worker process instead." + ) + if self.uri.startswith("memory://"): + raise TypeError( + "Cannot pickle an in-memory LanceDBConnection because its tables " + "exist only in this process. Pickle a LanceTable instead to " + "export its data, or connect to a persistent URI." + ) + return self.serialize() + + def __getstate__(self) -> dict[str, str]: + return {"serialized": self._pickle_state()} + + def __setstate__(self, state: dict[str, str]) -> None: + from . import deserialize_conn + + connection = deserialize_conn(state["serialized"], for_worker=True) + if not isinstance(connection, LanceDBConnection): + raise TypeError( + "Serialized connection did not reconstruct a LanceDBConnection" + ) + self.__dict__.update(connection.__dict__) + async def _async_get_table_names(self, start_after: Optional[str], limit: int): conn = AsyncConnection(await lancedb_connect(self.uri)) return await conn.table_names(start_after=start_after, limit=limit) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 463536619..1de49d935 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -584,7 +584,7 @@ class LanceNamespaceDBConnection(DBConnection): "storage_options": self.storage_options or None, "read_consistency_interval_seconds": ( self.read_consistency_interval.total_seconds() - if self.read_consistency_interval + if self.read_consistency_interval is not None else None ), } @@ -668,6 +668,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -706,6 +707,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, namespace_client=self._namespace_client, pushdown_operations=self._namespace_client_pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, @@ -1132,6 +1134,7 @@ class LanceNamespaceDBConnection(DBConnection): self, name, namespace_path=namespace_path, + storage_options=storage_options, location=table_uri, namespace_client=namespace_client, managed_versioning=managed_versioning, diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index a6f584f8a..c8e6f84e0 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -410,6 +410,8 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: from .remote.table import RemoteTable if isinstance(table, RemoteTable): + # RemoteTable already owns its reopen state; keep the table object so + # pickle delegates to its __getstate__ without duplicating the fields. return { "kind": "remote", "table": table, @@ -418,20 +420,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: if not isinstance(table, LanceTable): raise ValueError(f"Cannot pickle table of type {type(table)!r}") - base_uri = table._conn.uri - if base_uri.startswith("memory://"): + state = table.__getstate__() + if state.get("kind") == "memory": return { "kind": "memory", - "name": table.name, - "data": table.to_arrow(), + "state": state, } - return { - "kind": "local", - "name": table.name, - "uri": base_uri, - "namespace": table._namespace_path, - "storage_options": table._conn.storage_options, + "kind": "lance", + "state": state, } @@ -444,13 +441,25 @@ def _drop_base_version(permutation_data: pa.Table) -> pa.Table: return permutation_data.replace_schema_metadata(metadata) +def _lance_table_from_pickle_state(state: dict[str, Any]) -> LanceTable: + table = LanceTable.__new__(LanceTable) + table.__setstate__(state) + return table + + def _table_from_pickle_state(state: dict[str, Any]) -> Table: from . import connect kind = state["kind"] if kind == "remote": return state["table"] + if kind == "lance": + return _lance_table_from_pickle_state(state["state"]) if kind == "memory": + if "state" in state: + return _lance_table_from_pickle_state(state["state"]) + # Backward compatibility for pickles written before tables carried + # their own state. return connect("memory://").create_table(state["name"], state["data"]) if kind == "local": db = connect(state["uri"], storage_options=state["storage_options"]) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ff014396c..ea9dee024 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -299,7 +299,7 @@ def _maybe_add_fts_error_note( if TYPE_CHECKING: - from .db import LanceDBConnection + from .db import DBConnection, LanceDBConnection from ._lancedb import ( Table as LanceDBTable, OptimizeStats, @@ -4191,7 +4191,10 @@ class LanceTable(Table): namespace_path = [] self._conn = connection self._namespace_path = namespace_path + self._storage_options = storage_options + self._index_cache_size = index_cache_size self._location = location # Store location for use in _dataset_path + self._managed_versioning = managed_versioning self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() # When the connection built the namespace client natively (e.g. an @@ -4218,6 +4221,154 @@ class LanceTable(Table): ) # Take queries read the pushdown set from the inner table. self._table._pushdown_operations = self._pushdown_operations + # These coordinates live on the Python wrapper: the native table only + # reports its current branch and version, not whether it is pinned. + self._branch = self._table.current_branch() + self._checkout_version: Optional[int] = None + + def _pickle_connection_state(self) -> str: + """Serialize the connection, rejecting state a worker cannot recreate.""" + connection = self._conn + namespace_client = getattr(connection, "_namespace_client", None) + namespace_impl = getattr(connection, "_namespace_client_impl", None) + if namespace_client is not None and namespace_impl is None: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r} backed by a namespace " + "connection whose custom namespace_client cannot be " + "reconstructed. Connect through connect_namespace(impl, " + "properties) or provide a picklable worker-side namespace " + "connection instead." + ) + + pickle_state = getattr(connection, "_pickle_state", None) + if pickle_state is not None: + return pickle_state() + + session = getattr(connection, "session", None) + if session is not None: + raise TypeError( + "Cannot pickle a LanceTable whose connection was created with a " + "Session; Session objects are not serializable. Create the " + "Session in each worker process instead." + ) + return connection.serialize() + + def _namespace_client_for_pickle(self) -> Optional[Any]: + """Keep a table-level namespace client only when pickle can carry it.""" + namespace_client = self._namespace_client + if namespace_client is None: + return None + if namespace_client is getattr(self._conn, "_namespace_client", None): + # The serialized connection rebuilds its own namespace client. + return None + if namespace_client is getattr(self._conn, "_cached_namespace_client", None): + # Local manifest-mode connections cache their namespace client here. + return None + + import pickle + + try: + pickle.dumps(namespace_client) + except Exception as error: + raise TypeError( + f"Cannot pickle LanceTable {self.name!r}: its custom " + f"namespace_client ({type(namespace_client).__name__}) is not " + "serializable. Reopen the table in the worker through a " + "picklable namespace connection instead." + ) from error + return namespace_client + + @classmethod + def _open_from_pickle_state( + cls, connection: "DBConnection", state: dict[str, Any] + ) -> "LanceTable": + """Reopen a table from the state returned by ``__getstate__``.""" + async_connection = getattr(connection, "_conn", None) + if async_connection is None: + async_connection = connection._inner + + # Only a table-level explicit client travels in the state. A connection + # namespace client must reopen through its own provider path so caller + # storage options keep their layering; passing the reconstructed client + # here would turn it into an explicit table provider. + namespace_client = state.get("namespace_client") + + async_table = LOOP.run( + async_connection.open_table( + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + ) + ) + table = cls( + connection, + state["name"], + namespace_path=state["namespace_path"], + storage_options=state["storage_options"], + index_cache_size=state["index_cache_size"], + location=state["location"], + namespace_client=namespace_client, + managed_versioning=state["managed_versioning"], + pushdown_operations=state["pushdown_operations"], + route_pushdown_to_rust=state["route_pushdown_to_rust"], + _async=async_table, + ) + + version = state["checkout_version"] + if state["branch"] is not None: + table = table.branches.checkout(state["branch"], version) + elif version is not None: + table.checkout(version) + return table + + def __getstate__(self) -> dict[str, Any]: + """Return a process-independent state for pickle-based workers.""" + if self._conn.uri.startswith("memory://"): + # In-memory databases cannot be reopened by name in another process. + # Keep the established behavior of exporting the visible table. + return {"kind": "memory", "name": self.name, "data": self.to_arrow()} + + # The native handle is authoritative: a tag checkout can move this + # wrapper onto another branch, so never trust the branch captured at + # construction time. + self._branch = self.current_branch() + return { + "kind": "lance", + "connection_state": self._pickle_connection_state(), + "name": self.name, + "namespace_path": list(self._namespace_path), + # Only caller-supplied overrides are safe to replay. Namespace-provided + # initial options may contain rotating credentials and must be fetched + # again by the reopened connection's storage-options provider. + "storage_options": self._storage_options, + "index_cache_size": self._index_cache_size, + "location": self._location, + "namespace_client": self._namespace_client_for_pickle(), + "managed_versioning": self._managed_versioning, + "pushdown_operations": set(self._pushdown_operations), + "route_pushdown_to_rust": self._route_pushdown_to_rust, + "branch": self._branch, + "checkout_version": self._checkout_version, + } + + def __setstate__(self, state: dict[str, Any]) -> None: + """Rebuild a table from ``__getstate__`` in the current process.""" + if state.get("kind") == "memory": + from . import connect + + rebuilt = connect("memory://").create_table(state["name"], state["data"]) + self.__dict__.update(rebuilt.__dict__) + return + + from . import deserialize_conn + + connection = deserialize_conn(state["connection_state"], for_worker=True) + reopened = type(self)._open_from_pickle_state(connection, state) + self.__dict__.update(reopened.__dict__) @property def name(self) -> str: @@ -4456,18 +4607,23 @@ class LanceTable(Table): def _wrap_branch_handle( self, async_table: "AsyncTable", version: Optional[int] = None ) -> "LanceTable": - # version is unused locally: the pin already lives on async_table and a - # local handle is not reopened via a serialized connection. - return LanceTable( + table = LanceTable( self._conn, async_table.name, namespace_path=self._namespace_path, + storage_options=self._storage_options, + index_cache_size=self._index_cache_size, namespace_client=self._namespace_client, + managed_versioning=self._managed_versioning, pushdown_operations=self._pushdown_operations, route_pushdown_to_rust=self._route_pushdown_to_rust, location=self._location, _async=async_table, ) + # The native handle knows its branch but not whether this wrapper is a + # pinned branch version, so carry that coordinate explicitly. + table._checkout_version = version + return table def checkout(self, version: Union[int, str]): """Checkout a version of the table. This is an in-place operation. @@ -4506,6 +4662,8 @@ class LanceTable(Table): 0 [1.1, 0.9] vector """ LOOP.run(self._table.checkout(version)) + self._checkout_version = self.version + self._branch = self.current_branch() def checkout_latest(self): """Checkout the latest version of the table. This is an in-place operation. @@ -4514,6 +4672,8 @@ class LanceTable(Table): version of the table. """ LOOP.run(self._table.checkout_latest()) + self._checkout_version = None + self._branch = self.current_branch() def restore(self, version: Optional[Union[int, str]] = None): """Restore a version of the table. This is an in-place operation. @@ -4562,6 +4722,8 @@ class LanceTable(Table): if version is not None: LOOP.run(self._table.checkout(version)) LOOP.run(self._table.restore()) + self._checkout_version = None + self._branch = self.current_branch() def count_rows(self, filter: Optional[str] = None) -> int: return LOOP.run(self._table.count_rows(filter)) @@ -5651,7 +5813,9 @@ class LanceTable(Table): self = cls.__new__(cls) self._conn = db self._namespace_path = namespace_path + self._index_cache_size = None self._location = location + self._managed_versioning = None self._namespace_client = namespace_client self._pushdown_operations = pushdown_operations or set() self._route_pushdown_to_rust = route_pushdown_to_rust @@ -5679,6 +5843,7 @@ class LanceTable(Table): enable_v2_manifest_paths ).lower() + self._storage_options = storage_options self._table = LOOP.run( self._conn._conn.create_table( name, @@ -5695,6 +5860,8 @@ class LanceTable(Table): namespace_client=namespace_client, ) ) + self._branch = self._table.current_branch() + self._checkout_version = None return self def delete(self, where: Union[str, Expr]) -> DeleteResult: diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 80a98bc18..fa09a9e19 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -4,6 +4,7 @@ import contextlib import inspect +import pickle import re import sys from datetime import timedelta @@ -69,6 +70,29 @@ def test_basic(tmp_path): assert db.open_table("test").name == db["test"].name +def test_lance_db_connection_pickle_roundtrip(tmp_path): + interval = timedelta(seconds=2) + db = lancedb.connect(tmp_path, read_consistency_interval=interval) + db.create_table("pickle_conn", pa.table({"id": [1, 2]})) + + restored = pickle.loads(pickle.dumps(db)) + + assert restored.uri == str(tmp_path) + assert restored.read_consistency_interval == interval + assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2] + + +def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) + table = db.create_table("pickle_zero", pa.table({"id": [1]})) + + restored_db, restored_table = pickle.loads(pickle.dumps((db, table))) + lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]})) + + assert restored_db.read_consistency_interval == timedelta(0) + assert restored_table.to_arrow()["id"].to_pylist() == [1, 2] + + def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch): from lancedb.background_loop import LOOP diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index b4ca746b0..c965618cd 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -6,6 +6,8 @@ import tempfile import shutil import importlib +import asyncio +import pickle import warnings import http.server import json @@ -16,6 +18,7 @@ import copy import pyarrow as pa import lancedb from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError +from lance_namespace import DescribeTableResponse from utils import start_server_thread from lancedb.listing import AsyncListing, Listing from lancedb.index import FTS @@ -35,6 +38,37 @@ PUSHDOWN_DATA = pa.table( ) +class _RefreshNamespaceWithExpiringOptions(LanceNamespace): + def __init__(self, root): + self.root = root + + def namespace_id(self): + return f"refresh-test:{self.root}" + + def describe_table(self, request): + from pathlib import Path + + return DescribeTableResponse( + location=str(Path(self.root) / "t.lance"), + storage_options={"vended": "fresh", "expires_at_millis": "1"}, + ) + + +class _DeclaredNamespaceWithoutProperties(LanceNamespace): + root = None + + def __init__(self): + from lance.namespace import DirectoryNamespace + + self.client = DirectoryNamespace(root=self.root) + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + @pytest.mark.asyncio @pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) async def test_custom_namespace_table_exists_uses_namespace_api(table_id): @@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id): assert await adb.table_exists(table_id) is (table_id != ["missing"]) +def test_table_pickle_rejects_custom_namespace_connection(tmp_path): + pytest.importorskip("lance") + from lance.namespace import DirectoryNamespace + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + + class UnserializableNamespace(LanceNamespace): + def __init__(self, root): + from threading import Lock + + self.client = DirectoryNamespace(root=str(root)) + self.lock = Lock() + + def namespace_id(self): + return self.client.namespace_id() + + def describe_table(self, request): + return self.client.describe_table(request) + + db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path)) + table = db.open_table("t") + + with pytest.raises(TypeError, match="namespace"): + pickle.dumps(table) + + +def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path): + lancedb.connect(tmp_path).create_table("t", [{"id": 1}]) + db = lancedb.connect_namespace( + f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)} + ) + table = db.open_table("t", storage_options={"caller_only": "keep"}) + + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_only"] == "keep" + assert options["vended"] == "fresh" + + +def test_table_pickle_allows_declared_namespace_without_properties(tmp_path): + pytest.importorskip("lance") + + lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table( + "t", [{"id": 1}] + ) + _DeclaredNamespaceWithoutProperties.root = str(tmp_path) + try: + impl = f"{__name__}._DeclaredNamespaceWithoutProperties" + db = LanceNamespaceDBConnection( + _DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl + ) + table = db.open_table("t") + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.to_arrow()["id"].to_pylist() == [1] + finally: + _DeclaredNamespaceWithoutProperties.root = None + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -309,6 +407,328 @@ def paginated_rest_namespace(): thread.join() +def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path): + from time import time + + local = lancedb.connect(tmp_path) + local.create_table("t", [{"id": 1}]) + location = str(tmp_path / "t.lance") + ipc = _ipc_file(pa.table({"id": [42]})) + seen = [] + current_options = { + "block_size": "4096", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + seen.append(path) + if path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + content_type = "application/json" + elif path.endswith("/query"): + body = ipc + content_type = "application/vnd.apache.arrow.file" + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + namespace_client_pushdown_operations=["QueryTable"], + ) + table = db.open_table("t") + restored = pickle.loads(pickle.dumps(table)) + + seen.clear() + assert restored.search().limit(1).to_list() == [{"id": 42}] + assert seen == ["/v1/table/t/query"] + + current_options = { + "block_size": "8192", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + assert table.latest_storage_options()["block_size"] == "8192" + assert restored.latest_storage_options()["block_size"] == "8192" + finally: + server.shutdown() + thread.join() + + +def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path): + from time import time + + location = str(tmp_path / "t.lance") + current_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + body = json.dumps( + {"location": location, "storage_options": current_options} + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", {"uri": f"http://127.0.0.1:{server.server_port}"} + ) + table = db.create_table("t", [{"id": 1}]) + payload = pickle.dumps(table) + assert b"short-lived" not in payload + restored = pickle.loads(payload) + + current_options = {} + assert table.latest_storage_options() == {} + assert restored.latest_storage_options() == {} + finally: + server.shutdown() + thread.join() + + +@pytest.mark.parametrize("entrypoint", ["create", "open"]) +def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint): + from time import time + + location = str(tmp_path / "t.lance") + caller_options = {"caller_option": "kept", "conflict": "caller"} + vended_options = { + "vended_1": "old", + "conflict": "vended", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if path.endswith("/declare") or path.endswith("/describe"): + body = json.dumps( + {"location": location, "storage_options": vended_options} + ).encode() + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + db = lancedb.connect_namespace( + "rest", + {"uri": f"http://127.0.0.1:{server.server_port}"}, + ) + if entrypoint == "create": + table = db.create_table( + "t", [{"id": 1}], storage_options=caller_options + ) + else: + db.create_table("t", [{"id": 1}]) + table = db.open_table("t", storage_options=caller_options) + restored = pickle.loads(pickle.dumps(table)) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["conflict"] == "vended" + + vended_options.update( + { + "vended_2": "new", + "conflict": "vended-new", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + } + ) + + for current in (table, restored): + options = current.latest_storage_options() + assert options["caller_option"] == "kept" + assert options["vended_2"] == "new" + assert options["conflict"] == "vended-new" + finally: + server.shutdown() + thread.join() + + +def test_namespace_open_uses_explicit_storage_options_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + if not (path.endswith("/declare") or path.endswith("/describe")): + self.send_error(404) + return + result = {"location": location, "storage_options": seed_options} + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + db = lancedb.connect_namespace("rest", properties) + db.create_table("t", [{"id": 1}]) + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.open_table("t", namespace_client=client) + options = await table.latest_storage_options() + assert client.calls > 0 + assert options["explicit_provider"] == "fresh" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + +def test_namespace_create_without_seed_uses_connection_provider(tmp_path): + from time import time + + from lancedb._lancedb import connect_namespace as connect_namespace_inner + from lancedb.db import AsyncConnection + + location = str(tmp_path / "t.lance") + seed_options = { + "vended_seed": "short-lived", + "expires_at_millis": str(int(time() * 1000) + 30_000), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + path = urlparse(self.path).path + result = {"location": location} + if path.endswith("/describe"): + result["storage_options"] = seed_options + elif not path.endswith("/declare"): + self.send_error(404) + return + body = json.dumps(result).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + class ExplicitClient(LanceNamespace): + calls = 0 + + def namespace_id(self): + return "explicit-storage-options-provider" + + def describe_table(self, request): + self.calls += 1 + return DescribeTableResponse( + location=location, + storage_options={ + "explicit_provider": "fresh", + "expires_at_millis": str(int(time() * 1000) + 3_600_000), + }, + ) + + with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = start_server_thread(server) + try: + properties = {"uri": f"http://127.0.0.1:{server.server_port}"} + + async def check(): + connection = AsyncConnection( + connect_namespace_inner("rest", properties) + ) + client = ExplicitClient() + table = await connection.create_table( + "t", [{"id": 1}], namespace_client=client + ) + options = await table.latest_storage_options() + assert client.calls == 0 + assert options["vended_seed"] == "short-lived" + + asyncio.run(check()) + finally: + server.shutdown() + thread.join() + + @pytest.mark.asyncio @pytest.mark.parametrize("namespace_path", [[], ["n"]]) async def test_rest_namespace_table_names_collects_pages( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 90ae62d1b..e999390a1 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -6,6 +6,7 @@ import ctypes import gc import json import os +import pickle import sys import threading import warnings @@ -1228,6 +1229,128 @@ def test_list_versions_timestamp_precision_remote(): assert versions[0]["timestamp"].microsecond == 274000 +def test_lance_table_is_picklable(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_table", pa.table({"id": [1, 2, 3]})) + payload = pickle.dumps(table) + + # A standard-mode handle must reopen at latest, not freeze the version that + # happened to be current when pickle.dumps ran. + tmp_db.open_table("pickle_table").add(pa.table({"id": [4]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_table" + assert restored.count_rows() == 4 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3, 4] + + +def test_lance_table_pickle_preserves_checkout(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_checkout", pa.table({"id": [1]})) + table.add(pa.table({"id": [2]})) + table.checkout(1) + payload = pickle.dumps(table) + + tmp_db.open_table("pickle_checkout").add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.version == 1 + assert restored.to_arrow()["id"].to_pylist() == [1] + + restored.checkout_latest() + assert restored.version == 3 + assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3] + + +def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_tag_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch.tags.create("exp_tag", branch.version) + + # Advance main independently, then resolve a tag that points into exp. + main.add(pa.table({"id": [9]})) + main.checkout("exp_tag") + assert main.current_branch() == "exp" + assert main.version == 2 + assert main.to_arrow()["id"].to_pylist() == [0, 1] + + restored = pickle.loads(pickle.dumps(main)) + assert restored.current_branch() == "exp" + assert restored.version == 2 + assert restored.to_arrow()["id"].to_pylist() == [0, 1] + + +def test_lance_table_pickle_preserves_branch_and_version(tmp_path): + db = lancedb.connect(tmp_path) + main = db.create_table("pickle_branch", pa.table({"id": [0]})) + branch = main.branches.create("exp") + branch.add(pa.table({"id": [1]})) + branch_version = branch.version + + branch_payload = pickle.dumps(branch) + pinned = db.open_table("pickle_branch", branch="exp", version=branch_version) + pinned_payload = pickle.dumps(pinned) + + db.open_table("pickle_branch", branch="exp").add(pa.table({"id": [2]})) + + restored_branch = pickle.loads(branch_payload) + assert restored_branch.current_branch() == "exp" + assert restored_branch.to_arrow()["id"].to_pylist() == [0, 1, 2] + + restored_pinned = pickle.loads(pinned_payload) + assert restored_pinned.current_branch() == "exp" + assert restored_pinned.version == branch_version + assert restored_pinned.to_arrow()["id"].to_pylist() == [0, 1] + assert main.count_rows() == 1 + + +def test_lance_table_pickle_memory_uses_arrow_snapshot(mem_db: DBConnection): + table = mem_db.create_table("pickle_memory", pa.table({"id": [1, 2]})) + payload = pickle.dumps(table) + + table.add(pa.table({"id": [3]})) + + restored = pickle.loads(payload) + assert restored.name == "pickle_memory" + assert restored.to_arrow()["id"].to_pylist() == [1, 2] + + +def test_memory_connection_pickle_requires_a_table_snapshot(mem_db: DBConnection): + with pytest.raises(TypeError, match="in-memory LanceDBConnection"): + pickle.dumps(mem_db) + + +def test_pickle_rejects_session_backed_connection(tmp_path): + db = lancedb.connect(tmp_path, session=lancedb.Session()) + table = db.create_table("pickle_session", pa.table({"id": [1]})) + + with pytest.raises(TypeError, match="Session"): + pickle.dumps(db) + with pytest.raises(TypeError, match="Session"): + pickle.dumps(table) + + +def test_pickle_rejects_custom_namespace_client(tmp_db: DBConnection): + table = tmp_db.create_table("pickle_custom_ns", pa.table({"id": [1]})) + table._namespace_client = threading.Lock() + + with pytest.raises(TypeError, match="namespace_client"): + pickle.dumps(table) + + +def test_lance_table_pickle_preserves_namespace_path(tmp_path): + pytest.importorskip("lance") + db = lancedb.connect_namespace("dir", {"root": str(tmp_path)}) + db.create_namespace(["ns1"]) + table = db.create_table("pickle_ns", pa.table({"id": [1]}), namespace_path=["ns1"]) + + restored = pickle.loads(pickle.dumps(table)) + + assert restored.namespace == ["ns1"] + assert restored.count_rows() == 1 + assert restored._conn._namespace_client_properties == {"root": str(tmp_path)} + + def test_versioning(mem_db: DBConnection): table = mem_db.create_table( "test", diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index befa3c10f..1cc6500bd 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -135,6 +135,23 @@ def _open_native_table(uri: str, table_name: str): return lancedb.connect(uri).open_table(table_name) +class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset): + """User-style Dataset that keeps both the connection and table.""" + + def __init__(self, db, table): + self._db = db + self._table = table + + def __len__(self): + return self._table.count_rows() + + def __getitem__(self, index): + row = self._table.take_offsets([index]).to_arrow().to_pylist()[0] + # Touch the connection too, so workers prove both objects were restored. + row["db_uri"] = self._db.uri + return row + + def test_table_dataloader(mem_db): table = mem_db.create_table("test_table", pa.table({"a": range(1000)})) dataloader = torch.utils.data.DataLoader( @@ -229,6 +246,30 @@ def test_permutation_with_memory_base_is_picklable(mem_db): assert restored.__getitems__([0, 10, 49]) == [{"a": 0}, {"a": 10}, {"a": 49}] +@pytest.mark.parametrize("start_method", ["spawn", "forkserver"]) +def test_dataset_with_connection_and_table_dataloader(tmp_path, start_method): + if start_method not in mp.get_all_start_methods(): + pytest.skip(f"{start_method} start method is not available") + + db = lancedb.connect(tmp_path) + table = db.create_table("test_table", pa.table({"a": range(20)})) + dataset = _DatasetHoldingConnectionAndTable(db, table) + + dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=4, + num_workers=2, + multiprocessing_context=start_method, + ) + + seen = [] + expected_uri = str(tmp_path) + for batch in dataloader: + seen.extend(batch["a"].tolist()) + assert all(uri == expected_uri for uri in batch["db_uri"]) + assert sorted(seen) == list(range(20)) + + def test_permutation_dataloader_multiprocessing(tmp_db): """Using a Permutation with a PyTorch DataLoader that has num_workers > 0 must work end-to-end. Each worker process gets a pickled copy of the diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index bbefc3ca8..db6aa2ba8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -90,6 +90,75 @@ fn set_storage_options_provider( store_params.storage_options_accessor = Some(Arc::new(accessor)); } +/// Preserve caller-supplied options across provider refreshes. +/// +/// Namespace providers return a fresh credential map and replace the accessor +/// cache, so a plain initial-options accessor would drop caller-only settings +/// after the first refresh. This wrapper merges the caller options into every +/// provider result, with provider values winning overlapping keys. +#[derive(Debug)] +pub(crate) struct LayeredStorageOptionsProvider { + caller_options: HashMap, + inner: Arc, +} + +impl LayeredStorageOptionsProvider { + pub(crate) fn new( + caller_options: HashMap, + inner: Arc, + ) -> Self { + Self { + caller_options, + inner, + } + } + + fn layer( + &self, + mut options: Option>, + ) -> Option> { + let mut merged = self.caller_options.clone(); + match options.take() { + Some(options) => { + merged.extend(options); + Some(merged) + } + None if merged.is_empty() => None, + None => Some(merged), + } + } +} + +#[async_trait::async_trait] +impl StorageOptionsProvider for LayeredStorageOptionsProvider { + async fn fetch_storage_options(&self) -> lance_core::Result>> { + Ok(self.layer(self.inner.fetch_storage_options().await?)) + } + + async fn force_fetch_storage_options( + &self, + ) -> lance_core::Result>> { + Ok(self.layer(self.inner.force_fetch_storage_options().await?)) + } + + fn provider_id(&self) -> String { + use std::hash::{Hash, Hasher}; + + let mut entries: Vec<_> = self.caller_options.iter().collect(); + entries.sort_by_key(|(key, _)| *key); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for (key, value) in entries { + key.hash(&mut hasher); + value.hash(&mut hasher); + } + format!( + "layered(caller_options={:x},{})", + hasher.finish(), + self.inner.provider_id() + ) + } +} + /// A builder for configuring a [`Connection::table_names`] operation pub struct TableNamesBuilder { parent: Arc, diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 4e61710ff..d603a878b 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -9,7 +9,10 @@ use std::sync::{Arc, Mutex}; use async_trait::async_trait; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; -use lance_io::object_store::{ObjectStoreParams, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, ObjectStoreParams, StorageOptionsAccessor, + StorageOptionsProvider, +}; use lance_namespace::{ LanceNamespace, error::{ErrorCode, NamespaceError}, @@ -25,7 +28,9 @@ use lance_table::io::commit::CommitHandler; use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; use crate::blob::ensure_blob_storage_version; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{ + LayeredStorageOptionsProvider, NamespaceClientPushdownOperation, merge_storage_options, +}; use crate::database::ReadConsistency; use crate::database::listing::{NewTableConfig, take_request_creation_overrides}; use crate::database::read_freshness::{ @@ -465,13 +470,29 @@ impl Database for LanceNamespaceDatabase { params.mode = WriteMode::Overwrite; } - // Set up storage options if provided + // Set up storage options if provided. Namespace options take + // precedence for overlapping keys, but must not discard caller-only + // options supplied with the create request. + let store_params = params + .store_params + .get_or_insert_with(ObjectStoreParams::default); + let caller_storage_options = store_params.storage_options().cloned().unwrap_or_default(); if let Some(storage_opts) = initial_storage_options { - let store_params = params - .store_params - .get_or_insert_with(ObjectStoreParams::default); + merge_storage_options(store_params, storage_opts); + } + if let Some(initial_options) = store_params + .storage_options() + .cloned() + .filter(|options| !options.is_empty()) + { + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(self.namespace.clone(), table_id.clone()), + ); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(caller_storage_options, namespace_provider), + ); store_params.storage_options_accessor = Some(Arc::new( - StorageOptionsAccessor::with_static_options(storage_opts), + StorageOptionsAccessor::with_initial_and_provider(initial_options, provider), )); } @@ -618,6 +639,7 @@ mod tests { use arrow_array::{Int32Array, RecordBatch, StringArray}; use arrow_schema::{DataType, Field, Schema}; use futures::TryStreamExt; + use lance_io::object_store::StorageOptionsAccessor; use tempfile::tempdir; #[derive(Debug)] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 775261bb5..4d663649e 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -29,7 +29,9 @@ use lance::index::scalar::load_segment_params; use lance::io::{ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_index::IndexCriteria; -use lance_io::object_store::{LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor}; +use lance_io::object_store::{ + LanceNamespaceStorageOptionsProvider, StorageOptionsAccessor, StorageOptionsProvider, +}; pub use query::AnyQuery; use lance::io::commit::namespace_manifest::LanceNamespaceExternalManifestStore; @@ -49,7 +51,7 @@ use std::format; use std::path::Path; use std::sync::Arc; -use crate::connection::NamespaceClientPushdownOperation; +use crate::connection::{LayeredStorageOptionsProvider, NamespaceClientPushdownOperation}; use crate::DistanceType; use crate::blob::BlobRangeRequest; @@ -3679,7 +3681,7 @@ impl NativeTable { } // patch the params if we have a write store wrapper - let params = match write_store_wrapper.clone() { + let mut params = match write_store_wrapper.clone() { Some(wrapper) => params.patch_with_store_wrapper(wrapper)?, None => params, }; @@ -3690,9 +3692,49 @@ impl NativeTable { // Use DatasetBuilder::from_namespace which automatically fetches location // and storage options from the namespace - let builder = DatasetBuilder::from_namespace(namespace_client.clone(), table_id) - .await - .map_err(|e| map_namespace_lance_error(e, name))?; + let mut builder = + DatasetBuilder::from_namespace(namespace_client.clone(), table_id.clone()) + .await + .map_err(|e| map_namespace_lance_error(e, name))?; + + // A caller-supplied read-params accessor replaces the namespace-backed + // accessor in with_read_params. Preserve an explicit provider/accessor; + // only layer static caller options onto the live namespace provider so + // refresh keeps working and namespace values retain their precedence. + if let Some(mut store_options) = params.store_options.take() { + if let Some(accessor) = store_options.get_accessor() { + if accessor.provider().is_some() { + builder = builder.with_store_params(store_options); + } else { + let caller_options = accessor + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let namespace_provider: Arc = + Arc::new(LanceNamespaceStorageOptionsProvider::new( + namespace_client.clone(), + table_id, + )); + let provider: Arc = + Arc::new(LayeredStorageOptionsProvider::new( + caller_options.clone(), + namespace_provider, + )); + let accessor = if caller_options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + caller_options, + provider, + )) + }; + store_options.storage_options_accessor = Some(accessor); + builder = builder.with_store_params(store_options); + } + } else { + builder = builder.with_store_params(store_options); + } + } let dataset = builder .with_read_params(params) @@ -3901,10 +3943,9 @@ impl NativeTable { table_id.push(name.to_string()); // Set up storage options provider from namespace - let storage_options_provider = Arc::new(LanceNamespaceStorageOptionsProvider::new( - namespace_client.clone(), - table_id, - )); + let namespace_provider: Arc = Arc::new( + LanceNamespaceStorageOptionsProvider::new(namespace_client.clone(), table_id), + ); // Start with provided params or defaults let mut params = params.unwrap_or_default(); @@ -3914,17 +3955,40 @@ impl NativeTable { params.session = Some(sess); } - // Ensure store_params exists and set the storage options provider + // Ensure store_params exists and preserve an already-layered provider + // from create_table, or attach the namespace provider to the caller's + // initial options for other callers. let store_params = params .store_params .get_or_insert_with(ObjectStoreParams::default); - let accessor = match store_params.storage_options().cloned() { - Some(options) => { - StorageOptionsAccessor::with_initial_and_provider(options, storage_options_provider) + let accessor = match store_params.storage_options_accessor.take() { + Some(existing) + if existing.provider().is_some() + && existing.initial_storage_options().is_some() => + { + existing } - None => StorageOptionsAccessor::with_provider(storage_options_provider), + Some(existing) => { + let options = existing + .initial_storage_options() + .cloned() + .unwrap_or_default(); + let provider: Arc = Arc::new( + LayeredStorageOptionsProvider::new(options.clone(), namespace_provider), + ); + if options.is_empty() { + Arc::new(StorageOptionsAccessor::with_provider(provider)) + } else { + Arc::new(StorageOptionsAccessor::with_initial_and_provider( + options, provider, + )) + } + } + None => Arc::new(StorageOptionsAccessor::with_provider(Arc::new( + LayeredStorageOptionsProvider::new(HashMap::new(), namespace_provider), + ))), }; - store_params.storage_options_accessor = Some(Arc::new(accessor)); + store_params.storage_options_accessor = Some(accessor); // Patch the params if we have a write store wrapper let params = match write_store_wrapper.clone() { From 28e9ebb3ddda2cafac6f861919375ca31e91fb4a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:22:12 +0800 Subject: [PATCH 178/203] fix(python): reject unsupported fragment constraints (#5120) `with_fragments()` / `fragment_ids()` were only honored by the embedded plain-scan blob Pandas path. Every other sync, async, and remote terminal could silently ignore the selection and scan the full table, and async query conversions plus FTS `count_rows()` could drop the constraint before execution. This change makes unsupported paths fail with `NotImplementedError` before I/O, preserves fragment state across async Standard/Vector/FTS/Hybrid conversions, and keeps the supported embedded blob `to_pandas()` behavior unchanged. The FTS `count_rows()` sync and async entry points now reject fragment constraints explicitly. Refs OSS-2859 --- python/python/lancedb/query.py | 205 ++++++++++++++++---- python/python/tests/test_hybrid_query.py | 25 +++ python/python/tests/test_query.py | 231 +++++++++++++++++++++++ python/python/tests/test_remote_db.py | 30 +++ 4 files changed, 456 insertions(+), 35 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index dee2a480d..60fab3b8e 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -273,6 +273,24 @@ def _query_needs_lance_scanner(builder: Any) -> bool: ) +def _raise_unsupported_fragment_constraints( + fragments: Optional[Any], + fragment_ids: Optional[List[int]], + *, + operation: str, +) -> None: + """Reject fragment selection where execution would silently scan everything.""" + if fragments is None and fragment_ids is None: + return + raise NotImplementedError( + "with_fragments() and fragment_ids() are only supported for embedded " + "plain-scan blob queries executed through to_pandas(). " + f"{operation} would ignore the fragment selection and scan the full " + "table. Remove the fragment constraint, or use table.to_lance() with " + "a Lance scanner for this query shape." + ) + + def _query_is_plain_scan(query: Query) -> bool: return ( query.vector is None @@ -1686,11 +1704,19 @@ class LanceQueryBuilder(ABC): return self._user_requested_row_id() or self._blob_auto_row_id_enabled() def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query: + self._ensure_fragment_constraints_supported("this query") query = self.to_query_object() if self._scan_needs_row_id() or blob_sources: query.with_row_id = True return query + def _ensure_fragment_constraints_supported(self, operation: str) -> None: + _raise_unsupported_fragment_constraints( + self._fragments, + self._fragment_ids, + operation=operation, + ) + def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: if blob_mode != "bytes": return False @@ -1826,12 +1852,51 @@ class LanceQueryBuilder(ABC): return self def with_fragments(self, fragments: Any) -> Self: - """Set the Lance fragments to scan for plain scanner-backed queries.""" + """Restrict an embedded plain-scan blob query to the given Lance fragments. + + Fragment selection is supported only when ``to_pandas()`` uses the + embedded Lance plain-scan path: the table is an embedded, non-memory + Lance dataset, the query is a plain scan (no vector, full-text, take, + postfilter, or ordering), and the selected output includes a blob + column. Other terminals and remote tables raise ``NotImplementedError`` + before scanning instead of silently scanning the full table. + Blob-specific ``to_pandas()`` fallbacks keep their existing validation + errors. + + Parameters + ---------- + fragments : list[lance.Fragment] + Fragments from ``table.to_lance().get_fragments()``. Pass fragments + from the same dataset snapshot. + + Returns + ------- + LanceQueryBuilder + The LanceQueryBuilder object. + """ self._fragments = fragments return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """Set the Lance fragment ids to scan for plain scanner-backed queries.""" + """Restrict an embedded plain-scan blob query to the given fragment ids. + + Fragment selection uses the same supported ``to_pandas()`` path as + ``with_fragments()``. On that path, an empty list selects no rows and + missing ids raise ``ValueError``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. + + Parameters + ---------- + fragment_ids : list[int] + Fragment ids from ``table.to_lance().get_fragments()``. + + Returns + ------- + LanceQueryBuilder + The LanceQueryBuilder object. + """ self._fragment_ids = fragment_ids return self @@ -1887,6 +1952,7 @@ class LanceQueryBuilder(ABC): ------- plan : str """ # noqa: E501 + self._ensure_fragment_constraints_supported("explain_plan()") return self._table._explain_plan(self.to_query_object(), verbose=verbose) def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: @@ -1961,6 +2027,7 @@ class LanceQueryBuilder(ABC): plan : str The physical query execution plan with runtime metrics. """ + self._ensure_fragment_constraints_supported("analyze_plan()") return self._table._analyze_plan( self.to_query_object(), distributed_metrics=distributed_metrics ) @@ -2629,6 +2696,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): For example, ``table.search("gripper closed", query_type="fts",`` ``operator="AND").where("active = true").count_rows()``. """ + self._ensure_fragment_constraints_supported("count_rows()") self._table._ensure_no_legacy_fts_index() query = self._table._table._sync_query_to_async(self.to_query_object()) assert isinstance(query, AsyncFTSQuery) @@ -3522,6 +3590,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): def _create_query_builders(self): """Set up and configure the vector and FTS query builders.""" + self._ensure_fragment_constraints_supported("this hybrid query") vector_query, fts_query = self._validate_query( self._query, self._vector, self._text ) @@ -3640,6 +3709,19 @@ class AsyncQueryBase(object): def _user_requested_row_id(self) -> bool: return self._with_row_id is True + def _ensure_fragment_constraints_supported(self, operation: str) -> None: + _raise_unsupported_fragment_constraints( + self._fragments, + self._fragment_ids, + operation=operation, + ) + + def _inherit_fragment_constraints(self, query: Any) -> Any: + """Carry a fragment selection across an async query conversion.""" + query._fragments = self._fragments + query._fragment_ids = self._fragment_ids + return query + def _blob_auto_row_id_enabled(self) -> bool: return self._blob_auto_row_id @@ -3750,15 +3832,30 @@ class AsyncQueryBase(object): return self def with_fragments(self, fragments: Any) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragments. + """Restrict an embedded plain-scan blob query to the given Lance fragments. + + Fragment selection is supported only when ``to_pandas()`` uses the + embedded Lance plain-scan path: the table is an embedded, non-memory + Lance dataset, the query is a plain scan (no vector, full-text, take, + postfilter, or ordering), and the selected output includes a blob + column. The constraint is preserved when converting between async + query types. Other terminals and remote tables raise + ``NotImplementedError`` before scanning instead of silently scanning + the full table. Blob-specific ``to_pandas()`` fallbacks keep their + existing validation errors. """ self._fragments = fragments return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragment ids. + """Restrict an embedded plain-scan blob query to the given fragment ids. + + Fragment selection uses the same supported ``to_pandas()`` path as + ``with_fragments()``. On that path, an empty list selects no rows and + missing ids raise ``ValueError``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. """ self._fragment_ids = fragment_ids return self @@ -3838,6 +3935,7 @@ class AsyncQueryBase(object): timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: + self._ensure_fragment_constraints_supported("to_batches()") if ( blob_sources and not self._user_requested_row_id() @@ -4245,6 +4343,7 @@ class AsyncQueryBase(object): ------- plan : str """ # noqa: E501 + self._ensure_fragment_constraints_supported("explain_plan()") return await self._inner.explain_plan(verbose) async def analyze_plan( @@ -4262,6 +4361,7 @@ class AsyncQueryBase(object): ------- plan : str """ + self._ensure_fragment_constraints_supported("analyze_plan()") return await self._inner.analyze_plan(distributed_metrics) @@ -4501,11 +4601,17 @@ class AsyncQuery(AsyncStandardQuery): new_self = self._inner.nearest_to(query_vectors[0]) for v in query_vectors[1:]: new_self.add_query_vector(v) - return AsyncVectorQuery(new_self, self._table) + return self._inherit_fragment_constraints( + AsyncVectorQuery(new_self, self._table) + ) else: - return AsyncVectorQuery( - self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)), - self._table, + return self._inherit_fragment_constraints( + AsyncVectorQuery( + self._inner.nearest_to( + AsyncQuery._query_vec_to_array(query_vector) + ), + self._table, + ) ) def nearest_to_text( @@ -4545,18 +4651,22 @@ class AsyncQuery(AsyncStandardQuery): columns = [] if isinstance(query, str): - return AsyncFTSQuery( - self._inner.nearest_to_text( - { - "query": query, - "columns": columns, - "operator": fts_query.operator, - } - ), - self._table, + return self._inherit_fragment_constraints( + AsyncFTSQuery( + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), + self._table, + ) ) # FullTextQuery object - return AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table) + return self._inherit_fragment_constraints( + AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table) + ) class AsyncFTSQuery(AsyncStandardQuery): @@ -4577,6 +4687,7 @@ class AsyncFTSQuery(AsyncStandardQuery): For example, ``await table.query().nearest_to_text("gripper closed",`` ``operator="AND").where("active = true").count_rows()``. """ + self._ensure_fragment_constraints_supported("count_rows()") try: return await self._inner.count_rows() except Exception as error: @@ -4662,11 +4773,17 @@ class AsyncFTSQuery(AsyncStandardQuery): new_self = self._inner.nearest_to(query_vectors[0]) for v in query_vectors[1:]: new_self.add_query_vector(v) - return AsyncHybridQuery(new_self, self._table) + return self._inherit_fragment_constraints( + AsyncHybridQuery(new_self, self._table) + ) else: - return AsyncHybridQuery( - self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)), - self._table, + return self._inherit_fragment_constraints( + AsyncHybridQuery( + self._inner.nearest_to( + AsyncQuery._query_vec_to_array(query_vector) + ), + self._table, + ) ) async def _execute_batches( @@ -5002,15 +5119,21 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): columns = [] if isinstance(query, str): - return AsyncHybridQuery( - self._inner.nearest_to_text( - {"query": query, "columns": columns, "operator": fts_query.operator} - ), - self._table, + return self._inherit_fragment_constraints( + AsyncHybridQuery( + self._inner.nearest_to_text( + { + "query": query, + "columns": columns, + "operator": fts_query.operator, + } + ), + self._table, + ) ) # FullTextQuery object - return AsyncHybridQuery( - self._inner.nearest_to_text({"query": query}), self._table + return self._inherit_fragment_constraints( + AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table) ) async def _execute_batches( @@ -5098,6 +5221,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): the hybrid query itself. The key the legs are fused on, if any, is left on `self._pk_fusion`. """ + self._ensure_fragment_constraints_supported("this hybrid query") fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table) vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table) @@ -5394,15 +5518,26 @@ class BaseQueryBuilder(object): return self def with_fragments(self, fragments: Any) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragments. + """Restrict execution to the given Lance fragments. + + Fragment selection is supported only by embedded plain-scan blob + queries through ``to_pandas()``. Other terminals and remote tables + raise ``NotImplementedError`` before scanning instead of silently + scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep + their existing validation errors. """ self._inner.with_fragments(fragments) return self def fragment_ids(self, fragment_ids: List[int]) -> Self: - """ - Restrict scanner-backed plain query results to the given Lance fragment ids. + """Restrict execution to the given Lance fragment ids. + + Fragment selection is supported only by embedded plain-scan blob + queries through ``to_pandas()``. On that path, an empty list selects no + rows and missing ids raise ``ValueError``. Other terminals and remote + tables raise ``NotImplementedError`` before scanning instead of + silently scanning the full table. Blob-specific ``to_pandas()`` + fallbacks keep their existing validation errors. """ self._inner.fragment_ids(fragment_ids) return self diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 443fdebc4..ec6060db3 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -81,6 +81,31 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable): assert result["_rowid"].to_pylist() == [0, 3] +def test_hybrid_fragment_constraints_fail_loud(sync_table: Table): + query = ( + sync_table.search("dog", query_type="hybrid") + .vector([0.5, -0.5]) + .fragment_ids([0]) + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + query.to_arrow() + with pytest.raises(NotImplementedError, match="fragment selection"): + query.explain_plan() + + +@pytest.mark.asyncio +async def test_async_hybrid_fragment_constraints_fail_loud(table: AsyncTable): + query = ( + table.query().nearest_to([0.5, -0.5]).nearest_to_text("dog").fragment_ids([0]) + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.analyze_plan() + + @pytest.mark.asyncio async def test_async_hybrid_query_filters(table: AsyncTable): # test that query params are passed down from the regular builder to diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index aee67d32a..88bed9c1f 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -69,6 +69,36 @@ def _blob_query_data(): ) +def _fragment_query_data(): + return pa.table( + { + "id": pa.array([1, 2, 3, 4], pa.int64()), + "text": pa.array(["one", "two", "three", "four"], pa.utf8()), + "vector": pa.array( + [[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]], + type=pa.list_(pa.float32(), list_size=2), + ), + } + ) + + +def _fragment_query_table(db, name): + data = _fragment_query_data() + table = db.create_table(name, data.slice(0, 2)) + table.add(data.slice(2, 2)) + return table + + +def _apply_fragment_restriction(query, restriction, fragment): + if restriction == "ids": + return query.fragment_ids([fragment.fragment_id]) + if restriction == "empty": + return query.fragment_ids([]) + if restriction == "fragments": + return query.with_fragments([fragment]) + raise AssertionError(f"unknown restriction: {restriction}") + + def _create_blob_v2_query_table(db, name): schema = pa.schema( [ @@ -435,6 +465,207 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db): ) assert df_by_fragment["id"].tolist() == [1, 2] + empty = ( + table.search() + .select(["id", "blob"]) + .fragment_ids([]) + .to_pandas(blob_mode="descriptions") + ) + assert empty.empty + with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"): + ( + table.search() + .select(["id", "blob"]) + .fragment_ids([999]) + .to_pandas(blob_mode="descriptions") + ) + + +@pytest.mark.parametrize( + "terminal", + [ + "to_arrow", + "to_batches", + "to_pandas", + "to_polars", + "to_list", + "explain_plan", + "analyze_plan", + ], +) +def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}") + fragment_id = table.to_lance().get_fragments()[0].fragment_id + query = table.search().fragment_ids([fragment_id]) + + with pytest.raises(NotImplementedError, match="fragment selection"): + getattr(query, terminal)() + + +def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments") + fragment = table.to_lance().get_fragments()[0] + + for query in ( + table.search().with_fragments([fragment]), + table.search([0.0, 0.0]).with_fragments([fragment]), + ): + with pytest.raises(NotImplementedError, match="fragment selection"): + query.to_arrow() + + +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction): + pytest.importorskip("lance") + table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}") + table.create_index("text", config=FTS(with_position=False)) + fragment = table.to_lance().get_fragments()[1] + query = _apply_fragment_restriction( + table.search("one", query_type="fts"), restriction, fragment + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + query.count_rows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "terminal", + [ + "to_arrow", + "to_batches", + "to_pandas", + "to_polars", + "to_list", + "explain_plan", + "analyze_plan", + ], +) +async def test_async_fragment_constraints_fail_loud_on_unsupported_paths( + tmp_db_async, terminal +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_fragment_guard_{terminal}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + query = table.query().fragment_ids([fragments[0].fragment_id]) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await getattr(query, terminal)() + + +@pytest.mark.asyncio +async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries( + tmp_db_async, +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + "async_fragment_guard_with_fragments", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + + for query in ( + table.query().with_fragments([fragments[0]]), + table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]), + ): + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + + +@pytest.mark.asyncio +async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async): + pytest.importorskip("lance") + data = _blob_query_data() + table = await tmp_db_async.create_table( + "async_fragment_supported", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + await table.add(data.slice(2, 2)) + fragments = (await table.to_lance()).get_fragments() + + df = await ( + table.query() + .select(["id", "blob"]) + .fragment_ids([fragments[1].fragment_id]) + .to_pandas(blob_mode="descriptions") + ) + + assert df["id"].tolist() == [3, 4] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +async def test_async_fts_count_rows_rejects_fragment_constraints( + tmp_db_async, restriction +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_fts_count_rows_{restriction}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + await table.create_index("text", config=FTS(with_position=False)) + fragment = (await table.to_lance()).get_fragments()[1] + query = _apply_fragment_restriction( + table.query().nearest_to_text("one"), restriction, fragment + ) + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.count_rows() + + transitioned = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to_text("one") + with pytest.raises(NotImplementedError, match="fragment selection"): + await transitioned.count_rows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"]) +@pytest.mark.parametrize( + "transition", + ["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"], +) +async def test_async_fragment_constraints_survive_query_transitions( + tmp_db_async, transition, restriction +): + pytest.importorskip("lance") + data = _fragment_query_data() + table = await tmp_db_async.create_table( + f"async_transition_{transition}_{restriction}", data.slice(0, 2) + ) + await table.add(data.slice(2, 2)) + await table.create_index("text", config=FTS(with_position=False)) + fragment = (await table.to_lance()).get_fragments()[1] + + if transition == "query_to_vector": + query = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to([0.0, 0.0]) + elif transition == "query_to_fts": + query = _apply_fragment_restriction( + table.query(), restriction, fragment + ).nearest_to_text("one") + elif transition == "fts_to_hybrid": + query = _apply_fragment_restriction( + table.query().nearest_to_text("one"), restriction, fragment + ).nearest_to([0.0, 0.0]) + else: + query = _apply_fragment_restriction( + table.query().nearest_to([0.0, 0.0]), restriction, fragment + ).nearest_to_text("one") + + with pytest.raises(NotImplementedError, match="fragment selection"): + await query.to_arrow() + @pytest.mark.asyncio async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async): diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a2a26b595..ad46b5d3b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -4163,6 +4163,36 @@ def query_test_table( yield table +def test_remote_fragment_constraints_fail_before_query(): + query_calls = 0 + + def query_handler(body): + nonlocal query_calls + query_calls += 1 + return pa.table({"text": ["unexpected"]}) + + with query_test_table(query_handler) as table: + with pytest.raises(NotImplementedError, match="fragment selection"): + table.search().fragment_ids([0]).to_arrow() + + assert query_calls == 0 + + +def test_remote_fts_count_rows_rejects_fragment_constraints(): + query_calls = 0 + + def query_handler(body): + nonlocal query_calls + query_calls += 1 + return pa.table({"text": ["unexpected"]}) + + with query_test_table(query_handler) as table: + with pytest.raises(NotImplementedError, match="fragment selection"): + table.search("hello", query_type="fts").fragment_ids([0]).count_rows() + + assert query_calls == 0 + + @pytest.mark.parametrize( "query,search_kwargs,expected_column", [ From 164aec17538b47b54d3e78643b3a32d76144d51a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:24:15 +0800 Subject: [PATCH 179/203] fix(python): start background event loop lazily (#5111) ## Summary Importing `lancedb` currently starts a daemon thread running a private asyncio loop, even when the process never performs a synchronous database operation. Start that loop on the first actual coroutine submission instead. Concurrent first callers share one initialization, and a forked child resets the singleton to the unstarted state without touching the inherited thread or lock, then starts fresh work lazily on first use. The Rust-side runtime and the existing fork/reopen contracts are unchanged. ## Validation - New import, first-use, concurrent first-use, and fork parent/child coverage passes. - Existing import, debugger-inspection, cancellation, and remote fork tests pass. - `ruff format --check .` and `ruff check .` pass. --- python/python/lancedb/background_loop.py | 62 +++-- python/python/tests/test_background_loop.py | 236 ++++++++++++++++++++ python/python/tests/test_remote_db.py | 6 +- 3 files changed, 285 insertions(+), 19 deletions(-) create mode 100644 python/python/tests/test_background_loop.py diff --git a/python/python/lancedb/background_loop.py b/python/python/lancedb/background_loop.py index 9e1fdfbd8..7e55e708b 100644 --- a/python/python/lancedb/background_loop.py +++ b/python/python/lancedb/background_loop.py @@ -13,22 +13,51 @@ class BackgroundEventLoop: A background event loop that can run futures. Used to bridge sync and async code, without messing with users event loops. + + The loop and its thread are created by the first call to :meth:`run`, not + by constructing this object, so importing lancedb does not leave an idle + background thread behind. """ def __init__(self): - self._start() + self.loop: asyncio.AbstractEventLoop | None = None + self.thread: threading.Thread | None = None + self._start_lock = threading.Lock() - def _start(self): - self.loop = asyncio.new_event_loop() - self.thread = threading.Thread( - target=self.loop.run_forever, - name="LanceDBBackgroundEventLoop", - daemon=True, - ) - self.thread.start() + def _start(self) -> asyncio.AbstractEventLoop: + loop = self.loop + if loop is not None: + return loop + with self._start_lock: + loop = self.loop + if loop is not None: + return loop + loop = asyncio.new_event_loop() + thread = threading.Thread( + target=loop.run_forever, + name="LanceDBBackgroundEventLoop", + daemon=True, + ) + thread.start() + # Publish the loop first and the thread last. Callers that reach + # _start while this is in progress wait on _start_lock, so they + # cannot observe a half-initialized loop/thread pair. + self.loop = loop + self.thread = thread + return loop + + def _reset_after_fork(self): + # Threads do not survive fork(). Reset to the unstarted state without + # calling into the inherited loop or thread: the thread is gone, and + # it may have held _start_lock when the fork happened. A fresh lock + # lets the child start a new loop on its first run(). + self.loop = None + self.thread = None + self._start_lock = threading.Lock() def run(self, future): - concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop) + loop = self._start() + concurrent_future = asyncio.run_coroutine_threadsafe(future, loop) try: return concurrent_future.result() except BaseException: @@ -60,12 +89,15 @@ _FORK_WARNED = False def _reset_after_fork(): - # Threads do not survive fork(), so the asyncio loop in LOOP.thread is - # dead in the child. Re-initialize the singleton in place so existing + # Threads do not survive fork(), so the loop in LOOP.thread is dead in + # the child. Reset the singleton in place so existing # `from .background_loop import LOOP` references in other modules see - # the new state. The Rust-side tokio runtime is reset analogously by a - # pthread_atfork hook installed in the _lancedb extension. - LOOP._start() + # the unstarted state and create a fresh loop on their first run(). Do + # not restart it here: the child may never use LanceDB, and the at-fork + # handler must not touch the vanished thread or acquire inherited locks. + # The Rust-side tokio runtime is reset analogously by a pthread_atfork + # hook installed in the _lancedb extension. + LOOP._reset_after_fork() # The embedding executor's worker threads are dead in the child as well. # Replace it with a fresh pool (threads are spawned lazily, so this is # cheap); we don't shut down the old one, since joining its dead workers diff --git a/python/python/tests/test_background_loop.py b/python/python/tests/test_background_loop.py new file mode 100644 index 000000000..52b8b1f73 --- /dev/null +++ b/python/python/tests/test_background_loop.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import multiprocessing as mp +import os +import subprocess +import sys +import textwrap +import traceback + +import pytest + + +BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop" + + +def _run_in_subprocess(code: str) -> subprocess.CompletedProcess: + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) + return subprocess.run( + [sys.executable, "-c", textwrap.dedent(code)], + check=False, + capture_output=True, + text=True, + env=env, + timeout=30, + ) + + +def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None: + assert result.returncode == 0, result.stderr or result.stdout + + +def test_import_and_inspection_do_not_start_background_loop(): + result = _run_in_subprocess( + f""" + import threading + + import lancedb + from lancedb.background_loop import BackgroundEventLoop, LOOP + + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + + assert LOOP.thread is None + assert LOOP.loop is None + assert background_threads() == [] + + # Inspecting a fresh instance is also side-effect free. + loop = BackgroundEventLoop() + assert loop.thread is None + assert loop.loop is None + assert background_threads() == [] + """ + ) + _assert_subprocess_ok(result) + + +def test_first_sync_call_starts_one_daemon_thread(): + result = _run_in_subprocess( + f""" + import threading + + import lancedb + from lancedb.background_loop import LOOP + + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + + assert LOOP.thread is None + assert LOOP.loop is None + + db = lancedb.connect("memory://") + assert db.table_names() == [] + + worker = LOOP.thread + assert worker is not None + assert worker is background_threads()[0] + assert len(background_threads()) == 1 + assert worker.daemon + assert worker.is_alive() + assert LOOP.loop is not None + """ + ) + _assert_subprocess_ok(result) + + +def test_concurrent_first_use_initializes_one_background_thread(): + result = _run_in_subprocess( + f""" + import asyncio + import threading + + from lancedb.background_loop import LOOP + + worker_count = 8 + barrier = threading.Barrier(worker_count) + results = [] + errors = [] + results_lock = threading.Lock() + + def submit(index): + try: + barrier.wait(timeout=10) + value = LOOP.run(asyncio.sleep(0.05, result=index)) + with results_lock: + results.append(value) + except BaseException as exc: + with results_lock: + errors.append(repr(exc)) + + threads = [ + threading.Thread(target=submit, args=(index,)) + for index in range(worker_count) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=20) + + assert all(not thread.is_alive() for thread in threads) + assert errors == [] + assert sorted(results) == list(range(worker_count)) + + background_threads = [ + thread + for thread in threading.enumerate() + if thread.name == {BACKGROUND_THREAD_NAME!r} + ] + assert len(background_threads) == 1 + assert background_threads[0].daemon + """ + ) + _assert_subprocess_ok(result) + + +def _fork_child_starts_lazily(queue): + def background_threads(): + import threading + + return [ + thread + for thread in threading.enumerate() + if thread.name == BACKGROUND_THREAD_NAME + ] + + try: + from lancedb.background_loop import LOOP + + inherited_thread_is_none = LOOP.thread is None + inherited_loop_is_none = LOOP.loop is None + background_threads_before = [thread.name for thread in background_threads()] + + import lancedb + + db = lancedb.connect("memory://") + tables = db.table_names() + + worker = LOOP.thread + queue.put( + { + "error": None, + "inherited_thread_is_none": inherited_thread_is_none, + "inherited_loop_is_none": inherited_loop_is_none, + "background_threads_before": background_threads_before, + "tables": tables, + "thread_alive": False if worker is None else worker.is_alive(), + "thread_daemon": False if worker is None else worker.daemon, + "background_thread_count": len(background_threads()), + } + ) + except BaseException: + queue.put({"error": traceback.format_exc()}) + + +@pytest.mark.skipif( + sys.platform != "linux", + reason=( + "fork() is unavailable on Windows and unsafe on macOS " + "(Apple frameworks/TLS are not fork-safe)" + ), +) +def test_forked_child_starts_background_loop_lazily(): + import asyncio + + from lancedb.background_loop import LOOP + + assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before" + parent_thread = LOOP.thread + assert parent_thread is not None + + ctx = mp.get_context("fork") + queue = ctx.Queue() + + # Simulate forking while another thread held the initialization lock. The + # child must replace the inherited lock instead of trying to acquire it. + LOOP._start_lock.acquire() + try: + proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,)) + proc.start() + finally: + LOOP._start_lock.release() + + proc.join(timeout=20) + if proc.is_alive(): + proc.terminate() + proc.join(timeout=5) + if proc.is_alive(): + proc.kill() + proc.join() + pytest.fail("Forked child hung starting the background loop") + + assert proc.exitcode == 0, f"child exited with code {proc.exitcode}" + payload = queue.get(timeout=5) + queue.close() + assert payload["error"] is None, payload["error"] + assert payload["inherited_thread_is_none"] is True + assert payload["inherited_loop_is_none"] is True + assert payload["background_threads_before"] == [] + assert payload["tables"] == [] + assert payload["thread_alive"] is True + assert payload["thread_daemon"] is True + assert payload["background_thread_count"] == 1 + + # The child's reset must not disturb the parent's loop. + assert LOOP.thread is parent_thread + assert parent_thread.is_alive() + assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after" diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ad46b5d3b..e3ab986e2 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5370,12 +5370,10 @@ def test_background_loop_cancellation(exception): mock_future = MagicMock() mock_future.result.side_effect = exception() - with ( - patch.object(BackgroundEventLoop, "__init__", return_value=None), - patch("asyncio.run_coroutine_threadsafe", return_value=mock_future), - ): + with patch("asyncio.run_coroutine_threadsafe", return_value=mock_future): loop = BackgroundEventLoop() loop.loop = MagicMock() + loop.thread = MagicMock() with pytest.raises(exception): loop.run(None) mock_future.cancel.assert_called_once() From b9a2807049ee13ab3688672b2633c82831d2416f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:25:06 +0800 Subject: [PATCH 180/203] fix(python): accept column names in order_by and validate early (#5119) ## Summary - Accept column names, `(column_name, "asc"|"desc")` tuples, `ColumnOrdering`, and `{"column_name": ...}` dicts in both sync and async `order_by`, including mixed lists. - Distinguish a bare direction tuple from a list of column names by container type; `None` and `[]` clear ordering. - Validate at setter time with actionable errors for unknown dict keys and invalid directions. - Export `ColumnOrdering` from `lancedb` and document the accepted forms with examples. - Reject non-empty ordering on sync hybrid queries explicitly instead of silently ignoring it. Fixes OSS-3108. Namespace pushdown (OSS-3126) is intentionally out of scope. ## Tests - `python/tests/test_query.py` (214 passed, 1 skipped) - `python/tests/test_query.py -k order_by` (7 passed) - `python/tests/test_fts.py -k order_by` (2 passed) - `python/tests/test_remote_db.py::test_query_sync_maximal` - `pytest --doctest-modules python/lancedb/query.py` (21 passed) - `ruff format` / `ruff check` --- docs/src/python/python.md | 2 + python/python/lancedb/__init__.py | 1 + python/python/lancedb/query.py | 172 ++++++++++++++++++++++++++++-- python/python/tests/test_query.py | 107 +++++++++++++++++++ 4 files changed, 271 insertions(+), 11 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 752bf540f..122a73019 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -793,6 +793,8 @@ of raw SQL strings with [where][lancedb.query.LanceQueryBuilder.where] and ::: lancedb.query.Query +::: lancedb.query.ColumnOrdering + ::: lancedb.query.LanceQueryBuilder ::: lancedb.query.LanceVectorQueryBuilder diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 129a4b1c5..5095fddb0 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -79,6 +79,7 @@ from .materialized_view import ( from .view import ViewDescription as ViewDescription from .graph import PropertyGraph, PropertyGraphDescription from .table import AsyncTable, CompactionOptions, Table +from .query import ColumnOrdering as ColumnOrdering from .types import BaseTokenizerType from ._lancedb import Session from .namespace import ( diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 60fab3b8e..76d98e4f6 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -589,11 +589,107 @@ def ensure_vector_query( class ColumnOrdering(pydantic.BaseModel): + """A single sort key for ``order_by``. + + Attributes + ---------- + column_name: str + The column to sort by. + ascending: bool, default True + Sort ascending when true, descending otherwise. + nulls_first: bool, default False + Place null values before non-null values when true. + """ + column_name: str ascending: bool = True nulls_first: bool = False +_OrderingItem = Union[str, Tuple[str, str], ColumnOrdering, Dict[str, Any]] +_OrderingInput = Optional[Union[_OrderingItem, List[_OrderingItem]]] +_COLUMN_ORDERING_KEYS = frozenset({"column_name", "ascending", "nulls_first"}) +_ORDERING_EXAMPLE = '[{"column_name": "uris", "ascending": True}]' + + +def _normalize_ordering(ordering: _OrderingInput) -> Optional[List[ColumnOrdering]]: + """Normalize the accepted ``order_by`` inputs into ``ColumnOrdering`` models. + + ``None`` and an empty list clear the ordering. A tuple is always a single + ``(column_name, "asc"|"desc")`` pair, while a list is always a sequence of + separate orderings, so ``("a", "desc")`` and ``["a", "desc"]`` differ. + """ + if ordering is None: + return None + if isinstance(ordering, tuple): + items: List[Any] = [ordering] + elif isinstance(ordering, list): + items = ordering + else: + items = [ordering] + + normalized = [ + _normalize_ordering_item(item, index) for index, item in enumerate(items) + ] + return normalized or None + + +def _normalize_ordering_item(item: Any, index: int) -> ColumnOrdering: + prefix = f"order_by entry {index}" + if isinstance(item, ColumnOrdering): + if not item.column_name: + raise ValueError(f"{prefix} has an empty column_name") + return item + if isinstance(item, str): + if not item: + raise ValueError(f"{prefix} is an empty column name") + return ColumnOrdering(column_name=item) + if isinstance(item, tuple): + if len(item) != 2: + raise ValueError( + f"{prefix} must be a (column_name, 'asc'|'desc') tuple; got {item!r}" + ) + column_name, direction = item + if not isinstance(column_name, str) or not column_name: + raise ValueError( + f"{prefix} must start with a non-empty column name; got {item!r}" + ) + if not isinstance(direction, str) or direction.lower() not in ("asc", "desc"): + raise ValueError( + f"{prefix} has invalid direction {direction!r}; " + "expected 'asc' or 'desc'" + ) + return ColumnOrdering( + column_name=column_name, ascending=direction.lower() == "asc" + ) + if isinstance(item, dict): + unknown_keys = set(item) - _COLUMN_ORDERING_KEYS + if unknown_keys: + raise ValueError( + f"{prefix} has unsupported key(s) {sorted(map(str, unknown_keys))}; " + f"expected keys: {sorted(_COLUMN_ORDERING_KEYS)}. " + f"Example: {_ORDERING_EXAMPLE}" + ) + if "column_name" not in item: + raise ValueError( + f"{prefix} is missing 'column_name'. Example: {_ORDERING_EXAMPLE}" + ) + try: + normalized = ColumnOrdering(**item) + except pydantic.ValidationError as err: + raise ValueError( + f"{prefix} is not a valid ordering: {err}. Example: {_ORDERING_EXAMPLE}" + ) from err + if not normalized.column_name: + raise ValueError(f"{prefix} has an empty column_name") + return normalized + raise TypeError( + f"{prefix} must be a column name, a (column_name, 'asc'|'desc') tuple, " + f"a ColumnOrdering, or a dict with 'column_name'; " + f"got {type(item).__name__}" + ) + + class FullTextQueryType(str, Enum): MATCH = "match" MATCH_PHRASE = "match_phrase" @@ -1955,22 +2051,37 @@ class LanceQueryBuilder(ABC): self._ensure_fragment_constraints_supported("explain_plan()") return self._table._explain_plan(self.to_query_object(), verbose=verbose) - def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: + def order_by(self, ordering: _OrderingInput = None) -> Self: """ Set the ordering for the results. Parameters ---------- - ordering: Optional[List[ColumnOrdering]] - The ordering to use for the results. If None, then the default ordering - will be used. + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + The ordering to use for the results. Each entry can be a column + name, a ``(column_name, "asc"|"desc")`` tuple, a + [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a + ``column_name`` key. A bare tuple is a single direction pair, while + a list contains separate orderings, so ``("a", "desc")`` sorts by + ``a`` descending and ``["a", "desc"]`` sorts by both columns. + Pass ``None`` or an empty list to clear the ordering. Returns ------- LanceQueryBuilder The LanceQueryBuilder object. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table("ordering", [{"name": "b"}, {"name": "a"}]) + >>> table.search().order_by(["name"]).to_list() + [{'name': 'a'}, {'name': 'b'}] + >>> table.search().order_by([("name", "desc")]).to_list() + [{'name': 'b'}, {'name': 'a'}] """ - self._order_by = ordering + self._order_by = _normalize_ordering(ordering) return self def analyze_plan( @@ -2930,6 +3041,29 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): # the reranker's own use, so it cannot answer "did the caller ask?". self._caller_requested_row_id = False + def order_by(self, ordering: _OrderingInput = None) -> Self: + """ + Set the ordering for the results. + + Hybrid results are fused and reranked, so ordering the two search legs + does not define the final result order. Order the returned rows after + reranking instead. + + Parameters + ---------- + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + Must be ``None`` or an empty list. Any non-empty ordering raises + ``NotImplementedError``. + """ + normalized = _normalize_ordering(ordering) + if normalized: + raise NotImplementedError( + "order_by is not supported for hybrid queries; " + "sort the returned results after reranking instead." + ) + self._order_by = None + return self + def _validate_query(self, query, vector=None, text=None): if query is not None and (vector is not None or text is not None): raise ValueError( @@ -4434,20 +4568,36 @@ class AsyncStandardQuery(AsyncQueryBase): self._inner.offset(offset) return self - def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self: + def order_by(self, ordering: _OrderingInput = None) -> Self: """ Set the ordering for the results. Parameters ---------- - ordering: Optional[List[ColumnOrdering]] - The ordering to use for the results. If None, then the default ordering - will be used. + ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]] + The ordering to use for the results. Each entry can be a column + name, a ``(column_name, "asc"|"desc")`` tuple, a + [ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a + ``column_name`` key. A bare tuple is a single direction pair, while + a list contains separate orderings, so ``("a", "desc")`` sorts by + ``a`` descending and ``["a", "desc"]`` sorts by both columns. + Pass ``None`` or an empty list to clear the ordering. + + Examples + -------- + >>> import lancedb + >>> db = await lancedb.connect_async("memory://") # doctest: +SKIP + >>> table = await db.create_table( # doctest: +SKIP + ... "ordering", [{"name": "b"}, {"name": "a"}] + ... ) + >>> await table.query().order_by(["name"]).to_list() # doctest: +SKIP + [{'name': 'a'}, {'name': 'b'}] """ - if ordering is None: + normalized = _normalize_ordering(ordering) + if normalized is None: self._inner.order_by(None) else: - self._inner.order_by([o.model_dump() for o in ordering]) + self._inner.order_by([o.model_dump() for o in normalized]) return self def fast_search(self) -> Self: diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 88bed9c1f..82b40f9c6 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1042,6 +1042,113 @@ async def test_order_by_async_query(mem_db_async: AsyncConnection): ] +def test_order_by_accepts_strings_tuples_and_dicts(mem_db): + table = mem_db.create_table( + "test_order_by_forms", + pa.table( + { + "group": [1, 1, 1, 2], + "score": [None, 1.0, 1.0, 0.5], + "name": ["z", "b", "a", "c"], + } + ), + ) + + rows = ( + table.search() + .order_by( + [ + "group", + ("score", "desc"), + {"column_name": "name", "ascending": True}, + ] + ) + .select(["name"]) + .to_list() + ) + assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}] + + # A bare tuple is one direction pair; a list holds separate orderings. + assert table.search().order_by("name").select(["name"]).to_list() == [ + {"name": "a"}, + {"name": "b"}, + {"name": "c"}, + {"name": "z"}, + ] + assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [ + {"name": "z"}, + {"name": "c"}, + {"name": "b"}, + {"name": "a"}, + ] + assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [ + {"name": "a"}, + {"name": "b"}, + {"name": "z"}, + {"name": "c"}, + ] + + +def test_order_by_clears_with_none_and_empty_list(mem_db): + table = mem_db.create_table("test_order_by_clear", [{"name": "a"}]) + + query = table.search().order_by("name") + assert query.to_query_object().order_by is not None + assert query.order_by(None).to_query_object().order_by is None + assert query.order_by([]).to_query_object().order_by is None + + +def test_order_by_rejects_invalid_input_early(mem_db): + table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}]) + + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + table.search().order_by([{"column": "name", "ascending": True}]) + with pytest.raises(ValueError, match="missing 'column_name'"): + table.search().order_by({"ascending": True}) + with pytest.raises(ValueError, match="invalid direction"): + table.search().order_by([("name", "sideways")]) + with pytest.raises(TypeError, match="must be a column name"): + table.search().order_by([42]) + + +@pytest.mark.asyncio +async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection): + table = await mem_db_async.create_table( + "test_order_by_async_forms", + pa.table({"name": ["z", "b", "a", "c"]}), + ) + + rows = await ( + table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow() + ) + assert rows["name"].to_pylist() == ["z", "c", "b", "a"] + + query = table.query().order_by("name") + assert query.to_query_object().order_by is not None + assert query.order_by(None).to_query_object().order_by is None + assert query.order_by([]).to_query_object().order_by is None + + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + table.query().order_by([{"column": "name"}]) + + +def test_column_ordering_is_exported_at_top_level(): + assert lancedb.ColumnOrdering is ColumnOrdering + + +def test_order_by_hybrid_sync_is_explicitly_unsupported(table): + query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a") + + with pytest.raises(NotImplementedError, match="order_by is not supported"): + query.order_by(["id"]) + + # Clearing is still allowed, and invalid input still fails on its own terms. + query.order_by(None) + query.order_by([]) + with pytest.raises(ValueError, match="unsupported key\\(s\\)"): + query.order_by([{"column": "id"}]) + + def test_query_builder(table): rs = ( LanceVectorQueryBuilder(table, [0, 0], "vector") From 121de72cc449e7aacf88e0f66a6a6c64018a6e19 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:26:40 +0800 Subject: [PATCH 181/203] fix(python): keep Permutation builder copies shallow (#5121) ## Summary `Permutation`'s `with_*` builders use `copy.copy`, but `Permutation` had no `__copy__`. Python therefore fell back to `__getstate__`/`__setstate__`, which calls `permutation_table.to_arrow()` (unsupported for remote tables) and rebuilds the base table and reader on every builder call. Add a targeted `__copy__` that shallow-copies the instance state. The copy keeps the existing table handles and reader and can change its own attributes without affecting the original. Pickle serialization and persist semantics are unchanged. Refs OSS-2857. The persist feature remains open. --- python/python/lancedb/permutation.py | 14 ++++++++ python/python/tests/test_permutation.py | 45 ++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index c8e6f84e0..fcdbaa397 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -788,6 +788,20 @@ class Permutation: self.reader = None self._pid = None + def __copy__(self) -> "Permutation": + """Return a shallow copy without going through the pickle path. + + The ``with_*`` builders use ``copy.copy`` to derive a new permutation. + The default copy protocol would use ``__getstate__``/``__setstate__``, + which materializes the permutation table with ``to_arrow()`` (not + supported for remote tables) and rebuilds the base table and reader. + A shallow copy instead keeps the existing table handles and reader; + the caller replaces only the attribute it is changing. + """ + new = self.__class__.__new__(self.__class__) + new.__dict__ = self.__dict__.copy() + return new + def _ensure_open(self) -> None: pid = os.getpid() if self.reader is not None and getattr(self, "_pid", None) == pid: diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 165172622..a52aa420e 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -7,7 +7,13 @@ import pytest from lancedb import DBConnection, Table, connect from lancedb.background_loop import LOOP -from lancedb.permutation import Permutation, Permutations, permutation_builder +from lancedb.permutation import ( + DEFAULT_BATCH_SIZE, + Permutation, + Permutations, + Transforms, + permutation_builder, +) from utils import ( MockPermutationServer, assert_server_safe_row_id_requests, @@ -81,6 +87,43 @@ def test_pickled_permutation_reads_pinned_version(tmp_path): assert sorted(row["idx"] for row in rows) == list(range(20)) +def test_builder_copy_is_shallow_and_does_not_materialize( + some_table: Table, some_perm_table: Table, monkeypatch +): + """The with_* builders use copy.copy, which must stay a shallow copy. + + Without ``Permutation.__copy__`` the copy falls back to the pickle path, + which materializes the permutation table with ``to_arrow()`` before + rebuilding the base table and reader. That is expensive for in-memory + tables and fails for remote permutation tables. + """ + permutation = Permutation.from_tables(some_table, some_perm_table) + + def fail_materialize(*args, **kwargs): + raise AssertionError("copy.copy must not materialize the permutation table") + + def fail_getstate(_self): + raise AssertionError("copy.copy must not pickle the permutation") + + monkeypatch.setattr(permutation.permutation_table, "to_arrow", fail_materialize) + monkeypatch.setattr(Permutation, "__getstate__", fail_getstate) + + formatted = permutation.with_format("arrow") + assert formatted is not permutation + assert formatted.transform_fn is Transforms.arrow2arrow + assert permutation.transform_fn is Transforms.arrow2python + assert formatted.base_table is permutation.base_table + assert formatted.permutation_table is permutation.permutation_table + assert formatted.reader is permutation.reader + + resized = permutation.with_batch_size(7) + assert resized.batch_size == 7 + assert permutation.batch_size == DEFAULT_BATCH_SIZE + assert resized.selection is permutation.selection + resized.selection = {"id": "id"} + assert permutation.selection is not resized.selection + + def test_split_random_counts(mem_db): """Test random splitting with absolute counts.""" tbl = mem_db.create_table( From 3c9851966cab18b4290a0e0806524e809a14b1f6 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:28:47 +0800 Subject: [PATCH 182/203] chore(python): clarify package summary and search keywords (#5124) Replace the placeholder `lancedb` PyPI summary with factual wording covering vector, full-text, and hybrid search on Lance tables. Narrow the keywords to `lance`, `vector-search`, `full-text-search`, `dataset`, and `versioning`. Metadata-only change; runtime behavior is unchanged. Refs OSS-2883 --- python/pyproject.toml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index ff64d9772..69130e16c 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -12,17 +12,17 @@ dependencies = [ "tqdm>=4.27.0", "lance-namespace>=0.13.0" ] -description = "lancedb" +description = "Embedded database for vector, full-text and hybrid search on Lance tables" authors = [{ name = "LanceDB Devs", email = "dev@lancedb.com" }] license = { file = "LICENSE" } readme = "README.md" requires-python = ">=3.10" keywords = [ - "data-format", - "data-science", - "machine-learning", - "arrow", - "data-analytics", + "lance", + "vector-search", + "full-text-search", + "dataset", + "versioning", ] classifiers = [ "Development Status :: 3 - Alpha", From 56638a9e71d89d043d2e680e4fbf8008c42607f5 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:34:49 +0800 Subject: [PATCH 183/203] fix(python): reject Expr inputs on unregistered Function definitions (#5125) `FunctionDefinition.__call__` ran the decorated Python callable with any value it was given, so `my_function(value=col("value"))` executed user code against an `Expr` or silently returned one, with errors such as `float() argument must be a string or a real number, not 'Expr'`. A column reference is not a local value: it binds only on a registered `FunctionVersion`. An unregistered definition now rejects `Expr` positional and keyword arguments with `TypeError` before the callable runs, and names the supported path: `create_function`/`create_function_async`, then `col(...)` on the returned version. Plain Python and Arrow arguments, and the class `__init__`/`__call__` lifecycle, are unchanged. The Function authoring guide's batch example did not register either: a `pyarrow.Array` annotation carries no element types, so `score_batch` raised `TypeError` for missing `input_schema` and `output_schema`, and the page claimed one `pa.RecordBatch` parameter could read several columns. The example now passes both schemas, shows one `pa.Array` parameter per input column for multi-column functions, and states that `input_schema` matches parameters one to one, so a `RecordBatch` parameter binds one input column. The GPU class example on the same page had the same missing-schema defect and is fixed too. Compatibility: code that passed `col(...)` to an unregistered definition now gets `TypeError` instead of running user code against an `Expr`. That call was never a supported binding and produced no usable result; no supported call changes. --- docs/src/python/python.md | 4 +- docs/web/curation/create-function.mdx | 35 +++++++++++++-- python/python/lancedb/functions.py | 28 +++++++++++- .../python/tests/test_function_packaging.py | 43 +++++++++++++++++++ 4 files changed, 103 insertions(+), 7 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 122a73019..dfd2752b8 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -449,7 +449,9 @@ and then call the returned instance; call `close()` if the class defines it. Thi path uses the current Python environment and does not create a registered `FunctionVersion`, build the declared remote runtime, resolve Secrets, or execute the remote Arrow adapter. A registered `FunctionVersion` call instead binds -`col(...)` inputs and returns a remote `FunctionApplication`. +`col(...)` inputs and returns a remote `FunctionApplication`. Passing an `Expr` +such as `col("value")` to a definition raises `TypeError` before the callable +runs; bind it on the registered `FunctionVersion` instead. ```python from lancedb import function diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 0342849b4..109846bea 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -98,10 +98,12 @@ is not a substitute for `lancedb.blob`. ## 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: +A function is called once per batch instead of once per row when all of its +parameters are annotated `pyarrow.Array`. Those annotations say that a whole +column arrives in one call, but not which Arrow type the column holds, so a +batch function also passes `input_schema` and `output_schema`; every field of +`input_schema` matches a parameter by name and by order. The same doubling +logic, vectorized over a whole batch at once: ```python Python icon="python" @@ -111,6 +113,8 @@ from lancedb import function @function( pip=["numpy==2.2.0"], + input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), + output_schema=pa.float64(), batch_size=32, max_concurrency=4, row_timeout_seconds=90, @@ -120,6 +124,27 @@ def score_batch(value: pa.Array) -> pa.Array: ``` +Read several columns in one call by taking one `pa.Array` parameter per +column, with one schema field for each: + +```python +@function( + input_schema=pa.schema([ + pa.field("value", pa.float64(), nullable=False), + pa.field("weight", pa.float64(), nullable=False), + ]), + output_schema=pa.float64(), +) +def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array: + return pc.multiply(value, weight) +``` + +A single `pyarrow.RecordBatch` parameter is also a batch function, but it does +not read several columns at once: `input_schema` declares one field per +parameter, so a `RecordBatch` parameter binds one input column and receives +that column as a batch. A schema with more fields than the callable has +parameters is rejected at decoration. + 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. @@ -185,6 +210,8 @@ gpu_class = next( gpu=True, gpu_class=gpu_class, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], + input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]), + output_schema=pa.list_(pa.float32(), 384), ) class embed_text: def __init__(self, model_name: str = "all-MiniLM-L6-v2"): diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 2d369e3ec..43226fdf3 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -3182,6 +3182,12 @@ class FunctionDefinition: remote application or build the declared remote runtime, and it does not need the private implementation attribute. + Arguments to this call are Python and Arrow values. An + [Expr][lancedb.expr.Expr] argument, such as ``col("value")``, is a column + binding that only a registered + [FunctionVersion][lancedb.functions.FunctionVersion] can carry, so this + call rejects it with ``TypeError`` instead of running the callable. + Remote execution adapts the callable to the internal Arrow batch ABI described by the registration artifact. By default it invokes the callable once per row. A callable whose parameters are all annotated as @@ -3451,6 +3457,16 @@ class FunctionDefinition: return self._request._copy(update={"secret_bindings": resolved}) def __call__(self, *args, **kwargs): + from lancedb.expr import Expr + + if any(isinstance(value, Expr) for value in (*args, *kwargs.values())): + raise TypeError( + "a FunctionDefinition runs locally on Python and Arrow values; " + "an Expr input binds only on a registered FunctionVersion. " + "Register the definition with create_function or " + "create_function_async, then bind col(...) on the returned " + "version." + ) return self._function(*args, **kwargs) @@ -3541,7 +3557,12 @@ def function( 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: + ``__call__`` method. Each ``input_schema`` field names one parameter, so + several input columns take one ``pyarrow.Array`` parameter each, while a + single ``pyarrow.RecordBatch`` parameter binds one input column and + receives it as a batch. The + [Function authoring guide](https://lancedb.com/docs/curation/create-function#batch) + has the worked examples. 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, @@ -3803,7 +3824,10 @@ def function( remote environment, resolve Secrets, or run the remote Arrow adapter or sandbox. A registered ``FunctionVersion`` call is different: it binds ``col(...)`` inputs and returns a remote - [FunctionApplication][lancedb.functions.FunctionApplication]. + [FunctionApplication][lancedb.functions.FunctionApplication]. Passing an + [Expr][lancedb.expr.Expr] to a definition raises ``TypeError`` before the + callable runs, because a column reference binds only on a registered + version. ```python scaled = scale(factor=2.0) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 874dd809f..8d2d282a9 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,6 +20,7 @@ from typing import Annotated, Optional, get_type_hints import numpy as np import pyarrow as pa +import pyarrow.compute as pc import pytest from lancedb import col @@ -582,6 +583,48 @@ def test_array_batch_annotations_accept_explicit_schemas(): assert identity(values).equals(values) +def test_batch_functions_take_one_array_parameter_per_input_column(): + @function( + input_schema=pa.schema( + [ + pa.field("value", pa.float64(), nullable=False), + pa.field("weight", pa.float64(), nullable=False), + ] + ), + output_schema=pa.float64(), + ) + def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array: + return pc.multiply(value, weight) + + signature = weighted_score.registration_request.signature + assert [parameter.name for parameter in signature.inputs] == ["value", "weight"] + result = weighted_score(pa.array([1.0, 2.0]), pa.array([3.0, 4.0])) + assert result.to_pylist() == [3.0, 8.0] + + +@pytest.mark.parametrize( + "invoke", + [ + lambda definition: definition(col("value")), + lambda definition: definition(value=col("value")), + lambda definition: definition(value=col("value") * 2), + ], + ids=["positional", "keyword", "derived"], +) +def test_definition_calls_reject_expr_inputs_before_user_code(invoke): + @function + def double(value: float) -> float: + raise AssertionError("user code ran") + + with pytest.raises(TypeError, match="registered FunctionVersion"): + invoke(double) + + +def test_class_definition_binds_initialization_only_on_a_version(): + with pytest.raises(TypeError, match="registered FunctionVersion"): + scale(factor=col("factor"), label="x") + + @pytest.mark.parametrize("class_function", [False, True]) @pytest.mark.parametrize("postponed", [False, True]) @pytest.mark.parametrize( From f460c34bdd62e03145b8bddd1670c734829648ef Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:36:29 +0800 Subject: [PATCH 184/203] fix: pin native permutation builds to one snapshot (#5126) ## Problem `PermutationBuilder` pinned backends that returned a snapshot handle, but `NativeTable` returned `None`. A namespace-backed latest handle could count and record the local table version while its row-id scan was pushed to a server that returned newer rows. A native handle with read refresh enabled could also advance between the version read, count, and scan. The result was a permutation whose recorded version, row count, and row ids did not describe one snapshot. ## Fix - Return an independent pinned native handle from `NativeTable::snapshot_at_current_version()`, so one build's version, count, and scan share a dataset. - Report `scan_order_is_deterministic()` false when a main/latest native handle may push queries to a namespace server, whose `QueryTable` request carries no order. Local scans remain deterministic at a fixed version. Refs OSS-3109 The query `scan_in_order` API and Python dispatch remain a separate slice. --- .../src/dataloader/permutation/builder.rs | 187 +++++++++++++++++- .../src/dataloader/permutation/split.rs | 4 +- rust/lancedb/src/table.rs | 22 ++- 3 files changed, 204 insertions(+), 9 deletions(-) diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 15f8c3cd3..770a956eb 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -249,10 +249,10 @@ impl PermutationBuilder { /// Builds the permutation table and stores it in the given database. pub async fn build(mut self) -> Result
  • { - // Remote tables resolve latest independently for each request. Use a - // separate pinned handle so count, projection, and scan all refer to one - // snapshot without changing the caller's table checkout state. Native - // tables return `None` here and retain their existing behavior. + // Remote tables resolve latest independently for each request, and a + // native handle can refresh or answer a query from a namespace server. + // Use a separate pinned handle so count, projection, and scan all refer + // to one snapshot without changing the caller's table checkout state. if let Some(snapshot) = self .base_table .base_table() @@ -396,6 +396,51 @@ mod tests { use super::*; + /// Stands in for a namespace server whose table has advanced past the local + /// dataset. A pushed-down query reads this newer row instead of the local + /// snapshot. + #[derive(Debug, Default)] + struct ServerLatestNamespace { + query_table_calls: std::sync::atomic::AtomicUsize, + latest_row_id: u64, + } + + #[async_trait::async_trait] + impl lance_namespace::LanceNamespace for ServerLatestNamespace { + fn namespace_id(&self) -> String { + "server-latest".to_string() + } + + async fn query_table( + &self, + _request: lance_namespace::models::QueryTableRequest, + ) -> lance::Result { + self.query_table_calls + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + use arrow_array::UInt64Array; + use arrow_schema::{DataType, Field, Schema}; + + let schema = Arc::new(Schema::new(vec![Field::new( + ROW_ID, + DataType::UInt64, + false, + )])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(UInt64Array::from(vec![self.latest_row_id]))], + ) + .unwrap(); + let mut body = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + Ok(bytes::Bytes::from(body)) + } + } + #[tokio::test] async fn test_permutation_table_only_stores_row_id_and_split_id() { let temp_dir = tempfile::tempdir().unwrap(); @@ -451,6 +496,140 @@ mod tests { // Native tables skip the canonicalizing sort; remote does not. assert!(table.base_table().scan_order_is_deterministic()); + + // A main/latest handle may answer from a namespace server, and its + // QueryTable request carries no order. The local native scan guarantee + // does not extend to that path. + let mut pushed_down = table.as_native().unwrap().clone(); + pushed_down.namespace_client = Some(Arc::new(ServerLatestNamespace::default())); + pushed_down + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let pushed_down: Arc = Arc::new(pushed_down); + let pushed_down = Table::from(pushed_down); + assert!(!pushed_down.base_table().scan_order_is_deterministic()); + } + + /// The builder must pin one native snapshot before it counts or scans. A + /// namespace-backed latest handle can otherwise count local rows, scan + /// server-latest rows, and record the local version as if they agreed. + #[tokio::test] + async fn test_native_permutation_builder_pins_namespace_pushdown() { + use std::sync::atomic::Ordering; + + use arrow_array::{cast::AsArray, types::UInt64Type}; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let namespace = Arc::new(ServerLatestNamespace { + latest_row_id: 10, + ..Default::default() + }); + let mut native = table.as_native().unwrap().clone(); + native.namespace_client = Some(namespace.clone()); + native + .pushdown_operations + .insert(crate::connection::NamespaceClientPushdownOperation::QueryTable); + let native: Arc = Arc::new(native); + let table = Table::from(native); + + let permutation = PermutationBuilder::new(table.clone()) + .build() + .await + .unwrap(); + + assert_eq!( + namespace.query_table_calls.load(Ordering::SeqCst), + 0, + "the builder must read its pinned local snapshot, not server-latest rows" + ); + assert_eq!(permutation.count_rows(None).await.unwrap(), 10); + + let batches: Vec = permutation + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch[SRC_ROW_ID_COL] + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(ids, (0..10).collect::>()); + + let recorded = permutation + .schema() + .await + .unwrap() + .metadata + .get(BASE_VERSION_CONFIG_KEY) + .expect("permutation should record its base version") + .parse::() + .unwrap(); + assert_eq!(recorded, table.version().await.unwrap()); + } + + /// `snapshot_at_current_version` is the builder's one-snapshot hook. With + /// read refresh enabled, the caller can advance while the pin stays put. + #[tokio::test] + async fn test_native_snapshot_pins_count_scan_and_version() { + use std::time::Duration; + + use crate::connection::ConnectBuilder; + + let temp_dir = tempfile::tempdir().unwrap(); + let db = ConnectBuilder::new(temp_dir.path().to_str().unwrap()) + .read_consistency_interval(Duration::ZERO) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let snapshot = table + .base_table() + .snapshot_at_current_version() + .await + .unwrap() + .expect("native tables should provide an independent pinned handle"); + let version = snapshot.version().await.unwrap(); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(5), BatchCount::from(1)); + table.add(more_data).execute().await.unwrap(); + assert!(table.version().await.unwrap() > version); + + assert_eq!(snapshot.version().await.unwrap(), version); + assert_eq!(snapshot.count_rows(None).await.unwrap(), 10); + let batches: Vec = Table::from(snapshot) + .query() + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 10); + assert_eq!(table.count_rows(None).await.unwrap(), 15); } #[cfg(feature = "remote")] diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index b4e5deac1..0fb7f669b 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -406,8 +406,8 @@ impl Splitter { .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 + // separately computed `num_rows` count checked by `validate`. `apply` does + // not require its caller to pass a count and scan from 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; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4d663649e..045517968 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4172,10 +4172,18 @@ impl BaseTable for NativeTable { self } - /// Lance scans fragments in order (`Scanner::ordered` defaults to true, and we - /// never clear it), so repeated identical scans agree. + /// Lance scans fragments in order at one dataset version (`Scanner::ordered` + /// defaults to true, and we never clear it), so repeated scans of a local + /// handle agree. A main/latest handle that may push its query to a namespace + /// server does not: the QueryTable request carries no order. fn scan_order_is_deterministic(&self) -> bool { - true + let may_push_down_namespace_query = self.namespace_client.is_some() + && self + .pushdown_operations + .contains(&NamespaceClientPushdownOperation::QueryTable) + && self.dataset.current_branch().is_none() + && self.dataset.time_travel_version().is_none(); + !may_push_down_namespace_query } fn name(&self) -> &str { @@ -4217,6 +4225,14 @@ impl BaseTable for NativeTable { })) } + async fn snapshot_at_current_version(&self) -> Result>> { + // A native handle can advance between requests when read consistency + // refreshes, and a namespace-backed handle can answer a query from a + // different snapshot than the local count/version. Hand the caller an + // independent time-travel handle so one build sees one dataset. + Ok(Some(self.checkout_current().await?)) + } + async fn checkout(&self, version: u64) -> Result<()> { self.dataset.as_time_travel(version).await } From ea4f1a38cf720ba7dd9d7c7d1350f8dfca99d293 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:45:03 +0800 Subject: [PATCH 185/203] fix: keep nonempty order_by out of namespace query pushdown (#5122) ## Problem With namespace `QueryTable` pushdown enabled, a query with a nonempty `order_by` was sent to the namespace server even though the request schema has no `order_by` field. With `limit(1)` this returned the wrong top row instead of the requested ordering. ## Fix Treat a nonempty `order_by` as requiring local execution in both the Python and Rust namespace pushdown gates. `None` or an empty ordering still uses pushdown. Local execution preserves branch, version and RTE semantics; if local storage cannot be read, the query fails explicitly rather than silently dropping the ordering. ## Validation - Public Python sync `search().order_by(...).limit(1).to_arrow()` and async `query().order_by(...).limit(1).to_arrow()` against a namespace mock: returned id 1 with zero pushdown calls. - `python/tests/test_namespace.py`: 83 passed. - Rust namespace pushdown tests: 5 passed; `table::query::tests`: 21 passed. - `cargo fmt`, `cargo clippy`, and Ruff clean. Fixes [OSS-3126](https://linear.app/lancedb/issue/OSS-3126/bug-namespace-querytable-pushdown-silently-drops-order-by). --- python/python/lancedb/namespace.py | 16 ++++-- python/python/lancedb/table.py | 3 ++ python/python/tests/test_namespace.py | 37 +++++++++++++- rust/lancedb/src/connection.rs | 7 +++ rust/lancedb/src/table/query.rs | 70 +++++++++++++++++++++++++-- 5 files changed, 124 insertions(+), 9 deletions(-) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 1de49d935..735eab51e 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -509,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection): Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1208,7 +1210,9 @@ class AsyncLanceNamespaceDBConnection: Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1811,7 +1815,9 @@ def connect_namespace( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access the + table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1902,7 +1908,9 @@ def connect_namespace_async( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access the + table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ea9dee024..492526344 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -146,6 +146,9 @@ def _requires_local_namespace_execution(query: Query) -> bool: or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None + # The namespace QueryTable request has no order_by field. Pushing a + # nonempty ordering down would drop it and return the wrong top-K rows. + or bool(query.order_by) or ( query.full_text_query is not None and query.fast_search is True diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index c965618cd..937572cc0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -29,7 +29,7 @@ from lancedb.namespace import ( LanceNamespaceDBConnection, _query_to_namespace_request, ) -from lancedb.query import FullTextSearchQuery, Query +from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query from lancedb.table import AsyncTable, LanceTable @@ -1772,6 +1772,23 @@ class TestPushdownOperations: assert request.maximum_nprobes == 0 assert request.to_dict()["maximum_nprobes"] == 0 + def test_lance_table_order_by_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = lancedb.connect(str(tmp_path / "db")) + table = db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = table._execute_query( + Query(limit=1, order_by=[ColumnOrdering(column_name="id")]) + ).read_all() + + # Pushing this query down would drop order_by and return id 3. + assert result.column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1834,6 +1851,24 @@ class TestAsyncPushdownOperations: assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K] assert all(r.k <= 2**31 - 1 for r in namespace_client.requests) + async def test_async_table_order_by_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = await lancedb.connect_async(str(tmp_path / "db")) + table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = await table._execute_query( + Query(limit=1, order_by=[ColumnOrdering(column_name="id")]) + ) + + # Pushing this query down would drop order_by and return id 3. + batches = await result.read_all() + assert pa.Table.from_batches(batches).column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.parametrize( "query_kwargs", [ diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index db6aa2ba8..d413b2b78 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -2138,6 +2138,9 @@ use std::collections::HashSet; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum NamespaceClientPushdownOperation { /// Execute queries on the namespace server via `query_table()` instead of locally. + /// + /// Queries with a nonempty `order_by` execute locally and require client access + /// to the table storage. QueryTable, /// Execute table creation on the namespace server via `create_table()` /// instead of using `declare_table` + local write. @@ -2253,6 +2256,10 @@ impl ConnectNamespaceBuilder { /// - [`NamespaceClientPushdownOperation::QueryTable`]: Execute queries via `namespace.query_table()` /// - [`NamespaceClientPushdownOperation::CreateTable`]: Execute table creation via `namespace.create_table()` /// + /// Some query options cannot be represented in the namespace request. A query + /// with a nonempty `order_by` executes locally and requires client access to + /// the table storage. + /// /// By default, no operations are pushed down (all executed locally). pub fn pushdown_operation(mut self, operation: NamespaceClientPushdownOperation) -> Self { self.pushdown_operations.insert(operation); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 7d98dc001..6789714e1 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -120,10 +120,18 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R } fn requires_local_namespace_execution(query: &AnyQuery) -> bool { - // The namespace QueryTable request cannot represent approx_mode, search_effort or use_rte. - // For use_rte that is worse than a tuning miss: RTE read routing lives only - // in `create_plan`, so a pushed-down query would return stale base-only data. - if query.base().use_rte.is_some() || query.base().has_take() { + // The namespace QueryTable request cannot represent approx_mode, search_effort, + // use_rte or order_by. For use_rte that is worse than a tuning miss: RTE read + // routing lives only in `create_plan`, so a pushed-down query would return + // stale base-only data. A dropped order_by would return the wrong top-K rows. + if query.base().use_rte.is_some() + || query.base().has_take() + || query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { return true; } if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) @@ -1858,6 +1866,60 @@ mod tests { assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn test_execute_query_order_by_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use crate::table::query::execute_query; + use arrow_array::{Int32Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + // Insertion order differs from ascending id, so a pushed-down query that + // drops order_by would return 3 instead of the correct top-1 row 1. + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3, 1, 2]))]).unwrap(); + + let table = conn + .create_table("test_order_by_namespace_fallback", vec![batch]) + .execute() + .await + .unwrap(); + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + limit: Some(1), + order_by: Some(vec![ColumnOrdering::asc_nulls_first("id".to_string())]), + ..Default::default() + }); + + let stream = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap(); + let batches = stream.try_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, vec![1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn test_query_snapshot_disables_namespace_pushdown() { use crate::connect; From df8bf9ea5a3eb57a884da7710247afb4d97085ae Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:47:50 +0800 Subject: [PATCH 186/203] fix: reject unsupported layout options in remote add (#5118) ## Summary `RemoteTable::add` only transmits the write mode to the remote insert endpoint, so non-default layout options in `lance_write_params` were silently ignored. This rejects them before schema lookup and before either single-request or multipart transmission. Guarded fields: - `max_rows_per_file` - `max_rows_per_group` - `max_bytes_per_file` Default `WriteParams` and `mode = Overwrite` keep their existing behavior. Other write parameters remain untouched. ## Tests - Focused remote-table regressions cover each guarded field on both single-request and multipart paths, and verify default, `Create`, `Append`, and `Overwrite` behavior. - `cargo fmt --all -- --check` - `cargo clippy --quiet --features remote -p lancedb --tests` - Targeted `cargo test --features remote -p lancedb --lib remote::table::tests::...` Refs OSS-2882. This is the P0 hotfix; the table-level persistent layout design remains tracked separately in OSS-2882 and is not closed by this PR. --- rust/lancedb/src/remote/table.rs | 131 ++++++++++++++++++++++++++++++- rust/lancedb/src/table.rs | 4 + 2 files changed, 134 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 54b7ea7b2..4c7f3a105 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -79,7 +79,7 @@ use http::{HeaderName, StatusCode}; use lance::arrow::json::{JsonDataType, JsonSchema}; use lance::dataset::refs::TagContents; use lance::dataset::scanner::DatasetRecordBatchStream; -use lance::dataset::{ColumnAlteration, NewColumnTransform, Version}; +use lance::dataset::{ColumnAlteration, NewColumnTransform, Version, WriteParams}; use lance_core::datatypes::Schema as LanceSchema; use lance_datafusion::exec::{OneShotExec, execute_plan}; use reqwest::{RequestBuilder, Response}; @@ -2647,6 +2647,44 @@ impl RemoteTable { } } +/// Reject per-write layout options that the remote insert protocol cannot carry. +/// +/// Remote inserts only transmit `mode`; file and row-group sizing is managed by +/// the server. Silently dropping these values would produce a different layout +/// than the caller requested. +fn ensure_remote_add_supports_write_params(write_params: Option<&WriteParams>) -> Result<()> { + let Some(write_params) = write_params else { + return Ok(()); + }; + let defaults = WriteParams::default(); + let unsupported: Vec<&str> = [ + ( + "max_rows_per_file", + write_params.max_rows_per_file != defaults.max_rows_per_file, + ), + ( + "max_rows_per_group", + write_params.max_rows_per_group != defaults.max_rows_per_group, + ), + ( + "max_bytes_per_file", + write_params.max_bytes_per_file != defaults.max_bytes_per_file, + ), + ] + .into_iter() + .filter_map(|(name, differs)| differs.then_some(name)) + .collect(); + if unsupported.is_empty() { + return Ok(()); + } + Err(Error::NotSupported { + message: format!( + "write_options.lance_write_params layout options are not supported when adding data to a LanceDB Enterprise table: {}; only mode=overwrite is supported", + unsupported.join(", ") + ), + }) +} + #[async_trait] impl BaseTable for RemoteTable { fn as_any(&self) -> &dyn std::any::Any { @@ -3301,6 +3339,7 @@ impl BaseTable for RemoteTable { } async fn add(&self, mut add: AddDataBuilder) -> Result { self.check_mutable().await?; + ensure_remote_add_supports_write_params(add.write_options.lance_write_params.as_ref())?; if add.allow_external_blob_outside_bases { return Err(Error::NotSupported { @@ -5460,6 +5499,96 @@ mod tests { assert!(err.to_string().contains("LanceDB Embedded")); } + #[rstest] + #[case("max_rows_per_file")] + #[case("max_rows_per_group")] + #[case("max_bytes_per_file")] + #[tokio::test] + async fn add_rejects_layout_write_params_before_any_request(#[case] field: &str) { + for write_parallelism in [None, Some(2)] { + let table = Table::new_with_handler::("my_table", |request| { + panic!("Unexpected request: {}", request.url().path()) + }); + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let mut params = WriteParams::default(); + match field { + "max_rows_per_file" => params.max_rows_per_file = 50_000, + "max_rows_per_group" => params.max_rows_per_group = 100, + "max_bytes_per_file" => params.max_bytes_per_file = 64 * 1024 * 1024, + other => panic!("unexpected field: {other}"), + } + + let mut add = table.add(data).write_options(crate::table::WriteOptions { + lance_write_params: Some(params), + }); + if let Some(write_parallelism) = write_parallelism { + add = add.write_parallelism(write_parallelism); + } + + let err = add.execute().await.unwrap_err(); + assert!( + matches!(err, Error::NotSupported { .. }), + "{field}: {err:?}" + ); + let message = err.to_string(); + assert!(message.contains(field), "{field}: {message}"); + assert!( + message.contains("only mode=overwrite is supported"), + "{field}: {message}" + ); + } + } + + #[rstest] + #[case(None, false)] + #[case(Some(lance::dataset::WriteMode::Create), false)] + #[case(Some(lance::dataset::WriteMode::Append), false)] + #[case(Some(lance::dataset::WriteMode::Overwrite), true)] + #[tokio::test] + async fn add_preserves_supported_write_params( + #[case] mode: Option, + #[case] expect_overwrite: bool, + ) { + let data = record_batch!(("a", Int32, [1, 2, 3])).unwrap(); + let describe_body = describe_response(&data.schema()); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_body.clone()) + .unwrap(), + "/v1/table/my_table/insert/" => { + let mode = request + .url() + .query_pairs() + .find(|(k, _)| k == "mode") + .map(|(_, v)| v.into_owned()); + assert_eq!( + mode.as_deref(), + expect_overwrite.then_some("overwrite"), + "unexpected insert mode for {mode:?}" + ); + http::Response::builder() + .status(200) + .body(r#"{"version": 9}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected request path: {}", path), + }); + + let mut add = table.add(data); + if let Some(mode) = mode { + add = add.write_options(crate::table::WriteOptions { + lance_write_params: Some(WriteParams { + mode, + ..Default::default() + }), + }); + } + + assert_eq!(add.execute().await.unwrap().version, 9); + } + #[tokio::test] async fn add_string_blob_becomes_uri_struct_without_the_local_flag() { let table_schema = Schema::new(vec![ diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 045517968..fd7358e9a 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -283,6 +283,10 @@ pub struct WriteOptions { /// /// Overlapping `OpenTableBuilder` options (e.g. [AddDataBuilder::mode]) will take /// precedence over their counterparts in `WriteOptions` (e.g. [WriteParams::mode]). + /// + /// In LanceDB Enterprise, `add` returns [`Error::NotSupported`] when + /// `max_rows_per_file`, `max_rows_per_group`, or `max_bytes_per_file` is + /// non-default, because the remote insert protocol only transmits the write mode. pub lance_write_params: Option, } From 122e5e91d738c2c8a51ec799c57808548498d6b6 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:48:37 +0800 Subject: [PATCH 187/203] fix(python): isolate tokio runtime shutdown across fork generations (#5113) ## Problem A Python process that forks while LanceDB work is in flight inherits the parent's tokio runtime and its outstanding-call count, but the worker threads that would release that count do not survive the fork. A child that exits without using LanceDB can wait for parent work and try to shut down the inherited runtime; a child that creates its own runtime can have stale guards decrement its fresh counter. ## Behavior In-flight calls are now counted per fork generation. An inherited guard only updates the counter it was created with, and `shutdown` waits only for the current generation. A runtime tagged with an older generation is removed and leaked in the child instead of being shut down or joined. The at-fork child handler still only increments the generation counter. The fork hook is installed at the start of the first top-level call, before generation accounting, closing the window where a fork between accounting and runtime initialization could leave the child sharing the parent counter. ## Validation - New fork regressions cover parent work held across fork, child exit without and with its own runtime, and an inherited guard. Each passes when run alone in a fresh process. - `cargo test --quiet --features remote -p lancedb-python --lib runtime::tests` passes 8 tests in both default parallel and serial modes. - `cargo clippy --quiet --features remote -p lancedb-python --tests --examples` and `cargo fmt --all -- --check` pass. - Rebuilt the PyO3 extension; `test_remote_connection_after_fork` and `test_inherited_remote_table_reopens_after_fork` pass. --- python/src/runtime.rs | 537 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 475 insertions(+), 62 deletions(-) diff --git a/python/src/runtime.rs b/python/src/runtime.rs index 8891e2bf2..85d536939 100644 --- a/python/src/runtime.rs +++ b/python/src/runtime.rs @@ -21,37 +21,47 @@ //! rests on three separate mechanisms, each solving one problem the others //! cannot: //! -//! **`OUTSTANDING`, not `Arc::strong_count`, decides when the runtime is -//! idle.** Early versions tried to infer "is anything still using this -//! runtime" from how many `Arc` clones existed. That signal is -//! wrong in both directions: a clone taken only for the instant a task is -//! *submitted* says nothing about whether that task has actually finished -//! running (`Runtime::shutdown_timeout` gives spawned, non-blocking tasks -//! no grace period at all -- a task "keeps running until it yields, then is -//! dropped" -- so a reclaim landing right after submission would silently -//! abandon it before it ever got to run); and a clone held for a task's -//! *whole* lifetime can end up making that task the final owner of the -//! `Runtime`, so completing it drops the `Runtime` from inside one of its -//! own worker threads, which tokio itself forbids ("cannot drop a runtime -//! in a context where blocking is not allowed") and panics. `OUTSTANDING` -//! is an explicit courtesy counter instead: every top-level `spawn`, -//! `spawn_blocking`, or `block_on` call increments it before it starts and -//! decrements it (via [`OutstandingGuard`]) when it is truly done, entirely -//! decoupled from how many `Arc` clones exist at any instant. `shutdown` -//! waits for it to reach zero before ever touching the runtime, which also -//! closes a narrower race: because the counter is incremented *before* -//! `get_runtime()` is even called, an install already in progress when -//! `shutdown` runs is never invisible to it the way an empty slot would be. -//! If the counter never reaches zero within the bound, `shutdown` stops -//! waiting and forces the retirement attempt anyway -- silently returning -//! with the runtime and its workers still fully alive would just recreate -//! the exact race this function exists to close, for any call slower than -//! the grace period. +//! **A per-generation counter, not `Arc::strong_count`, decides when the +//! runtime is idle.** Early versions tried to infer "is anything still +//! using this runtime" from how many `Arc` clones existed. That +//! signal is wrong in both directions: a clone taken only for the instant a +//! task is *submitted* says nothing about whether that task has actually +//! finished running (`Runtime::shutdown_timeout` gives spawned, non-blocking +//! tasks no grace period at all -- a task "keeps running until it yields, +//! then is dropped" -- so a reclaim landing right after submission would +//! silently abandon it before it ever got to run); and a clone held for a +//! task's *whole* lifetime can end up making that task the final owner of +//! the `Runtime`, so completing it drops the `Runtime` from inside one of +//! its own worker threads, which tokio itself forbids ("cannot drop a +//! runtime in a context where blocking is not allowed") and panics. +//! [`GenerationCalls`] is an explicit courtesy counter instead: every +//! top-level `spawn`, `spawn_blocking`, or `block_on` call increments it +//! before it starts and decrements it (via [`OutstandingGuard`]) when it is +//! truly done, entirely decoupled from how many `Arc` clones exist at any +//! instant. `shutdown` waits for the current generation's counter to reach +//! zero before ever touching the runtime, which also closes a narrower +//! race: because the counter is incremented *before* `get_runtime()` is +//! even called, an install already in progress when `shutdown` runs is +//! never invisible to it the way an empty slot would be. If the counter +//! never reaches zero within the bound, `shutdown` stops waiting and forces +//! the retirement attempt anyway -- silently returning with the runtime and +//! its workers still fully alive would just recreate the exact race this +//! function exists to close, for any call slower than the grace period. //! -//! **Tasks never hold an `Arc`.** Because `OUTSTANDING` (not -//! reference counting) is what `shutdown` waits on, a top-level task only -//! needs to carry an `OutstandingGuard` -- a token whose `Drop` is a plain -//! atomic decrement -- not a clone of the runtime itself. That is what +//! **The counter is scoped to a fork generation, not the process.** A +//! single process-wide count cannot survive `fork()`: the child inherits the +//! parent's in-flight value, but the tasks that would decrement it do not +//! run there, and a guard copied onto the forking thread would later +//! decrement the child's count even though it belongs to the parent. Every +//! [`OutstandingGuard`] therefore holds an `Arc` for the +//! generation it was created in. A stale guard can only decrement its own +//! counter, while the child's first call lazily creates a fresh counter, and +//! `shutdown` only waits on the counter matching the live generation. +//! +//! **Tasks never hold an `Arc`.** Because the generation counter +//! (not reference counting) is what `shutdown` waits on, a top-level task +//! only needs to carry an `OutstandingGuard` -- a token whose `Drop` is a +//! plain atomic decrement -- not a clone of the runtime itself. That is what //! makes it impossible for a task's completion to become the final, //! worker-thread-side drop of the `Runtime`: nothing a task holds ever //! *is* the `Runtime`. @@ -74,11 +84,18 @@ //! installed runtime was built in against the live counter on every call, //! from ordinary (non-signal) context, and treats a mismatch as "stale, //! rebuild" -- exactly the check `atfork_child` used to perform directly. +//! [`shutdown`] makes the same comparison, because a child that exits +//! without ever installing its own runtime still finds the parent's stale +//! [`Tagged`] in the slot. It removes that slot and deliberately leaks the +//! instance instead of calling `shutdown_timeout` on it: its worker threads +//! do not exist in this process, so waiting for its counter or trying to +//! join them would hang, and a leaked reference prevents any inherited +//! `Arc` clone from becoming the final owner that drops it. use std::future::Future; use std::pin::Pin; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use arc_swap::ArcSwapOption; @@ -110,12 +127,21 @@ static RUNTIME: ArcSwapOption = ArcSwapOption::const_empty(); /// access -- just one atomic add, which is all a `pthread_atfork` child /// handler is ever safe to do. static GENERATION: AtomicU64 = AtomicU64::new(0); -/// Count of top-level `spawn`/`spawn_blocking`/`block_on` calls that have -/// started but not yet finished. See the module docs for why this, and not -/// `Arc::strong_count`, is what `shutdown` waits on. -static OUTSTANDING: AtomicU64 = AtomicU64::new(0); +/// In-flight top-level calls for one fork generation. Guards hold an `Arc` +/// to this object for their whole lifetime, so one inherited across `fork()` +/// can only decrement the counter it was created against, never the child's +/// fresh one. +struct GenerationCalls { + generation: u64, + outstanding: AtomicUsize, +} +static CALLS: ArcSwapOption = ArcSwapOption::const_empty(); static ATFORK_INSTALLED: AtomicBool = AtomicBool::new(false); +#[cfg(test)] +static TEST_WORKER_THREADS: AtomicUsize = AtomicUsize::new(0); + +#[cfg(not(test))] fn create_runtime() -> runtime::Runtime { runtime::Builder::new_multi_thread() .enable_all() @@ -124,9 +150,68 @@ fn create_runtime() -> runtime::Runtime { .expect("Failed to build tokio runtime") } +#[cfg(test)] +fn create_runtime() -> runtime::Runtime { + let mut builder = runtime::Builder::new_multi_thread(); + builder.enable_all().thread_name("lancedb-tokio-worker"); + // Fork tests hold two runtimes open at once. Keeping their worker count + // small avoids turning an unrelated parallel build on the same host into + // an apparent hang when the process thread limit is close to full. + let worker_threads = TEST_WORKER_THREADS.load(Ordering::Relaxed); + if worker_threads != 0 { + builder.worker_threads(worker_threads); + } + builder.build().expect("Failed to build tokio runtime") +} + +/// Register the fork-child handler once, before any generation-scoped state +/// is created. +/// +/// The first top-level call deliberately installs the hook before it starts +/// counting itself. Otherwise a fork between taking that first counter and +/// `get_runtime()` installing the hook would leave the child sharing the +/// parent's counter with no generation change to separate them. +fn ensure_atfork_installed() { + if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { + install_atfork(); + } +} + +/// Get the in-flight counter for the current fork generation, creating it on +/// the first top-level call after a fork. +fn current_calls() -> Arc { + ensure_atfork_installed(); + let current_gen = GENERATION.load(Ordering::SeqCst); + loop { + let existing = CALLS.load_full(); + if let Some(existing) = &existing + && existing.generation == current_gen + { + return Arc::clone(existing); + } + let candidate = Arc::new(GenerationCalls { + generation: current_gen, + outstanding: AtomicUsize::new(0), + }); + let previous = CALLS.compare_and_swap(&existing, Some(Arc::clone(&candidate))); + let won = match (&*previous, &existing) { + (None, None) => true, + (Some(prev), Some(exist)) => Arc::ptr_eq(prev, exist), + _ => false, + }; + if won { + // A stale counter is only an integer: unlike a runtime it has no + // worker threads to join, so letting the slot's old reference go + // here is safe even in a forked child. + return candidate; + } + } +} + /// Get a live, owned handle to the shared runtime, rebuilding it if the /// installed one predates the most recent `fork()`. fn get_runtime() -> Arc { + ensure_atfork_installed(); let current_gen = GENERATION.load(Ordering::SeqCst); loop { let existing = RUNTIME.load_full(); @@ -135,9 +220,6 @@ fn get_runtime() -> Arc { { return Arc::clone(existing); } - if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) { - install_atfork(); - } // Built optimistically, outside any lock: on the rare race where two // threads both find the slot empty (or stale), one candidate wins // the compare-and-swap below and the other is simply dropped here, @@ -167,23 +249,26 @@ fn get_runtime() -> Arc { } } -/// RAII token tracked by [`OUTSTANDING`]. Held for the duration of a -/// top-level `block_on` call, or moved into a top-level `spawn`/ -/// `spawn_blocking` task so it decrements only once that task's *entire* -/// body -- including anything it nested-spawns and awaits -- has run to -/// completion or been dropped without completing. -struct OutstandingGuard; +/// RAII token tracked by the current [`GenerationCalls`] counter. Held for +/// the duration of a top-level `block_on` call, or moved into a top-level +/// `spawn`/`spawn_blocking` task so it decrements only once that task's +/// *entire* body -- including anything it nested-spawns and awaits -- has run +/// to completion or been dropped without completing. +struct OutstandingGuard { + calls: Arc, +} impl OutstandingGuard { fn new() -> Self { - OUTSTANDING.fetch_add(1, Ordering::SeqCst); - Self + let calls = current_calls(); + calls.outstanding.fetch_add(1, Ordering::SeqCst); + Self { calls } } } impl Drop for OutstandingGuard { fn drop(&mut self) { - OUTSTANDING.fetch_sub(1, Ordering::SeqCst); + self.calls.outstanding.fetch_sub(1, Ordering::SeqCst); } } @@ -219,13 +304,15 @@ where /// Gracefully quiesce the shared runtime, meant to run at normal process exit. /// -/// Waits (bounded by `timeout`) for [`OUTSTANDING`] to reach zero -- i.e. -/// for every top-level call already under way to actually finish, not just -/// for `Arc::strong_count` to look low -- before ever touching the runtime. -/// If the bound elapses first, it stops waiting and attempts retirement -/// anyway: leaving the runtime and its worker threads untouched would just -/// recreate the exact race this function exists to close, for any call -/// slower than the grace period. +/// Waits (bounded by `timeout`) for the current generation's +/// [`GenerationCalls`] counter to reach zero -- i.e. for every top-level call +/// already under way in *this* process to actually finish, not just for +/// `Arc::strong_count` to look low -- before ever touching the runtime. Work +/// inherited from a parent process at `fork()` belongs to an older +/// generation and is never waited on. If the bound elapses first, it stops +/// waiting and attempts retirement anyway: leaving the runtime and its worker +/// threads untouched would just recreate the exact race this function exists +/// to close, for any call slower than the grace period. /// /// Retirement itself removes the runtime from the slot and calls /// `shutdown_timeout` rather than a bare `drop`: dropping a tokio `Runtime` @@ -238,14 +325,22 @@ where /// the slot and finishing its own call, this abandons the runtime instead /// of forcing the issue -- the same trade `atfork_child` already makes. /// +/// A runtime tagged with a generation older than the live counter was +/// inherited through `fork()` and is never retired here; see the module docs. +/// /// Neither of the two ways this can fail to cleanly retire the runtime -- /// the wait timing out, or `try_unwrap` losing that race -- has any other /// signal to report through (`shutdown_timeout` itself returns nothing), /// so both log a warning instead of failing silently. pub fn shutdown(timeout: Duration) { let deadline = Instant::now() + timeout; + let generation = GENERATION.load(Ordering::SeqCst); + let calls = CALLS.load_full(); + let calls = calls + .as_ref() + .filter(|calls| calls.generation == generation); loop { - let outstanding = OUTSTANDING.load(Ordering::SeqCst); + let outstanding = calls.map_or(0, |calls| calls.outstanding.load(Ordering::SeqCst)); if outstanding == 0 { break; } @@ -260,6 +355,18 @@ pub fn shutdown(timeout: Duration) { let Some(current) = RUNTIME.load_full() else { return; }; + if current.generation != generation { + // The child inherited the parent's installed runtime. Its worker + // threads do not exist here, so waiting on its counter or calling + // `shutdown_timeout` would wait for work that can never finish and + // join threads that can never exit. Remove the slot in ordinary + // context and deliberately leak the instance: inherited `Arc` clones + // may still be dropped in this process, and the leaked reference + // keeps a dropped clone from becoming the final owner. + RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); + std::mem::forget(current); + return; + } RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None); match Arc::try_unwrap(current) { Ok(tagged) => { @@ -320,7 +427,7 @@ impl Runtime for LanceRuntime { /// awaits its `JoinHandle`. `Handle::try_current` pins that nested call /// to whatever runtime is already executing it, so only the first, /// outermost call of a chain -- one running on a thread outside any - /// runtime -- ever consults [`get_runtime`] or [`OUTSTANDING`]. + /// runtime -- ever consults [`get_runtime`] or [`OutstandingGuard`]. fn spawn(fut: F) -> Self::JoinHandle where F: Future + Send + 'static, @@ -391,14 +498,14 @@ where mod tests { use super::*; - // RUNTIME, GENERATION, OUTSTANDING, and ATFORK_INSTALLED are process-wide + // RUNTIME, CALLS, GENERATION, and ATFORK_INSTALLED are process-wide // statics, and Rust's test harness runs tests in parallel by default, // so separate test functions below would otherwise race each other // through this shared state (this reproduced in CI: one test's // in-flight task got reclaimed by a *different* test's concurrent - // `shutdown()` call, and another observed `OUTSTANDING` left non-zero - // by a still-running sibling). Every test takes this lock first so - // only one of them touches the shared runtime state at a time; a + // `shutdown()` call, and another observed the in-flight counter left + // non-zero by a still-running sibling). Every test takes this lock first + // so only one of them touches the shared runtime state at a time; a // poisoned lock (a previous test's genuine failure) is still honored // rather than cascading into every later test as an unrelated panic. static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -570,7 +677,7 @@ mod tests { use std::sync::mpsc; let _lock = lock_runtime_state_for_test(); - // Clean slate: no runtime installed, OUTSTANDING at zero. + // Clean slate: no runtime installed, no in-flight calls. shutdown(Duration::from_secs(5)); let (installer_ready_tx, installer_ready_rx) = mpsc::channel::<()>(); @@ -596,6 +703,312 @@ mod tests { // shutdown must have waited for the install to finish and then // retired it, not returned early and left it stranded. assert!(RUNTIME.load_full().is_none()); - assert_eq!(OUTSTANDING.load(Ordering::SeqCst), 0); + let calls = CALLS + .load_full() + .expect("install race left no generation counter"); + assert_eq!(calls.outstanding.load(Ordering::SeqCst), 0); + } + + /// Keep fork-test runtimes small; see [`TEST_WORKER_THREADS`]. + #[cfg(target_os = "linux")] + struct TestWorkerThreads(usize); + + #[cfg(target_os = "linux")] + impl TestWorkerThreads { + fn new(worker_threads: usize) -> Self { + Self(TEST_WORKER_THREADS.swap(worker_threads, Ordering::SeqCst)) + } + } + + #[cfg(target_os = "linux")] + impl Drop for TestWorkerThreads { + fn drop(&mut self) { + TEST_WORKER_THREADS.store(self.0, Ordering::SeqCst); + } + } + + /// Run `f` in a forked child and return the `i32` it reports, or `None` + /// if the child did not report within the bound. The child leaves with + /// `_exit` so it never runs destructors inherited from the test process. + #[cfg(target_os = "linux")] + fn run_in_forked_child(f: F) -> Option + where + F: FnOnce() -> i32, + { + let mut pipe = [0; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0, "pipe failed"); + let (read_fd, write_fd) = (pipe[0], pipe[1]); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { libc::close(read_fd) }; + let result = f(); + let bytes = result.to_ne_bytes(); + let written = unsafe { libc::write(write_fd, bytes.as_ptr().cast(), bytes.len()) }; + unsafe { libc::close(write_fd) }; + unsafe { + libc::_exit(if written == bytes.len() as isize { + 0 + } else { + 1 + }) + }; + } + + unsafe { libc::close(write_fd) }; + let mut poll_fd = libc::pollfd { + fd: read_fd, + events: libc::POLLIN, + revents: 0, + }; + let ready = loop { + let ready = unsafe { libc::poll(&mut poll_fd, 1, 10_000) }; + if ready >= 0 { + break ready; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "poll failed: {error}" + ); + }; + if ready == 0 { + unsafe { libc::kill(pid, libc::SIGKILL) }; + } + + let mut result = None; + if ready == 1 { + let mut bytes = [0u8; std::mem::size_of::()]; + let read = loop { + let read = unsafe { libc::read(read_fd, bytes.as_mut_ptr().cast(), bytes.len()) }; + if read >= 0 { + break read; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "read failed: {error}" + ); + }; + if read == bytes.len() as isize { + result = Some(i32::from_ne_bytes(bytes)); + } + } + unsafe { libc::close(read_fd) }; + + let mut status = 0; + loop { + let waited = unsafe { libc::waitpid(pid, &mut status, 0) }; + if waited == pid { + break; + } + let error = std::io::Error::last_os_error(); + assert_eq!( + error.kind(), + std::io::ErrorKind::Interrupted, + "waitpid failed: {error}" + ); + } + if ready == 0 { + return None; + } + assert_eq!(status, 0, "forked child did not exit successfully"); + result + } + + // The child inherits the parent's installed runtime and its outstanding + // count, but not the worker thread that would ever release that count. + // Its exit-time shutdown must therefore ignore both: waiting for parent + // work would burn the whole grace period, and retiring the inherited + // runtime would try to join worker threads that do not exist here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_shutdown_does_not_wait_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + // Much longer than the watchdog: if this waits for inherited + // parent work at all, the child fails to report in time instead + // of the test comparing two elapsed durations. + shutdown(Duration::from_secs(30)); + i32::from(RUNTIME.load_full().is_some()) + }); + assert_eq!( + child_result, + Some(0), + "child shutdown waited for parent work or retired the inherited runtime" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A child that builds its own runtime must drain that runtime's own + // work, and only that work: the parent's held task is still outstanding + // in the inherited copy of the counter but can never finish here. + #[cfg(target_os = "linux")] + #[test] + fn test_forked_child_drains_its_own_runtime_without_waiting_for_parent_work() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + drop(LanceRuntime::spawn(async move { + started_tx.send(()).unwrap(); + let _ = release_rx.await; + let _ = done_tx.send(()); + })); + started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task did not start"); + + let child_result = run_in_forked_child(|| { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Keep the child's own task outstanding while shutdown starts, + // then release it once the shutdown thread is about to enter. + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + let rebuilt = block_on(async { 40 + 2 }) == 42; + shutdown(Duration::from_secs(30)); + i32::from(!(drained && retired && rebuilt)) + }); + assert_eq!( + child_result, + Some(0), + "child did not drain its own runtime or waited for parent work" + ); + + release_tx.send(()).unwrap(); + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("parent task was disturbed by the forked child"); + shutdown(Duration::from_secs(5)); + } + + // A guard created before `fork()` belongs to the parent generation. If + // the child drops that inherited guard, it must decrement the counter it + // was created against, not the child's fresh counter (a naive reset in + // the child would underflow here and make shutdown wait forever). The + // second parent guard stays held across the fork without being dropped + // in the child, so this also proves the child does not wait for work + // that can only finish in the parent. + #[cfg(target_os = "linux")] + #[test] + fn test_inherited_guard_does_not_corrupt_child_generation_counter() { + use std::sync::mpsc; + use tokio::sync::oneshot; + + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(2); + shutdown(Duration::from_secs(5)); + + // This test forks before any runtime exists, so make the hook + // initialization explicit through the same path the first top-level + // call uses; otherwise this test only works after a preceding test + // has installed the process-wide hook. + ensure_atfork_installed(); + // Stands in for a top-level call that was in progress when the + // parent forked and is dropped by the child after it starts work. + let inherited_guard = OutstandingGuard::new(); + // Stays outstanding in the parent for the whole fork, as parent work + // that no child task can ever complete. + let parent_guard = OutstandingGuard::new(); + + let child_result = run_in_forked_child(move || { + let child_done = Arc::new(AtomicBool::new(false)); + let child_done_flag = Arc::clone(&child_done); + let (task_started_tx, task_started_rx) = mpsc::channel(); + let (release_tx, release_rx) = oneshot::channel::<()>(); + let (child_tx, child_rx) = mpsc::channel(); + drop(LanceRuntime::spawn(async move { + task_started_tx.send(()).unwrap(); + let _ = release_rx.await; + child_done_flag.store(true, Ordering::SeqCst); + let _ = child_tx.send(()); + })); + task_started_rx + .recv_timeout(Duration::from_secs(5)) + .expect("child task did not start"); + + // Drop the inherited guard while the child has its own task + // outstanding, so a shared or reset counter would visibly + // perturb the child's accounting. + drop(inherited_guard); + + let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel(); + let shutdown_thread = std::thread::spawn(move || { + shutdown_ready_tx.send(()).unwrap(); + shutdown(Duration::from_secs(30)); + }); + shutdown_ready_rx.recv().unwrap(); + release_tx.send(()).unwrap(); + shutdown_thread.join().unwrap(); + + let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok() + && child_done.load(Ordering::SeqCst); + let retired = RUNTIME.load_full().is_none(); + i32::from(!(drained && retired)) + }); + assert_eq!( + child_result, + Some(0), + "inherited guard corrupted the child generation counter" + ); + + drop(parent_guard); + shutdown(Duration::from_secs(5)); } } From dcded7fb70e09206cdacb63366f6acb1c7cab77b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 21:01:25 +0800 Subject: [PATCH 188/203] feat(python): default StreamingDataLoader workers to forkserver (#5112) ## Problem `StreamingDataLoader` left PyTorch's platform default in place for worker processes, which is `fork` on Linux. Forked workers inherit the parent process's native runtime and connections, which is the failure mode behind the fork-isolation work. ## Behavior When `num_workers > 0` and `multiprocessing_context` is omitted or `None`, workers now use `forkserver` when the platform provides it, otherwise `spawn`. Explicit start-method names and context objects are unchanged. With `num_workers == 0`, no context is selected, preserving PyTorch's single-process handling. Callbacks and worker state must be picklable under the selected start method, following PyTorch's DataLoader rules. Existing `StreamingDataset` serialization is sufficient for the default worker path. This does not change the explicit fork opt-in or the native client reopen path in #3851. --- docs/web/training/checkpointing.mdx | 2 + python/python/lancedb/streaming.py | 21 +++- .../python/tests/test_elastic_dataloader.py | 100 ++++++++++++++++++ 3 files changed, 122 insertions(+), 1 deletion(-) diff --git a/docs/web/training/checkpointing.mdx b/docs/web/training/checkpointing.mdx index 119601d98..99124549a 100644 --- a/docs/web/training/checkpointing.mdx +++ b/docs/web/training/checkpointing.mdx @@ -54,6 +54,8 @@ Python's built-in `torch.utils.data.DataLoader` produces a safe checkpoint when 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`. +With `num_workers > 0` and `multiprocessing_context` omitted or `None`, `StreamingDataLoader` uses `forkserver` where the platform provides it and falls back to `spawn`. Callback functions and worker state must be picklable under that start method. Multi-worker scripts should keep their entry point behind the standard `if __name__ == "__main__":` guard so spawned workers can import the module safely. + ```py Python icon=Python from lancedb.streaming import StreamingDataset, StreamingDataLoader diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 810911e28..23a81c135 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -30,7 +30,7 @@ import warnings from collections import deque from concurrent.futures import ThreadPoolExecutor from copy import deepcopy -from multiprocessing import RawArray, get_context +from multiprocessing import RawArray, get_all_start_methods, get_context from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union import pyarrow as pa @@ -60,6 +60,13 @@ DEFAULT_PREFETCH_BATCHES = 4 _UNSET = object() +def _default_worker_start_method() -> str: + """Return the worker start method used when the caller omits a context.""" + if "forkserver" in get_all_start_methods(): + return "forkserver" + return "spawn" + + class _WorkerSample(NamedTuple): data: Any dataset: "StreamingDataset" @@ -1999,6 +2006,14 @@ class StreamingDataLoader(DataLoader): because the custom iterator cannot provide the exact per-yield checkpoint snapshots required by this loader. + When ``num_workers > 0`` and ``multiprocessing_context`` is omitted or + ``None``, workers default to the ``forkserver`` start method when the + platform provides it, and to ``spawn`` otherwise. Explicit start-method + names and context objects are used unchanged. With ``num_workers == 0``, + no context is selected, leaving PyTorch's single-process behavior intact. + Callbacks and worker state must be picklable under the selected start + method, following PyTorch's DataLoader rules. + Examples -------- >>> # dataset = StreamingDataset(table, num_splits=2) @@ -2028,6 +2043,10 @@ class StreamingDataLoader(DataLoader): ) self._streaming_dataset = dataset super().__init__(_StreamingDatasetAdapter(dataset), *args, **kwargs) + # Fill the default only after DataLoader has handled an explicit context; + # num_workers=0 keeps whatever PyTorch decided. + if self.num_workers > 0 and self.multiprocessing_context is None: + self.multiprocessing_context = _default_worker_start_method() if self.drop_last: raise ValueError( "StreamingDataLoader does not support drop_last=True because " diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index e9fb56c8a..6e6ab45d1 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -32,6 +32,7 @@ Parameters used throughout: import dataclasses import logging +import multiprocessing as mp import threading from unittest.mock import patch @@ -1028,6 +1029,105 @@ def test_multi_worker_elastic_det_across_worker_counts(lance_table): ) +# ── Worker start method defaults ───────────────────────────────────────────── + + +def _loader_start_method(loader: StreamingDataLoader) -> str: + context = loader.multiprocessing_context + if isinstance(context, str): + return context + assert context is not None + return context.get_start_method() + + +def _platform_worker_start_method() -> str: + return "forkserver" if "forkserver" in mp.get_all_start_methods() else "spawn" + + +def test_default_worker_start_method_prefers_forkserver(): + with patch.object( + streaming, + "get_all_start_methods", + return_value=["fork", "spawn", "forkserver"], + ): + assert streaming._default_worker_start_method() == "forkserver" + + +def test_streaming_dataloader_falls_back_to_spawn_without_forkserver(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + with patch.object(streaming, "get_all_start_methods", return_value=["spawn"]): + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1) + + assert _loader_start_method(loader) == "spawn" + + +def test_streaming_dataloader_omitted_context_uses_platform_method(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1) + + assert _loader_start_method(loader) == _platform_worker_start_method() + + +def test_streaming_dataloader_treats_none_context_as_omitted(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context=None, + ) + + assert _loader_start_method(loader) == _platform_worker_start_method() + + +def test_streaming_dataloader_preserves_explicit_start_method(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context="spawn", + ) + + assert _loader_start_method(loader) == "spawn" + + +def test_streaming_dataloader_preserves_explicit_context_object(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + context = mp.get_context("spawn") + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context=context, + ) + + assert loader.multiprocessing_context is context + + +def test_streaming_dataloader_zero_workers_leave_context_unset(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=12, num_workers=0) + + assert loader.multiprocessing_context is None + ids = [row_id for batch in loader for row_id in batch["id"].tolist()] + assert sorted(ids) == list(range(NUM_ROWS)) + + +def test_streaming_dataloader_default_context_runs_real_worker(lance_table): + dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=12, num_workers=1) + assert _loader_start_method(loader) == _platform_worker_start_method() + + iterator = iter(loader) + try: + ids = [row_id for batch in iterator for row_id in batch["id"].tolist()] + finally: + iterator._shutdown_workers() + + assert sorted(ids) == list(range(NUM_ROWS)) + + # ── Resumability with num_workers ───────────────────────────────────────────── From 97996869864ff3c9b59a87532881f498a31f329b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 21:30:40 +0800 Subject: [PATCH 189/203] perf(python): add native eager collection for to_arrow (#5127) ## Summary `to_arrow()` currently collects results one Python future per batch: both sync and async paths call `to_batches()`, which crosses the Python/Rust bridge for every default 1024-row batch. Vector queries also materialize the whole native stream even when no reranker is configured. This adds a shared Rust eager collector. `execute_to_reader` collects the batches in Rust, asks the core to skip the default 1024-row output slicing, and exposes the result through the Arrow C Stream interface, so Python builds the Table without a Python future per batch. Sync and async `to_arrow`, including FTS, vector and hybrid eager paths, use it. `AsyncVectorQuery.to_batches` no longer materializes results when there is no reranker and now honors `max_batch_length`. Schema, empty results, timeout, cancellation, and error behavior are preserved. The existing fragment guard is enforced on the new fast path, and namespace-pushdown routing keeps its existing Python/Rust split. ## Benchmark Development-profile editable build, full scans on one revision, 1 warmup + 5 measured runs. Absolute values are not release-profile numbers; compare before/after on the same build. | Workload | Before | After | |---|---|---| | 5M rows x 3 columns, async | 3.054 s | 0.087 s (35.1x) | | 5M rows x 3 columns, sync | 3.462 s | 0.090 s (38.3x) | | 200k rows x 129 columns, async | 0.354 s | 0.082 s (4.3x) | | 200k rows x 129 columns, sync | 0.387 s | 0.085 s (4.5x) | The narrow scan returned 4,883 batches capped at 1,024 rows before and 611 batches up to 8,192 rows after. --- python/python/lancedb/_lancedb.pyi | 12 +++ python/python/lancedb/query.py | 107 ++++++++++++++++++-- python/python/lancedb/remote/table.py | 8 ++ python/python/lancedb/table.py | 47 +++++++++ python/python/tests/test_eager_collector.py | 57 +++++++++++ python/python/tests/test_fts.py | 6 +- python/python/tests/test_query.py | 3 +- python/src/arrow.rs | 45 +++++++- python/src/query.rs | 64 ++++++++++++ 9 files changed, 333 insertions(+), 16 deletions(-) create mode 100644 python/python/tests/test_eager_collector.py diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5a89f100b..962000c99 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -962,6 +962,9 @@ class Query: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -974,6 +977,9 @@ class TakeQuery: def use_rte(self, enable: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1000,6 +1006,9 @@ class FTSQuery: async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1009,6 +1018,9 @@ class FTSQuery: class VectorQuery: async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... + async def execute_to_reader( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... def select(self, columns: List[Tuple[str, str]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 76d98e4f6..ce75dd68c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2567,10 +2567,24 @@ class LanceVectorQueryBuilder(LanceQueryBuilder): columns and raises for blobs inside lists. """ blob_sources = self._validated_blob_sources(blob_mode) + if blob_mode != "lazy": + return self._finalize_blob_query_table( + self.to_batches(timeout=timeout).read_all(), + blob_mode=blob_mode, + blob_sources=blob_sources, + ) + + self._ensure_fragment_constraints_supported("to_arrow()") + results = self._table._execute_arrow( + self._query_for_scan(blob_sources), timeout=timeout + ) + if self._reranker is not None: + source = results + results = self._reranker.rerank_vector(self._str_query, results) + check_reranker_result(results) + results = _merge_query_snapshot(results, source) return self._finalize_blob_query_table( - self.to_batches(timeout=timeout).read_all(), - blob_mode=blob_mode, - blob_sources=blob_sources, + results, blob_mode=blob_mode, blob_sources=blob_sources ) def to_query_object(self) -> Query: @@ -2895,8 +2909,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder): blob_sources = self._validated_blob_sources(blob_mode) self._table._ensure_no_legacy_fts_index() + self._ensure_fragment_constraints_supported("to_arrow()") query = self._query_for_scan(blob_sources) - results = self._table._execute_query(query, timeout=timeout).read_all() + if blob_mode == "lazy": + results = self._table._execute_arrow(query, timeout=timeout) + else: + results = self._table._execute_query(query, timeout=timeout).read_all() if self._reranker is not None: source = results results = self._reranker.rerank_fts(self._query, results) @@ -2945,8 +2963,18 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): blob_sources = self._validated_blob_sources(blob_mode) if blob_mode == "bytes" and blob_sources: return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all() + if blob_mode != "lazy": + return self._finalize_blob_query_table( + self.to_batches(timeout=timeout).read_all(), + blob_mode=blob_mode, + blob_sources=blob_sources, + ) + + self._ensure_fragment_constraints_supported("to_arrow()") return self._finalize_blob_query_table( - self.to_batches(timeout=timeout).read_all(), + self._table._execute_arrow( + self._query_for_scan(blob_sources), timeout=timeout + ), blob_mode=blob_mode, blob_sources=blob_sources, ) @@ -4062,6 +4090,17 @@ class AsyncQueryBase(object): return AsyncRecordBatchReader._from_batches(schema, batches()) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute with the native eager collector used by ``to_arrow``.""" + self._ensure_fragment_constraints_supported("to_arrow()") + await self._maybe_add_blob_row_id() + reader = await self._inner.execute_to_reader(None, timeout) + return pa.Table.from_batches(reader, schema=reader.schema) + async def _execute_batches( self, *, @@ -4187,10 +4226,17 @@ class AsyncQueryBase(object): if blob_mode == "bytes" and blob_sources: reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode) return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) - batch_iter = await self.to_batches(timeout=timeout) - tbl = self._finalize_blob_query_table( - pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema) - ) + if blob_mode != "lazy": + batch_iter = await self.to_batches(timeout=timeout) + tbl = self._finalize_blob_query_table( + pa.Table.from_batches( + await batch_iter.read_all(), schema=batch_iter.schema + ) + ) + else: + tbl = self._finalize_blob_query_table( + await self._execute_eager(timeout=timeout) + ) return await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources) async def to_list( @@ -4936,6 +4982,22 @@ class AsyncFTSQuery(AsyncStandardQuery): ) ) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + try: + results = await super()._execute_eager(timeout=timeout) + except Exception as error: + _add_fts_position_error_note(error) + raise + if self._reranker: + source = results + results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5286,6 +5348,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table) ) + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + results = await super()._execute_eager(timeout=timeout) + if self._reranker: + source = results + results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5294,8 +5368,12 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): blob_sources: Optional[dict[str, str]] = None, ) -> AsyncRecordBatchReader: reader = await super()._execute_batches( - timeout=timeout, blob_sources=blob_sources + max_batch_length=max_batch_length, + timeout=timeout, + blob_sources=blob_sources, ) + if self._reranker is None: + return reader results = pa.Table.from_batches(await reader.read_all(), reader.schema) if self._reranker: source = results @@ -5421,6 +5499,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): return fts_query, vec_query, limit, offset + async def _execute_eager( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + self._ensure_fragment_constraints_supported("to_arrow()") + reader = await self._execute_batches(timeout=timeout) + return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) + async def _execute_batches( self, *, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 51a656a52..47d0d048f 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -927,6 +927,14 @@ class RemoteTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + return LOOP.run(self._table._execute_arrow(query, timeout=timeout)) + def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: return LOOP.run(self._table._explain_plan(query, verbose)) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 492526344..863671bd5 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2926,6 +2926,15 @@ class Table(ABC): timeout: Optional[timedelta] = None, ) -> pa.RecordBatchReader: ... + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute a query and collect the whole result eagerly.""" + return self._execute_query(query, timeout=timeout).read_all() + @abstractmethod def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: ... @@ -5968,6 +5977,26 @@ class LanceTable(Table): return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync()) + def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + # Keep the Python namespace pushdown path, including its branch rule. + if ( + _should_push_down_query_table( + self._namespace_client, self._pushdown_operations + ) + and not self._route_pushdown_to_rust + and self.current_branch() is None + and not _requires_local_namespace_execution(query) + ): + return self._execute_query(query, timeout=timeout).read_all() + + async_query = self._table._sync_query_to_async(query) + return LOOP.run(async_query._execute_eager(timeout=timeout)) + def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: return LOOP.run(self._table._explain_plan(query, verbose)) @@ -8485,6 +8514,24 @@ class AsyncTable: max_batch_length=batch_size, timeout=timeout ) + async def _execute_arrow( + self, + query: Query, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + if ( + _should_push_down_query_table( + self._namespace_client, self._pushdown_operations + ) + and not self._route_pushdown_to_rust + and not _requires_local_namespace_execution(query) + ): + return (await self._execute_query(query, timeout=timeout)).read_all() + + async_query = self._sync_query_to_async(query) + return await async_query._execute_eager(timeout=timeout) + async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str: # This method is used by the sync table async_query = self._sync_query_to_async(query) diff --git a/python/python/tests/test_eager_collector.py b/python/python/tests/test_eager_collector.py new file mode 100644 index 000000000..1eaed9678 --- /dev/null +++ b/python/python/tests/test_eager_collector.py @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb + + +@pytest.mark.asyncio +async def test_execute_to_reader_collects_without_default_slicing(tmp_path): + db = await lancedb.connect_async(tmp_path) + rows = 5000 + data = pa.table( + { + "id": pa.array(range(rows), type=pa.int64()), + "text": pa.array([f"row-{i}" for i in range(rows)]), + } + ) + table = await db.create_table("test", data) + + reader = await table._inner.query().execute_to_reader(None, None) + batches = list(reader) + + assert sum(batch.num_rows for batch in batches) == rows + assert max(batch.num_rows for batch in batches) > 1024 + + +@pytest.mark.asyncio +async def test_execute_to_reader_preserves_empty_schema(tmp_path): + db = await lancedb.connect_async(tmp_path) + data = pa.table( + { + "id": pa.array([1, 2], type=pa.int64()), + "text": pa.array(["a", "b"]), + } + ) + table = await db.create_table("test", data) + + query = table._inner.query() + query.where("id < 0") + reader = await query.execute_to_reader(None, None) + result = pa.Table.from_batches(reader, schema=reader.schema) + + assert result.num_rows == 0 + assert result.schema == await table.query().where("id < 0").output_schema() + + +@pytest.mark.asyncio +async def test_execute_to_reader_propagates_timeout(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", data=[{"id": 1}, {"id": 2}]) + + with pytest.raises(Exception, match="Query timeout"): + await table._inner.query().execute_to_reader(None, timedelta(0)) diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 26ce5e528..1bf019fc2 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -1655,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object(): def test_fts_phrase_query_execution_preserves_user_text(): table = mock.Mock() table.schema = pa.schema([]) - table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader() + # to_arrow() collects through the eager path; keep a real Table so the + # reranker still receives and returns the real result contract. + table._execute_arrow.return_value = pa.table({"text": ["result"]}) class CapturingReranker: score = "relevance" @@ -1677,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text(): query.to_arrow() - backend_query = table._execute_query.call_args.args[0] + backend_query = table._execute_arrow.call_args.args[0] assert ( backend_query.full_text_query.query, reranker.queries, diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 82b40f9c6..3b0f3d5a2 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1739,7 +1739,7 @@ def test_query_builder_with_different_vector_column(): ds = mock.Mock() table.to_lance.return_value = ds builder.to_arrow() - table._execute_query.assert_called_once_with( + table._execute_arrow.assert_called_once_with( Query( vector=query, filter="b < 10", @@ -1748,7 +1748,6 @@ def test_query_builder_with_different_vector_column(): columns=["b"], vector_column="foo_vector", ), - batch_size=None, timeout=None, ) diff --git a/python/src/arrow.rs b/python/src/arrow.rs index f0b4bceed..0384f2b2a 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -2,15 +2,20 @@ // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::sync::Arc; +use std::time::Duration; use crate::error::PythonErrorExt; use crate::runtime::future_into_py; use arrow::{ datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, + record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader}, +}; +use futures::{TryStreamExt, stream::StreamExt}; +use lancedb::{ + arrow::SendableRecordBatchStream, + query::{ExecutableQuery, QueryExecutionOptions}, }; -use futures::stream::StreamExt; -use lancedb::arrow::SendableRecordBatchStream; use pyo3::{ Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyStopAsyncIteration, pyclass, pymethods, }; @@ -63,3 +68,39 @@ impl RecordBatchStream { }) } } + +/// Execute `query` and collect every batch in Rust before returning to Python. +/// +/// `to_arrow()` needs the complete table, so the default 1024-row output +/// slicing only adds work. Returning an Arrow C Stream reader also avoids a +/// Python future per batch while python materializes the table. +/// +/// The stream is collected inside the returned future, so timeout and +/// cancellation keep the same observable behavior as reading the stream from +/// Python: errors surface from the awaited call and dropping the future drops +/// the underlying stream. +pub fn execute_to_reader( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + future_into_py(py, async move { + let mut options = QueryExecutionOptions::default(); + // `None` means the caller wants one eager result, not the core's + // default batch size. An explicit value is still honored. + options.max_batch_length = max_batch_length.unwrap_or(0); + options.timeout = timeout; + let stream = query.execute_with_options(options).await.infer_error()?; + let schema = stream.schema(); + let batches = stream.try_collect::>().await.infer_error()?; + let reader: Box = Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + )); + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) + }) +} diff --git a/python/src/query.rs b/python/src/query.rs index 9864d7d74..3c6d9d662 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -696,6 +696,20 @@ impl Query { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -784,6 +798,20 @@ impl TakeQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -909,6 +937,28 @@ impl FTSQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { let mut inner = self_ .inner @@ -1148,6 +1198,20 @@ impl VectorQuery { }) } + /// Execute this query eagerly and return an Arrow C Stream reader. + /// + /// The returned reader exposes batches already collected in Rust, so + /// `pyarrow` can build a table without a Python future per batch. `None` + /// leaves out the core's default 1024-row output slicing. + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { From 85f966a9a9619a659ddadb613fa8420f56939ac0 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 22:08:29 +0800 Subject: [PATCH 190/203] fix: add dataset path hint and sync open_table location (#5128) ## Summary - Expose `location=` on sync `LanceDBConnection.open_table()`, matching the existing async entry point while leaving remote and namespace APIs unchanged. - When a `ListingDatabase` connection URI ends in `.lance`, append a parent-directory and table-stem hint to the derived-URI `TableNotFound` error. The error classification and source chain are preserved, and no extra storage probes are made. Context: OSS-2858 remains canceled. This is only the narrow embedded DX follow-up; it does not add a top-level `lancedb.open_table(uri)` API. ## Verification - Rust targeted listing tests for the `.lance` hint and the explicit-location path. - Python sync `open_table` tests for `location=` and the `.lance` hint. - Pickle round-trip of a sync `location=` table after #5114. - `cargo check --features remote --tests --examples`, `cargo fmt --check`, Ruff format/check. --- docs/src/python/python.md | 8 ++ python/python/lancedb/db.py | 6 + python/python/tests/test_db.py | 29 +++++ rust/lancedb/src/database/listing.rs | 159 +++++++++++++++++++++++---- rust/lancedb/src/error.rs | 46 +++++++- 5 files changed, 227 insertions(+), 21 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index dfd2752b8..5c31d0bb6 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -37,6 +37,14 @@ embedding_functions`. Prefer keyword arguments for optional parameters. ::: lancedb.db.DBConnection +Embedded connections support `location=` on `open_table` to open a table from an +explicit dataset URI instead of the derived `/.lance` path: + +```python +db = lancedb.connect("./data") +table = db.open_table("events", location="./datasets/events.lance") +``` + Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection) to include the responding server's release, Git revision, build date and Function runtime information in a bug report. It returns a JSON-compatible dictionary and diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index aa1d73b29..7a4a85cb6 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -2197,6 +2197,7 @@ class LanceDBConnection(DBConnection): namespace_path: Optional[List[str]] = None, storage_options: Optional[Dict[str, str]] = None, index_cache_size: Optional[int] = None, + location: Optional[str] = None, branch: Optional[str] = None, version: Optional[int] = None, ) -> LanceTable: @@ -2209,6 +2210,10 @@ class LanceDBConnection(DBConnection): namespace_path: List[str], optional The namespace to open the table from. When non-empty, the table is resolved through the directory namespace client. + location: str, optional + The explicit location (URI) of the table. If provided, the table will be + opened from this location instead of deriving it from the database URI + and table name. branch: str, optional If provided, open a handle scoped to this branch instead of the default branch. Reads and writes operate in the branch's context. @@ -2242,6 +2247,7 @@ class LanceDBConnection(DBConnection): namespace_path=namespace_path, storage_options=storage_options, index_cache_size=index_cache_size, + location=location, ) except (RuntimeError, ValueError) as e: if namespace_path and ( diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index fa09a9e19..764d082eb 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -869,6 +869,35 @@ def test_open_table_sync(tmp_db: lancedb.DBConnection): tmp_db.open_table("does_not_exist") +def test_open_table_sync_with_location(tmp_path): + db = lancedb.connect(tmp_path / "db") + db.create_table("test", data=[{"id": 0}]) + dataset_path = tmp_path / "db" / "test.lance" + + other_db = lancedb.connect(tmp_path / "other") + opened = other_db.open_table("test", location=str(dataset_path)) + assert opened.name == "test" + assert opened.count_rows() == 1 + + +def test_open_table_sync_lance_dataset_path_hint(tmp_path): + data_dir = tmp_path / "data" + lancedb.connect(data_dir).create_table("embeddings", data=[{"id": 0}]) + dataset_db = lancedb.connect(data_dir / "embeddings.lance") + + with pytest.raises(ValueError) as exc_info: + dataset_db.open_table("embeddings") + message = str(exc_info.value) + assert "Table 'embeddings' was not found" in message + assert "points to a Lance dataset rather than a database directory" in message + assert f"parent directory '{data_dir}'" in message + assert "open table 'embeddings' instead" in message + + with pytest.raises(ValueError) as exc_info: + dataset_db.open_table("missing", location=str(tmp_path / "missing.lance")) + assert "points to a Lance dataset" not in str(exc_info.value) + + @pytest.mark.asyncio async def test_open_table(tmp_path): from conftest import pandas_string_type diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 765c8af3d..17ecfadff 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -22,7 +22,7 @@ use crate::blob::ensure_blob_storage_version; use crate::connection::ConnectRequest; use crate::database::ReadConsistency; use crate::database::namespace::LanceNamespaceDatabase; -use crate::error::{CreateDirSnafu, Error, Result}; +use crate::error::{BoxError, CreateDirSnafu, Error, Result, TableNotFoundHint}; use crate::io::object_store::MirroringObjectStoreWrapper; use crate::table::NativeTable; use crate::utils::validate_table_name; @@ -698,6 +698,22 @@ impl ListingDatabase { Ok(()) } + /// Explain a miss caused by connecting to a Lance dataset as if it were a + /// database directory. The connection URI is enough to name the parent and + /// table stem, so this needs no storage probe. + fn lance_dataset_path_hint(&self) -> Option { + let uri = self.uri.trim_end_matches(['/', '\\']); + let (parent, file_name) = uri.rsplit_once(['/', '\\'])?; + let stem = file_name.strip_suffix(".lance")?; + if stem.is_empty() { + return None; + } + let parent = if parent.is_empty() { "." } else { parent }; + Some(format!( + ". The connection URI ends with '.lance', which points to a Lance dataset rather than a database directory. Connect to the parent directory '{parent}' and open table '{stem}' instead." + )) + } + /// Get the URI of a table in the database. fn table_uri(&self, name: &str) -> Result { validate_table_name(name)?; @@ -1180,6 +1196,7 @@ impl Database for ListingDatabase { if !request.namespace_path.is_empty() { return self.namespace_database().open_table(request).await; } + let derived_location = request.location.is_none(); // Use provided location if available, otherwise derive from table name let table_uri = match request.location.clone() { Some(location) => location, @@ -1233,20 +1250,29 @@ impl Database for ListingDatabase { }); read_params.session(self.session.clone()); - let native_table = Arc::new( - NativeTable::open_with_params( - &table_uri, - &request.name, - request.namespace_path, - self.store_wrapper.clone(), - Some(read_params), - self.read_consistency_interval, - request.namespace_client, - HashSet::new(), // listing database doesn't support server-side queries - request.managed_versioning, // Pass through managed_versioning from request - ) - .await?, - ); + let native_table = match NativeTable::open_with_params( + &table_uri, + &request.name, + request.namespace_path, + self.store_wrapper.clone(), + Some(read_params), + self.read_consistency_interval, + request.namespace_client, + HashSet::new(), // listing database doesn't support server-side queries + request.managed_versioning, // Pass through managed_versioning from request + ) + .await + { + Ok(table) => Arc::new(table), + Err(Error::TableNotFound { name, source }) if derived_location => { + let source: BoxError = match self.lance_dataset_path_hint() { + Some(hint) => Box::new(TableNotFoundHint::new(hint, source)), + None => source, + }; + return Err(Error::TableNotFound { name, source }); + } + Err(error) => return Err(error), + }; Ok(native_table) } @@ -1843,10 +1869,100 @@ mod tests { } } - async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { + /// A connection made to a dataset path cannot also be a database directory. The + /// miss names the parent and table stem so the caller can fix the connection. + #[tokio::test] + async fn test_open_table_dataset_path_hint() { let tempdir = tempdir().unwrap(); - let uri = tempdir.path().to_str().unwrap(); + let data_dir = tempdir.path().join("data"); + let data_db = setup_database_at(data_dir.to_str().unwrap()).await; + create_tables(&data_db, &["embeddings"]).await; + let dataset_path = data_dir.join("embeddings.lance"); + let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await; + let error = dataset_db + .open_table(OpenTableRequest { + name: "embeddings".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap_err(); + + assert!( + matches!(&error, Error::TableNotFound { name, .. } if name == "embeddings"), + "the dataset path miss changed classification: {error:?}" + ); + let message = error.to_string(); + assert!( + message.contains("points to a Lance dataset rather than a database directory"), + "the hint did not explain the dataset path: {message}" + ); + assert!( + message.contains(&format!("parent directory '{}'", data_dir.display())), + "the hint did not name the parent directory: {message}" + ); + assert!( + message.contains("open table 'embeddings' instead"), + "the hint did not name the table stem: {message}" + ); + } + + /// The hint belongs only to a derived URI. An explicit location is the caller's + /// own choice, so a miss there keeps the original message. + #[tokio::test] + async fn test_open_table_explicit_location_skips_dataset_path_hint() { + let tempdir = tempdir().unwrap(); + let data_dir = tempdir.path().join("data"); + let data_db = setup_database_at(data_dir.to_str().unwrap()).await; + create_tables(&data_db, &["embeddings"]).await; + let dataset_path = data_dir.join("embeddings.lance"); + let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await; + + let table = dataset_db + .open_table(OpenTableRequest { + name: "alias".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: Some(dataset_path.to_str().unwrap().to_string()), + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 0); + + let missing_path = tempdir.path().join("missing.lance"); + let error = dataset_db + .open_table(OpenTableRequest { + name: "missing".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: Some(missing_path.to_str().unwrap().to_string()), + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap_err(); + assert!( + matches!(&error, Error::TableNotFound { name, .. } if name == "missing"), + "the explicit location miss changed classification: {error:?}" + ); + assert!( + !error + .to_string() + .contains("points to a Lance dataset rather than a database directory"), + "an explicit location still received the connection hint: {error}" + ); + } + + async fn setup_database_at(uri: &str) -> ListingDatabase { let request = ConnectRequest { uri: uri.to_string(), #[cfg(feature = "remote")] @@ -1857,11 +1973,14 @@ mod tests { read_consistency_interval: None, session: None, }; - - let db = ListingDatabase::connect_with_options(&request) + ListingDatabase::connect_with_options(&request) .await - .unwrap(); + .unwrap() + } + async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { + let tempdir = tempdir().unwrap(); + let db = setup_database_at(tempdir.path().to_str().unwrap()).await; (tempdir, db) } diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 6aed94d71..3c8a485f9 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -344,6 +344,46 @@ fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static) String::new() } +/// Actionable guidance attached to a [`Error::TableNotFound`]. +/// +/// The hint is kept in the error source chain so the missing-table +/// classification and the original failure stay unchanged. +#[derive(Debug)] +pub(crate) struct TableNotFoundHint { + hint: String, + source: BoxError, +} + +impl TableNotFoundHint { + pub(crate) fn new(hint: impl Into, source: BoxError) -> Self { + Self { + hint: hint.into(), + source, + } + } +} + +impl Display for TableNotFoundHint { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str(&self.hint) + } +} + +impl std::error::Error for TableNotFoundHint { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(self.source.as_ref()) + } +} + +fn table_not_found_hint<'a>( + source: &'a (dyn std::error::Error + Send + Sync + 'static), +) -> &'a str { + source + .downcast_ref::() + .map(|hint| hint.hint.as_str()) + .unwrap_or_default() +} + #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { @@ -351,7 +391,11 @@ pub enum Error { InvalidTableName { name: String, reason: String }, #[snafu(display("Invalid input, {message}"))] InvalidInput { message: String }, - #[snafu(display("Table '{name}' was not found{}", server_build_suffix(source.as_ref())))] + #[snafu(display( + "Table '{name}' was not found{}{}", + server_build_suffix(source.as_ref()), + table_not_found_hint(source.as_ref()) + ))] TableNotFound { name: String, source: BoxError }, #[snafu(display( "Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}" From d46754cad456a95e8a5cb5b9d76eeebf8e225852 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 22:17:47 +0800 Subject: [PATCH 191/203] feat: register blob bases during table creation (#5117) ## Summary `create_table` / `create_empty_table` now accept registered storage bases and the embedded opt-in for blob URIs outside them. A create with data registers `initial_bases` in the same commit, so external Blob v2 references no longer need an empty create followed by `add`. - Rust `CreateTableBuilder::initial_bases` / `allow_external_blob_outside_bases`, with `BasePath` re-exported. - PyO3 and Python sync/async create paths accept lightweight `BasePath`, dicts, and duck-typed `lance.DatasetBasePath`; `id=None` lets Lance assign an ID and explicit `0` or duplicate explicit IDs are rejected. - `blob_uri_array` builds the standard four-field `lance.blob.v2` array without pylance and keeps field metadata such as `lancedb:logical_type=mp4`. - Enterprise create rejects non-empty `initial_bases` and the true opt-in before normalization, input iteration, or HTTP; empty/false defaults remain an ordinary create. - Native namespace create merges namespace and connection storage options into the caller's store parameters instead of replacing them. This is reconciled with #5114's refresh layering, so caller-scoped options survive create, refresh, and reopen while namespace-vended values keep their precedence. - The outside-base opt-in applies to one write: setting it on create does not carry over to a later `add()`. ## Validation - `cargo fmt --all -- --check`, `cargo check --quiet --features remote --tests --examples`, `cargo clippy --quiet --features remote --tests --examples`. - Rust: `blob_integration` 66 passed, `database::namespace` 23, `connection::create_table` 16, `remote::db` 128. - Python: `test_blob.py` 263 passed / 1 skipped, `test_blob_array.py` 4, remote create 12, `test_db.py -k "pickle or create_table"` 15, `test_namespace.py -k "pickle or refresh or create"` 29, `test_table.py -k pickle` 8; ruff 0.9.9 and pyright from `python/`. - `test_blob.py` also passes with pylance and pandas removed (177 passed / 87 skipped), matching the CI no-pylance suite. The lightweight and dict create cases keep version, schema, reopen, and exact-range assertions there; only the pylance-only manifest introspection moved into the `DatasetBasePath` case. - Rust and sync Python two-base probes assert that base 1's scoped option fails its read while base 2 still returns exact bytes after reopen. A separate async namespace test covers create and reopen with exact ranges. - `test_namespace_refresh_layers_caller_scoped_options` covers the expired namespace seed: create-time `base_1.caller_scoped` survives refresh, vended `timeout` is replaced (7s to 8s), fresh namespace values appear, and reopen with the caller option returns exact blob range bytes through the registered base. - Updated `main` through #5127 (including #5114) is merged; `rust/lancedb/src/database/namespace.rs` and `rust/lancedb/src/table.rs` match `main`, and no #5114 code was stacked before it merged. ## Dependency note The Lance dependency stays pinned at the `v15.0.0-beta.25` release on `main`. With that pin, mixing an automatic base ID (`id=0`) and an explicit non-zero ID may still collide; the approved upstream fix is https://github.com/lance-format/lance/pull/11307. Use distinct explicit non-zero IDs for multi-base creates, or automatic IDs for every base, until a Lance release containing that fix is pinned. A failed mixed create can leave the table name listed but unopenable; retrying with distinct explicit IDs succeeds. Multi-base validation here uses explicit IDs and bootstrap uses a single automatic ID, so the mixed-ID case is not claimed as verified until a Lance release containing that fix is pinned. --- docs/src/python/python.md | 43 ++- python/python/lancedb/__init__.py | 4 +- python/python/lancedb/_lancedb.pyi | 5 + python/python/lancedb/db.py | 64 ++++ python/python/lancedb/namespace.py | 8 + python/python/lancedb/remote/db.py | 16 + python/python/lancedb/schema.py | 199 ++++++++++ python/python/lancedb/table.py | 18 + python/python/tests/test_blob.py | 390 ++++++++++++++++++++ python/python/tests/test_blob_array.py | 130 +++++++ python/python/tests/test_remote_db.py | 120 ++++++ python/src/connection.rs | 156 +++++++- rust/lancedb/src/connection/create_table.rs | 81 ++++ rust/lancedb/src/lib.rs | 1 + rust/lancedb/src/remote/db.rs | 107 ++++++ rust/lancedb/tests/blob_integration.rs | 374 +++++++++++++++++++ 16 files changed, 1708 insertions(+), 8 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5c31d0bb6..1581a21b9 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -948,9 +948,42 @@ 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. +For external blob references, use [blob_uri_array][lancedb.blob_uri_array]. It builds the +same extension type from URI strings and optional `(position, size)` byte +ranges without requiring pylance. Inline `data` and external `uri` representations +are mutually exclusive. + +Register the object prefix with [BasePath][lancedb.BasePath] on +`create_table(..., initial_bases=[...])` to store a matched absolute blob URI +relative to a base and to scope credentials with `base_. @@ -74,19 +84,26 @@ sampling with replacement. In Rust, an explicit nonempty `QueryBase::order_by` list overrides the requested order; limits and offsets apply after restoring repeated rows. -`take_offsets` also preserves repeated offsets, but does not guarantee -input order. It tracks `_rowoffset` internally to restore repeated rows -and drops that column from the output unless you explicitly `select` it. -Add `_rowoffset` to your selection when you need to align a `take_offsets` -result with the input offsets. +`take_offsets` preserves repeated offsets. By default, it does not guarantee +input order and returns found rows as they arrive. Python sync and async +builders accept `preserve_order=True`, and Rust accepts `.preserve_order()`, +to return found rows in input order, including repeated offsets. Missing +non-negative offsets are omitted; negative offsets are rejected and are not +Python-style relative indices. The default unordered path remains the +existing incremental behavior. + +The method tracks `_rowoffset` internally to restore repeated rows and drops +that column from the output unless you explicitly `select` it. Add +`_rowoffset` to your selection when you need to align a `take_offsets` result +with the input offsets. -Ordered takes by row ID collect all matching batches, combine them into one -batch and reorder the rows before returning output batches. Even -`to_batches(max_batch_length=1)` only limits the returned batch size; it -does not bound working memory. For large requests or rows with large -column values, split the input IDs into smaller requests and use -`.select(...)` to fetch only the columns you need. +Ordered takes by row ID, and ordered offset takes with `preserve_order=True`, +collect all matching batches, combine them into one batch and reorder the rows +before returning output batches. Even `to_batches(max_batch_length=1)` only +limits the returned batch size; it does not bound working memory. For large +requests or rows with large column values, split the input IDs or offsets into +smaller requests and use `.select(...)` to fetch only the columns you need. Offsets are mostly useful for sampling: the valid range is always diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 9a53d8985..6bdcfffd1 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -985,6 +985,7 @@ class Query: class TakeQuery: def select(self, columns: List[str]): ... def with_row_id(self): ... + def preserve_order(self): ... def use_rte(self, enable: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute(self) -> RecordBatchStream: ... @@ -1092,6 +1093,7 @@ class PyQueryRequest: offset: Optional[int] take_offsets: Optional[List[int]] take_row_ids: Optional[List[int]] + preserve_order: Optional[bool] filter: Optional[Union[str, bytes]] full_text_search: Optional[FullTextQuery] select: Optional[Union[str, List[str]]] diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 845386181..6d3cf818b 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -1186,6 +1186,9 @@ class Query(pydantic.BaseModel): # Row IDs whose requested order and duplicate occurrences must be restored. take_row_ids: Optional[List[int]] = None + # Restore take-offset duplicates in the exact input order. + preserve_order: Optional[bool] = None + # if true, will only search the indexed data fast_search: Optional[bool] = None @@ -1212,6 +1215,7 @@ class Query(pydantic.BaseModel): query.offset = req.offset query.take_offsets = req.take_offsets query.take_row_ids = req.take_row_ids + query.preserve_order = req.preserve_order query.filter = req.filter query.full_text_query = req.full_text_search query.columns = req.select diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 47d0d048f..dba3a9eaf 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -1556,9 +1556,15 @@ class RemoteTable(Table): return LOOP.run(self._table.uri()) def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> LanceTakeQueryBuilder: - builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + builder = LanceTakeQueryBuilder( + self._table.take_offsets(offsets, preserve_order=preserve_order) + ) if with_row_id: builder.with_row_id() return builder diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 2a44d0221..52ae6b9fd 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2660,7 +2660,11 @@ class Table(ABC): @abstractmethod def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> LanceTakeQueryBuilder: """ Take a list of offsets from the table. @@ -2672,9 +2676,13 @@ class Table(ABC): Offsets are mostly useful for sampling as the set of all valid offsets is easily known in advance to be [0, len(table)). - No guarantees are made regarding the order in which results are returned. - Repeated offsets produce repeated rows, which makes this method suitable for - sampling with replacement. + By default, no guarantees are made regarding the order in which results + are returned. Repeated offsets produce repeated rows, which makes this + method suitable for sampling with replacement. Set ``preserve_order=True`` + to return found rows in input order, including repeated offsets. Missing + non-negative offsets are omitted. Negative offsets are rejected and are + not Python-style relative indices. ``preserve_order`` cannot be combined + with an explicit ``order_by``. Parameters ---------- @@ -2682,6 +2690,10 @@ class Table(ABC): The offsets to take. with_row_id: bool, default False If True, include the "_rowid" column in the results. + preserve_order: bool, default False + If True, return found rows in input order. Rust take queries apply + limit/offset after restoration; Python take builders and Query + conversion do not expose pagination. Returns ------- @@ -4533,9 +4545,15 @@ class LanceTable(Table): return LOOP.run(self._table.version()) def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> LanceTakeQueryBuilder: - builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets)) + builder = LanceTakeQueryBuilder( + self._table.take_offsets(offsets, preserve_order=preserve_order) + ) if with_row_id: builder.with_row_id() return builder @@ -8449,10 +8467,18 @@ class AsyncTable: if query.take_offsets is not None or query.take_row_ids is not None: if query.take_offsets is not None and query.take_row_ids is not None: raise ValueError("Only one of take_offsets and take_row_ids may be set") + if query.preserve_order is True and query.take_offsets is None: + raise ValueError("preserve_order only supports take_offsets") + if query.preserve_order is True and query.order_by: + raise ValueError( + "preserve_order cannot be combined with an explicit order_by" + ) take_query = ( self.take_row_ids(query.take_row_ids) if query.take_row_ids is not None - else self.take_offsets(query.take_offsets) + else self.take_offsets( + query.take_offsets, preserve_order=query.preserve_order is True + ) ) if query.columns is not None: columns = query.columns @@ -9662,7 +9688,11 @@ class AsyncTable: await self._inner.restore(version) def take_offsets( - self, offsets: list[int], *, with_row_id: bool = False + self, + offsets: list[int], + *, + with_row_id: bool = False, + preserve_order: bool = False, ) -> AsyncTakeQuery: """ Take a list of offsets from the table. @@ -9674,8 +9704,12 @@ class AsyncTable: Offsets are mostly useful for sampling as the set of all valid offsets is easily known in advance to be [0, len(table)). - No guarantees are made regarding the order in which results are returned. - Repeated offsets produce repeated rows. + By default, no guarantees are made regarding the order in which results + are returned. Repeated offsets produce repeated rows. Set + ``preserve_order=True`` to return found rows in input order, including + repeated offsets. Missing non-negative offsets are omitted. Negative + offsets are rejected and are not Python-style relative indices. + ``preserve_order`` cannot be combined with an explicit ``order_by``. Parameters ---------- @@ -9683,6 +9717,10 @@ class AsyncTable: The offsets to take. with_row_id: bool, default False If True, include the "_rowid" column in the results. + preserve_order: bool, default False + If True, return found rows in input order. Rust take queries apply + limit/offset after restoration; Python take builders and Query + conversion do not expose pagination. Returns ------- @@ -9691,6 +9729,8 @@ class AsyncTable: offsets. """ query = AsyncTakeQuery(self._inner.take_offsets(offsets), self) + if preserve_order: + query._inner.preserve_order() if with_row_id: query.with_row_id() return query diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index 7373bbdf4..57dbc09ff 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode(): 1: b"one", 2: b"two", } + ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow( + blob_mode="bytes" + ) + assert ordered["id"].to_pylist() == [2, 1] + assert ordered["image"].to_pylist() == [b"two", b"one"] assert [ row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes") ] == [b"one"] diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index c9a96167c..ec747bd40 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -975,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async): df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes") assert set(df["blob"]) == {b"two", b"three"} + ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas( + blob_mode="bytes" + ) + assert ordered["blob"].tolist() == [b"three", b"two"] def test_order_by_plain_query(mem_db): @@ -2815,6 +2819,86 @@ def test_take_queries(tmp_path): assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17] +def test_take_offsets_preserve_order_sync(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", pa.table({"idx": range(4)})) + table.add(pa.table({"idx": range(4, 8)})) + table.delete("idx IN (1, 6)") + requested = [5, 0, 5, 2, 99, 4, 0] + expected = [7, 0, 7, 3, 5, 0] + + actual = ( + table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow() + ) + assert actual.column_names == ["idx"] + assert actual["idx"].to_pylist() == expected + + batches = list( + table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_batches(max_batch_length=1) + ) + assert all(batch.num_rows <= 1 for batch in batches) + assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected + + # The default path keeps its unspecified-order behavior. + default = table.take_offsets(requested).select(["idx"]).to_arrow() + assert sorted(default["idx"].to_pylist()) == sorted(expected) + + assert table.take_offsets(requested).to_query_object().preserve_order is None + query = ( + table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_query_object() + ) + assert query.preserve_order is True + assert table._execute_query(query).read_all()["idx"].to_pylist() == expected + + empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow() + assert empty.num_rows == 0 + assert empty.column_names == ["idx"] + + query.order_by = [ColumnOrdering(column_name="idx")] + with pytest.raises( + ValueError, match="preserve_order cannot be combined with an explicit order_by" + ): + table._execute_query(query) + + +@pytest.mark.asyncio +async def test_take_offsets_preserve_order_async(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", pa.table({"idx": range(4)})) + await table.add(pa.table({"idx": range(4, 8)})) + await table.delete("idx IN (1, 6)") + requested = [5, 0, 5, 2, 99, 4, 0] + expected = [7, 0, 7, 3, 5, 0] + + actual = ( + await table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_arrow() + ) + assert actual.column_names == ["idx"] + assert actual["idx"].to_pylist() == expected + + reader = ( + await table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_batches(max_batch_length=1) + ) + batches = [batch async for batch in reader] + assert all(batch.num_rows <= 1 for batch in batches) + assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected + + query = ( + table.take_offsets(requested, preserve_order=True) + .select(["idx"]) + .to_query_object() + ) + assert query.preserve_order is True + + @pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}]) @pytest.mark.parametrize("empty", [False, True]) def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty): @@ -2921,6 +3005,13 @@ def test_getitems(tmp_path): assert table.__getitems__(offsets) == pa.table({"idx": offsets}) +def test_getitems_rejects_missing_offsets(tmp_path): + table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)})) + + with pytest.raises(pa.ArrowIndexError, match="out of bounds"): + table.__getitems__([0, 99]) + + @pytest.mark.asyncio async def test_query_timeout_async(tmp_path): db = await lancedb.connect_async(tmp_path) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a4edd78a0..7089f1e0b 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1404,6 +1404,12 @@ def test_remote_permutation_is_picklable(): {"a": 2}, {"a": 4}, ] + assert table.take_offsets([0, 2, 0, 4], preserve_order=True).to_list() == [ + {"a": 0}, + {"a": 2}, + {"a": 0}, + {"a": 4}, + ] permutation = Permutation.identity(table) restored = pickle.loads(pickle.dumps(permutation)) @@ -6083,14 +6089,26 @@ def blob_remote_table( if requests is not None: requests.append(("query", body)) columns = body.get("columns") - assert columns in ( + take_offsets_query = isinstance(columns, list) and "_rowoffset" in columns + assert take_offsets_query or columns in ( None, ["id", "image"], ["id"], ["image"], {"payload": "image"}, ) - if isinstance(columns, dict): + if take_offsets_query: + response_table = blob_query_response_table().append_column( + "_rowoffset", pa.array(range(3), type=pa.uint64()) + ) + response_table = response_table.select( + [name for name in columns if name != "_rowid"] + ) + if body.get("with_row_id", False): + response_table = response_table.append_column( + "_rowid", blob_query_response_table()["_rowid"] + ) + elif isinstance(columns, dict): response_table = blob_query_response_table().select(["image", "_rowid"]) response_table = response_table.rename_columns(["payload", "_rowid"]) if not body.get("with_row_id", False): @@ -6725,6 +6743,18 @@ def test_remote_blob_fetch_accepts_metadata_free_query_table(api): handle.close() +def test_remote_take_offsets_preserve_order_with_blob_bytes(): + with blob_remote_table() as table: + hits = ( + table.take_offsets([2, 0, 2], preserve_order=True) + .select(["id", "image"]) + .to_arrow(blob_mode="bytes") + ) + + assert hits["id"].to_pylist() == [3, 1, 3] + assert hits["image"].to_pylist() == [b"gamma", b"alpha", b"gamma"] + + @pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"]) def test_remote_blob_fetch_from_query_result_keeps_query_snapshot(api): requests = [] diff --git a/python/src/query.rs b/python/src/query.rs index 3c6d9d662..2c1a606eb 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -357,6 +357,7 @@ pub struct PyQueryRequest { pub offset: Option, pub take_offsets: Option>, pub take_row_ids: Option>, + pub preserve_order: Option, pub filter: Option, pub full_text_search: Option>, pub select: PySelect, @@ -390,6 +391,7 @@ impl From for PyQueryRequest { offset: query_request.offset, take_offsets: query_request.take_offsets, take_row_ids: query_request.take_row_ids, + preserve_order: query_request.preserve_order.then_some(true), filter: query_request.filter.map(PyQueryFilter), full_text_search: query_request .full_text_search @@ -423,6 +425,7 @@ impl From for PyQueryRequest { offset: vector_query.base.offset, take_offsets: vector_query.base.take_offsets, take_row_ids: vector_query.base.take_row_ids, + preserve_order: vector_query.base.preserve_order.then_some(true), filter: vector_query.base.filter.map(PyQueryFilter), full_text_search: None, select_source_columns: PySelect::source_columns(&vector_query.base.select), @@ -765,6 +768,10 @@ impl TakeQuery { self.inner = self.inner.clone().with_row_id(); } + pub fn preserve_order(&mut self) { + self.inner = self.inner.clone().preserve_order(); + } + pub fn use_rte(&mut self, enable: bool) { self.inner = self.inner.clone().use_rte(enable); } diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 157440910..57af7f28d 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -867,6 +867,13 @@ pub struct QueryRequest { #[doc(hidden)] pub take_row_ids: Option>, + /// Restore `take_offsets` occurrences in the exact requested input order. + /// + /// This is client-side execution metadata and is not sent to remote + /// services. It cannot be combined with an explicit `order_by`. + #[doc(hidden)] + pub preserve_order: bool, + /// Apply filter to the returned rows. pub filter: Option, @@ -937,6 +944,7 @@ impl Default for QueryRequest { offset: None, take_offsets: None, take_row_ids: None, + preserve_order: false, filter: None, filter_error: None, full_text_search: None, @@ -2065,7 +2073,6 @@ impl ExecutionPlan for TakeRestoreExec { pub struct TakeQuery { parent: Arc, request: QueryRequest, - preserve_order: bool, } struct TakeLookup { @@ -2100,7 +2107,6 @@ impl TakeQuery { take_offsets: Some(offsets), ..Default::default() }, - preserve_order: false, } } @@ -2122,16 +2128,17 @@ impl TakeQuery { take_row_ids: Some(row_ids), ..Default::default() }, - preserve_order: false, } } /// Preserve the requested offset order when restoring duplicate occurrences. /// - /// This is reserved for readers whose API explicitly guarantees ordering. - pub(crate) fn preserve_order(mut self) -> Self { + /// Found rows follow the input order, including repeated offsets. Missing + /// non-negative offsets are omitted. This cannot be combined with an + /// explicit `order_by`. + pub fn preserve_order(mut self) -> Self { debug_assert!(self.request.take_offsets.is_some()); - self.preserve_order = true; + self.request.preserve_order = true; self } @@ -2203,8 +2210,25 @@ impl TakeQuery { }); } }; - let preserve_order = - preserve_order || (by_row_id && request.order_by.as_ref().is_none_or(Vec::is_empty)); + // The explicit flag only applies to offset takes. Row-id takes retain + // their existing implicit ordering behavior: input order when no sort is + // requested, and the explicit sort otherwise. + let explicit_preserve_order = !by_row_id && (preserve_order || request.preserve_order); + if explicit_preserve_order + && request + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return Err(Error::InvalidInput { + message: "preserve_order cannot be combined with an explicit order_by".to_string(), + }); + } + let preserve_order = if by_row_id { + request.order_by.as_ref().is_none_or(Vec::is_empty) + } else { + explicit_preserve_order + }; let (mut request, ordering_column, drop_ordering_column, output_projection) = if by_row_id { let mut request = request.clone(); let with_row_id = request.with_row_id; @@ -2527,7 +2551,7 @@ impl ExecutableQuery for TakeQuery { self.parent.as_ref(), &self.request, options, - self.preserve_order, + self.request.preserve_order, ) .await; } @@ -2564,7 +2588,7 @@ impl ExecutableQuery for TakeQuery { self.parent.as_ref(), &self.request, verbose, - self.preserve_order, + self.request.preserve_order, ) .await; } @@ -4295,6 +4319,53 @@ mod tests { ); } + async fn make_preserve_order_test_table(tmp_dir: &tempfile::TempDir) -> Table { + let dataset_path = tmp_dir.path().join("preserve_order.lance"); + let conn = connect(dataset_path.to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_table( + "my_table", + RecordBatch::try_from_iter([( + "idx", + Arc::new(Int32Array::from(vec![0, 1, 2, 3])) as Arc, + )]) + .unwrap(), + ) + .execute() + .await + .unwrap(); + table + .add( + RecordBatch::try_from_iter([( + "idx", + Arc::new(Int32Array::from(vec![4, 5, 6, 7])) as Arc, + )]) + .unwrap(), + ) + .execute() + .await + .unwrap(); + table.delete("idx IN (1, 6)").await.unwrap(); + table + } + + fn collect_ids(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("idx") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect() + } + #[tokio::test] async fn test_take_offsets_applies_pagination_after_restoration() { let tmp_dir = tempdir().unwrap(); @@ -4345,6 +4416,104 @@ mod tests { ); } + #[tokio::test] + async fn test_take_offsets_preserve_order_across_fragments_deletes_and_batches() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + let offsets = vec![5, 0, 5, 2, 99, 4, 0]; + let expected = vec![7, 0, 7, 3, 5, 0]; + + let batches = table + .take_offsets(offsets.clone()) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + assert!(batches.iter().all(|batch| batch.num_rows() <= 1)); + assert_eq!(collect_ids(&batches), expected); + + let converted = table + .take_offsets(offsets) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .into_request(); + let batches = table + .base_table() + .query( + &AnyQuery::Query(converted), + QueryExecutionOptions::default(), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_ids(&batches), expected); + + let batches = table + .take_offsets(vec![]) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 0); + } + + #[tokio::test] + async fn test_take_offsets_preserve_order_paginates_after_restoration() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + + let batches = table + .take_offsets(vec![5, 0, 5, 2, 4, 0]) + .preserve_order() + .select(Select::Columns(vec!["idx".to_string()])) + .offset(2) + .limit(4) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_ids(&batches), vec![7, 3, 5, 0]); + } + + #[tokio::test] + async fn test_take_offsets_preserve_order_rejects_order_by() { + let tmp_dir = tempdir().unwrap(); + let table = make_preserve_order_test_table(&tmp_dir).await; + + let error = table + .take_offsets(vec![0, 2]) + .preserve_order() + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "idx".to_string(), + )])) + .execute() + .await + .err() + .unwrap(); + assert!( + error + .to_string() + .contains("preserve_order cannot be combined with an explicit order_by"), + "{error}" + ); + } + #[tokio::test] async fn test_take_offsets_create_plan_restores_occurrences() { let tmp_dir = tempdir().unwrap(); @@ -4613,6 +4782,35 @@ mod tests { } } + #[tokio::test] + async fn test_take_row_ids_ignores_offset_preserve_flag_with_explicit_sort() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let mut request = table + .take_row_ids(vec![17, 5, 1, 5]) + .order_by(Some(vec![ColumnOrdering::asc_nulls_first( + "id".to_string(), + )])) + .offset(1) + .limit(2) + .into_request(); + request.preserve_order = true; + + let batches = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let actual = concat_batches(&batches[0].schema(), &batches).unwrap(); + assert_eq!( + actual["id"].as_primitive::().values().as_ref(), + &[5, 5] + ); + } + #[tokio::test] async fn test_take_row_ids_explicit_order_by() { let tmp_dir = tempdir().unwrap(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 4c7f3a105..760ab83fe 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3420,7 +3420,8 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - return crate::query::create_take_plan(self, request, options, false).await; + return crate::query::create_take_plan(self, request, options, request.preserve_order) + .await; } let streams = self.execute_query(query, &options).await?; @@ -3444,8 +3445,13 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - let plan = - crate::query::create_take_plan(self, request, options.clone(), false).await?; + let plan = crate::query::create_take_plan( + self, + request, + options.clone(), + request.preserve_order, + ) + .await?; let inner = execute_plan(plan, Default::default())?; let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize); let inner = if let Some(timeout) = options.timeout { @@ -3508,7 +3514,8 @@ impl BaseTable for RemoteTable { if let AnyQuery::Query(request) = query && request.has_take() { - return crate::query::explain_take_plan(self, request, verbose, false).await; + return crate::query::explain_take_plan(self, request, verbose, request.preserve_order) + .await; } let base_request = self @@ -8601,8 +8608,8 @@ mod tests { Field::new("_rowoffset", DataType::UInt64, false), ])), vec![ - Arc::new(Int32Array::from(vec![5])), - Arc::new(arrow_array::UInt64Array::from(vec![5])), + Arc::new(Int32Array::from(vec![1, 5])), + Arc::new(arrow_array::UInt64Array::from(vec![1, 5])), ], ) .unwrap(); @@ -8614,7 +8621,8 @@ mod tests { }); let request = table - .take_offsets(vec![5, 5]) + .take_offsets(vec![5, 1, 5]) + .preserve_order() .select(crate::query::Select::columns(&["id"])) .into_request(); let batches = table @@ -8626,12 +8634,24 @@ mod tests { .await .unwrap(); - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 3); assert!( batches .iter() .all(|batch| batch.schema().fields().len() == 1) ); + let ids = batches + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect::>(); + assert_eq!(ids, vec![5, 1, 5]); } #[rstest::rstest] diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 6789714e1..b69b85cb3 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -180,7 +180,8 @@ pub async fn create_plan( if let AnyQuery::Query(request) = &query && request.has_take() { - return crate::query::create_take_plan(table, request, options, false).await; + return crate::query::create_take_plan(table, request, options, request.preserve_order) + .await; } let query = match query { From 13fe33581e6fa0c9433f0ff99e6981eab4ba1a07 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 04:41:11 +0800 Subject: [PATCH 199/203] perf(python): add direct sync query execution (#5141) ## Summary Route ordinary local `table.search(...).to_arrow()` queries through private synchronous schema and eager-collection bindings instead of the Python background event loop. Plain scans, vector searches (including default vector-column inference), and native FTS in lazy Blob mode now complete with zero `LOOP.run` submissions. The synchronous path reuses the existing query lowering, core query execution, eager collector, Arrow ownership, projection validation, fragments, row ids, Blob finalization, reranking, and snapshot handling. It uses the generation-scoped Tokio runtime and `OutstandingGuard`, releases the GIL while waiting, checks CPython signals on the caller thread at a bounded interval, and aborts and drops collected state when a handler raises. Multi-threaded Tokio callback re-entry uses `block_in_place`; current-thread contexts return a Python error. Namespace, RemoteTable, Enterprise, streaming, take, and non-lazy Blob routing are unchanged. No public API is added. ## Benchmark Workload: 200,000 rows, 64 dimensions, BTREE on `id`, IVF_PQ on `vector`; 50 warmups + 500 calls, p50/p99 of three alternating runs. Build: `release-with-debug`. Baseline Python package from `03fc5404` ran against the same candidate extension as the candidate, so this isolates the Python event-loop route; a separately built matching baseline extension is a follow-up validation target. The host had competing Rust builds, so these numbers are preliminary, not isolated release throughput. | Workload | LOOP/schema per call before -> after | p50 before -> after | p99 before -> after | |---|---|---|---| | plain point lookup `to_arrow()` | 2 / 1 -> 0 / 1 | 2.32 / 3.26 / 2.64 ms -> 1.64 / 1.89 / 1.80 ms | 3.87 / 3.92 / 3.69 ms -> 2.42 / 2.63 / 2.62 ms | | indexed vector `to_arrow()` | 3 / 2 -> 0 / 2 | 5.20 / 5.13 / 3.79 ms -> 4.65 / 4.22 / 4.31 ms | 7.18 / 7.52 / 6.45 ms -> 6.29 / 6.01 / 6.43 ms | `to_batches()` remains on the existing streaming path. OSS-2868 1/2/4/8/16-thread scaling and fully matched build artifacts remain separate follow-up. ## Validation - `test_sync_query_direct.py`: plain/vector/native FTS with `LOOP.run` patched to fail, default vector inference, empty schema, timeout, single-worker progress-callback re-entry, and SIGINT/runtime reuse. - `test_query.py` with direct tests: 253 passed, 1 skipped. - `test_blob.py`: 266 passed, 1 skipped. - `test_fts.py` + `test_rerankers.py`: 163 passed, 13 skipped. - `test_table.py` + `test_namespace.py` + `test_sync_api_parity.py`: 649 passed, 17 skipped. - Remote query/blob/schema subset: 206 passed. - Runtime unit tests: 12 passed; `cargo check`, `cargo clippy`, `cargo fmt --check`, and Python ruff passed. The SIGINT case is marked slow and was run in focused validation; it is not part of the default suite. Refs OSS-2867 (non-closing). --- python/python/lancedb/_lancedb.pyi | 10 + python/python/lancedb/query.py | 60 ++++++ python/python/lancedb/table.py | 15 +- python/python/tests/test_query.py | 8 +- python/python/tests/test_sync_query_direct.py | 160 ++++++++++++++ python/src/arrow.rs | 53 +++-- python/src/query.rs | 50 +++++ python/src/runtime.rs | 200 +++++++++++++++++- python/src/table.rs | 10 +- 9 files changed, 546 insertions(+), 20 deletions(-) create mode 100644 python/python/tests/test_sync_query_direct.py diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 6bdcfffd1..eb8536f3e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -575,6 +575,7 @@ class Table: def _is_native(self) -> bool: ... def close(self) -> None: ... async def schema(self) -> pa.Schema: ... + def schema_sync(self) -> pa.Schema: ... async def add( self, data: pa.RecordBatchReader, @@ -976,6 +977,9 @@ class Query: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1021,6 +1025,9 @@ class FTSQuery: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... async def explain_plan(self, verbose: Optional[bool]) -> str: ... async def analyze_plan( self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None @@ -1033,6 +1040,9 @@ class VectorQuery: async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def execute_to_reader_sync( + self, max_batch_length: Optional[int], timeout: Optional[timedelta] + ) -> pa.RecordBatchReader: ... def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... def select(self, columns: List[Tuple[str, str]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 6d3cf818b..19e9051f7 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -4033,6 +4033,26 @@ class AsyncQueryBase(object): self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) self._inner.with_row_id() + def _maybe_add_blob_row_id_sync(self) -> None: + if self._table is None: + self._blob_auto_row_id = False + self._blob_paths = () + return + + req = self._inner.to_query_request() + schema = self._table._schema_sync() + projection = _query_request_projection(req) + self._blob_auto_row_id = blob_auto_row_id_for_scan( + schema, + projection, + with_row_id=self._with_row_id, + ) + if not self._blob_auto_row_id: + self._blob_paths = () + return + self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) + self._inner.with_row_id() + async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool: if blob_mode != "bytes" or self._table is None: return False @@ -4220,6 +4240,18 @@ class AsyncQueryBase(object): reader = await self._inner.execute_to_reader(None, timeout) return pa.Table.from_batches(reader, schema=reader.schema) + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + """Execute with the synchronous native eager collector.""" + self._ensure_fragment_constraints_supported("to_arrow()") + if not self._blob_row_id_prepared: + self._maybe_add_blob_row_id_sync() + reader = self._inner.execute_to_reader_sync(None, timeout) + return pa.Table.from_batches(reader, schema=reader.schema) + async def _execute_batches( self, *, @@ -5118,6 +5150,22 @@ class AsyncFTSQuery(AsyncStandardQuery): results = _merge_query_snapshot(results, source) return results + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + try: + results = super()._execute_eager_sync(timeout=timeout) + except Exception as error: + _add_fts_position_error_note(error) + raise + if self._reranker: + source = results + results = self._reranker.rerank_fts(self.get_query(), results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, @@ -5480,6 +5528,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase): results = _merge_query_snapshot(results, source) return results + def _execute_eager_sync( + self, + *, + timeout: Optional[timedelta] = None, + ) -> pa.Table: + results = super()._execute_eager_sync(timeout=timeout) + if self._reranker: + source = results + results = self._reranker.rerank_vector(self._query_string, results) + results = _merge_query_snapshot(results, source) + return results + async def _execute_batches( self, *, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 52ae6b9fd..fdcea6aa8 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4533,7 +4533,10 @@ class LanceTable(Table): ------- pa.Schema A PyArrow schema object.""" - return LOOP.run(self._table.schema()) + schema_sync = getattr(self._table, "_schema_sync", None) + if schema_sync is None: + return LOOP.run(self._table.schema()) + return schema_sync() def list_versions(self) -> List[Dict[str, Any]]: """List all versions of the table""" @@ -6060,6 +6063,13 @@ class LanceTable(Table): async_query = self._table._sync_query_to_async(query) async_query._blob_row_id_prepared = query._blob_row_id_prepared + if ( + self._table._inner._is_native() + and self._namespace_client is None + and not self._route_pushdown_to_rust + and isinstance(async_query, (AsyncQuery, AsyncVectorQuery, AsyncFTSQuery)) + ): + return async_query._execute_eager_sync(timeout=timeout) return LOOP.run(async_query._execute_eager(timeout=timeout)) def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: @@ -7430,6 +7440,9 @@ class AsyncTable: """ return _restore_blob_extensions(await self._inner.schema()) + def _schema_sync(self) -> pa.Schema: + return _restore_blob_extensions(self._inner.schema_sync()) + async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]: """ Get the embedding functions for the table diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index ec747bd40..c01b3f9dc 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -2676,14 +2676,14 @@ def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch): ) calls = 0 - original = AsyncTable.schema + original = AsyncTable._schema_sync - async def counted(self): + def counted(self): nonlocal calls calls += 1 - return await original(self) + return original(self) - monkeypatch.setattr(AsyncTable, "schema", counted) + monkeypatch.setattr(AsyncTable, "_schema_sync", counted) table.search().where("id = 1").select(["id"]).to_arrow() assert calls <= 1 diff --git a/python/python/tests/test_sync_query_direct.py b/python/python/tests/test_sync_query_direct.py new file mode 100644 index 000000000..9863f66c4 --- /dev/null +++ b/python/python/tests/test_sync_query_direct.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import signal +import os +import subprocess +import sys +import threading +from datetime import timedelta + +import pyarrow as pa +import pytest + +import lancedb +from lancedb import background_loop +from lancedb.index import BTree, FTS, IvfFlat + + +def _direct_query_table(tmp_path): + table = lancedb.connect(tmp_path).create_table( + "direct", + pa.table( + { + "id": pa.array([1, 2, 3, 4], pa.int64()), + "text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"], + "vector": pa.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + pa.list_(pa.float32(), 4), + ), + } + ), + ) + table.create_index("id", config=BTree()) + table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1)) + table.create_index("text", config=FTS(with_position=True)) + return table + + +def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch): + table = _direct_query_table(tmp_path) + expected_empty_schema = table.search().where("id < 0").output_schema() + + def fail(*_args, **_kwargs): + raise AssertionError("LOOP.run must not be used by direct sync queries") + + monkeypatch.setattr(background_loop.LOOP, "run", fail) + + point = table.search().where("id = 1").select(["id", "text"]).to_arrow() + assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}] + + with_row_id = ( + table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow() + ) + assert with_row_id["_rowid"].to_pylist() == [0] + + # The vector column is inferred from the sync schema binding. + vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow() + assert vector["id"].to_pylist() == [1, 2] + assert "_distance" in vector.column_names + + fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow() + assert sorted(fts["id"].to_pylist()) == [1, 2] + assert "_score" in fts.column_names + + phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow() + assert phrase["id"].to_pylist() == [1] + + empty = table.search().where("id < 0").to_arrow() + assert empty.num_rows == 0 + assert empty.schema == expected_empty_schema + + with pytest.raises(Exception, match="Query timeout"): + table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0)) + + +@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity") +def test_direct_sync_query_from_single_worker_progress_callback(tmp_path): + script = r""" +import os +import sys + +try: + cpus = sorted(os.sched_getaffinity(0)) + if not cpus: + print("SKIP") + sys.exit(0) + os.sched_setaffinity(0, {cpus[0]}) +except OSError: + print("SKIP") + sys.exit(0) + +import lancedb + +db = lancedb.connect("memory:///") +target = db.create_table( + "target", + [{"id": 1, "value": "one"}, {"id": 2, "value": "two"}], +) +source = db.create_table("source", [{"id": 1}]) +seen = [] + +def progress(_update): + if not seen: + seen.append( + target.search() + .where("id = 1") + .select(["value"]) + .to_arrow() + .to_pylist() + ) + +source.add([{"id": 2}], progress=progress) +assert seen == [[{"value": "one"}]], seen +print("OK") +""" + result = subprocess.run( + [sys.executable, "-c", script], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=30, + ) + if "SKIP" in result.stdout: + pytest.skip("sched_setaffinity did not leave a usable CPU") + assert result.returncode == 0, result.stdout + result.stderr + assert "OK" in result.stdout + + +@pytest.mark.slow +def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path): + rows = 500_000 + table = lancedb.connect(tmp_path).create_table( + "sigint", + pa.table( + { + "id": pa.array(range(rows), pa.int64()), + "text": pa.array([f"row-{row}" for row in range(rows)]), + } + ), + ) + # Warm the runtime and page cache so the timed call is long enough to observe. + table.search().select(["id"]).to_arrow() + + timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT)) + timer.start() + try: + with pytest.raises(KeyboardInterrupt): + table.search().select(["id", "text"]).to_arrow() + finally: + timer.cancel() + timer.join() + + # The shared runtime and its generation counter remain usable. + after = table.search().where("id = 1").select(["id", "text"]).to_arrow() + assert after.to_pylist() == [{"id": 1, "text": "row-1"}] diff --git a/python/src/arrow.rs b/python/src/arrow.rs index 0384f2b2a..a4de3a911 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::time::Duration; use crate::error::PythonErrorExt; -use crate::runtime::future_into_py; +use crate::runtime::{block_on_interruptible, future_into_py}; use arrow::{ datatypes::SchemaRef, pyarrow::{IntoPyArrow, ToPyArrow}, @@ -89,18 +89,45 @@ where Q: ExecutableQuery + Send + 'static, { future_into_py(py, async move { - let mut options = QueryExecutionOptions::default(); - // `None` means the caller wants one eager result, not the core's - // default batch size. An explicit value is still honored. - options.max_batch_length = max_batch_length.unwrap_or(0); - options.timeout = timeout; - let stream = query.execute_with_options(options).await.infer_error()?; - let schema = stream.schema(); - let batches = stream.try_collect::>().await.infer_error()?; - let reader: Box = Box::new(RecordBatchIterator::new( - batches.into_iter().map(Ok), - schema, - )); + let reader = collect_to_reader(query, max_batch_length, timeout).await?; Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) }) } + +/// Synchronous counterpart of [`execute_to_reader`]. +/// +/// The returned reader owns the collected batches; the caller converts it to +/// Python after reattaching to the interpreter. The wait releases the GIL and +/// keeps Python signal handlers on the calling thread. +pub fn execute_to_reader_sync( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + block_on_interruptible(collect_to_reader(query, max_batch_length, timeout)) +} + +async fn collect_to_reader( + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let mut options = QueryExecutionOptions::default(); + // `None` means the caller wants one eager result, not the core's + // default batch size. An explicit value is still honored. + options.max_batch_length = max_batch_length.unwrap_or(0); + options.timeout = timeout; + let stream = query.execute_with_options(options).await.infer_error()?; + let schema = stream.schema(); + let batches = stream.try_collect::>().await.infer_error()?; + Ok(Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + ))) +} diff --git a/python/src/query.rs b/python/src/query.rs index 2c1a606eb..7a7e34416 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -33,6 +33,7 @@ use lancedb::query::{HasQuery, QueryBase}; use lancedb::table::AnyQuery; use pyo3::Bound; use pyo3::IntoPyObject; +use pyo3::Py; use pyo3::PyAny; use pyo3::PyRef; use pyo3::PyResult; @@ -65,6 +66,20 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +where + Q: ExecutableQuery + Send + 'static, +{ + let reader = + py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?; + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) +} + impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { type Error = PyErr; @@ -713,6 +728,15 @@ impl Query { crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { @@ -966,6 +990,23 @@ impl FTSQuery { ) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync( + self_.py(), + self_ + .inner + .clone() + .full_text_search(self_.fts_query.clone()), + max_batch_length, + timeout, + ) + } + pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult> { let mut inner = self_ .inner @@ -1219,6 +1260,15 @@ impl VectorQuery { crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) } + #[pyo3(signature = (max_batch_length=None, timeout=None))] + pub fn execute_to_reader_sync( + self_: PyRef<'_, Self>, + max_batch_length: Option, + timeout: Option, + ) -> PyResult> { + execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { diff --git a/python/src/runtime.rs b/python/src/runtime.rs index 85d536939..436b0d40b 100644 --- a/python/src/runtime.rs +++ b/python/src/runtime.rs @@ -93,15 +93,19 @@ //! `Arc` clone from becoming the final owner that drops it. use std::future::Future; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, RecvTimeoutError}; use std::time::{Duration, Instant}; use arc_swap::ArcSwapOption; -use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject}; +use futures::FutureExt; +use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError}; use pyo3_async_runtimes::{ TaskLocals, + err::RustPanic, generic::{ContextExt, JoinError, Runtime}, }; use tokio::{runtime, task}; @@ -282,6 +286,111 @@ pub fn block_on(fut: F) -> F::Output { get_runtime().block_on(fut) } +/// How often an interruptible wait returns to the Python caller for signal checks. +const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25); + +/// Block on `fut` while keeping the Python caller responsive to signals. +/// +/// The query task lives on the shared runtime and carries an [`OutstandingGuard`]. +/// The caller waits on the result channel without holding the GIL and periodically +/// reacquires it to run CPython's signal handlers on the same thread. A signal +/// exception aborts the task and drops the result receiver. +/// +/// A synchronous callback already running on a multi-threaded Tokio worker uses +/// [`tokio::task::block_in_place`] so the core can be handed off while the callback +/// waits. Current-thread runtimes and contexts that reject blocking are returned as +/// Python errors instead of falling back to the Python event loop. +pub fn block_on_interruptible(fut: F) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, +{ + block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals())) +} + +fn block_on_interruptible_with(fut: F, check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + match runtime::Handle::try_current() { + Ok(handle) => match handle.runtime_flavor() { + runtime::RuntimeFlavor::MultiThread => { + let result = catch_unwind(AssertUnwindSafe(|| { + task::block_in_place(|| block_on_interruptible_inner(fut, check)) + })); + match result { + Ok(result) => result, + Err(payload) => Err(PyRuntimeError::new_err(format!( + "synchronous query cannot block in this Tokio context: {}", + panic_message(payload.as_ref()) + ))), + } + } + _ => Err(PyRuntimeError::new_err( + "synchronous query execution cannot block on a current-thread Tokio runtime; use the async API", + )), + }, + Err(_) => block_on_interruptible_inner(fut, check), + } +} + +fn block_on_interruptible_inner(fut: F, mut check: C) -> PyResult +where + F: Future> + Send + 'static, + T: Send + 'static, + C: FnMut() -> PyResult<()>, +{ + let guard = OutstandingGuard::new(); + let (tx, rx) = mpsc::sync_channel(1); + let task = async move { + let _guard = guard; + let result = AssertUnwindSafe(fut).catch_unwind().await; + // Dropping a completed result is enough when the caller has already + // returned on an interrupt; the task's guard is dropped with it. + let _ = tx.send(result); + }; + let handle = get_runtime().spawn(task); + + loop { + match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) { + Ok(Ok(result)) => { + check()?; + return result; + } + Ok(Err(payload)) => { + check()?; + return Err(RustPanic::new_err(format!( + "rust future panicked: {}", + panic_message(payload.as_ref()) + ))); + } + Err(RecvTimeoutError::Timeout) => { + if let Err(error) = check() { + handle.abort(); + return Err(error); + } + } + Err(RecvTimeoutError::Disconnected) => { + return Err(PyRuntimeError::new_err( + "query task stopped before producing a result", + )); + } + } + } +} + +fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str { + if let Some(message) = payload.downcast_ref::<&str>() { + message + } else if let Some(message) = payload.downcast_ref::() { + message.as_str() + } else { + "unknown error" + } +} + /// Run a detached task, including when the caller is already on a runtime worker. /// Keep it visible to [`shutdown`] until it finishes. pub fn spawn_background(fut: F) @@ -571,6 +680,95 @@ mod tests { shutdown(Duration::from_secs(5)); } + #[test] + fn test_block_on_interruptible_aborts_and_drops_future() { + use std::sync::mpsc; + + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let (started_tx, started_rx) = mpsc::channel(); + let (dropped_tx, dropped_rx) = mpsc::channel(); + + struct DropNotify(Option>); + impl Drop for DropNotify { + fn drop(&mut self) { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + } + } + } + + let fut = async move { + started_tx.send(()).unwrap(); + let _notify = DropNotify(Some(dropped_tx)); + std::future::pending::<()>().await; + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }; + let result = block_on_interruptible_with(fut, || { + Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted")) + }); + + assert!(result.is_err()); + started_rx + .recv_timeout(Duration::from_secs(2)) + .expect("query task never started"); + dropped_rx + .recv_timeout(Duration::from_secs(2)) + .expect("interrupted query future was not dropped"); + shutdown(Duration::from_secs(5)); + } + + #[test] + fn test_block_on_interruptible_maps_panic() { + Python::initialize(); + let result = block_on_interruptible(async { + panic!("boom"); + #[allow(unreachable_code)] + Ok::<(), pyo3::PyErr>(()) + }); + assert!( + result + .expect_err("panic must become a Python exception") + .to_string() + .contains("rust future panicked: boom") + ); + } + + #[test] + fn test_block_on_interruptible_rejects_current_thread_runtime() { + Python::initialize(); + let runtime = runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current-thread runtime"); + let error = runtime + .block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) }) + .expect_err("current-thread runtime must be rejected"); + assert!(error.to_string().contains("current-thread")); + } + + #[cfg(target_os = "linux")] + #[test] + fn test_block_on_interruptible_from_single_worker_runtime() { + Python::initialize(); + let _lock = lock_runtime_state_for_test(); + let _worker_threads = TestWorkerThreads::new(1); + shutdown(Duration::from_secs(5)); + + let (done_tx, done_rx) = mpsc::channel(); + drop(get_runtime().spawn(async move { + let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) }); + let _ = done_tx.send(result.map_err(|error| error.to_string())); + })); + + let result = done_rx + .recv_timeout(Duration::from_secs(10)) + .expect("single-worker runtime made no progress"); + assert_eq!(result.expect("single-worker query failed"), 42); + shutdown(Duration::from_secs(5)); + } + // Adapted from the concurrent reproducer that found the original bug: // many threads hammering the runtime while shutdown races them, not // just the sequential rebuild path above. Before every reader held its diff --git a/python/src/table.rs b/python/src/table.rs index a4611d80c..f9c81d5a3 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -9,7 +9,7 @@ use std::{ }, }; -use crate::runtime::{block_on, future_into_py, spawn_background}; +use crate::runtime::{block_on, block_on_interruptible, future_into_py, spawn_background}; use crate::{ connection::Connection, error::PythonErrorExt, @@ -1619,6 +1619,14 @@ impl Table { }) } + pub fn schema_sync(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + let schema = self_.py().detach(move || { + block_on_interruptible(async move { inner.schema().await.infer_error() }) + })?; + Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind())) + } + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))] pub fn add<'a>( self_: PyRef<'a, Self>, From 74239973c70e76d58f399c24e22951087dd786cd Mon Sep 17 00:00:00 2001 From: Brendan Clement Date: Fri, 20 Nov 2026 12:47:31 -0800 Subject: [PATCH 200/203] docs: describe current Function refresh defaults (#5134) Several Function pages still said a refresh defaults to `error_policy = 'fail'` and that `skip` writes null outputs. The server now defaults new refreshes to skip with a 5% failed-row ceiling, and skip keeps a row's existing output, leaving only never-filled rows empty. This updates those pages to match. --- docs/web/feature-engineering/index.mdx | 8 ++++--- .../feature-engineering/refresh-column.mdx | 5 ++-- docs/web/management/function-failures.mdx | 23 +++++++++---------- docs/web/management/function.mdx | 12 ++++++---- docs/web/sql/dml/refresh-column.mdx | 2 +- 5 files changed, 27 insertions(+), 23 deletions(-) diff --git a/docs/web/feature-engineering/index.mdx b/docs/web/feature-engineering/index.mdx index 405f4e852..94c5d6f70 100644 --- a/docs/web/feature-engineering/index.mdx +++ b/docs/web/feature-engineering/index.mdx @@ -121,9 +121,11 @@ That is also why a function must declare the environment it needs. ## Recovering from a failure {#failures} -A function that raises fails the job. There is no per-row retry or skip policy -in the function definition, so a function calling a flaky external service -should handle that itself, inside the function body. +By default, a refresh skips rows where the function raises and records their +errors, up to a 5% failed-row ceiling; see +[Handle Function failures](/management/function-failures). A function can also +declare a retry policy for transient errors with `@function(retry_policy=...)` +where the SDK, server and Function image support it. 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 diff --git a/docs/web/feature-engineering/refresh-column.mdx b/docs/web/feature-engineering/refresh-column.mdx index f893118fc..de0b56888 100644 --- a/docs/web/feature-engineering/refresh-column.mdx +++ b/docs/web/feature-engineering/refresh-column.mdx @@ -536,8 +536,9 @@ refresh value overrides that default for this execution only. `batch_size` caps rows in one Function call; LanceDB adapts actual call and work sizes. For Function columns, the refresh defaults to -`error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for -failing rows and record them in the error store, subject to failure limits. +`error_policy = 'skip'` with a 5% failed-row ceiling: failing rows keep any +existing output, unassigned outputs stay unassigned, and their errors are +recorded in the error store. Set `error_policy = 'fail'` to stop on a row error. See the [SQL refresh options](/sql/dml/refresh-column#options). {/* diff --git a/docs/web/management/function-failures.mdx b/docs/web/management/function-failures.mdx index 226d8b573..76fbc0371 100644 --- a/docs/web/management/function-failures.mdx +++ b/docs/web/management/function-failures.mdx @@ -11,18 +11,16 @@ availability: A Function refresh can encounter a bad row, fail to initialize a model, lose a worker, or fail while publishing results. These need different remedies. -The native workflow below is draft guidance for an unreleased SDK and a -matching Enterprise server. The recipes that follow it remain available for -older deployments. +The native workflow below needs a recent SDK and a matching Enterprise server. +The recipes that follow it remain available for older deployments. -## Draft native workflow: server contract version 1 {#native} +## Native workflow: server contract version 1 {#native} -This section requires the SDK changes in [PR #5048](https://github.com/lancedb/lancedb/pull/5048) -and an Enterprise deployment advertising `workflow_version >= 1` in its -Function error response. No released SDK or Enterprise version is implied by -this draft. The SDK checks this capability before submitting native retry, -upgrade, quarantine, history or provenance requests, and rejects unsupported -servers before changing the column. +This section requires Python SDK 0.42.0b19 or later and an Enterprise +deployment advertising `workflow_version >= 1` in its Function error response. +The SDK checks this capability before submitting native retry, upgrade, +quarantine, history or provenance requests, and rejects unsupported servers +before changing the column. New Function refreshes default to `error_policy="skip"` with a 5% failed-row ceiling. Successful outputs are published before a threshold failure is @@ -145,8 +143,9 @@ remain unchanged. ## Choose a row-error policy {#policy} -The default `fail` stops the job on a row error. `skip` writes null outputs for -failed rows and records errors, subject to the refresh's failure limits: +On these deployments, the default `fail` stops the job on a row error. `skip` +retains a failed row's existing output, leaves an unassigned output unassigned +and records errors, subject to the refresh's failure limits: ```python job = table.refresh_column_async( diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index bc237d79e..4de54e78a 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -696,23 +696,25 @@ full worked example. For the full skip, inspect, grouped-error, stable-row-ID retry and quarantine workflow, see [Handle Function failures](/management/function-failures). -By default, a Function that raises fails the refresh job. Choose how the -refresh handles row errors with its error policy: +By default, a refresh skips rows where the Function raises, up to a 5% +failed-row ceiling. Choose how the refresh handles row errors with its error +policy: ```sql SQL icon="database" -REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip') +REFRESH COLUMN embedding ON documents WITH (error_policy = 'fail') ``` -`skip` writes null outputs for failing rows and records their errors. Inspect +`skip` retains a failing row's existing output, leaves an unassigned output +unassigned and records the error. Inspect them with `SHOW ERRORS` or `table.function_errors()`. Failure limits still apply, and initialization or infrastructure failures can still fail the job. See the [SQL refresh options](/sql/dml/refresh-column#options). A Function that calls a transiently failing external service can handle bounded retries inside its body. -Letting the job fail is the other option: fix the cause and refresh again. The +`fail` is the opt-in alternative: fix the cause and refresh again. The next unfiltered refresh [skips rows that are filled and current](/feature-engineering/refresh-column#idempotent), but how much of the failed job's work was kept is not guaranteed, so do not count on the retry costing only the rows that did not complete. A refresh with diff --git a/docs/web/sql/dml/refresh-column.mdx b/docs/web/sql/dml/refresh-column.mdx index fcb78bd35..e680823ef 100644 --- a/docs/web/sql/dml/refresh-column.mdx +++ b/docs/web/sql/dml/refresh-column.mdx @@ -59,7 +59,7 @@ to let LanceDB track which outputs need updating. | `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only | | `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only | | `row_timeout_seconds` | deadline for one Function call. Function columns only | -| `error_policy` | `'fail'` (default) stops on a row error; `'skip'` writes null outputs and records row errors, subject to failure limits. Function columns only | +| `error_policy` | `'skip'` (default, with a 5% failed-row ceiling) retains a failing row's existing output, leaves unassigned outputs unassigned and records row errors, subject to failure limits; `'fail'` stops on a row error. Function columns only | | `max_failed_fraction` | fail the job once more than this share of rows has failed. Function columns only | | `max_failed_rows` | fail the job once more than this many rows has failed. Function columns only | From 668fb1e2569f8206f418fbc12adad8cef8dea70a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 04:59:34 +0800 Subject: [PATCH 201/203] feat(python): add tag-based branch creation and default tag versions (#5136) Python `tags.create()` now defaults `version` to the handle's currently visible version, including checked-out handles. Existing `from_ref` / `from_version` branch selection and explicit tag versions keep their current behavior. `branches.create()` gains keyword-only `from_tag`, so a branch can fork from a tag through the existing `Ref::Tag` path. This preserves the tag's actual branch snapshot; resolving only its numeric version could fork from `main` when both branches share a version number. `from_tag` conflicts with `from_ref` / `from_version` are rejected before `from_ref="main"` normalization. When `from_ref` names a tag instead of a branch, the native missing-branch failure keeps its classification and receives a static `from_tag=` hint without another lookup. A missing version and an ambiguous Enterprise 404 keep their original errors. The Python sync and async APIs, PyO3 binding, stubs and docstrings are updated together, with native Rust coverage for a tag on a branch that shares main's numeric version. Node.js `fromTag` and optional `version` will follow in a separate PR after this one. --- docs/web-tests/py/test_tables.py | 16 ++- docs/web-tests/rs/tables.rs | 20 +++- docs/web/management/table.mdx | 5 + docs/web/snippets/tables.mdx | 6 +- docs/web/tables/branching.mdx | 8 +- python/python/lancedb/_lancedb.pyi | 4 +- python/python/lancedb/table.py | 55 ++++++++-- python/python/tests/test_table.py | 167 +++++++++++++++++++++++++++++ python/src/table.rs | 70 ++++++++++-- rust/lancedb/src/table.rs | 54 ++++++++++ 10 files changed, 382 insertions(+), 23 deletions(-) diff --git a/docs/web-tests/py/test_tables.py b/docs/web-tests/py/test_tables.py index 93c3729f7..465e6de47 100644 --- a/docs/web-tests/py/test_tables.py +++ b/docs/web-tests/py/test_tables.py @@ -1328,7 +1328,8 @@ def test_versioning_tags(tmp_db): # --8<-- [start:versioning_tags] # Create a tag pointing at a specific version table.tags.create("baseline", 1) - table.tags.create("with-edits", table.version) + # Omit version to tag the version this handle currently shows. + table.tags.create("with-edits") # List all tags on this table print(table.tags.list()) @@ -1343,6 +1344,9 @@ def test_versioning_tags(tmp_db): table.checkout("baseline") print(table.version) + # A checked-out handle tags the older version it shows, not the latest. + table.tags.create("baseline-checkout") + # Delete a tag (does not delete the underlying version) table.tags.delete("with-edits") @@ -1350,6 +1354,7 @@ def test_versioning_tags(tmp_db): table.checkout_latest() # --8<-- [end:versioning_tags] assert table.version == 3 + assert table.tags.get_version("baseline-checkout") == 2 assert "baseline" in table.tags.list() assert "with-edits" not in table.tags.list() @@ -1387,8 +1392,15 @@ def test_branches(tmp_db): # Fork an isolated, writable branch from main's latest version. # `create` returns a table handle scoped to the new branch. branch = table.branches.create("exp") + + # Fork from a tag. `from_tag` is keyword-only and cannot be combined with + # `from_ref` or `from_version`. + table.tags.create("baseline", 1) + tag_branch = table.branches.create("exp-from-tag", from_tag="baseline") # --8<-- [end:branch_create] + assert tag_branch.count_rows() == 3 + # --8<-- [start:branch_write] # Writes land on the branch handle only; main is left untouched. branch.add([{"id": 4, "author": "Lancelot", "quote": "For the realm!"}]) @@ -1414,6 +1426,8 @@ def test_branches(tmp_db): assert table.count_rows() == 3 assert "exp" not in table.branches.list() + assert "exp-from-tag" in table.branches.list() + table.branches.delete("exp-from-tag") # Setup: a branch with row results that we want to apply to main. candidate = table.branches.create("candidate") diff --git a/docs/web-tests/rs/tables.rs b/docs/web-tests/rs/tables.rs index 0d568530d..e5a8295df 100644 --- a/docs/web-tests/rs/tables.rs +++ b/docs/web-tests/rs/tables.rs @@ -1379,17 +1379,27 @@ async fn main() { .await .unwrap(); + // --8<-- [start:branch_create] use lancedb::table::Ref; - // --8<-- [start:branch_create] // Fork an isolated, writable branch from main's latest version. // `create_branch` returns a table handle scoped to the new branch. let branch = branches_table .create_branch("exp", Ref::Version(None, None)) .await .unwrap(); + + // Fork from a tag. A tag keeps its branch and version. + let mut tags = branches_table.tags().await.unwrap(); + tags.create("baseline", 1).await.unwrap(); + let tag_branch = branches_table + .create_branch("exp-from-tag", Ref::Tag("baseline".to_string())) + .await + .unwrap(); // --8<-- [end:branch_create] + assert_eq!(tag_branch.count_rows(None).await.unwrap(), 3); + // --8<-- [start:branch_write] // Writes land on the branch handle only; main is left untouched. branch @@ -1428,6 +1438,14 @@ async fn main() { assert_eq!(branches_table.count_rows(None).await.unwrap(), 3); assert!(!branches_table.list_branches().await.unwrap().contains_key("exp")); + assert!( + branches_table + .list_branches() + .await + .unwrap() + .contains_key("exp-from-tag") + ); + branches_table.delete_branch("exp-from-tag").await.unwrap(); // Setup: a branch with row results that we want to apply to main. let candidate = branches_table diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index c5dc4f8cd..14c1a9fc2 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -1742,6 +1742,11 @@ page). The tags API supports the standard CRUD operations (create, list, update, delete), plus checking out by tag name. +In Python, `tags.create()` accepts an optional `version`. If you omit it, the +tag uses the version the table handle currently shows. That includes a handle +checked out to an older version, so pass `version` explicitly when the tag must +not depend on the handle's checkout state. + {VersioningTags} diff --git a/docs/web/snippets/tables.mdx b/docs/web/snippets/tables.mdx index f4b0a1af8..ecbdc71c9 100644 --- a/docs/web/snippets/tables.mdx +++ b/docs/web/snippets/tables.mdx @@ -30,7 +30,7 @@ export const PyAlterVectorColumn = "data = [\n {\n \"id\": 1,\n export const PyBatchDataInsertion = "import pyarrow as pa\n\ndef make_batches():\n for i in range(5): # Create 5 batches\n yield pa.RecordBatch.from_arrays(\n [\n pa.array([[3.1, 4.1], [5.9, 26.5]], pa.list_(pa.float32(), 2)),\n pa.array([f\"item{i * 2 + 1}\", f\"item{i * 2 + 2}\"]),\n pa.array([float((i * 2 + 1) * 10), float((i * 2 + 2) * 10)]),\n ],\n [\"vector\", \"item\", \"price\"],\n )\n\nschema = pa.schema(\n [\n pa.field(\"vector\", pa.list_(pa.float32(), 2)),\n pa.field(\"item\", pa.utf8()),\n pa.field(\"price\", pa.float32()),\n ]\n)\n# Create table with batches\ntable_name = \"batch_ingestion_example\"\ntable = db.create_table(table_name, make_batches(), schema=schema, mode=\"overwrite\")\n"; -export const PyBranchCreate = "# Fork an isolated, writable branch from main's latest version.\n# `create` returns a table handle scoped to the new branch.\nbranch = table.branches.create(\"exp\")\n"; +export const PyBranchCreate = "# Fork an isolated, writable branch from main's latest version.\n# `create` returns a table handle scoped to the new branch.\nbranch = table.branches.create(\"exp\")\n\n# Fork from a tag. `from_tag` is keyword-only and cannot be combined with\n# `from_ref` or `from_version`.\ntable.tags.create(\"baseline\", 1)\ntag_branch = table.branches.create(\"exp-from-tag\", from_tag=\"baseline\")\n"; export const PyBranchDelete = "# Delete the branch and its branch-local history. Data on main is safe.\ntable.branches.delete(\"exp\")\n"; @@ -136,7 +136,7 @@ export const PyVersioningListAllVersions = "versions = table.list_versions()\nfo export const PyVersioningRollback = "table.restore(version_after_mod)\nversions = table.list_versions()\nversion_count_after_rollback = len(versions)\nprint(f\"Total number of versions after rollback: {version_count_after_rollback}\")\n"; -export const PyVersioningTags = "# Create a tag pointing at a specific version\ntable.tags.create(\"baseline\", 1)\ntable.tags.create(\"with-edits\", table.version)\n\n# List all tags on this table\nprint(table.tags.list())\n\n# Look up the version a tag points at\nprint(table.tags.get_version(\"baseline\"))\n\n# Move an existing tag to a different version\ntable.tags.update(\"baseline\", 2)\n\n# Check out a version by tag name\ntable.checkout(\"baseline\")\nprint(table.version)\n\n# Delete a tag (does not delete the underlying version)\ntable.tags.delete(\"with-edits\")\n\n# Return to the latest version\ntable.checkout_latest()\n"; +export const PyVersioningTags = "# Create a tag pointing at a specific version\ntable.tags.create(\"baseline\", 1)\n# Omit version to tag the version this handle currently shows.\ntable.tags.create(\"with-edits\")\n\n# List all tags on this table\nprint(table.tags.list())\n\n# Look up the version a tag points at\nprint(table.tags.get_version(\"baseline\"))\n\n# Move an existing tag to a different version\ntable.tags.update(\"baseline\", 2)\n\n# Check out a version by tag name\ntable.checkout(\"baseline\")\nprint(table.version)\n\n# A checked-out handle tags the older version it shows, not the latest.\ntable.tags.create(\"baseline-checkout\")\n\n# Delete a tag (does not delete the underlying version)\ntable.tags.delete(\"with-edits\")\n\n# Return to the latest version\ntable.checkout_latest()\n"; export const PyVersioningUpdateData = "table.update(where=\"author='Richard'\", values={\"author\": \"Richard Daniel Sanchez\"})\nrows_after_update = table.count_rows(\"author = 'Richard Daniel Sanchez'\")\nprint(f\"Rows updated to Richard Daniel Sanchez: {rows_after_update}\")\n"; @@ -274,7 +274,7 @@ export const RsAlterColumnsWithExpression = "// For custom transforms, create a export const RsAlterVectorColumn = "let old_dim = 384;\nlet new_dim = 1024;\nlet vector_schema = Arc::new(Schema::new(vec![\n Field::new(\"id\", DataType::Int64, false),\n Field::new(\n \"embedding\",\n DataType::FixedSizeList(\n Arc::new(Field::new(\"item\", DataType::Float32, true)),\n old_dim,\n ),\n true,\n ),\n]));\nlet vector_batch = RecordBatch::try_new(\n vector_schema.clone(),\n vec![\n Arc::new(Int64Array::from(vec![1])),\n Arc::new(\n FixedSizeListArray::from_iter_primitive::(\n vec![Some(vec![Some(0.1_f32); old_dim as usize])],\n old_dim,\n ),\n ),\n ],\n)\n.unwrap();\nlet vector_reader: Box =\n Box::new(RecordBatchIterator::new(vec![Ok(vector_batch)].into_iter(), vector_schema.clone()));\nlet vector_table = db\n .create_table(\"vector_alter_example\", vector_reader)\n .mode(CreateTableMode::Overwrite)\n .execute()\n .await\n .unwrap();\n\n// Changing FixedSizeList dimensions (384 -> 1024) is not supported via alter_columns.\n// Use add_columns + drop_columns + alter_columns(rename) to replace the column.\nvector_table\n .add_columns(\n NewColumnTransform::SqlExpressions(vec![(\n \"embedding_v2\".to_string(),\n format!(\"arrow_cast(NULL, 'FixedSizeList({}, Float32)')\", new_dim),\n )]),\n None,\n )\n .await\n .unwrap();\nvector_table.drop_columns(&[\"embedding\"]).await.unwrap();\nvector_table\n .alter_columns(&[ColumnAlteration::new(\"embedding_v2\".to_string())\n .rename(\"embedding\".to_string())])\n .await\n .unwrap();\n"; -export const RsBranchCreate = "// Fork an isolated, writable branch from main's latest version.\n// `create_branch` returns a table handle scoped to the new branch.\nlet branch = branches_table\n .create_branch(\"exp\", Ref::Version(None, None))\n .await\n .unwrap();\n"; +export const RsBranchCreate = "use lancedb::table::Ref;\n\n// Fork an isolated, writable branch from main's latest version.\n// `create_branch` returns a table handle scoped to the new branch.\nlet branch = branches_table\n .create_branch(\"exp\", Ref::Version(None, None))\n .await\n .unwrap();\n\n// Fork from a tag. A tag keeps its branch and version.\nlet mut tags = branches_table.tags().await.unwrap();\ntags.create(\"baseline\", 1).await.unwrap();\nlet tag_branch = branches_table\n .create_branch(\"exp-from-tag\", Ref::Tag(\"baseline\".to_string()))\n .await\n .unwrap();\n"; export const RsBranchDelete = "// Delete the branch and its branch-local history. Data on main is safe.\nbranches_table.delete_branch(\"exp\").await.unwrap();\n"; diff --git a/docs/web/tables/branching.mdx b/docs/web/tables/branching.mdx index baf46b265..9edd7c669 100644 --- a/docs/web/tables/branching.mdx +++ b/docs/web/tables/branching.mdx @@ -127,8 +127,12 @@ small `quotes` table with three rows on `main`. ### Create a branch {#create-a-branch} Forking from `main` returns a table handle scoped to the new branch. `main` is -the reserved default source, so `create` needs only a name; to fork from -somewhere else, pass a branch name, a specific version, or both. +the reserved default source, so `create` needs only a name. To fork from another +branch, pass `from_ref`, optionally with `from_version`. In Python, use +keyword-only `from_tag` to fork from a tag; it cannot be combined with +`from_ref` or `from_version`. In Rust, pass `Ref::Tag` to `create_branch`. A +tag carries its own branch and version, so the tag source forks from that exact +snapshot. diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index eb8536f3e..a3a9610c9 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -879,7 +879,7 @@ class Table: class Tags: async def list(self) -> Dict[str, Tag]: ... async def get_version(self, tag: str) -> int: ... - async def create(self, tag: str, version: int): ... + async def create(self, tag: str, version: Optional[int] = None): ... async def delete(self, tag: str): ... async def update(self, tag: str, version: int): ... @@ -890,6 +890,8 @@ class Branches: name: str, from_ref: Optional[str] = None, from_version: Optional[int] = None, + *, + from_tag: Optional[str] = None, ) -> Table: ... async def checkout(self, name: str, version: Optional[int] = None) -> Table: ... async def delete(self, name: str) -> None: ... diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index fdcea6aa8..a6ba1692e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -10250,6 +10250,26 @@ class FragmentSummaryStats: p99: int +def _validate_branch_source( + from_ref: Optional[str], + from_version: Optional[int], + from_tag: Optional[str], +) -> None: + if from_tag is None: + return + conflicts = [ + name + for name, value in (("from_ref", from_ref), ("from_version", from_version)) + if value is not None + ] + if conflicts: + raise ValueError( + "from_tag cannot be combined with " + + " or ".join(conflicts) + + "; pass only one source" + ) + + class Tags: """ Table tag manager. @@ -10280,7 +10300,7 @@ class Tags: """ return LOOP.run(self._table.tags.get_version(tag)) - def create(self, tag: str, version: int) -> None: + def create(self, tag: str, version: Optional[int] = None) -> None: """ Create a tag for a given table version. @@ -10289,8 +10309,9 @@ class Tags: tag: str, The name of the tag to create. This name must be unique among all tag names for the table. - version: int, - The table version to tag. + version: int, optional + The table version to tag. Defaults to the version visible to this + handle, including a checked-out version. """ LOOP.run(self._table.tags.create(tag, version)) @@ -10337,6 +10358,8 @@ class Branches: name: str, from_ref: Optional[str] = None, from_version: Optional[int] = None, + *, + from_tag: Optional[str] = None, ) -> "Table": """Create a branch and return a handle scoped to it. @@ -10348,9 +10371,13 @@ class Branches: Source branch to fork from. Defaults to ``main``. from_version: int, optional A specific version on ``from_ref`` to fork from. Defaults to latest. + from_tag: str, optional + Source tag to fork from. Cannot be combined with ``from_ref`` or + ``from_version``. """ + _validate_branch_source(from_ref, from_version, from_tag) async_table = LOOP.run( - self._table.branches.create(name, from_ref, from_version) + self._table.branches.create(name, from_ref, from_version, from_tag=from_tag) ) return self._wrap(async_table) @@ -10432,7 +10459,7 @@ class AsyncTags: """ return await self._table.tags.get_version(tag) - async def create(self, tag: str, version: int) -> None: + async def create(self, tag: str, version: Optional[int] = None) -> None: """ Create a tag for a given table version. @@ -10441,8 +10468,9 @@ class AsyncTags: tag: str, The name of the tag to create. This name must be unique among all tag names for the table. - version: int, - The table version to tag. + version: int, optional + The table version to tag. Defaults to the version visible to this + handle, including a checked-out version. """ await self._table.tags.create(tag, version) @@ -10486,6 +10514,8 @@ class AsyncBranches: name: str, from_ref: Optional[str] = None, from_version: Optional[int] = None, + *, + from_tag: Optional[str] = None, ) -> "AsyncTable": """Create a branch and return a handle scoped to it. @@ -10497,12 +10527,19 @@ class AsyncBranches: Source branch to fork from. Defaults to ``main``. from_version: int, optional A specific version on ``from_ref`` to fork from. Defaults to latest. + from_tag: str, optional + Source tag to fork from. Cannot be combined with ``from_ref`` or + ``from_version``. """ + _validate_branch_source(from_ref, from_version, from_tag) # "main" and None are two spellings of the root branch in lance; normalize - # so from_ref="main" behaves identically to the default. + # so from_ref="main" behaves identically to the default. This must happen + # after validating from_tag conflicts so an explicit from_ref is not lost. if from_ref == "main": from_ref = None - inner = await self._table.branches.create(name, from_ref, from_version) + inner = await self._table.branches.create( + name, from_ref, from_version, from_tag=from_tag + ) return AsyncTable(inner) async def checkout(self, name: str, version: Optional[int] = None) -> "AsyncTable": diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e999390a1..c9a587950 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1426,6 +1426,31 @@ def test_tags(mem_db: DBConnection): ) +def test_tags_create_defaults_to_visible_version(mem_db: DBConnection): + table = mem_db.create_table("test", data=[{"id": 1}]) + table.add(data=[{"id": 2}]) + + table.tags.create("live") + assert table.tags.get_version("live") == 2 + + table.checkout(1) + table.tags.create("pinned") + assert table.tags.get_version("pinned") == 1 + + # An explicit version is independent of the version this handle shows. + table.tags.create("explicit", 2) + assert table.tags.get_version("explicit") == 2 + + # A tag checkout is still a visible version, not "latest". + table.checkout_latest() + table.add(data=[{"id": 3}]) + assert table.version == 3 + table.checkout("live") + assert table.version == 2 + table.tags.create("tag-checkout") + assert table.tags.get_version("tag-checkout") == 2 + + @pytest.mark.asyncio async def test_async_tags(mem_db_async: AsyncConnection): table = await mem_db_async.create_table( @@ -1480,6 +1505,34 @@ async def test_async_tags(mem_db_async: AsyncConnection): ) +@pytest.mark.asyncio +async def test_async_tags_create_defaults_to_visible_version( + mem_db_async: AsyncConnection, +): + table = await mem_db_async.create_table("test", data=[{"id": 1}]) + await table.add(data=[{"id": 2}]) + + await table.tags.create("live") + assert await table.tags.get_version("live") == 2 + + await table.checkout(1) + await table.tags.create("pinned") + assert await table.tags.get_version("pinned") == 1 + + # An explicit version is independent of the version this handle shows. + await table.tags.create("explicit", 2) + assert await table.tags.get_version("explicit") == 2 + + # A tag checkout is still a visible version, not "latest". + await table.checkout_latest() + await table.add(data=[{"id": 3}]) + assert await table.version() == 3 + await table.checkout("live") + assert await table.version() == 2 + await table.tags.create("tag-checkout") + assert await table.tags.get_version("tag-checkout") == 2 + + def test_branches(tmp_path): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) table = db.create_table( @@ -1519,6 +1572,62 @@ def test_branches(tmp_path): assert "exp" not in table.branches.list() +def test_branches_create_from_tag(tmp_path): + db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) + table = db.create_table("test", data=[{"i": 0}]) + + exp = table.branches.create("exp") + exp.add([{"i": 10}]) + exp_version = exp.version + exp.tags.create("exp-v2", exp_version) + + # main reaches the same numeric version with different rows. + table.add([{"i": 100}]) + assert table.version == exp_version + + forked = table.branches.create("from-tag", from_tag="exp-v2") + assert forked.current_branch() == "from-tag" + assert forked.count_rows("i = 10") == 1 + assert forked.count_rows("i = 100") == 0 + + +def test_branches_create_from_tag_rejects_other_sources(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", data=[{"i": 0}]) + table.tags.create("baseline") + + # from_ref="main" must be rejected before it is normalized to the default. + with pytest.raises(ValueError, match="from_tag cannot be combined"): + table.branches.create("exp", from_ref="main", from_tag="baseline") + with pytest.raises(ValueError, match="from_tag cannot be combined"): + table.branches.create("exp", from_version=1, from_tag="baseline") + + +def test_branches_create_from_missing_ref_hint_applies_only_to_branches(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("test", data=[{"i": 0}]) + base = table.branches.create("base") + base.add([{"i": 1}]) + table.tags.create("baseline") + + # A tag passed through from_ref is not a branch. Keep the original failure + # classification and add guidance without probing the ref a second time. + with pytest.raises(RuntimeError) as exc_info: + table.branches.create("exp", from_ref="baseline") + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "from_tag='baseline'" in detail + + # An existing branch with an absent version is a version failure, not an + # unresolved branch, so it must not suggest from_tag. + with pytest.raises(RuntimeError) as exc_info: + table.branches.create("exp", from_ref="base", from_version=9999) + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "9999" in detail + assert "from_tag=" not in detail + + def test_branch_handle_tracks_concurrent_writes(tmp_path): db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0)) table = db.create_table("t", [{"id": 1}]) @@ -1814,6 +1923,64 @@ async def test_async_branches(tmp_path): assert "exp" not in await table.branches.list() +@pytest.mark.asyncio +async def test_async_branches_create_from_tag(tmp_path): + db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0)) + table = await db.create_table("test", data=[{"i": 0}]) + + exp = await table.branches.create("exp") + await exp.add([{"i": 10}]) + exp_version = await exp.version() + await exp.tags.create("exp-v2", exp_version) + + # main reaches the same numeric version with different rows. + await table.add([{"i": 100}]) + assert await table.version() == exp_version + + forked = await table.branches.create("from-tag", from_tag="exp-v2") + assert forked.current_branch() == "from-tag" + assert await forked.count_rows("i = 10") == 1 + assert await forked.count_rows("i = 100") == 0 + + +@pytest.mark.asyncio +async def test_async_branches_create_from_tag_rejects_other_sources(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", data=[{"i": 0}]) + await table.tags.create("baseline") + + with pytest.raises(ValueError, match="from_tag cannot be combined"): + await table.branches.create("exp", from_ref="main", from_tag="baseline") + with pytest.raises(ValueError, match="from_tag cannot be combined"): + await table.branches.create("exp", from_version=1, from_tag="baseline") + + +@pytest.mark.asyncio +async def test_async_branches_create_from_missing_ref_hint_applies_only_to_branches( + tmp_path, +): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("test", data=[{"i": 0}]) + base = await table.branches.create("base") + await base.add([{"i": 1}]) + await table.tags.create("baseline") + + with pytest.raises(RuntimeError) as exc_info: + await table.branches.create("exp", from_ref="baseline") + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "from_tag='baseline'" in detail + + # An existing branch with an absent version is a version failure, not an + # unresolved branch, so it must not suggest from_tag. + with pytest.raises(RuntimeError) as exc_info: + await table.branches.create("exp", from_ref="base", from_version=9999) + + detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ()))) + assert "9999" in detail + assert "from_tag=" not in detail + + @pytest.mark.asyncio async def test_async_open_table_with_branch_version(tmp_path): db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0)) diff --git a/python/src/table.rs b/python/src/table.rs index f9c81d5a3..227247307 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -36,7 +36,7 @@ use lancedb::table::{ }; use lancedb::tokenize as lancedb_tokenize; use pyo3::{ - Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, + Bound, FromPyObject, Py, PyAny, PyErr, PyRef, PyResult, Python, exceptions::{PyRuntimeError, PyValueError}, pyclass, pyfunction, pymethods, types::{ @@ -3261,9 +3261,14 @@ impl Tags { }) } - pub fn create(self_: PyRef, tag: String, version: u64) -> PyResult> { + #[pyo3(signature = (tag, version=None))] + pub fn create(self_: PyRef, tag: String, version: Option) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { + let version = match version { + Some(version) => version, + None => inner.version().await.infer_error()?, + }; let mut tags = inner.tags().await.infer_error()?; tags.create(tag.as_str(), version).await.infer_error()?; Ok(()) @@ -3300,6 +3305,35 @@ impl Branches { } } +/// Add the from_tag hint to a native branch lookup failure. +/// +/// The caller only invokes this for a native `NotFound`, which identifies an +/// unresolved branch path. A missing version is `VersionNotFound`, and a REST +/// 404 is an ambiguous `TableNotFound`, so neither gets the hint. The original +/// exception class and message are preserved apart from the added note. +fn add_from_tag_hint(error: PyErr, branch: &str) -> PyErr { + let hint = format!("If '{branch}' is a tag, pass from_tag='{branch}' instead of from_ref."); + Python::attach(|py| { + let value = error.value(py); + if value.hasattr("add_note").unwrap_or(false) + && value.call_method1("add_note", (hint.clone(),)).is_ok() + { + return error; + } + // Python 3.10 has no BaseException.add_note. Native branch lookup + // failures are runtime errors with one string argument, so append the + // hint to that message without changing the exception class. + let Ok(args) = value.getattr("args") else { + return error; + }; + let Ok(original) = args.get_item(0).and_then(|arg| arg.extract::()) else { + return error; + }; + let _ = value.setattr("args", (format!("{original}\n{hint}"),)); + error + }) +} + #[pymethods] impl Branches { pub fn list(self_: PyRef<'_, Self>) -> PyResult> { @@ -3320,18 +3354,42 @@ impl Branches { }) } - #[pyo3(signature = (name, from_ref=None, from_version=None))] + #[pyo3(signature = (name, from_ref=None, from_version=None, *, from_tag=None))] pub fn create( self_: PyRef<'_, Self>, name: String, from_ref: Option, from_version: Option, + from_tag: Option, ) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - let from = Ref::Version(from_ref, from_version); - let table = inner.create_branch(&name, from).await.infer_error()?; - Ok(Table::new(table)) + let from_branch = if from_tag.is_none() { + from_ref.clone() + } else { + None + }; + let from = match from_tag { + Some(tag) => Ref::Tag(tag), + None => Ref::Version(from_ref, from_version), + }; + match inner.create_branch(&name, from).await { + Ok(table) => Ok(Table::new(table)), + Err(error) => { + // A missing branch is a native NotFound. A missing version + // is VersionNotFound, and a remote 404 is an ambiguous + // TableNotFound, so only the native branch case hints. + let missing_branch = matches!( + &error, + lancedb::Error::Lance { source } if source.is_not_found() + ); + let error = Err::<(), _>(error).infer_error().unwrap_err(); + match from_branch { + Some(branch) if missing_branch => Err(add_from_tag_hint(error, &branch)), + _ => Err(error), + } + } + } }) } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index fd7358e9a..b168ff6ff 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -5813,6 +5813,60 @@ mod tests { assert_eq!(at2.count_rows(Some("i = 10".to_string())).await.unwrap(), 0); } + #[tokio::test] + async fn test_create_branch_from_tag_on_branch_with_same_version_as_main() { + let tmp_dir = tempdir().unwrap(); + let uri = tmp_dir.path().to_str().unwrap(); + let conn = ConnectBuilder::new(uri) + .read_consistency_interval(Duration::from_secs(0)) + .execute() + .await + .unwrap(); + + let table = conn + .create_table("my_table", sample_rows(vec![0])) + .execute() + .await + .unwrap(); + let fork_point = table.version().await.unwrap(); + + // Advance exp and main to the same version number with different rows. + let exp = table.create_branch("exp", fork_point).await.unwrap(); + exp.add(sample_rows(vec![10])).execute().await.unwrap(); + let exp_version = exp.version().await.unwrap(); + table.add(sample_rows(vec![100])).execute().await.unwrap(); + assert_eq!(exp_version, table.version().await.unwrap()); + + // Tag exp at that shared version number. The tag must keep exp's branch + // identity, so forking from it sees exp's snapshot rather than main's + // version with the same number. + let mut tags = exp.tags().await.unwrap(); + tags.create("exp-v2", exp_version).await.unwrap(); + + let from_tag = table + .create_branch( + "from-tag", + lance::dataset::refs::Ref::Tag("exp-v2".to_string()), + ) + .await + .unwrap(); + assert_eq!(from_tag.current_branch().as_deref(), Some("from-tag")); + assert_eq!( + from_tag + .count_rows(Some("i = 10".to_string())) + .await + .unwrap(), + 1 + ); + assert_eq!( + from_tag + .count_rows(Some("i = 100".to_string())) + .await + .unwrap(), + 0 + ); + } + #[tokio::test] async fn test_branch_name_validation() { let tmp_dir = tempdir().unwrap(); From 0d2655edbae904bbc351fb98df5b35ee24c65d23 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 05:04:30 +0800 Subject: [PATCH 202/203] test(python): isolate the background-loop fork scenario (#5142) ## Summary Follow-up to #5111. `test_forked_child_starts_background_loop_lazily` forked the shared pytest process. On CI that process may already own native Tokio/parking_lot state from earlier tests such as `test_authz.py`, so the forked child can crash in a non-Python native thread during `table_names()` for reasons unrelated to this scenario. Run the entire fork scenario in a fresh `python -c` subprocess. The parent still starts `LOOP` via `parent-before`, forks while holding `LOOP._start_lock` (released in `finally`), and the child still verifies that it sees no inherited loop, thread, or background threads before using the real native sync API (`connect("memory://")` / `table_names()`). The child must then gain exactly one live daemon thread, while the parent's original thread stays alive and serves `parent-after`. This is test isolation, not a production fix or a root-cause claim. The original assertions and cleanup are preserved, with a 40s outer timeout for `join(20)`, `terminate()` + `join(5)`, `queue.get(5)`, and diagnostics. ## CI evidence The failure was observed on a docs-only main run (`b4459f35`), so it is not caused by a product change in that run: - [Minimum dependencies job 136441279987](https://github.com/lancedb/lancedb/actions/runs/44780367013/job/136441279987): timed out at ~20s. - [Linux Python 3.13 job 136441280394](https://github.com/lancedb/lancedb/actions/runs/44780367013/job/136441280394): native SIGSEGV in a non-Python native thread during `table_names()` after `connect`, following `test_authz.py` in the same stage. ## Validation - `python/tests/test_background_loop.py`: 4 passed. - Same pytest process, `test_authz.py` followed by `test_background_loop.py`: 83 passed. - `uv run make check`: cargo fmt, ruff format, cargo clippy, and ruff check passed. No production code changes. --- python/python/tests/test_background_loop.py | 171 +++++++++++--------- 1 file changed, 91 insertions(+), 80 deletions(-) diff --git a/python/python/tests/test_background_loop.py b/python/python/tests/test_background_loop.py index 52b8b1f73..8a3a2c247 100644 --- a/python/python/tests/test_background_loop.py +++ b/python/python/tests/test_background_loop.py @@ -1,12 +1,10 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -import multiprocessing as mp import os import subprocess import sys import textwrap -import traceback import pytest @@ -14,7 +12,7 @@ import pytest BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop" -def _run_in_subprocess(code: str) -> subprocess.CompletedProcess: +def _run_in_subprocess(code: str, timeout: int = 30) -> subprocess.CompletedProcess: env = os.environ.copy() env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) return subprocess.run( @@ -23,7 +21,7 @@ def _run_in_subprocess(code: str) -> subprocess.CompletedProcess: capture_output=True, text=True, env=env, - timeout=30, + timeout=timeout, ) @@ -142,45 +140,6 @@ def test_concurrent_first_use_initializes_one_background_thread(): _assert_subprocess_ok(result) -def _fork_child_starts_lazily(queue): - def background_threads(): - import threading - - return [ - thread - for thread in threading.enumerate() - if thread.name == BACKGROUND_THREAD_NAME - ] - - try: - from lancedb.background_loop import LOOP - - inherited_thread_is_none = LOOP.thread is None - inherited_loop_is_none = LOOP.loop is None - background_threads_before = [thread.name for thread in background_threads()] - - import lancedb - - db = lancedb.connect("memory://") - tables = db.table_names() - - worker = LOOP.thread - queue.put( - { - "error": None, - "inherited_thread_is_none": inherited_thread_is_none, - "inherited_loop_is_none": inherited_loop_is_none, - "background_threads_before": background_threads_before, - "tables": tables, - "thread_alive": False if worker is None else worker.is_alive(), - "thread_daemon": False if worker is None else worker.daemon, - "background_thread_count": len(background_threads()), - } - ) - except BaseException: - queue.put({"error": traceback.format_exc()}) - - @pytest.mark.skipif( sys.platform != "linux", reason=( @@ -189,48 +148,100 @@ def _fork_child_starts_lazily(queue): ), ) def test_forked_child_starts_background_loop_lazily(): - import asyncio + # Fork from a fresh interpreter: earlier tests in a shared pytest process + # may have left native runtime state that is not part of this scenario. + result = _run_in_subprocess( + f""" + import asyncio + import multiprocessing as mp + import threading + import traceback - from lancedb.background_loop import LOOP + from lancedb.background_loop import LOOP - assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before" - parent_thread = LOOP.thread - assert parent_thread is not None + BACKGROUND_THREAD_NAME = {BACKGROUND_THREAD_NAME!r} - ctx = mp.get_context("fork") - queue = ctx.Queue() + def background_threads(): + return [ + thread + for thread in threading.enumerate() + if thread.name == BACKGROUND_THREAD_NAME + ] - # Simulate forking while another thread held the initialization lock. The - # child must replace the inherited lock instead of trying to acquire it. - LOOP._start_lock.acquire() - try: - proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,)) - proc.start() - finally: - LOOP._start_lock.release() + def fork_child(queue): + try: + from lancedb.background_loop import LOOP - proc.join(timeout=20) - if proc.is_alive(): - proc.terminate() - proc.join(timeout=5) + inherited_thread_is_none = LOOP.thread is None + inherited_loop_is_none = LOOP.loop is None + background_threads_before = [ + thread.name for thread in background_threads() + ] + + import lancedb + + db = lancedb.connect("memory://") + tables = db.table_names() + + worker = LOOP.thread + queue.put( + dict( + error=None, + inherited_thread_is_none=inherited_thread_is_none, + inherited_loop_is_none=inherited_loop_is_none, + background_threads_before=background_threads_before, + tables=tables, + thread_alive=False if worker is None else worker.is_alive(), + thread_daemon=False if worker is None else worker.daemon, + background_thread_count=len(background_threads()), + ) + ) + except BaseException: + queue.put(dict(error=traceback.format_exc())) + + assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before" + parent_thread = LOOP.thread + assert parent_thread is not None + + ctx = mp.get_context("fork") + queue = ctx.Queue() + + # Simulate forking while another thread held the initialization lock. The + # child must replace the inherited lock instead of trying to acquire it. + LOOP._start_lock.acquire() + try: + proc = ctx.Process(target=fork_child, args=(queue,)) + proc.start() + finally: + LOOP._start_lock.release() + + proc.join(timeout=20) if proc.is_alive(): - proc.kill() - proc.join() - pytest.fail("Forked child hung starting the background loop") + proc.terminate() + proc.join(timeout=5) + if proc.is_alive(): + proc.kill() + proc.join() + raise AssertionError("Forked child hung starting the background loop") - assert proc.exitcode == 0, f"child exited with code {proc.exitcode}" - payload = queue.get(timeout=5) - queue.close() - assert payload["error"] is None, payload["error"] - assert payload["inherited_thread_is_none"] is True - assert payload["inherited_loop_is_none"] is True - assert payload["background_threads_before"] == [] - assert payload["tables"] == [] - assert payload["thread_alive"] is True - assert payload["thread_daemon"] is True - assert payload["background_thread_count"] == 1 + assert proc.exitcode == 0, "child exited with code %s" % proc.exitcode + payload = queue.get(timeout=5) + queue.close() + assert payload["error"] is None, payload["error"] + assert payload["inherited_thread_is_none"] is True + assert payload["inherited_loop_is_none"] is True + assert payload["background_threads_before"] == [] + assert payload["tables"] == [] + assert payload["thread_alive"] is True + assert payload["thread_daemon"] is True + assert payload["background_thread_count"] == 1 - # The child's reset must not disturb the parent's loop. - assert LOOP.thread is parent_thread - assert parent_thread.is_alive() - assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after" + # The child's reset must not disturb the parent's loop. + assert LOOP.thread is parent_thread + assert parent_thread.is_alive() + assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after" + """, + # join(20) + terminate join(5) + queue get(5), plus startup and traceback. + timeout=40, + ) + _assert_subprocess_ok(result) From c55b7c0390e2b75b7640c0466bbd1d193612bc2c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 21 Nov 2026 05:20:16 +0800 Subject: [PATCH 203/203] feat!: add explicit scan order contract for local queries (#5138) BREAKING CHANGE: `QueryRequest` now has a public `scan_in_order: Option` field. Existing code that constructs `QueryRequest` with an exhaustive struct literal must add `scan_in_order: None` to retain the previous backend default, or use `..Default::default()` where appropriate. Python defaults are unchanged: leaving `scan_in_order()` uncalled keeps `None`. ## Problem Plain Embedded LanceDB scans already use Lance's ordered scan on a fixed snapshot, but the storage-order contract was undocumented and callers had no way to require it. Explicit `order_by` sorts the whole result. Ranked, Enterprise, RTE/LSM, legacy scalar-index and namespace-pushdown paths cannot always preserve base manifest order. ## Behavior - `scan_in_order(true)` requires manifest order without adding a sort: fragments in manifest order, then rows in fragment order. - `true` disables scalar-index filter planning. Legacy scalar-index plans can materialize index rows in a different sequence, so filters are evaluated over the manifest-ordered scan instead. Filter semantics are unchanged, but the scan can read more data. Default filtered scans can still use those plans and may not preserve manifest order. - `scan_in_order(false)` permits the backend to scan unordered. It does **not** guarantee a different order; an explicit nonempty `order_by` still sorts. - Leaving the option unset preserves the backend default. The documented manifest-order default applies to an unfiltered base-only scan of a pinned Embedded table version. RTE tables scan the LSM by default and need `use_rte(false)` for the base-only guarantee. Enterprise and namespace-pushed scans have no order guarantee. - `true` conflicts with nonempty `order_by`, take queries, vector/full-text/hybrid/reranked queries, RTE/LSM reads, and Enterprise tables. These fail explicitly instead of silently dropping the requirement. Take conflict validation happens at the shared take-preparation boundary before offset or row-id selectors are stripped. - `with_fragments()` is rejected with `scan_in_order(true)` because fragment objects cannot be validated against the pinned dataset version. Use `fragment_ids()`, which resolves fragment ids from the manifest and preserves manifest order. Both sync and async pandas scanner paths share this rule. - Namespace `QueryTable` pushdown executes `true` against Embedded storage instead of dropping the order. The existing path preserves projection, filtering, limits, version/branch selection, and RTE routing; if Embedded storage cannot be read, the query fails. Supported entry points are plain Rust `Table::query()`, Python sync `table.search()` and async `table.query()`. The Python pandas scanner fast path forwards the option and disables scalar-index planning for explicit order. Existing takes and `with_fragments()` calls with `None` or `false` are unchanged. ## Validation - Rust: 6 `scan_in_order` tests, 32 take tests, 25 query-route tests. - Python: `test_query.py` and `test_namespace.py` 352 passed, 1 skipped against a matching extension. - Scoped `pytest --doctest-modules python/lancedb/query.py -k scan_in_order`: 2 passed. The Rust/Python examples create their own tables and are executable. - Regressions cover legacy 0.1 and stable BTREE tables with update and a filter admitting every row, across pinned versions before and after update; reversed `fragment_ids`; explicit `with_fragments()` rejection; and fixed-version multi-fragment reads with deletions, one-row batches, and limit/offset. No `SortExec` is added. - `cargo clippy --features remote --tests --examples`; `cargo fmt --check`; Ruff format/check; `git diff --check`. - Local checks ran on this branch. CI on this PR evaluates the merge with current `main`; no combined local binary validation is claimed here. Refs OSS-3109. --- python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/namespace.py | 16 +- python/python/lancedb/query.py | 120 ++++++++- python/python/lancedb/table.py | 5 + python/python/tests/test_namespace.py | 48 ++++ python/python/tests/test_query.py | 195 ++++++++++++++ python/src/query.rs | 7 + rust/lancedb/src/query.rs | 161 ++++++++++- rust/lancedb/src/remote/table.rs | 28 ++ rust/lancedb/src/table.rs | 15 +- rust/lancedb/src/table/query.rs | 372 +++++++++++++++++++++++++- rust/lancedb/src/table/query/lsm.rs | 5 + 12 files changed, 956 insertions(+), 18 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a3a9610c9..f40fbc30c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -972,6 +972,7 @@ class Query: def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ... def nearest_to_text(self, query: dict) -> FTSQuery: ... def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... + def scan_in_order(self, ordered: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] @@ -1129,6 +1130,7 @@ class PyQueryRequest: postfilter: Optional[bool] norm: Optional[str] order_by: Optional[List[ColumnOrdering]] + scan_in_order: Optional[bool] class CompactionStats: fragments_removed: int diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 3940e7b7e..4c8ec1a62 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -510,8 +510,8 @@ class LanceNamespaceDBConnection(DBConnection): - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a - nonempty ``order_by`` execute locally and require the client to - access the table storage. + nonempty ``order_by`` or an explicit ``scan_in_order(True)`` + execute on the client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1215,8 +1215,8 @@ class AsyncLanceNamespaceDBConnection: - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a - nonempty ``order_by`` execute locally and require the client to - access the table storage. + nonempty ``order_by`` or an explicit ``scan_in_order(True)`` + execute on the client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1824,8 +1824,8 @@ def connect_namespace( - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a nonempty - ``order_by`` execute locally and require the client to access the - table storage. + ``order_by`` or an explicit ``scan_in_order(True)`` execute on the + client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1917,8 +1917,8 @@ def connect_namespace_async( - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a nonempty - ``order_by`` execute locally and require the client to access the - table storage. + ``order_by`` or an explicit ``scan_in_order(True)`` execute on the + client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 19e9051f7..68598dd68 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -371,6 +371,10 @@ def _scanner_kwargs_for_query( "with_row_id": with_row_id if with_row_id is not None else query.with_row_id, "with_row_address": query.with_row_address, "fast_search": query.fast_search, + "scan_in_order": query.scan_in_order, + # Legacy scalar-index plans can reorder rows. Explicit storage order + # evaluates filters over the manifest-ordered scan instead. + "use_scalar_index": False if query.scan_in_order is True else None, "blob_handling": BLOB_MODE_TO_HANDLING[blob_mode], "fragments": fragments, } @@ -381,6 +385,12 @@ def _scanner_fragments_for_query(query: Query, dataset: Optional[Any]) -> Option if query.fragments is not None and query.fragment_ids is not None: raise ValueError("fragments and fragment_ids cannot both be set") if query.fragments is not None: + if query.scan_in_order is True: + raise ValueError( + "scan_in_order(True) cannot validate with_fragments() against " + "the scanned dataset version; use fragment_ids() to select " + "fragments by manifest id" + ) return query.fragments if query.fragment_ids is None: return None @@ -1208,6 +1218,10 @@ class Query(pydantic.BaseModel): order_by: Optional[List[ColumnOrdering]] = None + # Tri-state storage-order requirement: None preserves the backend default, + # True requires manifest order, False allows an unordered scan. + scan_in_order: Optional[bool] = None + @classmethod def from_inner(cls, req: PyQueryRequest) -> Self: query = cls() @@ -1241,6 +1255,7 @@ class Query(pydantic.BaseModel): query.postfilter = req.postfilter if req.order_by is not None: query.order_by = [ColumnOrdering(**o) for o in req.order_by] + query.scan_in_order = req.scan_in_order if req.full_text_search is not None: query.full_text_query = FullTextSearchQuery( columns=None, @@ -1415,6 +1430,7 @@ class LanceQueryBuilder(ABC): self._approx_mode = None self._bypass_vector_index = None self._order_by = None + self._scan_in_order = None @deprecation.deprecated( deprecated_in="0.3.1", @@ -2023,7 +2039,9 @@ class LanceQueryBuilder(ABC): ---------- fragments : list[lance.Fragment] Fragments from ``table.to_lance().get_fragments()``. Pass fragments - from the same dataset snapshot. + from the same dataset snapshot. Use ``fragment_ids()`` instead when + ``scan_in_order(True)`` is set; fragment objects cannot be validated + against the pinned dataset version. Returns ------- @@ -3082,6 +3100,52 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): schema=schema, ) + def scan_in_order(self, ordered: bool = True) -> Self: + """Control whether an ordinary scan must preserve storage order. + + Parameters + ---------- + ordered: bool, default True + ``True`` requires manifest order: fragments in manifest order, then + rows in fragment order. ``False`` allows the backend to scan + unordered. Leave the method uncalled to preserve the backend + default. + + An unfiltered plain base-only scan of an Embedded table, pinned to one + dataset version, returns manifest order by default. RTE tables scan the + LSM by default and do not provide this guarantee unless + ``use_rte(False)`` selects the base table. Explicit ``True`` also + disables scalar-index filter planning, because legacy scalar-index plans + can return a different sequence; default filtered scans can still use + those plans and may not preserve manifest order. Filters still apply, + but the scan can read more data. ``with_fragments()`` is not supported + with ``True`` because fragment objects cannot be validated against the + pinned dataset version; use ``fragment_ids()`` instead, which resolves + ids from the manifest and remains ordered. Compaction, updates, or + opening a newer version can change that order, so pin the table version + when positions must remain stable across executions. An explicit + ``order_by()`` replaces manifest order with a global sort, and vector, + full-text, hybrid, or reranked queries return ranked results; combining + those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise + tables and RTE/LSM reads raise ``NotImplementedError`` because they + cannot uphold the order; set ``use_rte(False)`` to read the RTE base + table in storage order. When ``QueryTable`` pushdown is enabled, the + backend default may not preserve order; requesting ``True`` executes + against Embedded storage instead, because the namespace request has no + order field. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table("scan_in_order", [{"id": 1}]) + >>> query = table.search().scan_in_order(True).select(["id"]) + >>> query.to_arrow()["id"].to_pylist() + [1] + """ + self._scan_in_order = ordered + return self + def to_query_object(self) -> Query: return Query( columns=self._columns, @@ -3094,6 +3158,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): use_rte=self._use_rte, offset=self._offset, order_by=self._order_by, + scan_in_order=self._scan_in_order, ) def output_schema(self) -> pa.Schema: @@ -4142,7 +4207,9 @@ class AsyncQueryBase(object): query types. Other terminals and remote tables raise ``NotImplementedError`` before scanning instead of silently scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep their - existing validation errors. + existing validation errors. Use ``fragment_ids()`` instead when + ``scan_in_order(True)`` is set; fragment objects cannot be validated + against the pinned dataset version. """ self._fragments = fragments return self @@ -4866,6 +4933,55 @@ class AsyncQuery(AsyncStandardQuery): super().__init__(inner, table) self._inner = inner + def scan_in_order(self, ordered: bool = True) -> Self: + """Control whether an ordinary scan must preserve storage order. + + Parameters + ---------- + ordered: bool, default True + ``True`` requires manifest order: fragments in manifest order, then + rows in fragment order. ``False`` allows the backend to scan + unordered. Leave the method uncalled to preserve the backend + default. + + An unfiltered plain base-only scan of an Embedded table, pinned to one + dataset version, returns manifest order by default. RTE tables scan the + LSM by default and do not provide this guarantee unless + ``use_rte(False)`` selects the base table. Explicit ``True`` also + disables scalar-index filter planning, because legacy scalar-index plans + can return a different sequence; default filtered scans can still use + those plans and may not preserve manifest order. Filters still apply, + but the scan can read more data. ``with_fragments()`` is not supported + with ``True`` because fragment objects cannot be validated against the + pinned dataset version; use ``fragment_ids()`` instead, which resolves + ids from the manifest and remains ordered. Compaction, updates, or + opening a newer version can change that order, so pin the table version + when positions must remain stable across executions. An explicit + ``order_by()`` replaces manifest order with a global sort, and vector, + full-text, hybrid, or reranked queries return ranked results; combining + those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise + tables and RTE/LSM reads raise ``NotImplementedError`` because they + cannot uphold the order; set ``use_rte(False)`` to read the RTE base + table in storage order. When ``QueryTable`` pushdown is enabled, the + backend default may not preserve order; requesting ``True`` executes + against Embedded storage instead, because the namespace request has no + order field. + + Examples + -------- + >>> import asyncio + >>> import lancedb + >>> async def example(): + ... db = await lancedb.connect_async("memory://") + ... table = await db.create_table("scan_in_order_async", [{"id": 1}]) + ... query = table.query().scan_in_order(True).select(["id"]) + ... return (await query.to_arrow())["id"].to_pylist() + >>> asyncio.run(example()) + [1] + """ + self._inner.scan_in_order(ordered) + return self + @classmethod def _query_vec_to_array(self, vec: Union[VEC, Tuple]): if isinstance(vec, list): diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index a6ba1692e..529375f6e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -149,6 +149,9 @@ def _requires_local_namespace_execution(query: Query) -> bool: # The namespace QueryTable request has no order_by field. Pushing a # nonempty ordering down would drop it and return the wrong top-K rows. or bool(query.order_by) + # An ordered scan is a local manifest-order guarantee. The request has + # no scan-order field, so run it locally where storage is available. + or query.scan_in_order is True or ( query.full_text_query is not None and query.fast_search is True @@ -8529,6 +8532,8 @@ class AsyncTable: async_query = async_query.with_row_id() if query.order_by: async_query = async_query.order_by(query.order_by) + if query.scan_in_order is not None: + async_query = async_query.scan_in_order(query.scan_in_order) if query.vector: async_query = async_query.nearest_to(query.vector).distance_range( diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 937572cc0..2c999d1b0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -1789,6 +1789,31 @@ class TestPushdownOperations: assert result.column("id").to_pylist() == [1] assert namespace_client.requests == [] + def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = lancedb.connect(str(tmp_path / "db")) + table = db.create_table("hist", data=[{"id": 3}, {"id": 1}]) + table.add([{"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = table._execute_query( + Query( + limit=2, + filter="id >= 1", + columns=["id"], + scan_in_order=True, + ) + ).read_all() + + # The namespace request has no scan-order field. Local execution keeps + # membership order, projection and limit; a dropped order or a sort + # would return [1, 3] or [1, 2]. + assert result.column("id").to_pylist() == [3, 1] + assert namespace_client.requests == [] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1869,6 +1894,29 @@ class TestAsyncPushdownOperations: assert pa.Table.from_batches(batches).column("id").to_pylist() == [1] assert namespace_client.requests == [] + async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = await lancedb.connect_async(str(tmp_path / "db")) + table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}]) + await table.add([{"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = await table._execute_query( + Query( + limit=2, + filter="id >= 1", + columns=["id"], + scan_in_order=True, + ) + ) + + batches = await result.read_all() + assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1] + assert namespace_client.requests == [] + @pytest.mark.parametrize( "query_kwargs", [ diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index c01b3f9dc..ed8e0d24f 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1102,6 +1102,201 @@ def test_order_by_clears_with_none_and_empty_list(mem_db): assert query.order_by([]).to_query_object().order_by is None +def test_scan_in_order_plain_query(tmp_db): + table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]})) + table.add(pa.table({"id": [2, 3]})) + table.add(pa.table({"id": [4, 5]})) + + fragments = table.to_lance().get_fragments() + assert len(fragments) == 3, "the test needs real multi-fragment data" + + version = table.version + table.checkout(version) + + default = table.search().select(["id"]).to_arrow()["id"].to_pylist() + assert default == [0, 1, 2, 3, 4, 5] + assert table.search().to_query_object().scan_in_order is None + + ordered = table.search().scan_in_order().select(["id"]).to_arrow() + assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5] + repeated = table.search().scan_in_order(True).select(["id"]).to_arrow() + assert repeated.equals(ordered) + + unordered = ( + table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist() + ) + assert sorted(unordered) == [0, 1, 2, 3, 4, 5] + + sorted_desc = ( + table.search() + .scan_in_order(False) + .order_by(("id", "desc")) + .select(["id"]) + .to_arrow()["id"] + .to_pylist() + ) + assert sorted_desc == [5, 4, 3, 2, 1, 0] + + with pytest.raises(ValueError, match="nonempty order_by"): + table.search().scan_in_order().order_by("id").to_arrow() + + +@pytest.mark.asyncio +async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection): + table = await tmp_db_async.create_table( + "scan_in_order_async", pa.table({"id": [0, 1]}) + ) + await table.add(pa.table({"id": [2, 3]})) + await table.add(pa.table({"id": [4, 5]})) + + assert len((await table.to_lance()).get_fragments()) == 3 + version = await table.version() + await table.checkout(version) + + ordered = await table.query().scan_in_order().select(["id"]).to_arrow() + assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5] + assert table.query().to_query_object().scan_in_order is None + + unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[ + "id" + ].to_pylist() + assert sorted(unordered) == [0, 1, 2, 3, 4, 5] + + with pytest.raises(ValueError, match="nonempty order_by"): + await table.query().scan_in_order().order_by("id").to_arrow() + with pytest.raises(ValueError, match="ranked results"): + await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow() + + +@pytest.mark.parametrize("ordered", [False, True]) +def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered): + pytest.importorskip("lance") + data = _blob_query_data() + table = tmp_db.create_table( + f"scan_in_order_scanner_{ordered}", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + table.add(data.slice(2, 2)) + + query = table.search().select(["id", "blob"]).scan_in_order(ordered) + + def fail_to_arrow(*args, **kwargs): + raise AssertionError("scanner-backed pandas must not collect through to_arrow") + + monkeypatch.setattr(query, "to_arrow", fail_to_arrow) + + dataset = table.to_lance() + dataset_cls = type(dataset) + real_scanner = dataset_cls.scanner + captured = {} + + def capture_scanner(self, **kwargs): + captured.update(kwargs) + return real_scanner(self, **kwargs) + + monkeypatch.setattr(dataset_cls, "scanner", capture_scanner) + + df = query.to_pandas(blob_mode="descriptions", flatten=True) + + assert captured["scan_in_order"] is ordered + assert captured.get("use_scalar_index") is (False if ordered else None) + assert sorted(df["id"].tolist()) == [1, 2, 3, 4] + + +@pytest.mark.parametrize("storage_version", ["legacy", "stable"]) +def test_scan_in_order_indexed_filter_preserves_manifest_order( + tmp_path, storage_version +): + lance = pytest.importorskip("lance") + data = pa.table({"id": list(range(20)), "value": list(range(20))}) + dataset = lance.write_dataset( + data, + tmp_path / "t.lance", + data_storage_version=storage_version, + max_rows_per_file=10, + ) + dataset.create_scalar_index("value", "BTREE") + version_before_update = dataset.version + dataset.update({"value": "100"}, where="id = 0") + + table = lancedb.connect(str(tmp_path)).open_table("t") + for version in (version_before_update, dataset.version): + table.checkout(version) + base = table.search().scan_in_order(True).select(["id"]).limit(100) + expected = base.to_arrow()["id"].to_pylist() + actual = base.where("value < 1000").to_arrow()["id"].to_pylist() + assert actual == expected + + +def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db): + pytest.importorskip("lance") + data = _blob_query_data() + table = tmp_db.create_table( + "scan_in_order_fragments", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + table.add(data.slice(2, 2)) + table.checkout(table.version) + + fragments = table.to_lance().get_fragments() + reversed_fragments = fragments[::-1] + with pytest.raises(ValueError, match="use fragment_ids"): + ( + table.search() + .scan_in_order() + .select(["id", "blob"]) + .with_fragments(reversed_fragments) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + + # fragment_ids is already resolved from the manifest and stays ordered. + df_by_id = ( + table.search() + .scan_in_order() + .select(["id", "blob"]) + .fragment_ids([fragment.fragment_id for fragment in reversed_fragments]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + assert df_by_id["id"].tolist() == [1, 2, 3, 4] + + +@pytest.mark.asyncio +async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids( + tmp_db_async, +): + pytest.importorskip("lance") + data = _blob_query_data() + table = await tmp_db_async.create_table( + "scan_in_order_fragments_async", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + await table.add(data.slice(2, 2)) + await table.checkout(await table.version()) + + fragments = (await table.to_lance()).get_fragments() + reversed_fragments = fragments[::-1] + with pytest.raises(ValueError, match="use fragment_ids"): + await ( + table.query() + .scan_in_order() + .with_fragments(fragments[::-1]) + .select(["id", "blob"]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + + df_by_id = await ( + table.query() + .scan_in_order() + .fragment_ids([fragment.fragment_id for fragment in reversed_fragments]) + .select(["id", "blob"]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + assert df_by_id["id"].tolist() == [1, 2, 3, 4] + + def test_order_by_rejects_invalid_input_early(mem_db): table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}]) diff --git a/python/src/query.rs b/python/src/query.rs index 7a7e34416..d8cfedfdb 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -396,6 +396,7 @@ pub struct PyQueryRequest { pub postfilter: Option, pub norm: Option, pub order_by: Option>, + pub scan_in_order: Option, } impl From for PyQueryRequest { @@ -434,6 +435,7 @@ impl From for PyQueryRequest { order_by: query_request .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: query_request.scan_in_order, }, AnyQuery::VectorQuery(vector_query) => Self { limit: vector_query.base.limit, @@ -467,6 +469,7 @@ impl From for PyQueryRequest { .base .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: vector_query.base.scan_in_order, }, } } @@ -685,6 +688,10 @@ impl Query { Ok(()) } + pub fn scan_in_order(&mut self, ordered: bool) { + self.inner = self.inner.clone().scan_in_order(ordered); + } + #[pyo3(signature = ())] pub fn output_schema(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 57af7f28d..bc460dc35 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -742,8 +742,14 @@ pub trait ExecutableQuery { /// an Stream of Arrow [`arrow_array::RecordBatch`] (and you can also independently /// access the [`arrow_schema::Schema`] without polling the stream). /// - /// Note: The size of the returned batches and the order of individual rows is - /// not deterministic. + /// Note: The size of the returned batches is not deterministic. Row order + /// depends on the query shape: an ordinary unfiltered base-only scan of a + /// fixed table version in Embedded returns manifest order unless + /// [`Query::scan_in_order`] is set to `false` or a nonempty + /// [`QueryBase::order_by`] adds a sort. RTE + /// tables scan the LSM by default; use `use_rte(false)` for the base-only + /// guarantee. Ranked searches return rank order, while Enterprise and + /// namespace-pushed scans have no order guarantee. /// /// LanceDb will use many threads to calculate results and, when /// the result set is large, multiple batches will be processed at one time. @@ -922,6 +928,11 @@ pub struct QueryRequest { /// This allows ordering query results by one or more columns in either ascending or descending order. pub order_by: Option>, + /// Require (`Some(true)`), allow (`Some(false)`), or leave unchanged (`None`) + /// the scan order. See [`Query::scan_in_order`] for the contract and its + /// boundaries. + pub scan_in_order: Option, + /// Controls RTE read routing. When unset (the default), a query against a /// table that carries an RTE write spec (see /// [`crate::Table::enable_rte`]) is routed through the LSM scanner so @@ -956,6 +967,7 @@ impl Default for QueryRequest { norm: None, disable_scoring_autoprojection: false, order_by: None, + scan_in_order: None, use_rte: None, } } @@ -1044,6 +1056,64 @@ impl Query { VectorQuery::new(self) } + /// Require the results to follow storage order instead of allowing an + /// unordered scan. + /// + /// An unfiltered plain base-only scan of an Embedded table, pinned to one + /// dataset version, returns rows in that version's manifest order: + /// fragments in manifest order, then rows in fragment order. Ordinary + /// unfiltered base-only scans already use Lance's ordered scan by default, + /// so leaving this unset preserves that behavior. RTE tables scan the LSM + /// by default and do not provide this guarantee unless `use_rte(false)` + /// selects the base table. Use `true` when a caller assigns meaning to row + /// positions and must fail instead of silently receiving a different order. + /// + /// Explicit `true` also disables scalar-index filter planning. Legacy + /// scalar-index plans can materialize index rows in a different sequence, + /// so filters are evaluated over the manifest-ordered scan instead. Default + /// filtered scans can still use those plans and may not preserve manifest + /// order. The filter result is unchanged, but the scan can read more data. + /// + /// Leaving this unset preserves the backend default. In particular, a + /// namespace-backed native table configured for `QueryTable` pushdown may + /// not preserve order because the request has no order field; request + /// `true` to execute against Embedded storage. + /// + /// The order is fixed only for the dataset version being scanned. + /// Compaction, updates, or opening a newer version can change it, so pin a + /// version when positions must remain stable across executions. A latest + /// handle can also observe a different version between two executions. + /// + /// - `true` requires manifest order without adding a sort. A nonempty + /// [`QueryBase::order_by`], take query, vector, full-text, hybrid, or + /// reranked query conflicts with storage order and fails with + /// [`Error::InvalidInput`]. + /// Enterprise tables and RTE/LSM reads fail with [`Error::NotSupported`] + /// because they cannot uphold the requirement; set `use_rte(false)` to + /// read the RTE base table in storage order. Namespace-backed native + /// tables execute against Embedded storage instead of using `QueryTable` + /// pushdown, which has no order field, and fail if that storage cannot be + /// read. + /// + /// # Examples + /// + /// ```no_run + /// # use lancedb::query::ExecutableQuery; + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// let rows = table.query().scan_in_order(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + /// - `false` allows the backend to scan without preserving order. An + /// explicit nonempty `order_by` still applies its sort. + /// + /// A nonempty `order_by` replaces manifest order with a global sort. Vector + /// and full-text searches return ranked results regardless of this option. + pub fn scan_in_order(mut self, ordered: bool) -> Self { + self.request.scan_in_order = Some(ordered); + self + } + /// Find the nearest vectors to the given query vector. /// /// This converts the query from a plain query to a vector query. @@ -2086,6 +2156,20 @@ struct TakeLookup { output_projection: Option>, } +/// Take queries restore rows in the requested offset or row-id order, so an +/// explicit storage-order requirement cannot be honored. Check this before the +/// lookup strips the take selectors and hands the inner request to a scan. +pub(crate) fn validate_take_scan_in_order(request: &QueryRequest) -> Result<()> { + if request.scan_in_order == Some(true) { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with take by row id or offset, which \ + defines its own result order" + .to_string(), + }); + } + Ok(()) +} + impl TakeQuery { /// Create a new `TakeQuery` that will return rows at the given offsets. /// @@ -2200,6 +2284,7 @@ impl TakeQuery { request: &QueryRequest, preserve_order: bool, ) -> Result { + validate_take_scan_in_order(request)?; let (indices, by_row_id) = match (&request.take_offsets, &request.take_row_ids) { (Some(indices), None) => (indices.clone(), false), (None, Some(indices)) => (indices.clone(), true), @@ -4564,6 +4649,78 @@ mod tests { assert!(!analyzed.contains("CoalescePartitionsExec")); } + #[tokio::test] + async fn test_take_scan_in_order_is_rejected_before_lookup() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + + let mut offsets = table + .take_offsets(vec![5, 1, 17]) + .select(Select::Columns(vec!["id".to_string()])) + .limit(2) + .offset(1); + offsets.mut_query().scan_in_order = Some(true); + + let plan_err = offsets + .create_plan(QueryExecutionOptions::default()) + .await + .expect_err("take planning must reject scan_in_order(true)"); + assert!( + matches!(&plan_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {plan_err}" + ); + + let execution_err = offsets + .execute() + .await + .err() + .expect("take execution must reject scan_in_order(true)"); + assert!( + matches!(&execution_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {execution_err}" + ); + + let explain_err = offsets + .explain_plan(false) + .await + .expect_err("take explain must reject scan_in_order(true)"); + assert!( + matches!(&explain_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {explain_err}" + ); + + let mut row_ids = table.take_row_ids(vec![5, 1]); + row_ids.mut_query().scan_in_order = Some(true); + let row_id_err = row_ids + .execute() + .await + .err() + .expect("take by row id must reject scan_in_order(true)"); + assert!( + matches!(&row_id_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {row_id_err}" + ); + + // Allowing unordered scans leaves an ordinary take unchanged. + let mut allowed = table.take_offsets(vec![5, 1]); + allowed.mut_query().scan_in_order = Some(false); + let batches = allowed + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 2 + ); + } + #[rstest::rstest] #[case::unsorted(vec![5, 1, 17], vec![5, 1, 17])] #[case::duplicate_and_missing(vec![17, 5, 17, u64::MAX, 1], vec![17, 5, 17, 1])] diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 760ab83fe..fc888e32b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1326,6 +1326,13 @@ impl RemoteTable { params: &QueryRequest, ) -> Result<()> { params.check_filter()?; + if params.scan_in_order == Some(true) { + return Err(Error::NotSupported { + message: "scan_in_order(true) requires an ordered scan of Embedded storage; \ + LanceDB Enterprise tables do not support storage-order scans yet" + .to_string(), + }); + } body["prefilter"] = params.prefilter.into(); // Only forward use_rte when explicitly set; a server that predates it // ignores the field and routes as it would by default. @@ -6718,6 +6725,27 @@ mod tests { assert_eq!(result.version, if old_server { 0 } else { 43 }); } + #[tokio::test] + async fn test_query_scan_in_order_true_is_not_supported() { + let table = Table::new_with_handler::<&str>("my_table", |_| { + panic!("scan_in_order(true) must fail before sending a request") + }); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("remote scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") + && message.contains("Enterprise tables")), + "unexpected error: {err}" + ); + } + #[tokio::test] async fn test_query_plain() { let expected_data = RecordBatch::try_new( diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index b168ff6ff..b79beca55 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1897,10 +1897,17 @@ impl Table { /// Create a [`Query`] Builder. /// /// Queries allow you to search your existing data. By default the query will - /// return all the data in the table in no particular order. The builder + /// return all the data in the table. The builder /// returned by this method can be used to control the query using filtering, /// vector similarity, sorting, and more. /// + /// An ordinary unfiltered base-only scan of a fixed table version in + /// Embedded returns manifest order: fragments in manifest order, then rows + /// in fragment order. RTE tables scan the LSM by default; use + /// `use_rte(false)` for the base table guarantee. Compaction, updates, and + /// newer versions can change that order. Use [`Query::scan_in_order`] to + /// require it explicitly and fail on paths that cannot uphold it. + /// /// Note: By default, all columns are returned. For best performance, you should /// only fetch the columns you need. See [`Query::select_with_projection`] for /// more details. @@ -1967,8 +1974,10 @@ impl Table { /// /// ## Full scan /// - /// This query will return everything in the table in no particular - /// order. + /// This query returns everything in the table. On an Embedded table, an + /// ordinary unfiltered base-only scan of a fixed version returns manifest + /// order. RTE tables scan the LSM by default and need `use_rte(false)` for + /// base manifest order. /// /// ```no_run /// # use arrow_array::RecordBatch; diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index b69b85cb3..4dd8df294 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -121,11 +121,13 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // The namespace QueryTable request cannot represent approx_mode, search_effort, - // use_rte or order_by. For use_rte that is worse than a tuning miss: RTE read - // routing lives only in `create_plan`, so a pushed-down query would return - // stale base-only data. A dropped order_by would return the wrong top-K rows. + // use_rte, order_by or scan_in_order. For use_rte that is worse than a tuning miss: + // RTE read routing lives only in `create_plan`, so a pushed-down query would return + // stale base-only data. A dropped order_by would return the wrong top-K rows, and a + // dropped ordered scan would silently stop guaranteeing manifest order. if query.base().use_rte.is_some() || query.base().has_take() + || query.base().scan_in_order == Some(true) || query .base() .order_by @@ -154,6 +156,47 @@ pub async fn analyze_query_plan( Ok(lance_analyze_plan(plan, Default::default()).await?) } +/// Reject requests that ask for storage order in a query shape that cannot +/// preserve it, or that also define a different result order. +fn validate_scan_in_order(query: &AnyQuery) -> Result<()> { + if query.base().scan_in_order != Some(true) { + return Ok(()); + } + + let ranked = match query { + AnyQuery::VectorQuery(_) => true, + AnyQuery::Query(query) => { + query.full_text_search.is_some() || query.reranker.is_some() || query.norm.is_some() + } + }; + if ranked { + return Err(Error::InvalidInput { + message: "scan_in_order(true) is only supported for ordinary scans; vector, \ + full-text, hybrid, and reranked queries return ranked results" + .to_string(), + }); + } + + if query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with a nonempty order_by; remove the \ + ordering to keep manifest order, or remove scan_in_order(true) to sort" + .to_string(), + }); + } + + if query.base().has_take() { + return crate::query::validate_take_scan_in_order(query.base()); + } + + Ok(()) +} + /// Local Execution Path (DataFusion) async fn execute_generic_query( table: &NativeTable, @@ -177,6 +220,7 @@ pub async fn create_plan( options: QueryExecutionOptions, ) -> Result> { let query = query.canonicalized()?; + validate_scan_in_order(&query)?; if let AnyQuery::Query(request) = &query && request.has_take() { @@ -435,6 +479,17 @@ pub async fn create_plan( scanner.order_by(Some(order_by.clone()))?; } + if let Some(scan_in_order) = query.base.scan_in_order { + scanner.scan_in_order(scan_in_order); + if scan_in_order { + // Legacy scalar-index plans can union materialized index rows with + // unindexed fragments and emit a different sequence. Explicit + // storage order must come from the manifest scan, so filters fall + // back to evaluating over the ordered fragments. + scanner.use_scalar_index(false); + } + } + let mut plan = scanner .create_plan() .await @@ -1191,6 +1246,21 @@ mod tests { FixedSizeListArray::try_new_from_values(Float32Array::from(values), dimension).unwrap() } + fn collect_i32(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + #[tokio::test] async fn test_parse_arrow_ipc_response_handles_file_and_stream() { use arrow_array::{Int32Array, RecordBatch}; @@ -2462,4 +2532,300 @@ mod tests { Some(ApproxMode::Accurate) ); } + + #[tokio::test] + async fn test_scan_in_order_local_multi_fragment_contract() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + + let table = conn + .create_table("scan_in_order_contract", batch(vec![0, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2, 3])).execute().await.unwrap(); + table.add(batch(vec![4, 5])).execute().await.unwrap(); + + let fragments = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .get_fragments() + .len(); + assert_eq!(fragments, 3, "the test needs real multi-fragment data"); + + // An ordered scan must not introduce a global sort. + let plan = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .explain_plan(false) + .await + .unwrap(); + assert!( + !plan.contains("SortExec"), + "scan_in_order(true) must not add a sort, got:\n{plan}" + ); + + // Pin one version so repeated executions describe the same manifest. + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + for _ in 0..2 { + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + } + + // The default keeps the ordered local behavior. + let batches = table + .query() + .select(Select::columns(&["id"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + + // Allowing unordered scans changes no membership. + let mut unordered = collect_i32( + &table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(), + ); + unordered.sort(); + assert_eq!(unordered, vec![0, 1, 2, 3, 4, 5]); + + // An explicit sort still wins when storage order is not required. + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .order_by(Some(vec![ColumnOrdering::desc_nulls_last( + "id".to_string(), + )])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![5, 4, 3, 2, 1, 0]); + + // Deletions keep manifest order, and small output batches plus + // limit/offset must not disturb it. + table.checkout_latest().await.unwrap(); + table.delete("id = 3").await.unwrap(); + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .offset(1) + .limit(2) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!( + batches.iter().all(|batch| batch.num_rows() <= 1), + "max_batch_length must stay bounded" + ); + assert_eq!(collect_i32(&batches), vec![1, 2]); + } + + #[tokio::test] + async fn test_scan_in_order_rejects_ranked_and_sorted_queries() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let vector = fixed_size_list_array(vec![0.0, 0.0, 1.0, 0.0, 2.0, 0.0], 2); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vector.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![0, 1, 2])), Arc::new(vector)], + ) + .unwrap(); + let table = conn + .create_table("scan_in_order_conflicts", batch) + .execute() + .await + .unwrap(); + + let err = table + .query() + .scan_in_order(true) + .order_by(Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())])) + .execute() + .await + .err() + .expect("ranked and sorted scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("nonempty order_by")), + "unexpected error: {err}" + ); + + let err = table + .query() + .scan_in_order(true) + .nearest_to(vec![0.0f32, 0.0]) + .unwrap() + .execute() + .await + .err() + .expect("ranked scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("ranked results")), + "unexpected error: {err}" + ); + } + + #[tokio::test] + async fn test_scan_in_order_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + // Insertion order differs from sorted order so a dropped scan order or + // an accidental sort changes the result. + let table = conn + .create_table("scan_in_order_namespace", batch(vec![3, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2])).execute().await.unwrap(); + + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + filter: Some(QueryFilter::Sql("id >= 1".to_string())), + select: Select::columns(&["id"]), + limit: Some(2), + scan_in_order: Some(true), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&query)); + + let batches = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![3, 1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + + // Allowing unordered scans does not require local execution. + let allow_unordered = AnyQuery::Query(QueryRequest { + scan_in_order: Some(false), + ..Default::default() + }); + assert!(!requires_local_namespace_execution(&allow_unordered)); + + // An explicit sort is already local because the namespace request has + // no order_by field. + let sorted = AnyQuery::Query(QueryRequest { + order_by: Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())]), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&sorted)); + } + + #[tokio::test] + async fn test_scan_in_order_true_rejected_on_rte() { + use crate::connect; + use crate::table::RTEWriteSpec; + use arrow_schema::{DataType, Field, Schema}; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![0, 1]))]).unwrap(); + let table = conn + .create_table("scan_in_order_rte", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("RTE scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") && message.contains("use_rte(false)")), + "unexpected error: {err}" + ); + + // The base table can still be read in storage order explicitly. + let batches = table + .query() + .scan_in_order(true) + .use_rte(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1]); + } } diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 400df6c82..eddb4d0c0 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -183,6 +183,11 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if query.base.order_by.is_some() { return unsupported("order_by"); } + if query.base.scan_in_order == Some(true) { + return unsupported( + "scan_in_order(true) (the LSM scanner does not preserve base manifest order)", + ); + } // Vector-only knobs the LSM scanner cannot honor. Both change results rather // than just recall, so error instead of silently ignoring them: distance_range // would return rows outside the bound, and use_index(false) asks for a